/* 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 __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all2) => { for (var name in all2) __defProp(target, name, { get: all2[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // node_modules/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 s3 = "short"; var l = "long"; var DATE_SHORT = { year: n, month: n, day: n }; var DATE_MED = { year: n, month: s3, day: n }; var DATE_MED_WITH_WEEKDAY = { year: n, month: s3, day: n, weekday: s3 }; 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: s3 }; 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: s3 }; 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: s3, day: n, hour: n, minute: n }; var DATETIME_MED_WITH_SECONDS = { year: n, month: s3, day: n, hour: n, minute: n, second: n }; var DATETIME_MED_WITH_WEEKDAY = { year: n, month: s3, day: n, weekday: s3, hour: n, minute: n }; var DATETIME_FULL = { year: n, month: l, day: n, hour: n, minute: n, timeZoneName: s3 }; var DATETIME_FULL_WITH_SECONDS = { year: n, month: l, day: n, hour: n, minute: n, second: n, timeZoneName: s3 }; var DATETIME_HUGE = { year: n, month: l, day: n, weekday: l, hour: n, minute: n, timeZoneName: l }; var DATETIME_HUGE_WITH_SECONDS = { year: n, month: l, day: n, weekday: l, hour: n, minute: n, second: n, timeZoneName: l }; var Zone = class { /** * The type of zone * @abstract * @type {string} */ get type() { throw new ZoneIsAbstractError(); } /** * The name of this zone. * @abstract * @type {string} */ get name() { throw new ZoneIsAbstractError(); } get ianaName() { return this.name; } /** * Returns whether the offset is known to be fixed for the whole year. * @abstract * @type {boolean} */ get isUniversal() { throw new ZoneIsAbstractError(); } /** * Returns the offset's common name (such as EST) at the specified timestamp * @abstract * @param {number} ts - Epoch milliseconds for which to get the name * @param {Object} opts - Options to affect the format * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'. * @param {string} opts.locale - What locale to return the offset name in. * @return {string} */ offsetName(ts, opts) { throw new ZoneIsAbstractError(); } /** * Returns the offset's value as a string * @abstract * @param {number} ts - Epoch milliseconds for which to get the offset * @param {string} format - What style of offset to return. * Accepts 'narrow', 'short', or 'techie'. Returning '+6', '+06:00', or '+0600' respectively * @return {string} */ formatOffset(ts, format2) { throw new ZoneIsAbstractError(); } /** * Return the offset in minutes for this zone at the specified timestamp. * @abstract * @param {number} ts - Epoch milliseconds for which to compute the offset * @return {number} */ offset(ts) { throw new ZoneIsAbstractError(); } /** * Return whether this Zone is equal to another zone * @abstract * @param {Zone} otherZone - the zone to compare * @return {boolean} */ equals(otherZone) { throw new ZoneIsAbstractError(); } /** * Return whether this Zone is valid. * @abstract * @type {boolean} */ get isValid() { throw new ZoneIsAbstractError(); } }; var singleton$1 = null; var SystemZone = class extends Zone { /** * Get a singleton instance of the local zone * @return {SystemZone} */ static get instance() { if (singleton$1 === null) { singleton$1 = new SystemZone(); } return singleton$1; } /** @override **/ get type() { return "system"; } /** @override **/ get name() { return new Intl.DateTimeFormat().resolvedOptions().timeZone; } /** @override **/ get isUniversal() { return false; } /** @override **/ offsetName(ts, { format: format2, locale: locale2 }) { return parseZoneInfo(ts, format2, locale2); } /** @override **/ formatOffset(ts, format2) { return formatOffset(this.offset(ts), format2); } /** @override **/ offset(ts) { return -new Date(ts).getTimezoneOffset(); } /** @override **/ equals(otherZone) { return otherZone.type === "system"; } /** @override **/ get isValid() { return true; } }; var dtfCache = {}; function makeDTF(zone) { if (!dtfCache[zone]) { dtfCache[zone] = new Intl.DateTimeFormat("en-US", { hour12: false, timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", era: "short" }); } return dtfCache[zone]; } var typeToPos = { year: 0, month: 1, day: 2, era: 3, hour: 4, minute: 5, second: 6 }; function hackyOffset(dtf, date) { const formatted = dtf.format(date).replace(/\u200E/g, ""), parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted), [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed; return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond]; } function partsOffset(dtf, date) { const formatted = dtf.formatToParts(date); const filled = []; for (let i2 = 0; i2 < formatted.length; i2++) { const { type: type2, value } = formatted[i2]; const pos = typeToPos[type2]; if (type2 === "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(s4) { return this.isValidZone(s4); } /** * 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 (e2) { return false; } } constructor(name) { super(); this.zoneName = name; this.valid = IANAZone.isValidZone(name); } /** @override **/ get type() { return "iana"; } /** @override **/ get name() { return this.zoneName; } /** @override **/ get isUniversal() { return false; } /** @override **/ offsetName(ts, { format: format2, locale: locale2 }) { return parseZoneInfo(ts, format2, locale2, this.name); } /** @override **/ formatOffset(ts, format2) { return formatOffset(this.offset(ts), format2); } /** @override **/ offset(ts) { const date = new Date(ts); if (isNaN(date)) return NaN; const dtf = makeDTF(this.name); let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date); if (adOrBc === "BC") { year = -Math.abs(year) + 1; } const adjustedHour = hour === 24 ? 0 : hour; const asUTC = objToLocalTS({ year, month, day, hour: adjustedHour, minute, second, millisecond: 0 }); let asTS = +date; const over = asTS % 1e3; asTS -= over >= 0 ? over : 1e3 + over; return (asUTC - asTS) / (60 * 1e3); } /** @override **/ equals(otherZone) { return otherZone.type === "iana" && otherZone.name === this.name; } /** @override **/ get isValid() { return this.valid; } }; var intlLFCache = {}; function getCachedLF(locString, opts = {}) { const key = JSON.stringify([locString, opts]); let dtf = intlLFCache[key]; if (!dtf) { dtf = new Intl.ListFormat(locString, opts); intlLFCache[key] = dtf; } return dtf; } var intlDTCache = {}; function getCachedDTF(locString, opts = {}) { const key = JSON.stringify([locString, opts]); let dtf = intlDTCache[key]; if (!dtf) { dtf = new Intl.DateTimeFormat(locString, opts); intlDTCache[key] = dtf; } return dtf; } var intlNumCache = {}; function getCachedINF(locString, opts = {}) { const key = JSON.stringify([locString, opts]); let inf = intlNumCache[key]; if (!inf) { inf = new Intl.NumberFormat(locString, opts); intlNumCache[key] = inf; } return inf; } var intlRelCache = {}; function getCachedRTF(locString, opts = {}) { const { base, ...cacheKeyOpts } = opts; const key = JSON.stringify([locString, cacheKeyOpts]); let inf = intlRelCache[key]; if (!inf) { inf = new Intl.RelativeTimeFormat(locString, opts); intlRelCache[key] = inf; } return inf; } var sysLocaleCache = null; function systemLocale() { if (sysLocaleCache) { return sysLocaleCache; } else { sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale; return sysLocaleCache; } } function parseLocaleString(localeStr) { const xIndex = localeStr.indexOf("-x-"); if (xIndex !== -1) { localeStr = localeStr.substring(0, xIndex); } const uIndex = localeStr.indexOf("-u-"); if (uIndex === -1) { return [localeStr]; } else { let options; let selectedStr; try { options = getCachedDTF(localeStr).resolvedOptions(); selectedStr = localeStr; } catch (e2) { 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 i2 = 1; i2 <= 12; i2++) { const dt = DateTime.utc(2009, i2, 1); ms.push(f(dt)); } return ms; } function mapWeekdays(f) { const ms = []; for (let i2 = 1; i2 <= 7; i2++) { const dt = DateTime.utc(2016, 11, 13 + i2); ms.push(f(dt)); } return ms; } function listStuff(loc, length, englishFn, intlFn) { const mode = loc.listingMode(); 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(i2) { if (this.inf) { const fixed = this.floor ? Math.floor(i2) : i2; return this.inf.format(fixed); } else { const fixed = this.floor ? Math.floor(i2) : roundTo(i2, 3); return padStart2(fixed, this.padTo); } } }; var PolyDateFormatter = class { constructor(dt, intl, opts) { this.opts = opts; this.originalZone = void 0; let z3 = void 0; if (this.opts.timeZone) { this.dt = dt; } else if (dt.zone.type === "fixed") { const gmtOffset = -1 * (dt.offset / 60); const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`; if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) { z3 = offsetZ; this.dt = dt; } else { z3 = "UTC"; this.dt = dt.offset === 0 ? dt : dt.setZone("UTC").plus({ minutes: dt.offset }); this.originalZone = dt.zone; } } else if (dt.zone.type === "system") { this.dt = dt; } else if (dt.zone.type === "iana") { this.dt = dt; z3 = dt.zone.name; } else { z3 = "UTC"; this.dt = dt.setZone("UTC").plus({ minutes: dt.offset }); this.originalZone = dt.zone; } const intlOpts = { ...this.opts }; intlOpts.timeZone = intlOpts.timeZone || z3; this.dtf = getCachedDTF(intl, intlOpts); } format() { if (this.originalZone) { return this.formatToParts().map(({ value }) => value).join(""); } return this.dtf.format(this.dt.toJSDate()); } formatToParts() { const parts = this.dtf.formatToParts(this.dt.toJSDate()); if (this.originalZone) { return parts.map((part) => { if (part.type === "timeZoneName") { const offsetName = this.originalZone.offsetName(this.dt.ts, { locale: this.dt.locale, format: this.opts.timeZoneName }); return { ...part, value: offsetName }; } else { return part; } }); } return parts; } resolvedOptions() { return this.dtf.resolvedOptions(); } }; var PolyRelFormatter = class { constructor(intl, isEnglish, opts) { this.opts = { style: "long", ...opts }; if (!isEnglish && hasRelative()) { this.rtf = getCachedRTF(intl, opts); } } format(count, unit) { if (this.rtf) { return this.rtf.format(count, unit); } else { return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long"); } } formatToParts(count, unit) { if (this.rtf) { return this.rtf.formatToParts(count, unit); } else { return []; } } }; var Locale = class { static fromOpts(opts) { return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN); } static create(locale2, numberingSystem, outputCalendar, defaultToEN = false) { const specifiedLocale = locale2 || 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: locale2, numberingSystem, outputCalendar } = {}) { return Locale.create(locale2, numberingSystem, outputCalendar); } constructor(locale2, numbering, outputCalendar, specifiedLocale) { const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale2); this.locale = parsedLocale; this.numberingSystem = numbering || parsedNumberingSystem || null; this.outputCalendar = outputCalendar || parsedOutputCalendar || null; this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar); this.weekdaysCache = { format: {}, standalone: {} }; this.monthsCache = { format: {}, standalone: {} }; this.meridiemCache = null; this.eraCache = {}; this.specifiedLocale = specifiedLocale; this.fastNumbersCached = null; } get fastNumbers() { if (this.fastNumbersCached == null) { this.fastNumbersCached = supportsFastNumbers(this); } return this.fastNumbersCached; } listingMode() { const isActuallyEn = this.isEnglish(); const hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory"); return isActuallyEn && hasNoWeirdness ? "en" : "intl"; } clone(alts) { if (!alts || Object.getOwnPropertyNames(alts).length === 0) { return this; } else { return Locale.create( alts.locale || this.specifiedLocale, alts.numberingSystem || this.numberingSystem, alts.outputCalendar || this.outputCalendar, alts.defaultToEN || false ); } } redefaultToEN(alts = {}) { return this.clone({ ...alts, defaultToEN: true }); } redefaultToSystem(alts = {}) { return this.clone({ ...alts, defaultToEN: false }); } months(length, format2 = false) { return listStuff(this, length, months, () => { const intl = format2 ? { month: length, day: "numeric" } : { month: length }, formatStr = format2 ? "format" : "standalone"; if (!this.monthsCache[formatStr][length]) { this.monthsCache[formatStr][length] = mapMonths((dt) => this.extract(dt, intl, "month")); } return this.monthsCache[formatStr][length]; }); } weekdays(length, format2 = false) { return listStuff(this, length, weekdays, () => { const intl = format2 ? { weekday: length, year: "numeric", month: "long", day: "numeric" } : { weekday: length }, formatStr = format2 ? "format" : "standalone"; if (!this.weekdaysCache[formatStr][length]) { this.weekdaysCache[formatStr][length] = mapWeekdays( (dt) => this.extract(dt, intl, "weekday") ); } return this.weekdaysCache[formatStr][length]; }); } meridiems() { return listStuff( this, void 0, () => 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) { return listStuff(this, length, 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((m3) => m3.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(s4) { if (s4) { const r = s4.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, format2) { return formatOffset(this.fixed, format2); } /** @override **/ get isUniversal() { return true; } /** @override **/ offset() { return this.fixed; } /** @override **/ equals(otherZone) { return otherZone.type === "fixed" && otherZone.fixed === this.fixed; } /** @override **/ get isValid() { return true; } }; var InvalidZone = class extends Zone { constructor(zoneName) { super(); this.zoneName = zoneName; } /** @override **/ get type() { return "invalid"; } /** @override **/ get name() { return this.zoneName; } /** @override **/ get isUniversal() { return false; } /** @override **/ offsetName() { return null; } /** @override **/ formatOffset() { return ""; } /** @override **/ offset() { return NaN; } /** @override **/ equals() { return false; } /** @override **/ get isValid() { return false; } }; function normalizeZone(input, defaultZone2) { if (isUndefined(input) || input === null) { return defaultZone2; } else if (input instanceof Zone) { return input; } else if (isString(input)) { const lowered = input.toLowerCase(); if (lowered === "default") return defaultZone2; else if (lowered === "local" || lowered === "system") return SystemZone.instance; else if (lowered === "utc" || lowered === "gmt") return FixedOffsetZone.utcInstance; else return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input); } else if (isNumber(input)) { return FixedOffsetZone.instance(input); } else if (typeof input === "object" && "offset" in input && typeof input.offset === "function") { 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(locale2) { defaultLocale = locale2; } /** * 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 interpreted as current century * @example Settings.twoDigitCutoffYear = 50 // '49' -> 1949; '50' -> 2050 * @example Settings.twoDigitCutoffYear = 1950 // interpreted as 50 * @example Settings.twoDigitCutoffYear = 2050 // ALSO interpreted 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 isInteger2(o) { return typeof o === "number" && o % 1 === 0; } function isString(o) { return typeof o === "string"; } function isDate2(o) { return Object.prototype.toString.call(o) === "[object Date]"; } function hasRelative() { try { return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat; } catch (e2) { 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((a3, k2) => { a3[k2] = obj[k2]; return a3; }, {}); } function hasOwnProperty2(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } function integerBetween(thing, bottom, top) { return isInteger2(thing) && thing >= bottom && thing <= top; } function floorMod(x2, n2) { return x2 - n2 * Math.floor(x2 / n2); } function padStart2(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(string3) { if (isUndefined(string3) || string3 === null || string3 === "") { return void 0; } else { return parseInt(string3, 10); } } function parseFloating(string3) { if (isUndefined(string3) || string3 === null || string3 === "") { return void 0; } else { return parseFloat(string3); } } 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 d3 = Date.UTC( obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond ); if (obj.year < 100 && obj.year >= 0) { d3 = new Date(d3); d3.setUTCFullYear(obj.year, obj.month - 1, obj.day); } return +d3; } 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, locale2, 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(locale2, modified).formatToParts(date).find((m3) => m3.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 u2 in obj) { if (hasOwnProperty2(obj, u2)) { const v = obj[u2]; if (v === void 0 || v === null) continue; normalized[normalizer(u2)] = asNumber(v); } } return normalized; } function formatOffset(offset2, format2) { const hours = Math.trunc(Math.abs(offset2 / 60)), minutes = Math.trunc(Math.abs(offset2 % 60)), sign = offset2 >= 0 ? "+" : "-"; switch (format2) { case "short": return `${sign}${padStart2(hours, 2)}:${padStart2(minutes, 2)}`; case "narrow": return `${sign}${hours}${minutes > 0 ? `:${minutes}` : ""}`; case "techie": return `${sign}${padStart2(hours, 2)}${padStart2(minutes, 2)}`; default: throw new RangeError(`Value format ${format2} is out of range for property format`); } } function timeObject(obj) { return pick(obj, ["hour", "minute", "second", "millisecond"]); } var monthsLong = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var monthsShort = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; var monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]; function months(length) { switch (length) { case "narrow": return [...monthsNarrow]; case "short": return [...monthsShort]; case "long": return [...monthsLong]; case "numeric": return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]; case "2-digit": return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]; default: return null; } } var weekdaysLong = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ]; var weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; var weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"]; function weekdays(length) { switch (length) { case "narrow": return [...weekdaysNarrow]; case "short": return [...weekdaysShort]; case "long": return [...weekdaysLong]; case "numeric": return ["1", "2", "3", "4", "5", "6", "7"]; default: return null; } } var meridiems = ["AM", "PM"]; var erasLong = ["Before Christ", "Anno Domini"]; var erasShort = ["BC", "AD"]; var erasNarrow = ["B", "A"]; function eras(length) { switch (length) { case "narrow": return [...erasNarrow]; case "short": return [...erasShort]; case "long": return [...erasLong]; default: return null; } } function meridiemForDateTime(dt) { return meridiems[dt.hour < 12 ? 0 : 1]; } function weekdayForDateTime(dt, length) { return weekdays(length)[dt.weekday - 1]; } function monthForDateTime(dt, length) { return months(length)[dt.month - 1]; } function eraForDateTime(dt, length) { return eras(length)[dt.year < 0 ? 0 : 1]; } function formatRelativeTime(unit, count, numeric = "always", narrow = false) { const units = { years: ["year", "yr."], quarters: ["quarter", "qtr."], months: ["month", "mo."], weeks: ["week", "wk."], days: ["day", "day", "days"], hours: ["hour", "hr."], minutes: ["minute", "min."], seconds: ["second", "sec."] }; const lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1; if (numeric === "auto" && lastable) { const isDay = unit === "days"; switch (count) { case 1: return isDay ? "tomorrow" : `next ${units[unit][0]}`; case -1: return isDay ? "yesterday" : `last ${units[unit][0]}`; case 0: return isDay ? "today" : `this ${units[unit][0]}`; } } const isInPast = Object.is(count, -0) || count < 0, fmtValue = Math.abs(count), singular = fmtValue === 1, lilUnits = units[unit], fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit; return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`; } function stringifyTokens(splits, tokenToString) { let s4 = ""; for (const token of splits) { if (token.literal) { s4 += token.val; } else { s4 += tokenToString(token.val); } } return s4; } var macroTokenToFormatOpts = { D: DATE_SHORT, DD: DATE_MED, DDD: DATE_FULL, DDDD: DATE_HUGE, t: TIME_SIMPLE, tt: TIME_WITH_SECONDS, ttt: TIME_WITH_SHORT_OFFSET, tttt: TIME_WITH_LONG_OFFSET, T: TIME_24_SIMPLE, TT: TIME_24_WITH_SECONDS, TTT: TIME_24_WITH_SHORT_OFFSET, TTTT: TIME_24_WITH_LONG_OFFSET, f: DATETIME_SHORT, ff: DATETIME_MED, fff: DATETIME_FULL, ffff: DATETIME_HUGE, F: DATETIME_SHORT_WITH_SECONDS, FF: DATETIME_MED_WITH_SECONDS, FFF: DATETIME_FULL_WITH_SECONDS, FFFF: DATETIME_HUGE_WITH_SECONDS }; var Formatter = class { static create(locale2, opts = {}) { return new Formatter(locale2, opts); } static parseFormat(fmt) { let current = null, currentFull = "", bracketed = false; const splits = []; for (let i2 = 0; i2 < fmt.length; i2++) { const c2 = fmt.charAt(i2); if (c2 === "'") { if (currentFull.length > 0) { splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull }); } current = null; currentFull = ""; bracketed = !bracketed; } else if (bracketed) { currentFull += c2; } else if (c2 === current) { currentFull += c2; } else { if (currentFull.length > 0) { splits.push({ literal: /^\s+$/.test(currentFull), val: currentFull }); } currentFull = c2; current = c2; } } if (currentFull.length > 0) { splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull }); } return splits; } static macroTokenToFormatOpts(token) { return macroTokenToFormatOpts[token]; } constructor(locale2, formatOpts) { this.opts = formatOpts; this.loc = locale2; 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(); } dtFormatter(dt, opts = {}) { return this.loc.dtFormatter(dt, { ...this.opts, ...opts }); } formatDateTime(dt, opts) { return this.dtFormatter(dt, opts).format(); } formatDateTimeParts(dt, opts) { return this.dtFormatter(dt, opts).formatToParts(); } formatInterval(interval, opts) { const df = this.dtFormatter(interval.start, opts); return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate()); } resolvedOptions(dt, opts) { return this.dtFormatter(dt, opts).resolvedOptions(); } num(n2, p = 0) { if (this.opts.forceSimple) { return padStart2(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", string3 = (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) : string3({ hour: "numeric", hourCycle: "h12" }, "dayperiod"), month = (length, standalone) => knownEnglish ? monthForDateTime(dt, length) : string3(standalone ? { month: length } : { month: length, day: "numeric" }, "month"), weekday = (length, standalone) => knownEnglish ? weekdayForDateTime(dt, length) : string3( standalone ? { weekday: length } : { weekday: length, month: "long", day: "numeric" }, "weekday" ), maybeMacro = (token) => { const formatOpts = Formatter.macroTokenToFormatOpts(token); if (formatOpts) { return this.formatWithSystemDefault(dt, formatOpts); } else { return token; } }, era = (length) => knownEnglish ? eraForDateTime(dt, length) : string3({ 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 ? string3({ day: "numeric" }, "day") : this.num(dt.day); case "dd": return useDateTimeFormatter ? string3({ 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 ? string3({ month: "numeric", day: "numeric" }, "month") : this.num(dt.month); case "LL": return useDateTimeFormatter ? string3({ 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 ? string3({ month: "numeric" }, "month") : this.num(dt.month); case "MM": return useDateTimeFormatter ? string3({ 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 ? string3({ year: "numeric" }, "year") : this.num(dt.year); case "yy": return useDateTimeFormatter ? string3({ year: "2-digit" }, "year") : this.num(dt.year.toString().slice(-2), 2); case "yyyy": return useDateTimeFormatter ? string3({ year: "numeric" }, "year") : this.num(dt.year, 4); case "yyyyyy": return useDateTimeFormatter ? string3({ year: "numeric" }, "year") : this.num(dt.year, 6); case "G": return era("short"); case "GG": return era("long"); case "GGGGG": return era("narrow"); case "kk": return this.num(dt.weekYear.toString().slice(-2), 2); case "kkkk": return this.num(dt.weekYear, 4); case "W": return this.num(dt.weekNumber); case "WW": return this.num(dt.weekNumber, 2); case "o": return this.num(dt.ordinal); case "ooo": return this.num(dt.ordinal, 3); case "q": return this.num(dt.quarter); case "qq": return this.num(dt.quarter, 2); case "X": return this.num(Math.floor(dt.ts / 1e3)); case "x": return this.num(dt.ts); default: return maybeMacro(token); } }; return stringifyTokens(Formatter.parseFormat(fmt), tokenToString); } formatDurationFromString(dur, fmt) { const tokenToField = (token) => { switch (token[0]) { case "S": return "millisecond"; case "s": return "second"; case "m": return "minute"; case "h": return "hour"; case "d": return "day"; case "w": return "week"; case "M": return "month"; case "y": return "year"; default: return null; } }, tokenToString = (lildur) => (token) => { const mapped = tokenToField(token); if (mapped) { return this.num(lildur.get(mapped), token.length); } else { return token; } }, tokens = Formatter.parseFormat(fmt), realTokens = tokens.reduce( (found, { literal, val }) => literal ? found : found.concat(val), [] ), collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((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 (m3) => extractors.reduce( ([mergedVals, mergedZone, cursor], ex) => { const [val, zone, next] = ex(m3, cursor); return [{ ...mergedVals, ...val }, zone || mergedZone, next]; }, [{}, null, 1] ).slice(0, 2); } function parse3(s4, ...patterns) { if (s4 == null) { return [null, null]; } for (const [regex, extractor] of patterns) { const m3 = regex.exec(s4); if (m3) { return extractor(m3); } } return [null, null]; } function simpleParse(...keys) { return (match3, cursor) => { const ret = {}; let i2; for (i2 = 0; i2 < keys.length; i2++) { ret[keys[i2]] = parseInteger(match3[cursor + i2]); } return [ret, null, cursor + i2]; }; } 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 int2(match3, pos, fallback) { const m3 = match3[pos]; return isUndefined(m3) ? fallback : parseInteger(m3); } function extractISOYmd(match3, cursor) { const item = { year: int2(match3, cursor), month: int2(match3, cursor + 1, 1), day: int2(match3, cursor + 2, 1) }; return [item, null, cursor + 3]; } function extractISOTime(match3, cursor) { const item = { hours: int2(match3, cursor, 0), minutes: int2(match3, cursor + 1, 0), seconds: int2(match3, cursor + 2, 0), milliseconds: parseMillis(match3[cursor + 3]) }; return [item, null, cursor + 4]; } function extractISOOffset(match3, cursor) { const local = !match3[cursor] && !match3[cursor + 1], fullOffset = signedOffset(match3[cursor + 1], match3[cursor + 2]), zone = local ? null : FixedOffsetZone.instance(fullOffset); return [{}, zone, cursor + 3]; } function extractIANAZone(match3, cursor) { const zone = match3[cursor] ? IANAZone.create(match3[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(match3) { const [s4, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = match3; const hasNegativePrefix = s4[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(match3) { const [ , weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr, obsOffset, milOffset, offHourStr, offMinuteStr ] = match3, 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(s4) { return s4.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(match3) { const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match3, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); return [result, FixedOffsetZone.utcInstance]; } function extractASCII(match3) { const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match3, 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(s4) { return parse3( s4, [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], [isoTimeCombinedRegex, extractISOTimeAndOffset] ); } function parseRFC2822Date(s4) { return parse3(preprocessRFC2822(s4), [rfc2822, extractRFC2822]); } function parseHTTPDate(s4) { return parse3( s4, [rfc1123, extractRFC1123Or850], [rfc850, extractRFC1123Or850], [ascii, extractASCII] ); } function parseISODuration(s4) { return parse3(s4, [isoDuration, extractISODuration]); } var extractISOTimeOnly = combineExtractors(extractISOTime); function parseISOTimeOnly(s4) { return parse3(s4, [isoTimeOnly, extractISOTimeOnly]); } var sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex); var sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex); var extractISOTimeOffsetAndIANAZone = combineExtractors( extractISOTime, extractISOOffset, extractIANAZone ); function parseSQL(s4) { return parse3( s4, [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 durationToMillis(matrix, vals) { var _a; let sum = (_a = vals.milliseconds) != null ? _a : 0; for (const unit of reverseUnits.slice(1)) { if (vals[unit]) { sum += vals[unit] * matrix[unit]["milliseconds"]; } } return sum; } function normalizeValues(matrix, vals) { const factor = durationToMillis(matrix, vals) < 0 ? -1 : 1; orderedUnits$1.reduceRight((previous3, current) => { if (!isUndefined(vals[current])) { if (previous3) { const previousVal = vals[previous3] * factor; const conv = matrix[current][previous3]; const rollUp = Math.floor(previousVal / conv); vals[current] += rollUp * factor; vals[previous3] -= rollUp * conv * factor; } return current; } else { return previous3; } }, null); orderedUnits$1.reduce((previous3, current) => { if (!isUndefined(vals[current])) { if (previous3) { const fraction = vals[previous3] % 1; vals[previous3] -= fraction; vals[current] += fraction * matrix[previous3][current]; } return current; } else { return previous3; } }, 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(text3, opts) { const [parsed] = parseISODuration(text3); if (parsed) { return Duration.fromObject(parsed, opts); } else { return Duration.invalid("unparsable", `the input "${text3}" 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(text3, opts) { const [parsed] = parseISOTimeOnly(text3); if (parsed) { return Duration.fromObject(parsed, opts); } else { return Duration.invalid("unparsable", `the input "${text3}" can't be parsed as ISO 8601`); } } /** * Create an invalid Duration. * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information * @return {Duration} */ static invalid(reason, explanation = null) { if (!reason) { throw new InvalidArgumentError("need to specify a reason the Duration is invalid"); } const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); if (Settings.throwOnInvalid) { throw new InvalidDurationError(invalid); } else { return new Duration({ invalid }); } } /** * @private */ static normalizeUnit(unit) { const normalized = { year: "years", years: "years", quarter: "quarters", quarters: "quarters", month: "months", months: "months", week: "weeks", weeks: "weeks", day: "days", days: "days", hour: "hours", hours: "hours", minute: "minutes", minutes: "minutes", second: "seconds", seconds: "seconds", millisecond: "milliseconds", milliseconds: "milliseconds" }[unit ? unit.toLowerCase() : unit]; if (!normalized) throw new InvalidUnitError(unit); return normalized; } /** * Check if an object is a Duration. Works across context boundaries * @param {object} o * @return {boolean} */ static isDuration(o) { return o && o.isLuxonDuration || false; } /** * Get the locale of a Duration, such 'en-GB' * @type {string} */ get locale() { return this.isValid ? this.loc.locale : null; } /** * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration * * @type {string} */ get numberingSystem() { return this.isValid ? this.loc.numberingSystem : null; } /** * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens: * * `S` for milliseconds * * `s` for seconds * * `m` for minutes * * `h` for hours * * `d` for days * * `w` for weeks * * `M` for months * * `y` for years * Notes: * * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits * * Tokens can be escaped by wrapping with single quotes. * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting. * @param {string} fmt - the format string * @param {Object} opts - options * @param {boolean} [opts.floor=true] - floor numerical values * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2" * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002" * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000" * @return {string} */ toFormat(fmt, opts = {}) { const fmtOpts = { ...opts, floor: opts.round !== false && opts.floor !== false }; return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID$2; } /** * Returns a string representation of a Duration with all units included. * To modify its behavior use the `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat * @param opts - On option object to override the formatting. Accepts the same keys as the options parameter of the native `Int.NumberFormat` constructor, as well as `listStyle`. * @example * ```js * var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 }) * dur.toHuman() //=> '1 day, 5 hours, 6 minutes' * dur.toHuman({ listStyle: "long" }) //=> '1 day, 5 hours, and 6 minutes' * dur.toHuman({ unitDisplay: "short" }) //=> '1 day, 5 hr, 6 min' * ``` */ toHuman(opts = {}) { if (!this.isValid) return INVALID$2; 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 s4 = "P"; if (this.years !== 0) s4 += this.years + "Y"; if (this.months !== 0 || this.quarters !== 0) s4 += this.months + this.quarters * 3 + "M"; if (this.weeks !== 0) s4 += this.weeks + "W"; if (this.days !== 0) s4 += this.days + "D"; if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) s4 += "T"; if (this.hours !== 0) s4 += this.hours + "H"; if (this.minutes !== 0) s4 += this.minutes + "M"; if (this.seconds !== 0 || this.milliseconds !== 0) s4 += roundTo(this.seconds + this.milliseconds / 1e3, 3) + "S"; if (s4 === "P") s4 += "T0S"; return s4; } /** * 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, includeOffset: false }; const dateTime = DateTime.fromMillis(millis, { zone: "UTC" }); return dateTime.toISOTime(opts); } /** * 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() { if (!this.isValid) return NaN; return durationToMillis(this.matrix, this.values); } /** * 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 k2 of orderedUnits$1) { if (hasOwnProperty2(dur.values, k2) || hasOwnProperty2(this.values, k2)) { result[k2] = dur.get(k2) + this.get(k2); } } 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 k2 of Object.keys(this.values)) { result[k2] = asNumber(fn(this.values[k2], k2)); } 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: locale2, numberingSystem, conversionAccuracy, matrix } = {}) { const loc = this.loc.clone({ locale: locale2, 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. * Assuming the overall value of the Duration is positive, this means: * - excessive values for lower-order units are converted to higher-order units (if possible, see first and second example) * - negative lower-order units are converted to higher order units (there must be such a higher order unit, otherwise * the overall value would be negative, see second example) * - fractional values for higher-order units are converted to lower-order units (if possible, see fourth example) * * If the overall value is negative, the result of this method is equivalent to `this.negate().normalize().negate()`. * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 } * @example Duration.fromObject({ days: 5000 }).normalize().toObject() //=> { days: 5000 } * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 } * @example Duration.fromObject({ years: 2.5, days: 0, hours: 0 }).normalize().toObject() //=> { years: 2, days: 182, hours: 12 } * @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((u2) => Duration.normalizeUnit(u2)); const built = {}, accumulated = {}, vals = this.toObject(); let lastUnit; for (const k2 of orderedUnits$1) { if (units.indexOf(k2) >= 0) { lastUnit = k2; let own2 = 0; for (const ak in accumulated) { own2 += this.matrix[ak][k2] * accumulated[ak]; accumulated[ak] = 0; } if (isNumber(vals[k2])) { own2 += vals[k2]; } const i2 = Math.trunc(own2); built[k2] = i2; accumulated[k2] = (own2 * 1e3 - i2 * 1e3) / 1e3; } else if (isNumber(vals[k2])) { accumulated[k2] = vals[k2]; } } for (const key in accumulated) { if (accumulated[key] !== 0) { built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key]; } } normalizeValues(this.matrix, built); return clone$1(this, { values: built }, true); } /** * 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 k2 of Object.keys(this.values)) { negated[k2] = this.values[k2] === 0 ? 0 : -this.values[k2]; } 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 u2 of orderedUnits$1) { if (!eq(this.values[u2], other.values[u2])) { 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 `/`, `/`, and `/` 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(text3, opts) { const [s4, e2] = (text3 || "").split("/", 2); if (s4 && e2) { let start, startIsValid; try { start = DateTime.fromISO(s4, opts); startIsValid = start.isValid; } catch (e3) { startIsValid = false; } let end, endIsValid; try { end = DateTime.fromISO(e2, opts); endIsValid = end.isValid; } catch (e3) { endIsValid = false; } if (startIsValid && endIsValid) { return Interval.fromDateTimes(start, end); } if (startIsValid) { const dur = Duration.fromISO(e2, opts); if (dur.isValid) { return Interval.after(start, dur); } } else if (endIsValid) { const dur = Duration.fromISO(s4, opts); if (dur.isValid) { return Interval.before(end, dur); } } } return Interval.invalid("unparsable", `the input "${text3}" 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)) + (end.valueOf() !== this.end.valueOf()); } /** * Returns whether this Interval's start and end are both in the same unit of time * @param {string} unit - the unit of time to check sameness on * @return {boolean} */ hasSame(unit) { return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false; } /** * Return whether this Interval has the same start and end DateTimes. * @return {boolean} */ isEmpty() { return this.s.valueOf() === this.e.valueOf(); } /** * Return whether this Interval's start is after the specified DateTime. * @param {DateTime} dateTime * @return {boolean} */ isAfter(dateTime) { if (!this.isValid) return false; return this.s > dateTime; } /** * Return whether this Interval's end is before the specified DateTime. * @param {DateTime} dateTime * @return {boolean} */ isBefore(dateTime) { if (!this.isValid) return false; return this.e <= dateTime; } /** * Return whether this Interval contains the specified DateTime. * @param {DateTime} dateTime * @return {boolean} */ contains(dateTime) { if (!this.isValid) return false; return this.s <= dateTime && this.e > dateTime; } /** * "Sets" the start and/or end dates. Returns a newly-constructed Interval. * @param {Object} values - the values to set * @param {DateTime} values.start - the starting DateTime * @param {DateTime} values.end - the ending DateTime * @return {Interval} */ set({ start, 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((d3) => this.contains(d3)).sort(), results = []; let { s: s4 } = this, i2 = 0; while (s4 < this.e) { const added = sorted[i2] || this.e, next = +added > +this.e ? this.e : added; results.push(Interval.fromDateTimes(s4, next)); s4 = next; i2 += 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: s4 } = this, idx = 1, next; const results = []; while (s4 < this.e) { const added = this.start.plus(dur.mapUnits((x2) => x2 * idx)); next = +added > +this.e ? this.e : added; results.push(Interval.fromDateTimes(s4, next)); s4 = 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 s4 = this.s > other.s ? this.s : other.s, e2 = this.e < other.e ? this.e : other.e; if (s4 >= e2) { return null; } else { return Interval.fromDateTimes(s4, e2); } } /** * 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 s4 = this.s < other.s ? this.s : other.s, e2 = this.e > other.e ? this.e : other.e; return Interval.fromDateTimes(s4, e2); } /** * 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((a3, b2) => a3.s - b2.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((i2) => [ { time: i2.s, type: "s" }, { time: i2.e, type: "e" } ]), flattened = Array.prototype.concat(...ends), arr = flattened.sort((a3, b2) => a3.time - b2.time); for (const i2 of arr) { currentCount += i2.type === "s" ? 1 : -1; if (currentCount === 1) { start = i2.time; } else { if (start && +start !== +i2.time) { results.push(Interval.fromDateTimes(start, i2.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((i2) => this.intersection(i2)).filter((i2) => i2 && !i2.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 ? Formatter.create(this.s.loc.clone(opts), formatOpts).formatInterval(this) : INVALID$1; } /** * Returns an ISO 8601-compliant string representation of this Interval. * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals * @param {Object} opts - The same options as {@link DateTime#toISO} * @return {string} */ toISO(opts) { if (!this.isValid) return INVALID$1; return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`; } /** * Returns an ISO 8601-compliant string representation of date of this Interval. * The time components are ignored. * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals * @return {string} */ toISODate() { if (!this.isValid) return INVALID$1; return `${this.s.toISODate()}/${this.e.toISODate()}`; } /** * Returns an ISO 8601-compliant string representation of time of this Interval. * The date components are ignored. * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals * @param {Object} opts - The same options as {@link DateTime#toISO} * @return {string} */ toISOTime(opts) { if (!this.isValid) return INVALID$1; return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`; } /** * Returns a string representation of this Interval formatted according to the specified format * string. **You may not want this.** See {@link Interval#toLocaleString} for a more flexible * formatting tool. * @param {string} dateFormat - The format string. This string formats the start and end time. * See {@link DateTime#toFormat} for details. * @param {Object} opts - Options. * @param {string} [opts.separator = ' – '] - A separator to place between the start and end * representations. * @return {string} */ toFormat(dateFormat, { separator = " \u2013 " } = {}) { if (!this.isValid) return INVALID$1; return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`; } /** * Return a Duration representing the time spanned by this interval. * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration. * @param {Object} opts - options that affect the creation of the Duration * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 } * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 } * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 } * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 } * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 } * @return {Duration} */ toDuration(unit, opts) { if (!this.isValid) { return Duration.invalid(this.invalidReason); } return this.e.diff(this.s, unit, opts); } /** * Run mapFn on the interval start and end, returning a new Interval from the resulting DateTimes * @param {function} mapFn * @return {Interval} * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.toUTC()) * @example Interval.fromDateTimes(dt1, dt2).mapEndpoints(endpoint => endpoint.plus({ hours: 2 })) */ mapEndpoints(mapFn) { return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e)); } }; var Info = class { /** * Return whether the specified zone contains a DST. * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone. * @return {boolean} */ static hasDST(zone = Settings.defaultZone) { const proto = DateTime.now().setZone(zone).set({ month: 12 }); return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset; } /** * Return whether the specified zone is a valid IANA specifier. * @param {string} zone - Zone to check * @return {boolean} */ static isValidIANAZone(zone) { return IANAZone.isValidZone(zone); } /** * Converts the input into a {@link Zone} instance. * * * If `input` is already a Zone instance, it is returned unchanged. * * If `input` is a string containing a valid time zone name, a Zone instance * with that name is returned. * * If `input` is a string that doesn't refer to a known time zone, a Zone * instance with {@link Zone#isValid} == false is returned. * * If `input is a number, a Zone instance with the specified fixed offset * in minutes is returned. * * If `input` is `null` or `undefined`, the default zone is returned. * @param {string|Zone|number} [input] - the value to be converted * @return {Zone} */ static normalizeZone(input) { return normalizeZone(input, Settings.defaultZone); } /** * Return an array of standalone month names. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @param {string} [opts.locObj=null] - an existing locale object to use * @param {string} [opts.outputCalendar='gregory'] - the calendar * @example Info.months()[0] //=> 'January' * @example Info.months('short')[0] //=> 'Jan' * @example Info.months('numeric')[0] //=> '1' * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.' * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١' * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I' * @return {Array} */ static months(length = "long", { locale: locale2 = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) { return (locObj || Locale.create(locale2, 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: locale2 = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) { return (locObj || Locale.create(locale2, 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: locale2 = null, numberingSystem = null, locObj = null } = {}) { return (locObj || Locale.create(locale2, 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: locale2 = null, numberingSystem = null, locObj = null } = {}) { return (locObj || Locale.create(locale2, 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: locale2 = null } = {}) { return Locale.create(locale2).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: locale2 = null } = {}) { return Locale.create(locale2, 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", (a3, b2) => b2.year - a3.year], ["quarters", (a3, b2) => b2.quarter - a3.quarter + (b2.year - a3.year) * 4], ["months", (a3, b2) => b2.month - a3.month + (b2.year - a3.year) * 12], [ "weeks", (a3, b2) => { const days = dayDiff(a3, b2); 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); if (cursor > later) { highWater = cursor; 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( (u2) => ["hours", "minutes", "seconds", "milliseconds"].indexOf(u2) >= 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(str2) { let value = parseInt(str2, 10); if (isNaN(value)) { value = ""; for (let i2 = 0; i2 < str2.length; i2++) { const code = str2.charCodeAt(i2); if (str2[i2].search(numberingSystems.hanidec) !== -1) { value += hanidecChars.indexOf(str2[i2]); } 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(regex, post = (i2) => i2) { return { regex, deser: ([s4]) => post(parseDigits(s4)) }; } var NBSP = String.fromCharCode(160); var spaceOrNBSP = `[ ${NBSP}]`; var spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g"); function fixListRegex(s4) { return s4.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP); } function stripInsensitivities(s4) { return s4.replace(/\./g, "").replace(spaceOrNBSPRegExp, " ").toLowerCase(); } function oneOf(strings, startIndex) { if (strings === null) { return null; } else { return { regex: RegExp(strings.map(fixListRegex).join("|")), deser: ([s4]) => strings.findIndex((i2) => stripInsensitivities(s4) === stripInsensitivities(i2)) + startIndex }; } } function offset(regex, groups) { return { regex, deser: ([, h3, m3]) => signedOffset(h3, m3), groups }; } function simple(regex) { return { regex, deser: ([s4]) => s4 }; } function escapeToken(value) { return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); } function unitForToken(token, loc) { const one2 = 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: ([s4]) => s4, literal: true }), unitate = (t2) => { if (token.literal) { return literal(t2); } switch (t2.val) { case "G": return oneOf(loc.eras("short"), 0); case "GG": return oneOf(loc.eras("long"), 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), 1); case "MMMM": return oneOf(loc.months("long", true), 1); case "L": return intUnit(oneOrTwo); case "LL": return intUnit(two); case "LLL": return oneOf(loc.months("short", false), 1); case "LLLL": return oneOf(loc.months("long", 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(one2); 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(one2); case "EEE": return oneOf(loc.weekdays("short", false), 1); case "EEEE": return oneOf(loc.weekdays("long", false), 1); case "ccc": return oneOf(loc.weekdays("short", true), 1); case "cccc": return oneOf(loc.weekdays("long", true), 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); case " ": return simple(/[^\S\n\r]/); 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", hour12: { numeric: "h", "2-digit": "hh" }, hour24: { 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, resolvedOpts) { const { type: type2, value } = part; if (type2 === "literal") { const isSpace = /^\s+$/.test(value); return { literal: !isSpace, val: isSpace ? " " : value }; } const style = formatOpts[type2]; let actualType = type2; if (type2 === "hour") { if (formatOpts.hour12 != null) { actualType = formatOpts.hour12 ? "hour12" : "hour24"; } else if (formatOpts.hourCycle != null) { if (formatOpts.hourCycle === "h11" || formatOpts.hourCycle === "h12") { actualType = "hour12"; } else { actualType = "hour24"; } } else { actualType = resolvedOpts.hour12 ? "hour12" : "hour24"; } } let val = partTypeStyleToTokenVal[actualType]; if (typeof val === "object") { val = val[style]; } if (val) { return { literal: false, val }; } return void 0; } function buildRegex(units) { const re = units.map((u2) => u2.regex).reduce((f, r) => `${f}(${r.source})`, ""); return [`^${re}$`, units]; } function match2(input, regex, handlers) { const matches = input.match(regex); if (matches) { const all2 = {}; let matchIndex = 1; for (const i2 in handlers) { if (hasOwnProperty2(handlers, i2)) { const h3 = handlers[i2], groups = h3.groups ? h3.groups + 1 : 1; if (!h3.literal && h3.token) { all2[h3.token.val[0]] = h3.deser(matches.slice(matchIndex, matchIndex + groups)); } matchIndex += groups; } } return [matches, all2]; } 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, k2) => { const f = toField(k2); if (f) { r[f] = matches[k2]; } return r; }, {}); return [vals, zone, specificOffset]; } var dummyDateTimeCache = null; function getDummyDateTime() { if (!dummyDateTimeCache) { dummyDateTimeCache = DateTime.fromMillis(1555555555555); } return dummyDateTimeCache; } function maybeExpandMacroToken(token, locale2) { if (token.literal) { return token; } const formatOpts = Formatter.macroTokenToFormatOpts(token.val); const tokens = formatOptsToTokens(formatOpts, locale2); if (tokens == null || tokens.includes(void 0)) { return token; } return tokens; } function expandMacroTokens(tokens, locale2) { return Array.prototype.concat(...tokens.map((t2) => maybeExpandMacroToken(t2, locale2))); } function explainFromTokens(locale2, input, format2) { const tokens = expandMacroTokens(Formatter.parseFormat(format2), locale2), units = tokens.map((t2) => unitForToken(t2, locale2)), disqualifyingUnit = units.find((t2) => t2.invalidReason); if (disqualifyingUnit) { return { input, tokens, invalidReason: disqualifyingUnit.invalidReason }; } else { const [regexString, handlers] = buildRegex(units), regex = RegExp(regexString, "i"), [rawMatches, matches] = match2(input, regex, handlers), [result, zone, specificOffset] = matches ? dateTimeFromMatches(matches) : [null, null, void 0]; if (hasOwnProperty2(matches, "a") && hasOwnProperty2(matches, "H")) { throw new ConflictingSpecificationError( "Can't include meridiem when specifying 24-hour format" ); } return { input, tokens, regex, rawMatches, matches, result, zone, specificOffset }; } } function parseFromTokens(locale2, input, format2) { const { result, zone, specificOffset, invalidReason } = explainFromTokens(locale2, input, format2); return [result, zone, specificOffset, invalidReason]; } function formatOptsToTokens(formatOpts, locale2) { if (!formatOpts) { return null; } const formatter = Formatter.create(locale2, formatOpts); const df = formatter.dtFormatter(getDummyDateTime()); const parts = df.formatToParts(); const resolvedOpts = df.resolvedOptions(); return parts.map((p) => tokenForPart(p, formatOpts, resolvedOpts)); } 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 d3 = new Date(Date.UTC(year, month - 1, day)); if (year < 100 && year >= 0) { d3.setUTCFullYear(d3.getUTCFullYear() - 1900); } const js = d3.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((i2) => i2 < 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 = isInteger2(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 = isInteger2(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 = isInteger2(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 INVALID2 = "Invalid DateTime"; var MAX_DATE = 864e13; function unsupportedZone(zone) { return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`); } function possiblyCachedWeekData(dt) { if (dt.weekData === null) { dt.weekData = gregorianToWeek(dt.c); } return dt.weekData; } function clone(inst, alts) { const current = { ts: inst.ts, zone: inst.zone, c: inst.c, o: inst.o, loc: inst.loc, invalid: inst.invalid }; return new DateTime({ ...current, ...alts, old: current }); } function fixOffset(localTS, o, tz) { let utcGuess = localTS - o * 60 * 1e3; const o2 = tz.offset(utcGuess); if (o === o2) { return [utcGuess, o]; } utcGuess -= (o2 - o) * 60 * 1e3; const o3 = tz.offset(utcGuess); if (o2 === o3) { return [utcGuess, o2]; } return [localTS - Math.min(o2, o3) * 60 * 1e3, Math.max(o2, o3)]; } function tsToObj(ts, offset2) { ts += offset2 * 60 * 1e3; const d3 = new Date(ts); return { year: d3.getUTCFullYear(), month: d3.getUTCMonth() + 1, day: d3.getUTCDate(), hour: d3.getUTCHours(), minute: d3.getUTCMinutes(), second: d3.getUTCSeconds(), millisecond: d3.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, c2 = { ...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(c2); let [ts, o] = fixOffset(localTS, oPre, inst.zone); if (millisToAdd !== 0) { ts += millisToAdd; o = inst.zone.offset(ts); } return { ts, o }; } function parseDataToDateTime(parsed, parsedZone, opts, format2, text3, specificOffset) { const { setZone, zone } = opts; if (parsed && Object.keys(parsed).length !== 0 || parsedZone) { const interpretationZone = parsedZone || zone, inst = DateTime.fromObject(parsed, { ...opts, zone: interpretationZone, specificOffset }); return setZone ? inst : inst.setZone(zone); } else { return DateTime.invalid( new Invalid("unparsable", `the input "${text3}" can't be parsed as ${format2}`) ); } } function toTechFormat(dt, format2, allowZ = true) { return dt.isValid ? Formatter.create(Locale.create("en-US"), { allowZ, forceSimple: true }).formatDateTimeFromString(dt, format2) : null; } function toISODate(o, extended) { const longFormat = o.c.year > 9999 || o.c.year < 0; let c2 = ""; if (longFormat && o.c.year >= 0) c2 += "+"; c2 += padStart2(o.c.year, longFormat ? 6 : 4); if (extended) { c2 += "-"; c2 += padStart2(o.c.month); c2 += "-"; c2 += padStart2(o.c.day); } else { c2 += padStart2(o.c.month); c2 += padStart2(o.c.day); } return c2; } function toISOTime(o, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone) { let c2 = padStart2(o.c.hour); if (extended) { c2 += ":"; c2 += padStart2(o.c.minute); if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) { c2 += ":"; } } else { c2 += padStart2(o.c.minute); } if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) { c2 += padStart2(o.c.second); if (o.c.millisecond !== 0 || !suppressMilliseconds) { c2 += "."; c2 += padStart2(o.c.millisecond, 3); } } if (includeOffset) { if (o.isOffsetFixed && o.offset === 0 && !extendedZone) { c2 += "Z"; } else if (o.o < 0) { c2 += "-"; c2 += padStart2(Math.trunc(-o.o / 60)); c2 += ":"; c2 += padStart2(Math.trunc(-o.o % 60)); } else { c2 += "+"; c2 += padStart2(Math.trunc(o.o / 60)); c2 += ":"; c2 += padStart2(Math.trunc(o.o % 60)); } } if (extendedZone) { c2 += "[" + o.zone.ianaName + "]"; } return c2; } 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 u2 of orderedUnits) { if (isUndefined(obj[u2])) { obj[u2] = defaultUnitValues[u2]; } } 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, format2 = (c2, unit) => { c2 = roundTo(c2, round || opts.calendary ? 0 : 2, true); const formatter = end.loc.clone(opts).relFormatter(opts); return formatter.format(c2, 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 format2(differ(opts.unit), opts.unit); } for (const unit of opts.units) { const count = differ(unit); if (Math.abs(count) >= 1) { return format2(count, unit); } } return format2(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 c2 = null, o = null; if (!invalid) { const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); if (unchanged) { [c2, o] = [config.old.c, config.old.o]; } else { const ot = zone.offset(this.ts); c2 = tsToObj(this.ts, ot); invalid = Number.isNaN(c2.year) ? new Invalid("invalid input") : null; c2 = invalid ? null : c2; o = invalid ? null : ot; } } this._zone = zone; this.loc = config.loc || Locale.create(); this.invalid = invalid; this.weekData = null; this.c = c2; 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 = isDate2(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 u2 of units) { const v = normalized[u2]; if (!isUndefined(v)) { foundFirst = true; } else if (foundFirst) { normalized[u2] = defaultValues[u2]; } else { normalized[u2] = objNow[u2]; } } 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(text3, opts = {}) { const [vals, parsedZone] = parseISODate(text3); return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text3); } /** * 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(text3, opts = {}) { const [vals, parsedZone] = parseRFC2822Date(text3); return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text3); } /** * 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(text3, opts = {}) { const [vals, parsedZone] = parseHTTPDate(text3); 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(text3, fmt, opts = {}) { if (isUndefined(text3) || isUndefined(fmt)) { throw new InvalidArgumentError("fromFormat requires an input string and a format"); } const { locale: locale2 = null, numberingSystem = null } = opts, localeToUse = Locale.fromOpts({ locale: locale2, numberingSystem, defaultToEN: true }), [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text3, fmt); if (invalid) { return DateTime.invalid(invalid); } else { return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text3, specificOffset); } } /** * @deprecated use fromFormat instead */ static fromString(text3, fmt, opts = {}) { return DateTime.fromFormat(text3, 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(text3, opts = {}) { const [vals, parsedZone] = parseSQL(text3); return parseDataToDateTime(vals, parsedZone, opts, "SQL", text3); } /** * Create an invalid DateTime. * @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 {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(Formatter.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; } } /** * Get those DateTimes which have the same local time as this DateTime, but a different offset from UTC * in this DateTime's zone. During DST changes local time can be ambiguous, for example * `2023-10-29T02:30:00` in `Europe/Berlin` can have offset `+01:00` or `+02:00`. * This method will return both possible DateTimes if this DateTime's local time is ambiguous. * @returns {DateTime[]} */ getPossibleOffsets() { if (!this.isValid || this.isOffsetFixed) { return [this]; } const dayMs = 864e5; const minuteMs = 6e4; const localTS = objToLocalTS(this.c); const oEarlier = this.zone.offset(localTS - dayMs); const oLater = this.zone.offset(localTS + dayMs); const o1 = this.zone.offset(localTS - oEarlier * minuteMs); const o2 = this.zone.offset(localTS - oLater * minuteMs); if (o1 === o2) { return [this]; } const ts1 = localTS - o1 * minuteMs; const ts2 = localTS - o2 * minuteMs; const c1 = tsToObj(ts1, o1); const c2 = tsToObj(ts2, o2); if (c1.hour === c2.hour && c1.minute === c2.minute && c1.second === c2.second && c1.millisecond === c2.millisecond) { return [clone(this, { ts: ts1 }), clone(this, { ts: ts2 })]; } return [this]; } /** * 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: locale2, numberingSystem, calendar } = Formatter.create( this.loc.clone(opts), opts ).resolvedOptions(this); return { locale: locale2, 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 clone(this, { ts: newTS, zone }); } } /** * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime. * @param {Object} properties - the properties to set * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' }) * @return {DateTime} */ reconfigure({ locale: locale2, numberingSystem, outputCalendar } = {}) { const loc = this.loc.clone({ locale: locale2, numberingSystem, outputCalendar }); return clone(this, { loc }); } /** * "Set" the locale. Returns a newly-constructed DateTime. * Just a convenient alias for reconfigure({ locale }) * @example DateTime.local(2017, 5, 25).setLocale('en-GB') * @return {DateTime} */ setLocale(locale2) { return this.reconfigure({ locale: locale2 }); } /** * "Set" the values of specified units. Returns a newly-constructed DateTime. * You can only set units with this method; for "setting" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}. * @param {Object} values - a mapping of units to numbers * @example dt.set({ year: 2017 }) * @example dt.set({ hour: 8, minute: 30 }) * @example dt.set({ weekday: 5 }) * @example dt.set({ year: 2005, ordinal: 234 }) * @return {DateTime} */ set(values) { if (!this.isValid) return this; const normalized = normalizeObject(values, normalizeUnit), settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber; if ((containsGregor || containsOrdinal) && definiteWeekDef) { throw new ConflictingSpecificationError( "Can't mix weekYear/weekNumber units with year/month/day or ordinals" ); } if (containsGregorMD && containsOrdinal) { throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); } let mixed; if (settingWeekStuff) { mixed = weekToGregorian({ ...gregorianToWeek(this.c), ...normalized }); } else if (!isUndefined(normalized.ordinal)) { mixed = ordinalToGregorian({ ...gregorianToOrdinal(this.c), ...normalized }); } else { mixed = { ...this.toObject(), ...normalized }; if (isUndefined(normalized.day)) { mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day); } } const [ts, o] = objToTS(mixed, this.o, this.zone); return clone(this, { ts, o }); } /** * Add a period of time to this DateTime and return the resulting DateTime * * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between. * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() * @example DateTime.now().plus(123) //~> in 123 milliseconds * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min * @return {DateTime} */ plus(duration) { if (!this.isValid) return this; const dur = Duration.fromDurationLike(duration); return clone(this, adjustTime(this, dur)); } /** * Subtract a period of time to this DateTime and return the resulting DateTime * See {@link DateTime#plus} * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() @return {DateTime} */ minus(duration) { if (!this.isValid) return this; const dur = Duration.fromDurationLike(duration).negate(); return clone(this, adjustTime(this, dur)); } /** * "Set" this DateTime to the beginning of a unit of time. * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'. * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01' * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01' * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00' * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00' * @return {DateTime} */ startOf(unit) { if (!this.isValid) return this; const o = {}, normalizedUnit = Duration.normalizeUnit(unit); switch (normalizedUnit) { case "years": o.month = 1; case "quarters": case "months": o.day = 1; case "weeks": case "days": o.hour = 0; case "hours": o.minute = 0; case "minutes": o.second = 0; case "seconds": o.millisecond = 0; break; } if (normalizedUnit === "weeks") { o.weekday = 1; } if (normalizedUnit === "quarters") { const q2 = Math.ceil(this.month / 3); o.month = (q2 - 1) * 3 + 1; } return this.set(o); } /** * "Set" this DateTime to the end (meaning the last millisecond) of a unit of time * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'. * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00' * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00' * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00' * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00' * @return {DateTime} */ endOf(unit) { return this.isValid ? this.plus({ [unit]: 1 }).startOf(unit).minus(1) : this; } // OUTPUT /** * Returns a string representation of this DateTime formatted according to the specified format string. * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens). * Defaults to en-US if no locale has been specified, regardless of the system's locale. * @param {string} fmt - the format string * @param {Object} opts - opts to override the configuration options on this DateTime * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22' * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22' * @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22' * @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes' * @return {string} */ toFormat(fmt, opts = {}) { return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID2; } /** * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`. * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation * of the DateTime in the assigned locale. * Defaults to the system's locale if no locale has been specified * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options * @param {Object} opts - opts to override the configuration options on this DateTime * @example DateTime.now().toLocaleString(); //=> 4/20/2017 * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017' * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017' * @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022' * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM' * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM' * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20' * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM' * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32' * @return {string} */ toLocaleString(formatOpts = DATE_SHORT, opts = {}) { return this.isValid ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID2; } /** * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output. * Defaults to the system's locale if no locale has been specified * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`. * @example DateTime.now().toLocaleParts(); //=> [ * //=> { type: 'day', value: '25' }, * //=> { type: 'literal', value: '/' }, * //=> { type: 'month', value: '05' }, * //=> { type: 'literal', value: '/' }, * //=> { type: 'year', value: '1982' } * //=> ] */ toLocaleParts(opts = {}) { return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : []; } /** * Returns an ISO 8601-compliant string representation of this DateTime * @param {Object} opts - options * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @param {boolean} [opts.extendedZone=false] - add the time zone format extension * @param {string} [opts.format='extended'] - choose between the basic and extended format * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z' * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00' * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335' * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400' * @return {string} */ toISO({ format: format2 = "extended", suppressSeconds = false, suppressMilliseconds = false, includeOffset = true, extendedZone = false } = {}) { if (!this.isValid) { return null; } const ext = format2 === "extended"; let c2 = toISODate(this, ext); c2 += "T"; c2 += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone); return c2; } /** * Returns an ISO 8601-compliant string representation of this DateTime's date component * @param {Object} opts - options * @param {string} [opts.format='extended'] - choose between the basic and extended format * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25' * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525' * @return {string} */ toISODate({ format: format2 = "extended" } = {}) { if (!this.isValid) { return null; } return toISODate(this, format2 === "extended"); } /** * Returns an ISO 8601-compliant string representation of this DateTime's week date * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2' * @return {string} */ toISOWeekDate() { return toTechFormat(this, "kkkk-'W'WW-c"); } /** * Returns an ISO 8601-compliant string representation of this DateTime's time component * @param {Object} opts - options * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @param {boolean} [opts.extendedZone=true] - add the time zone format extension * @param {boolean} [opts.includePrefix=false] - include the `T` prefix * @param {string} [opts.format='extended'] - choose between the basic and extended format * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z' * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z' * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z' * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z' * @return {string} */ toISOTime({ suppressMilliseconds = false, suppressSeconds = false, includeOffset = true, includePrefix = false, extendedZone = false, format: format2 = "extended" } = {}) { if (!this.isValid) { return null; } let c2 = includePrefix ? "T" : ""; return c2 + toISOTime( this, format2 === "extended", suppressSeconds, suppressMilliseconds, includeOffset, extendedZone ); } /** * Returns an RFC 2822-compatible string representation of this DateTime * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000' * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400' * @return {string} */ toRFC2822() { return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false); } /** * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT. * Specifically, the string conforms to RFC 1123. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT' * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT' * @return {string} */ toHTTP() { return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'"); } /** * Returns a string representation of this DateTime appropriate for use in SQL Date * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13' * @return {string} */ toSQLDate() { if (!this.isValid) { return null; } return toISODate(this, true); } /** * Returns a string representation of this DateTime appropriate for use in SQL Time * @param {Object} opts - options * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00' * @example DateTime.utc().toSQL() //=> '05:15:16.345' * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00' * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345' * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York' * @return {string} */ toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) { let fmt = "HH:mm:ss.SSS"; if (includeZone || includeOffset) { if (includeOffsetSpace) { fmt += " "; } if (includeZone) { fmt += "z"; } else if (includeOffset) { fmt += "ZZ"; } } return toTechFormat(this, fmt, true); } /** * Returns a string representation of this DateTime appropriate for use in SQL DateTime * @param {Object} opts - options * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00' * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z' * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00' * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000' * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York' * @return {string} */ toSQL(opts = {}) { if (!this.isValid) { return null; } return `${this.toSQLDate()} ${this.toSQLTime(opts)}`; } /** * Returns a string representation of this DateTime appropriate for debugging * @return {string} */ toString() { return this.isValid ? this.toISO() : INVALID2; } /** * 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, (i2) => i2.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, (i2) => i2.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(text3, fmt, options = {}) { const { locale: locale2 = null, numberingSystem = null } = options, localeToUse = Locale.fromOpts({ locale: locale2, numberingSystem, defaultToEN: true }); return explainFromTokens(localeToUse, text3, fmt); } /** * @deprecated use fromFormatExplain instead */ static fromStringExplain(text3, fmt, options = {}) { return DateTime.fromFormatExplain(text3, 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(error) { this.error = error; 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(error) { return new Failure(error); } 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, (a3, b2) => success(f(a3, b2))); } 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: {} }; 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(e2) { if (t2[e2]) return t2[e2].exports; var u2 = t2[e2] = { i: e2, l: false, exports: {} }; return n2[e2].call(u2.exports, u2, u2.exports, r), u2.l = true, u2.exports; } return r.m = n2, r.c = t2, r.d = function(n3, t3, e2) { r.o(n3, t3) || Object.defineProperty(n3, t3, { configurable: false, enumerable: true, get: e2 }); }, 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 e2(n3) { if (!(this instanceof e2)) return new e2(n3); this._ = n3; } var u2 = e2.prototype; function o(n3, t3) { for (var r2 = 0; r2 < n3; r2++) t3(r2); } function i2(n3, t3, r2) { return function(n4, t4) { o(t4.length, function(r3) { n4(t4[r3], r3, t4); }); }(function(r3, e3, u3) { t3 = n3(t3, r3, e3, u3); }, r2), t3; } function a3(n3, t3) { return i2(function(t4, r2, e3, u3) { return t4.concat([n3(r2, e3, u3)]); }, [], 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 = i2(function(n6, t5, r3, e3) { return n6.concat(r3 === e3.length - 1 ? Buffer.from([t5, 0]).readUInt16BE(0) : e3.readUInt16BE(r3)); }, [], n5); return Buffer.from(a3(function(n6) { return (n6 << 1 & 65535) >> 8; }, t4)); }(r2.buf) }; }), r2; } function c2() { return "undefined" != typeof Buffer; } function s4() { if (!c2()) throw new Error("Buffer global does not exist; please use webpack if you need to parse Buffers in the browser."); } function l2(n3) { s4(); var t3 = i2(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, u3 = t3 / 8, o2 = (r2 = function(n4) { return n4 > 48; }, i2(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 e2(function(t4, r3) { var e3 = u3 + r3; return e3 > t4.length ? x2(r3, u3.toString() + " bytes") : b2(e3, i2(function(n4, t5) { var r4 = f(t5, n4.buf); return { coll: n4.coll.concat(r4.v), buf: r4.buf }; }, { coll: [], buf: t4.slice(r3, e3) }, n3).coll); }); } function h3(n3, t3) { return new e2(function(r2, e3) { return s4(), e3 + t3 > r2.length ? x2(e3, t3 + " bytes for " + n3) : b2(e3 + t3, r2.slice(e3, e3 + 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 d3(n3) { return p("uintBE", n3), h3("uintBE(" + n3 + ")", n3).map(function(t3) { return t3.readUIntBE(0, n3); }); } function v(n3) { return p("uintLE", n3), h3("uintLE(" + n3 + ")", n3).map(function(t3) { return t3.readUIntLE(0, n3); }); } function g(n3) { return p("intBE", n3), h3("intBE(" + n3 + ")", n3).map(function(t3) { return t3.readIntBE(0, n3); }); } function m3(n3) { return p("intLE", n3), h3("intLE(" + n3 + ")", n3).map(function(t3) { return t3.readIntLE(0, n3); }); } function y3(n3) { return n3 instanceof e2; } function E2(n3) { return "[object Array]" === {}.toString.call(n3); } function w2(n3) { return c2() && Buffer.isBuffer(n3); } function b2(n3, t3) { return { status: true, index: n3, value: t3, furthest: -1, expected: [] }; } function x2(n3, t3) { return E2(t3) || (t3 = [t3]), { status: false, index: -1, value: null, furthest: n3, expected: t3 }; } function B2(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 !== e2._supportsSet) return e2._supportsSet; var n5 = "undefined" != typeof Set; return e2._supportsSet = n5, n5; }() && Array.from) { for (var r3 = new Set(n4), u3 = 0; u3 < t4.length; u3++) r3.add(t4[u3]); var o2 = Array.from(r3); return o2.sort(), o2; } for (var i3 = {}, a4 = 0; a4 < n4.length; a4++) i3[n4[a4]] = true; for (var f2 = 0; f2 < t4.length; f2++) i3[t4[f2]] = true; var c3 = []; for (var s5 in i3) ({}).hasOwnProperty.call(i3, s5) && c3.push(s5); return c3.sort(), c3; }(n3.expected, t3.expected) : t3.expected; return { status: n3.status, index: n3.index, value: n3.value, furthest: t3.furthest, expected: r2 }; } var j = {}; function S3(n3, t3) { if (w2(n3)) return { offset: t3, line: -1, column: -1 }; n3 in j || (j[n3] = {}); for (var r2 = j[n3], e3 = 0, u3 = 0, o2 = 0, i3 = t3; i3 >= 0; ) { if (i3 in r2) { e3 = r2[i3].line, 0 === o2 && (o2 = r2[i3].lineStart); break; } ("\n" === n3.charAt(i3) || "\r" === n3.charAt(i3) && "\n" !== n3.charAt(i3 + 1)) && (u3++, 0 === o2 && (o2 = i3 + 1)), i3--; } var a4 = e3 + u3, f2 = t3 - o2; return r2[t3] = { line: a4, lineStart: o2 }, { offset: t3, line: a4 + 1, column: f2 + 1 }; } function _(n3) { if (!y3(n3)) throw new Error("not a parser: " + n3); } function L2(n3, t3) { return "string" == typeof n3 ? n3.charAt(t3) : n3[t3]; } function O2(n3) { if ("number" != typeof n3) throw new Error("not a number: " + n3); } function k2(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 q2 = 2, A = 3, I2 = 8, F = 5 * I2, M3 = 4 * I2, z3 = " "; function R2(n3, t3) { return new Array(t3 + 1).join(n3); } function U(n3, t3, r2) { var e3 = t3 - n3.length; return e3 <= 0 ? n3 : R2(r2, e3) + n3; } function W(n3, t3, r2, e3) { return { from: n3 - t3 > 0 ? n3 - t3 : 0, to: n3 + r2 > e3 ? e3 : n3 + r2 }; } function D2(n3, t3) { var r2, e3, u3, o2, f2, c3 = t3.index, s5 = c3.offset, l3 = 1; if (s5 === n3.length) return "Got the end of the input"; if (w2(n3)) { var h4 = s5 - s5 % I2, p2 = s5 - h4, d4 = W(h4, F, M3 + I2, n3.length), v2 = a3(function(n4) { return a3(function(n5) { return U(n5.toString(16), 2, "0"); }, n4); }, function(n4, t4) { var r3 = n4.length, e4 = [], u4 = 0; if (r3 <= t4) return [n4.slice()]; for (var o3 = 0; o3 < r3; o3++) e4[u4] || e4.push([]), e4[u4].push(n4[o3]), (o3 + 1) % t4 == 0 && u4++; return e4; }(n3.slice(d4.from, d4.to).toJSON().data, I2)); o2 = function(n4) { return 0 === n4.from && 1 === n4.to ? { from: n4.from, to: n4.to } : { from: n4.from / I2, to: Math.floor(n4.to / I2) }; }(d4), e3 = h4 / I2, r2 = 3 * p2, p2 >= 4 && (r2 += 1), l3 = 2, u3 = a3(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 = c3.column - 1, e3 = c3.line - 1, o2 = W(e3, q2, A, g2.length), u3 = g2.slice(o2.from, o2.to), f2 = o2.to.toString().length; } var m4 = e3 - o2.from; return w2(n3) && (f2 = (8 * (o2.to > 0 ? o2.to - 1 : o2.to)).toString(16).length) < 2 && (f2 = 2), i2(function(t4, e4, u4) { var i3, a4 = u4 === m4, c4 = a4 ? "> " : z3; return i3 = w2(n3) ? U((8 * (o2.from + u4)).toString(16), f2, "0") : U((o2.from + u4 + 1).toString(), f2, " "), [].concat(t4, [c4 + i3 + " | " + e4], a4 ? [z3 + R2(" ", f2) + " | " + U("", r2, " ") + R2("^", l3)] : []); }, [], u3).join("\n"); } function N(n3, t3) { return ["\n", "-- PARSING FAILED " + R2("-", 50), "\n\n", D2(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 G2(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) _(n3[r2]); return e2(function(r3, e3) { for (var u3, o2 = new Array(t3), i3 = 0; i3 < t3; i3 += 1) { if (!(u3 = B2(n3[i3]._(r3, e3), u3)).status) return u3; o2[i3] = u3.value, e3 = u3.index; } return B2(b2(e3, o2), u3); }); } 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 k2(t3), C.apply(null, n3).map(function(n4) { return t3.apply(null, n4); }); } function T2() { var n3 = [].slice.call(arguments), t3 = n3.length; if (0 === t3) return Y2("zero alternates"); for (var r2 = 0; r2 < t3; r2 += 1) _(n3[r2]); return e2(function(t4, r3) { for (var e3, u3 = 0; u3 < n3.length; u3 += 1) if ((e3 = B2(n3[u3]._(t4, r3), e3)).status) return e3; return e3; }); } function V(n3, t3) { return H3(n3, t3).or(X2([])); } function H3(n3, t3) { return _(n3), _(t3), J(n3, t3.then(n3).many(), function(n4, t4) { return [n4].concat(t4); }); } function K2(n3) { P(n3); var t3 = "'" + n3 + "'"; return e2(function(r2, e3) { var u3 = e3 + n3.length, o2 = r2.slice(e3, u3); return o2 === n3 ? b2(u3, o2) : x2(e3, t3); }); } function Q2(n3, t3) { !function(n4) { if (!(n4 instanceof RegExp)) throw new Error("not a regexp: " + n4); for (var t4 = G2(n4), r3 = 0; r3 < t4.length; r3++) { var e3 = t4.charAt(r3); if ("i" !== e3 && "m" !== e3 && "u" !== e3 && "s" !== e3) throw new Error('unsupported regexp flag "' + e3 + '": ' + n4); } }(n3), arguments.length >= 2 ? O2(t3) : t3 = 0; var r2 = function(n4) { return RegExp("^(?:" + n4.source + ")", G2(n4)); }(n3), u3 = "" + n3; return e2(function(n4, e3) { var o2 = r2.exec(n4.slice(e3)); if (o2) { if (0 <= t3 && t3 <= o2.length) { var i3 = o2[0], a4 = o2[t3]; return b2(e3 + i3.length, a4); } return x2(e3, "valid match group (0 to " + o2.length + ") in " + u3); } return x2(e3, u3); }); } function X2(n3) { return e2(function(t3, r2) { return b2(r2, n3); }); } function Y2(n3) { return e2(function(t3, r2) { return x2(r2, n3); }); } function Z(n3) { if (y3(n3)) return e2(function(t3, r2) { var e3 = n3._(t3, r2); return e3.index = r2, e3.value = "", e3; }); if ("string" == typeof n3) return Z(K2(n3)); if (n3 instanceof RegExp) return Z(Q2(n3)); throw new Error("not a string, regexp, or parser: " + n3); } function $(n3) { return _(n3), e2(function(t3, r2) { var e3 = n3._(t3, r2), u3 = t3.slice(r2, e3.index); return e3.status ? x2(r2, 'not "' + u3 + '"') : b2(r2, null); }); } function nn(n3) { return k2(n3), e2(function(t3, r2) { var e3 = L2(t3, r2); return r2 < t3.length && n3(e3) ? b2(r2 + 1, e3) : x2(r2, "a character/byte matching " + n3); }); } function tn(n3, t3) { arguments.length < 2 && (t3 = n3, n3 = void 0); var r2 = e2(function(n4, e3) { return r2._ = t3()._, r2._(n4, e3); }); return n3 ? r2.desc(n3) : r2; } function rn() { return Y2("fantasy-land/empty"); } u2.parse = function(n3) { if ("string" != typeof n3 && !w2(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: S3(n3, r2.furthest), expected: r2.expected }, delete j[n3], t3; }, u2.tryParse = function(n3) { var t3 = this.parse(n3); if (t3.status) return t3.value; var r2 = N(n3, t3), e3 = new Error(r2); throw e3.type = "ParsimmonError", e3.result = t3, e3; }, u2.assert = function(n3, t3) { return this.chain(function(r2) { return n3(r2) ? X2(r2) : Y2(t3); }); }, u2.or = function(n3) { return T2(this, n3); }, u2.trim = function(n3) { return this.wrap(n3, n3); }, u2.wrap = function(n3, t3) { return J(n3, this, t3, function(n4, t4) { return t4; }); }, u2.thru = function(n3) { return n3(this); }, u2.then = function(n3) { return _(n3), C(this, n3).map(function(n4) { return n4[1]; }); }, u2.many = function() { var n3 = this; return e2(function(t3, r2) { for (var e3 = [], u3 = void 0; ; ) { if (!(u3 = B2(n3._(t3, r2), u3)).status) return B2(b2(r2, e3), u3); if (r2 === u3.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 = u3.index, e3.push(u3.value); } }); }, u2.tieWith = function(n3) { return P(n3), this.map(function(t3) { if (function(n4) { if (!E2(n4)) throw new Error("not an array: " + n4); }(t3), t3.length) { P(t3[0]); for (var r2 = t3[0], e3 = 1; e3 < t3.length; e3++) P(t3[e3]), r2 += n3 + t3[e3]; return r2; } return ""; }); }, u2.tie = function() { return this.tieWith(""); }, u2.times = function(n3, t3) { var r2 = this; return arguments.length < 2 && (t3 = n3), O2(n3), O2(t3), e2(function(e3, u3) { for (var o2 = [], i3 = void 0, a4 = void 0, f2 = 0; f2 < n3; f2 += 1) { if (a4 = B2(i3 = r2._(e3, u3), a4), !i3.status) return a4; u3 = i3.index, o2.push(i3.value); } for (; f2 < t3 && (a4 = B2(i3 = r2._(e3, u3), a4), i3.status); f2 += 1) u3 = i3.index, o2.push(i3.value); return B2(b2(u3, o2), a4); }); }, u2.result = function(n3) { return this.map(function() { return n3; }); }, u2.atMost = function(n3) { return this.times(0, n3); }, u2.atLeast = function(n3) { return J(this.times(n3), this.many(), function(n4, t3) { return n4.concat(t3); }); }, u2.map = function(n3) { k2(n3); var t3 = this; return e2(function(r2, e3) { var u3 = t3._(r2, e3); return u3.status ? B2(b2(u3.index, n3(u3.value)), u3) : u3; }); }, u2.contramap = function(n3) { k2(n3); var t3 = this; return e2(function(r2, e3) { var u3 = t3.parse(n3(r2.slice(e3))); return u3.status ? b2(e3 + r2.length, u3.value) : u3; }); }, u2.promap = function(n3, t3) { return k2(n3), k2(t3), this.contramap(n3).map(t3); }, u2.skip = function(n3) { return C(this, n3).map(function(n4) { return n4[0]; }); }, u2.mark = function() { return J(en, this, en, function(n3, t3, r2) { return { start: n3, value: t3, end: r2 }; }); }, u2.node = function(n3) { return J(en, this, en, function(t3, r2, e3) { return { name: n3, value: r2, start: t3, end: e3 }; }); }, u2.sepBy = function(n3) { return V(this, n3); }, u2.sepBy1 = function(n3) { return H3(this, n3); }, u2.lookahead = function(n3) { return this.skip(Z(n3)); }, u2.notFollowedBy = function(n3) { return this.skip($(n3)); }, u2.desc = function(n3) { E2(n3) || (n3 = [n3]); var t3 = this; return e2(function(r2, e3) { var u3 = t3._(r2, e3); return u3.status || (u3.expected = n3), u3; }); }, u2.fallback = function(n3) { return this.or(X2(n3)); }, u2.ap = function(n3) { return J(n3, this, function(n4, t3) { return n4(t3); }); }, u2.chain = function(n3) { var t3 = this; return e2(function(r2, e3) { var u3 = t3._(r2, e3); return u3.status ? B2(n3(u3.value)._(r2, u3.index), u3) : u3; }); }, u2.concat = u2.or, u2.empty = rn, u2.of = X2, u2["fantasy-land/ap"] = u2.ap, u2["fantasy-land/chain"] = u2.chain, u2["fantasy-land/concat"] = u2.concat, u2["fantasy-land/empty"] = u2.empty, u2["fantasy-land/of"] = u2.of, u2["fantasy-land/map"] = u2.map; var en = e2(function(n3, t3) { return b2(t3, S3(n3, t3)); }), un = e2(function(n3, t3) { return t3 >= n3.length ? x2(t3, "any character/byte") : b2(t3 + 1, L2(n3, t3)); }), on = e2(function(n3, t3) { return b2(n3.length, n3.slice(t3)); }), an = e2(function(n3, t3) { return t3 < n3.length ? x2(t3, "EOF") : b2(t3, null); }), fn = Q2(/[0-9]/).desc("a digit"), cn = Q2(/[0-9]*/).desc("optional digits"), sn = Q2(/[a-z]/i).desc("a letter"), ln = Q2(/[a-z]*/i).desc("optional letters"), hn = Q2(/\s*/).desc("optional whitespace"), pn = Q2(/\s+/).desc("whitespace"), dn = K2("\r"), vn = K2("\n"), gn = K2("\r\n"), mn = T2(gn, vn, dn).desc("newline"), yn = T2(mn, an); e2.all = on, e2.alt = T2, e2.any = un, e2.cr = dn, e2.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; }, e2.crlf = gn, e2.custom = function(n3) { return e2(n3(b2, x2)); }, e2.digit = fn, e2.digits = cn, e2.empty = rn, e2.end = yn, e2.eof = an, e2.fail = Y2, e2.formatError = N, e2.index = en, e2.isParser = y3, e2.lazy = tn, e2.letter = sn, e2.letters = ln, e2.lf = vn, e2.lookahead = Z, e2.makeFailure = x2, e2.makeSuccess = b2, e2.newline = mn, e2.noneOf = function(n3) { return nn(function(t3) { return n3.indexOf(t3) < 0; }).desc("none of '" + n3 + "'"); }, e2.notFollowedBy = $, e2.of = X2, e2.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); }, e2.optWhitespace = hn, e2.Parser = e2, e2.range = function(n3, t3) { return nn(function(r2) { return n3 <= r2 && r2 <= t3; }).desc(n3 + "-" + t3); }, e2.regex = Q2, e2.regexp = Q2, e2.sepBy = V, e2.sepBy1 = H3, e2.seq = C, e2.seqMap = J, e2.seqObj = function() { for (var n3, t3 = {}, r2 = 0, u3 = (n3 = arguments, Array.prototype.slice.call(n3)), o2 = u3.length, i3 = 0; i3 < o2; i3 += 1) { var a4 = u3[i3]; if (!y3(a4)) { if (E2(a4) && 2 === a4.length && "string" == typeof a4[0] && y3(a4[1])) { var f2 = a4[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 e2(function(n4, t4) { for (var r3, e3 = {}, i4 = 0; i4 < o2; i4 += 1) { var a5, f3; if (E2(u3[i4]) ? (a5 = u3[i4][0], f3 = u3[i4][1]) : (a5 = null, f3 = u3[i4]), !(r3 = B2(f3._(n4, t4), r3)).status) return r3; a5 && (e3[a5] = r3.value), t4 = r3.index; } return B2(b2(t4, e3), r3); }); }, e2.string = K2, e2.succeed = X2, e2.takeWhile = function(n3) { return k2(n3), e2(function(t3, r2) { for (var e3 = r2; e3 < t3.length && n3(L2(t3, e3)); ) e3++; return b2(e3, t3.slice(r2, e3)); }); }, e2.test = nn, e2.whitespace = pn, e2["fantasy-land/empty"] = rn, e2["fantasy-land/of"] = X2, e2.Binary = { bitSeq: l2, bitSeqObj: function(n3) { s4(); var t3 = {}, r2 = 0, e3 = a3(function(n4) { if (E2(n4)) { var e4 = n4; if (2 !== e4.length) throw new Error("[" + e4.join(", ") + "] should be length 2, got length " + e4.length); if (P(e4[0]), O2(e4[1]), Object.prototype.hasOwnProperty.call(t3, e4[0])) throw new Error("duplicate key in bitSeqObj: " + e4[0]); return t3[e4[0]] = true, r2++, e4; } return O2(n4), [null, n4]; }, n3); if (r2 < 1) throw new Error("bitSeqObj expects at least one named pair, got [" + n3.join(", ") + "]"); var u3 = a3(function(n4) { return n4[0]; }, e3); return l2(a3(function(n4) { return n4[1]; }, e3)).map(function(n4) { return i2(function(n5, t4) { return null !== t4[0] && (n5[t4[0]] = t4[1]), n5; }, {}, a3(function(t4, r3) { return [t4, n4[r3]]; }, u3)); }); }, byte: function(n3) { if (s4(), O2(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 e2(function(r2, e3) { var u3 = L2(r2, e3); return u3 === n3 ? b2(e3 + 1, u3) : x2(e3, t3); }); }, buffer: function(n3) { return h3("buffer", n3).map(function(n4) { return Buffer.from(n4); }); }, encodedString: function(n3, t3) { return h3("string", t3).map(function(t4) { return t4.toString(n3); }); }, uintBE: d3, uint8BE: d3(1), uint16BE: d3(2), uint32BE: d3(4), uintLE: v, uint8LE: v(1), uint16LE: v(2), uint32LE: v(4), intBE: g, int8BE: g(1), int16BE: g(2), int32BE: g(4), intLE: m3, int8LE: m3(1), int16LE: m3(2), int32LE: m3(4), floatBE: h3("floatBE", 4).map(function(n3) { return n3.readFloatBE(0); }), floatLE: h3("floatLE", 4).map(function(n3) { return n3.readFloatLE(0); }), doubleBE: h3("doubleBE", 8).map(function(n3) { return n3.readDoubleBE(0); }), doubleLE: h3("doubleLE", 8).map(function(n3) { return n3.readDoubleLE(0); }) }, n2.exports = e2; }]); }); })(parsimmon_umd_min, parsimmon_umd_min.exports); var parsimmon_umd_minExports = parsimmon_umd_min.exports; var emojiRegex2 = () => { 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(?:[\uDC08\uDC26](?:\u200D\u2B1B)?|[\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-\uDC25\uDC27-\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\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\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-\uDEF8](?:\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-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC2\uDECE-\uDEDB\uDEE0-\uDEE8]|\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_minExports.alt(parsimmon_umd_minExports.regex(new RegExp(emojiRegex2(), "")), parsimmon_umd_minExports.regex(/[0-9\p{Letter}_-]+/u).map((str2) => str2.toLocaleLowerCase()), parsimmon_umd_minExports.whitespace.map((_) => "-"), parsimmon_umd_minExports.any.map((_) => "")).many().map((result) => result.join("")); var HEADER_CANONICALIZER = parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regex(new RegExp(emojiRegex2(), "")), parsimmon_umd_minExports.regex(/[0-9\p{Letter}_-]+/u), parsimmon_umd_minExports.whitespace.map((_) => " "), parsimmon_umd_minExports.any.map((_) => " ")).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 toString3(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 ""; case "array": let result = ""; if (recursive) result += "["; result += wrapped.value.map((f) => toString3(f, setting, true)).join(", "); if (recursive) result += "]"; return result; case "object": return "{ " + Object.entries(wrapped.value).map((e2) => e2[0] + ": " + toString3(e2[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 = toString3; function wrapValue(val) { if (isNull2(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 (isBoolean2(val)) return { type: "boolean", value: val }; else if (isDuration(val)) return { type: "duration", value: val }; else if (isDate3(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 : (x2) => x2; 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 index2 = 0; index2 < Math.min(f1.length, f2.length); index2++) { let comp = compareValue(f1[index2], f2[index2]); 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 isDate3(val) { return val instanceof DateTime; } Values2.isDate = isDate3; function isDuration(val) { return val instanceof Duration; } Values2.isDuration = isDuration; function isNull2(val) { return val === null || val === void 0; } Values2.isNull = isNull2; function isArray(val) { return Array.isArray(val); } Values2.isArray = isArray; function isBoolean2(val) { return typeof val === "boolean"; } Values2.isBoolean = isBoolean2; function isLink(val) { return val instanceof Link; } 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) && !isDate3(val) && !isLink(val) && val !== void 0 && !isNull2(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 element2 of entry) if (!isElementGroup(element2)) 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 Link = class { /** Create a link to a specific file. */ static file(path, embed = false, display) { return new Link({ path, embed, display, subpath: void 0, type: "file" }); } static infer(linkpath, embed = false, display) { if (linkpath.includes("#^")) { let split = linkpath.split("#^"); return Link.block(split[0], split[1], embed, display); } else if (linkpath.includes("#")) { let split = linkpath.split("#"); return Link.header(split[0], split[1], embed, display); } else return Link.file(linkpath, embed, display); } /** Create a link to a specific file and header in that file. */ static header(path, header, embed, display) { return new Link({ 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 Link({ path, embed, display, subpath: blockId, type: "block" }); } static fromObject(object) { return new Link(object); } constructor(fields) { Object.assign(this, fields); } /** 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 Link(Object.assign({}, this, { path })); } /** Return a new link which points to the same location but with a new display value. */ withDisplay(display) { return new Link(Object.assign({}, this, { display })); } /** Convert a file link into a link to a specific header. */ withHeader(header) { return Link.header(this.path, header, this.embed, this.display); } /** Convert any link into a link to its file. */ toFile() { return Link.file(this.path, this.embed, this.display); } /** Convert this link into an embedded link. */ toEmbed() { if (this.embed) { return this; } else { let link = new Link(this); link.embed = true; return link; } } /** Convert this link into a non-embedded link. */ fromEmbed() { if (!this.embed) { return this; } else { let link = new Link(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 index2(obj, index3) { return { type: "index", object: obj, index: index3 }; } Fields2.index = index2; function indexVariable(name) { let parts = name.split("."); let result = Fields2.variable(parts[0]); for (let index3 = 1; index3 < parts.length; index3++) { result = Fields2.index(result, Fields2.literal(parts[index3])); } 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 list2(values) { return { type: "list", values }; } Fields2.list = list2; 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(emojiRegex2(), ""); 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 Link.infer(link, false, display); } function createBinaryParser(child, sep, combine) { return parsimmon_umd_minExports.seqMap(child, parsimmon_umd_minExports.seq(parsimmon_umd_minExports.optWhitespace, sep, parsimmon_umd_minExports.optWhitespace, child).many(), (first, rest) => { if (rest.length == 0) return first; let node2 = combine(first, rest[0][1], rest[0][3]); for (let index2 = 1; index2 < rest.length; index2++) { node2 = combine(node2, rest[index2][1], rest[index2][3]); } return node2; }); } function chainOpt(base, ...funcs) { return parsimmon_umd_minExports.custom((success, failure) => { return (input, i2) => { let result = base._(input, i2); 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_minExports.createLanguage({ // A floating point number; the decimal point is optional. number: (q2) => parsimmon_umd_minExports.regexp(/-?[0-9]+(\.[0-9]+)?/).map((str2) => Number.parseFloat(str2)).desc("number"), // A quote-surrounded string which supports escape characters ('\'). string: (q2) => parsimmon_umd_minExports.string('"').then(parsimmon_umd_minExports.alt(q2.escapeCharacter, parsimmon_umd_minExports.noneOf('"\\')).atLeast(0).map((chars) => chars.join(""))).skip(parsimmon_umd_minExports.string('"')).desc("string"), escapeCharacter: (_) => parsimmon_umd_minExports.string("\\").then(parsimmon_umd_minExports.any).map((escaped) => { if (escaped === '"') return '"'; if (escaped === "\\") return "\\"; else return "\\" + escaped; }), // A boolean true/false value. bool: (_) => parsimmon_umd_minExports.regexp(/true|false|True|False/).map((str2) => str2.toLowerCase() == "true").desc("boolean ('true' or 'false')"), // A tag of the form '#stuff/hello-there'. tag: (_) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("#"), parsimmon_umd_minExports.alt(parsimmon_umd_minExports.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: (_) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regexp(/\p{Letter}/u), parsimmon_umd_minExports.regexp(EMOJI_REGEX).desc("text")), parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regexp(/[0-9\p{Letter}_-]/u), parsimmon_umd_minExports.regexp(EMOJI_REGEX).desc("text")).many(), (first, rest) => first + rest.join("")).desc("variable identifier"), // An Obsidian link of the form [[]]. link: (_) => parsimmon_umd_minExports.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: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("!").atMost(1), q2.link, (p, l2) => { if (p.length > 0) l2.embed = true; return l2; }).desc("file link"), // Binary plus or minus operator. binaryPlusMinus: (_) => parsimmon_umd_minExports.regexp(/\+|-/).map((str2) => str2).desc("'+' or '-'"), // Binary times or divide operator. binaryMulDiv: (_) => parsimmon_umd_minExports.regexp(/\*|\/|%/).map((str2) => str2).desc("'*' or '/' or '%'"), // Binary comparison operator. binaryCompareOp: (_) => parsimmon_umd_minExports.regexp(/>=|<=|!=|>|<|=/).map((str2) => str2).desc("'>=' or '<=' or '!=' or '=' or '>' or '<'"), // Binary boolean combination operator. binaryBooleanOp: (_) => parsimmon_umd_minExports.regexp(/and|or|&|\|/i).map((str2) => { if (str2.toLowerCase() == "and") return "&"; else if (str2.toLowerCase() == "or") return "|"; else return str2; }).desc("'and' or 'or'"), // A date which can be YYYY-MM[-DDTHH:mm:ss]. rootDate: (_) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/\d{4}/), parsimmon_umd_minExports.string("-"), parsimmon_umd_minExports.regexp(/\d{2}/), (year, _2, month) => { return DateTime.fromObject({ year: Number.parseInt(year), month: Number.parseInt(month) }); }).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS]"), dateShorthand: (_) => parsimmon_umd_minExports.alt(...Object.keys(DATE_SHORTHANDS).sort((a3, b2) => b2.length - a3.length).map(parsimmon_umd_minExports.string)), date: (q2) => chainOpt(q2.rootDate, (ym) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("-"), parsimmon_umd_minExports.regexp(/\d{2}/), (_, day) => ym.set({ day: Number.parseInt(day) })), (ymd) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("T"), parsimmon_umd_minExports.regexp(/\d{2}/), (_, hour) => ymd.set({ hour: Number.parseInt(hour) })), (ymdh) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string(":"), parsimmon_umd_minExports.regexp(/\d{2}/), (_, minute) => ymdh.set({ minute: Number.parseInt(minute) })), (ymdhm) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string(":"), parsimmon_umd_minExports.regexp(/\d{2}/), (_, second) => ymdhm.set({ second: Number.parseInt(second) })), (ymdhms) => parsimmon_umd_minExports.alt( parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("."), parsimmon_umd_minExports.regexp(/\d{3}/), (_, millisecond) => ymdhms.set({ millisecond: Number.parseInt(millisecond) })), parsimmon_umd_minExports.succeed(ymdhms) // pass ), (dt) => parsimmon_umd_minExports.alt(parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("+").or(parsimmon_umd_minExports.string("-")), parsimmon_umd_minExports.regexp(/\d{1,2}(:\d{2})?/), (pm, hr) => dt.setZone("UTC" + pm + hr, { keepLocalTime: true })), parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("Z"), () => dt.setZone("utc", { keepLocalTime: true })), parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("["), parsimmon_umd_minExports.regexp(/[0-9A-Za-z+-\/]+/u), parsimmon_umd_minExports.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: (q2) => parsimmon_umd_minExports.alt(q2.dateShorthand.map((d3) => DATE_SHORTHANDS[d3]()), q2.date).desc("date in format YYYY-MM[-DDTHH-MM-SS.MS] or in shorthand"), // A duration of time. durationType: (_) => parsimmon_umd_minExports.alt(...Object.keys(DURATION_TYPES).sort((a3, b2) => b2.length - a3.length).map(parsimmon_umd_minExports.string)), duration: (q2) => parsimmon_umd_minExports.seqMap(q2.number, parsimmon_umd_minExports.optWhitespace, q2.durationType, (count, _, t2) => DURATION_TYPES[t2].mapUnits((x2) => x2 * count)).sepBy1(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace).or(parsimmon_umd_minExports.optWhitespace)).map((durations) => durations.reduce((p, c2) => p.plus(c2))).desc("duration like 4hr2min"), // A raw null value. rawNull: (_) => parsimmon_umd_minExports.string("null"), // Source parsing. tagSource: (q2) => q2.tag.map((tag) => Sources.tag(tag)), csvSource: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("csv(").skip(parsimmon_umd_minExports.optWhitespace), q2.string, parsimmon_umd_minExports.string(")"), (_1, path, _2) => Sources.csv(path)), linkIncomingSource: (q2) => q2.link.map((link) => Sources.link(link.path, true)), linkOutgoingSource: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("outgoing(").skip(parsimmon_umd_minExports.optWhitespace), q2.link, parsimmon_umd_minExports.string(")"), (_1, link, _2) => Sources.link(link.path, false)), folderSource: (q2) => q2.string.map((str2) => Sources.folder(str2)), parensSource: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("("), parsimmon_umd_minExports.optWhitespace, q2.source, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (_1, _2, field, _3, _4) => field), negateSource: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.alt(parsimmon_umd_minExports.string("-"), parsimmon_umd_minExports.string("!")), q2.atomSource, (_, source) => Sources.negate(source)), atomSource: (q2) => parsimmon_umd_minExports.alt(q2.parensSource, q2.negateSource, q2.linkOutgoingSource, q2.linkIncomingSource, q2.folderSource, q2.tagSource, q2.csvSource), binaryOpSource: (q2) => createBinaryParser(q2.atomSource, q2.binaryBooleanOp.map((s4) => s4), Sources.binaryOp), source: (q2) => q2.binaryOpSource, // Field parsing. variableField: (q2) => q2.identifier.chain((r) => { if (KEYWORDS.includes(r.toUpperCase())) { return parsimmon_umd_minExports.fail("Variable fields cannot be a keyword (" + KEYWORDS.join(" or ") + ")"); } else { return parsimmon_umd_minExports.succeed(Fields.variable(r)); } }).desc("variable"), numberField: (q2) => q2.number.map((val) => Fields.literal(val)).desc("number"), stringField: (q2) => q2.string.map((val) => Fields.literal(val)).desc("string"), boolField: (q2) => q2.bool.map((val) => Fields.literal(val)).desc("boolean"), dateField: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("date("), parsimmon_umd_minExports.optWhitespace, q2.datePlus, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (prefix, _1, date, _2, postfix) => Fields.literal(date)).desc("date"), durationField: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("dur("), parsimmon_umd_minExports.optWhitespace, q2.duration, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (prefix, _1, dur, _2, postfix) => Fields.literal(dur)).desc("duration"), nullField: (q2) => q2.rawNull.map((_) => Fields.NULL), linkField: (q2) => q2.link.map((f) => Fields.literal(f)), listField: (q2) => q2.field.sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)).wrap(parsimmon_umd_minExports.string("[").skip(parsimmon_umd_minExports.optWhitespace), parsimmon_umd_minExports.optWhitespace.then(parsimmon_umd_minExports.string("]"))).map((l2) => Fields.list(l2)).desc("list ('[1, 2, 3]')"), objectField: (q2) => parsimmon_umd_minExports.seqMap(q2.identifier.or(q2.string), parsimmon_umd_minExports.string(":").trim(parsimmon_umd_minExports.optWhitespace), q2.field, (name, _sep, value) => { return { name, value }; }).sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)).wrap(parsimmon_umd_minExports.string("{").skip(parsimmon_umd_minExports.optWhitespace), parsimmon_umd_minExports.optWhitespace.then(parsimmon_umd_minExports.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: (q2) => parsimmon_umd_minExports.alt(q2.date, q2.duration.map((d3) => normalizeDuration(d3)), q2.string, q2.tag, q2.embedLink, q2.bool, q2.number, q2.rawNull), inlineFieldList: (q2) => q2.atomInlineField.sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace).lookahead(q2.atomInlineField)), inlineField: (q2) => parsimmon_umd_minExports.alt(parsimmon_umd_minExports.seqMap(q2.atomInlineField, parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace), q2.inlineFieldList, (f, _s, l2) => [f].concat(l2)), q2.atomInlineField), atomField: (q2) => parsimmon_umd_minExports.alt( // Place embed links above negated fields as they are the special parser case '![[thing]]' and are generally unambigious. q2.embedLink.map((l2) => Fields.literal(l2)), q2.negatedField, q2.linkField, q2.listField, q2.objectField, q2.lambdaField, q2.parensField, q2.boolField, q2.numberField, q2.stringField, q2.dateField, q2.durationField, q2.nullField, q2.variableField ), indexField: (q2) => parsimmon_umd_minExports.seqMap(q2.atomField, parsimmon_umd_minExports.alt(q2.dotPostfix, q2.indexPostfix, q2.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: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("!"), q2.indexField, (_, field) => Fields.negate(field)).desc("negated field"), parensField: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("("), parsimmon_umd_minExports.optWhitespace, q2.field, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (_1, _2, field, _3, _4) => field), lambdaField: (q2) => parsimmon_umd_minExports.seqMap(q2.identifier.sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)).wrap(parsimmon_umd_minExports.string("(").trim(parsimmon_umd_minExports.optWhitespace), parsimmon_umd_minExports.string(")").trim(parsimmon_umd_minExports.optWhitespace)), parsimmon_umd_minExports.string("=>").trim(parsimmon_umd_minExports.optWhitespace), q2.field, (ident, _ignore, value) => { return { type: "lambda", arguments: ident, value }; }), dotPostfix: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("."), q2.identifier, (_, field) => { return { type: "dot", field }; }), indexPostfix: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("["), parsimmon_umd_minExports.optWhitespace, q2.field, parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string("]"), (_, _2, field, _3, _4) => { return { type: "index", field }; }), functionPostfix: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.string("("), parsimmon_umd_minExports.optWhitespace, q2.field.sepBy(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)), parsimmon_umd_minExports.optWhitespace, parsimmon_umd_minExports.string(")"), (_, _1, fields, _2, _3) => { return { type: "function", fields }; }), // The precedence hierarchy of operators - multiply/divide, add/subtract, compare, and then boolean operations. binaryMulDivField: (q2) => createBinaryParser(q2.indexField, q2.binaryMulDiv, Fields.binaryOp), binaryPlusMinusField: (q2) => createBinaryParser(q2.binaryMulDivField, q2.binaryPlusMinus, Fields.binaryOp), binaryCompareField: (q2) => createBinaryParser(q2.binaryPlusMinusField, q2.binaryCompareOp, Fields.binaryOp), binaryBooleanField: (q2) => createBinaryParser(q2.binaryCompareField, q2.binaryBooleanOp, Fields.binaryOp), binaryOpField: (q2) => q2.binaryBooleanField, field: (q2) => q2.binaryOpField }); function parseField(text3) { try { return Result.success(EXPRESSION.field.tryParse(text3)); } catch (error) { return Result.failure("" + error); } } var QueryFields; (function(QueryFields2) { function named(name, field) { return { name, field }; } QueryFields2.named = named; function sortBy(field, dir) { return { field, direction: dir }; } QueryFields2.sortBy = sortBy; })(QueryFields || (QueryFields = {})); function captureRaw(base) { return parsimmon_umd_minExports.custom((success, failure) => { return (input, i2) => { let result = base._(input, i2); if (!result.status) return result; return Object.assign({}, result, { value: [result.value, input.substring(i2, result.index)] }); }; }); } function stripNewlines(text3) { return text3.split(/[\r\n]+/).map((t2) => t2.trim()).join(""); } function precededByWhitespaceIfNotEof(if_eof, parser) { return parsimmon_umd_minExports.eof.map(if_eof).or(parsimmon_umd_minExports.whitespace.then(parser)); } var QUERY_LANGUAGE = parsimmon_umd_minExports.createLanguage({ // Simple atom parsing, like words, identifiers, numbers. queryType: (q2) => parsimmon_umd_minExports.alt(parsimmon_umd_minExports.regexp(/TABLE|LIST|TASK|CALENDAR/i)).map((str2) => str2.toLowerCase()).desc("query type ('TABLE', 'LIST', 'TASK', or 'CALENDAR')"), explicitNamedField: (q2) => parsimmon_umd_minExports.seqMap(EXPRESSION.field.skip(parsimmon_umd_minExports.whitespace), parsimmon_umd_minExports.regexp(/AS/i).skip(parsimmon_umd_minExports.whitespace), EXPRESSION.identifier.or(EXPRESSION.string), (field, _as, ident) => QueryFields.named(ident, field)), namedField: (q2) => parsimmon_umd_minExports.alt(q2.explicitNamedField, captureRaw(EXPRESSION.field).map(([value, text3]) => QueryFields.named(stripNewlines(text3), value))), sortField: (q2) => parsimmon_umd_minExports.seqMap(EXPRESSION.field.skip(parsimmon_umd_minExports.optWhitespace), parsimmon_umd_minExports.regexp(/ASCENDING|DESCENDING|ASC|DESC/i).atMost(1), (field, dir) => { let direction = dir.length == 0 ? "ascending" : dir[0].toLowerCase(); if (direction == "desc") direction = "descending"; if (direction == "asc") direction = "ascending"; return { field, direction }; }), headerClause: (q2) => q2.queryType.chain((type2) => { switch (type2) { case "table": { return precededByWhitespaceIfNotEof(() => ({ type: type2, fields: [], showId: true }), parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/WITHOUT\s+ID/i).skip(parsimmon_umd_minExports.optWhitespace).atMost(1), parsimmon_umd_minExports.sepBy(q2.namedField, parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)), (withoutId, fields) => { return { type: type2, fields, showId: withoutId.length == 0 }; })); } case "list": return precededByWhitespaceIfNotEof(() => ({ type: type2, format: void 0, showId: true }), parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/WITHOUT\s+ID/i).skip(parsimmon_umd_minExports.optWhitespace).atMost(1), EXPRESSION.field.atMost(1), (withoutId, format2) => { return { type: type2, format: format2.length == 1 ? format2[0] : void 0, showId: withoutId.length == 0 }; })); case "task": return parsimmon_umd_minExports.succeed({ type: type2 }); case "calendar": return parsimmon_umd_minExports.whitespace.then(parsimmon_umd_minExports.seqMap(q2.namedField, (field) => { return { type: type2, showId: true, field }; })); default: return parsimmon_umd_minExports.fail(`Unrecognized query type '${type2}'`); } }).desc("TABLE or LIST or TASK or CALENDAR"), fromClause: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/FROM/i), parsimmon_umd_minExports.whitespace, EXPRESSION.source, (_1, _2, source) => source), whereClause: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/WHERE/i), parsimmon_umd_minExports.whitespace, EXPRESSION.field, (where, _, field) => { return { type: "where", clause: field }; }).desc("WHERE "), sortByClause: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/SORT/i), parsimmon_umd_minExports.whitespace, q2.sortField.sepBy1(parsimmon_umd_minExports.string(",").trim(parsimmon_umd_minExports.optWhitespace)), (sort, _1, fields) => { return { type: "sort", fields }; }).desc("SORT field [ASC/DESC]"), limitClause: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/LIMIT/i), parsimmon_umd_minExports.whitespace, EXPRESSION.field, (limit, _1, field) => { return { type: "limit", amount: field }; }).desc("LIMIT "), flattenClause: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/FLATTEN/i).skip(parsimmon_umd_minExports.whitespace), q2.namedField, (_, field) => { return { type: "flatten", field }; }).desc("FLATTEN [AS ]"), groupByClause: (q2) => parsimmon_umd_minExports.seqMap(parsimmon_umd_minExports.regexp(/GROUP BY/i).skip(parsimmon_umd_minExports.whitespace), q2.namedField, (_, field) => { return { type: "group", field }; }).desc("GROUP BY [AS ]"), // Full query parsing. clause: (q2) => parsimmon_umd_minExports.alt(q2.fromClause, q2.whereClause, q2.sortByClause, q2.limitClause, q2.groupByClause, q2.flattenClause), query: (q2) => parsimmon_umd_minExports.seqMap(q2.headerClause.trim(parsimmon_umd_minExports.optWhitespace), q2.fromClause.trim(parsimmon_umd_minExports.optWhitespace).atMost(1), q2.clause.trim(parsimmon_umd_minExports.optWhitespace).many(), (header, from, clauses) => { return { header, source: from.length == 0 ? Sources.folder("") : from[0], operations: clauses, settings: DEFAULT_QUERY_SETTINGS }; }) }); var getAPI2 = (app) => { var _a; if (app) return (_a = app.plugins.plugins.dataview) === null || _a === void 0 ? void 0 : _a.api; else return window.DataviewAPI; }; var isPluginEnabled = (app) => app.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 = getAPI2; exports.isPluginEnabled = isPluginEnabled; exports.parseField = parseField; } }); // node_modules/diff-match-patch/index.js var require_diff_match_patch = __commonJS({ "node_modules/diff-match-patch/index.js"(exports, module2) { var diff_match_patch2 = function() { this.Diff_Timeout = 1; this.Diff_EditCost = 4; this.Match_Threshold = 0.5; this.Match_Distance = 1e3; this.Patch_DeleteThreshold = 0.5; this.Patch_Margin = 4; this.Match_MaxBits = 32; }; var DIFF_DELETE2 = -1; var DIFF_INSERT2 = 1; var DIFF_EQUAL = 0; diff_match_patch2.Diff = function(op, text3) { return [op, text3]; }; diff_match_patch2.prototype.diff_main = function(text1, text22, opt_checklines, opt_deadline) { if (typeof opt_deadline == "undefined") { if (this.Diff_Timeout <= 0) { opt_deadline = Number.MAX_VALUE; } else { opt_deadline = new Date().getTime() + this.Diff_Timeout * 1e3; } } var deadline = opt_deadline; if (text1 == null || text22 == null) { throw new Error("Null input. (diff_main)"); } if (text1 == text22) { if (text1) { return [new diff_match_patch2.Diff(DIFF_EQUAL, text1)]; } return []; } if (typeof opt_checklines == "undefined") { opt_checklines = true; } var checklines = opt_checklines; var commonlength = this.diff_commonPrefix(text1, text22); var commonprefix = text1.substring(0, commonlength); text1 = text1.substring(commonlength); text22 = text22.substring(commonlength); commonlength = this.diff_commonSuffix(text1, text22); var commonsuffix = text1.substring(text1.length - commonlength); text1 = text1.substring(0, text1.length - commonlength); text22 = text22.substring(0, text22.length - commonlength); var diffs = this.diff_compute_(text1, text22, checklines, deadline); if (commonprefix) { diffs.unshift(new diff_match_patch2.Diff(DIFF_EQUAL, commonprefix)); } if (commonsuffix) { diffs.push(new diff_match_patch2.Diff(DIFF_EQUAL, commonsuffix)); } this.diff_cleanupMerge(diffs); return diffs; }; diff_match_patch2.prototype.diff_compute_ = function(text1, text22, checklines, deadline) { var diffs; if (!text1) { return [new diff_match_patch2.Diff(DIFF_INSERT2, text22)]; } if (!text22) { return [new diff_match_patch2.Diff(DIFF_DELETE2, text1)]; } var longtext = text1.length > text22.length ? text1 : text22; var shorttext = text1.length > text22.length ? text22 : text1; var i2 = longtext.indexOf(shorttext); if (i2 != -1) { diffs = [ new diff_match_patch2.Diff(DIFF_INSERT2, longtext.substring(0, i2)), new diff_match_patch2.Diff(DIFF_EQUAL, shorttext), new diff_match_patch2.Diff( DIFF_INSERT2, longtext.substring(i2 + shorttext.length) ) ]; if (text1.length > text22.length) { diffs[0][0] = diffs[2][0] = DIFF_DELETE2; } return diffs; } if (shorttext.length == 1) { return [ new diff_match_patch2.Diff(DIFF_DELETE2, text1), new diff_match_patch2.Diff(DIFF_INSERT2, text22) ]; } var hm = this.diff_halfMatch_(text1, text22); if (hm) { var text1_a = hm[0]; var text1_b = hm[1]; var text2_a = hm[2]; var text2_b = hm[3]; var mid_common = hm[4]; var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline); var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline); return diffs_a.concat( [new diff_match_patch2.Diff(DIFF_EQUAL, mid_common)], diffs_b ); } if (checklines && text1.length > 100 && text22.length > 100) { return this.diff_lineMode_(text1, text22, deadline); } return this.diff_bisect_(text1, text22, deadline); }; diff_match_patch2.prototype.diff_lineMode_ = function(text1, text22, deadline) { var a3 = this.diff_linesToChars_(text1, text22); text1 = a3.chars1; text22 = a3.chars2; var linearray = a3.lineArray; var diffs = this.diff_main(text1, text22, false, deadline); this.diff_charsToLines_(diffs, linearray); this.diff_cleanupSemantic(diffs); diffs.push(new diff_match_patch2.Diff(DIFF_EQUAL, "")); var pointer = 0; var count_delete = 0; var count_insert = 0; var text_delete = ""; var text_insert = ""; while (pointer < diffs.length) { switch (diffs[pointer][0]) { case DIFF_INSERT2: count_insert++; text_insert += diffs[pointer][1]; break; case DIFF_DELETE2: count_delete++; text_delete += diffs[pointer][1]; break; case DIFF_EQUAL: if (count_delete >= 1 && count_insert >= 1) { diffs.splice( pointer - count_delete - count_insert, count_delete + count_insert ); pointer = pointer - count_delete - count_insert; var subDiff = this.diff_main(text_delete, text_insert, false, deadline); for (var j = subDiff.length - 1; j >= 0; j--) { diffs.splice(pointer, 0, subDiff[j]); } pointer = pointer + subDiff.length; } count_insert = 0; count_delete = 0; text_delete = ""; text_insert = ""; break; } pointer++; } diffs.pop(); return diffs; }; diff_match_patch2.prototype.diff_bisect_ = function(text1, text22, deadline) { var text1_length = text1.length; var text2_length = text22.length; var max_d = Math.ceil((text1_length + text2_length) / 2); var v_offset = max_d; var v_length = 2 * max_d; var v1 = new Array(v_length); var v2 = new Array(v_length); for (var x2 = 0; x2 < v_length; x2++) { v1[x2] = -1; v2[x2] = -1; } v1[v_offset + 1] = 0; v2[v_offset + 1] = 0; var delta = text1_length - text2_length; var front = delta % 2 != 0; var k1start = 0; var k1end = 0; var k2start = 0; var k2end = 0; for (var d3 = 0; d3 < max_d; d3++) { if (new Date().getTime() > deadline) { break; } for (var k1 = -d3 + k1start; k1 <= d3 - k1end; k1 += 2) { var k1_offset = v_offset + k1; var x1; if (k1 == -d3 || k1 != d3 && v1[k1_offset - 1] < v1[k1_offset + 1]) { x1 = v1[k1_offset + 1]; } else { x1 = v1[k1_offset - 1] + 1; } var y1 = x1 - k1; while (x1 < text1_length && y1 < text2_length && text1.charAt(x1) == text22.charAt(y1)) { x1++; y1++; } v1[k1_offset] = x1; if (x1 > text1_length) { k1end += 2; } else if (y1 > text2_length) { k1start += 2; } else if (front) { var k2_offset = v_offset + delta - k1; if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) { var x22 = text1_length - v2[k2_offset]; if (x1 >= x22) { return this.diff_bisectSplit_(text1, text22, x1, y1, deadline); } } } } for (var k2 = -d3 + k2start; k2 <= d3 - k2end; k2 += 2) { var k2_offset = v_offset + k2; var x22; if (k2 == -d3 || k2 != d3 && v2[k2_offset - 1] < v2[k2_offset + 1]) { x22 = v2[k2_offset + 1]; } else { x22 = v2[k2_offset - 1] + 1; } var y22 = x22 - k2; while (x22 < text1_length && y22 < text2_length && text1.charAt(text1_length - x22 - 1) == text22.charAt(text2_length - y22 - 1)) { x22++; y22++; } v2[k2_offset] = x22; if (x22 > text1_length) { k2end += 2; } else if (y22 > text2_length) { k2start += 2; } else if (!front) { var k1_offset = v_offset + delta - k2; if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) { var x1 = v1[k1_offset]; var y1 = v_offset + x1 - k1_offset; x22 = text1_length - x22; if (x1 >= x22) { return this.diff_bisectSplit_(text1, text22, x1, y1, deadline); } } } } } return [ new diff_match_patch2.Diff(DIFF_DELETE2, text1), new diff_match_patch2.Diff(DIFF_INSERT2, text22) ]; }; diff_match_patch2.prototype.diff_bisectSplit_ = function(text1, text22, x2, y3, deadline) { var text1a = text1.substring(0, x2); var text2a = text22.substring(0, y3); var text1b = text1.substring(x2); var text2b = text22.substring(y3); var diffs = this.diff_main(text1a, text2a, false, deadline); var diffsb = this.diff_main(text1b, text2b, false, deadline); return diffs.concat(diffsb); }; diff_match_patch2.prototype.diff_linesToChars_ = function(text1, text22) { var lineArray = []; var lineHash = {}; lineArray[0] = ""; function diff_linesToCharsMunge_(text3) { var chars = ""; var lineStart = 0; var lineEnd = -1; var lineArrayLength = lineArray.length; while (lineEnd < text3.length - 1) { lineEnd = text3.indexOf("\n", lineStart); if (lineEnd == -1) { lineEnd = text3.length - 1; } var line = text3.substring(lineStart, lineEnd + 1); if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== void 0) { chars += String.fromCharCode(lineHash[line]); } else { if (lineArrayLength == maxLines) { line = text3.substring(lineStart); lineEnd = text3.length; } chars += String.fromCharCode(lineArrayLength); lineHash[line] = lineArrayLength; lineArray[lineArrayLength++] = line; } lineStart = lineEnd + 1; } return chars; } var maxLines = 4e4; var chars1 = diff_linesToCharsMunge_(text1); maxLines = 65535; var chars2 = diff_linesToCharsMunge_(text22); return { chars1, chars2, lineArray }; }; diff_match_patch2.prototype.diff_charsToLines_ = function(diffs, lineArray) { for (var i2 = 0; i2 < diffs.length; i2++) { var chars = diffs[i2][1]; var text3 = []; for (var j = 0; j < chars.length; j++) { text3[j] = lineArray[chars.charCodeAt(j)]; } diffs[i2][1] = text3.join(""); } }; diff_match_patch2.prototype.diff_commonPrefix = function(text1, text22) { if (!text1 || !text22 || text1.charAt(0) != text22.charAt(0)) { return 0; } var pointermin = 0; var pointermax = Math.min(text1.length, text22.length); var pointermid = pointermax; var pointerstart = 0; while (pointermin < pointermid) { if (text1.substring(pointerstart, pointermid) == text22.substring(pointerstart, pointermid)) { pointermin = pointermid; pointerstart = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } return pointermid; }; diff_match_patch2.prototype.diff_commonSuffix = function(text1, text22) { if (!text1 || !text22 || text1.charAt(text1.length - 1) != text22.charAt(text22.length - 1)) { return 0; } var pointermin = 0; var pointermax = Math.min(text1.length, text22.length); var pointermid = pointermax; var pointerend = 0; while (pointermin < pointermid) { if (text1.substring(text1.length - pointermid, text1.length - pointerend) == text22.substring(text22.length - pointermid, text22.length - pointerend)) { pointermin = pointermid; pointerend = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } return pointermid; }; diff_match_patch2.prototype.diff_commonOverlap_ = function(text1, text22) { var text1_length = text1.length; var text2_length = text22.length; if (text1_length == 0 || text2_length == 0) { return 0; } if (text1_length > text2_length) { text1 = text1.substring(text1_length - text2_length); } else if (text1_length < text2_length) { text22 = text22.substring(0, text1_length); } var text_length = Math.min(text1_length, text2_length); if (text1 == text22) { return text_length; } var best = 0; var length = 1; while (true) { var pattern = text1.substring(text_length - length); var found = text22.indexOf(pattern); if (found == -1) { return best; } length += found; if (found == 0 || text1.substring(text_length - length) == text22.substring(0, length)) { best = length; length++; } } }; diff_match_patch2.prototype.diff_halfMatch_ = function(text1, text22) { if (this.Diff_Timeout <= 0) { return null; } var longtext = text1.length > text22.length ? text1 : text22; var shorttext = text1.length > text22.length ? text22 : text1; if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { return null; } var dmp = this; function diff_halfMatchI_(longtext2, shorttext2, i2) { var seed = longtext2.substring(i2, i2 + Math.floor(longtext2.length / 4)); var j = -1; var best_common = ""; var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b; while ((j = shorttext2.indexOf(seed, j + 1)) != -1) { var prefixLength = dmp.diff_commonPrefix( longtext2.substring(i2), shorttext2.substring(j) ); var suffixLength = dmp.diff_commonSuffix( longtext2.substring(0, i2), shorttext2.substring(0, j) ); if (best_common.length < suffixLength + prefixLength) { best_common = shorttext2.substring(j - suffixLength, j) + shorttext2.substring(j, j + prefixLength); best_longtext_a = longtext2.substring(0, i2 - suffixLength); best_longtext_b = longtext2.substring(i2 + prefixLength); best_shorttext_a = shorttext2.substring(0, j - suffixLength); best_shorttext_b = shorttext2.substring(j + prefixLength); } } if (best_common.length * 2 >= longtext2.length) { return [ best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b, best_common ]; } else { return null; } } var hm1 = diff_halfMatchI_( longtext, shorttext, Math.ceil(longtext.length / 4) ); var hm2 = diff_halfMatchI_( longtext, shorttext, Math.ceil(longtext.length / 2) ); var hm; if (!hm1 && !hm2) { return null; } else if (!hm2) { hm = hm1; } else if (!hm1) { hm = hm2; } else { hm = hm1[4].length > hm2[4].length ? hm1 : hm2; } var text1_a, text1_b, text2_a, text2_b; if (text1.length > text22.length) { text1_a = hm[0]; text1_b = hm[1]; text2_a = hm[2]; text2_b = hm[3]; } else { text2_a = hm[0]; text2_b = hm[1]; text1_a = hm[2]; text1_b = hm[3]; } var mid_common = hm[4]; return [text1_a, text1_b, text2_a, text2_b, mid_common]; }; diff_match_patch2.prototype.diff_cleanupSemantic = function(diffs) { var changes = false; var equalities = []; var equalitiesLength = 0; var lastEquality = null; var pointer = 0; var length_insertions1 = 0; var length_deletions1 = 0; var length_insertions2 = 0; var length_deletions2 = 0; while (pointer < diffs.length) { if (diffs[pointer][0] == DIFF_EQUAL) { equalities[equalitiesLength++] = pointer; length_insertions1 = length_insertions2; length_deletions1 = length_deletions2; length_insertions2 = 0; length_deletions2 = 0; lastEquality = diffs[pointer][1]; } else { if (diffs[pointer][0] == DIFF_INSERT2) { length_insertions2 += diffs[pointer][1].length; } else { length_deletions2 += diffs[pointer][1].length; } if (lastEquality && lastEquality.length <= Math.max(length_insertions1, length_deletions1) && lastEquality.length <= Math.max( length_insertions2, length_deletions2 )) { diffs.splice( equalities[equalitiesLength - 1], 0, new diff_match_patch2.Diff(DIFF_DELETE2, lastEquality) ); diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT2; equalitiesLength--; equalitiesLength--; pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; length_insertions1 = 0; length_deletions1 = 0; length_insertions2 = 0; length_deletions2 = 0; lastEquality = null; changes = true; } } pointer++; } if (changes) { this.diff_cleanupMerge(diffs); } this.diff_cleanupSemanticLossless(diffs); pointer = 1; while (pointer < diffs.length) { if (diffs[pointer - 1][0] == DIFF_DELETE2 && diffs[pointer][0] == DIFF_INSERT2) { var deletion = diffs[pointer - 1][1]; var insertion = diffs[pointer][1]; var overlap_length1 = this.diff_commonOverlap_(deletion, insertion); var overlap_length2 = this.diff_commonOverlap_(insertion, deletion); if (overlap_length1 >= overlap_length2) { if (overlap_length1 >= deletion.length / 2 || overlap_length1 >= insertion.length / 2) { diffs.splice(pointer, 0, new diff_match_patch2.Diff( DIFF_EQUAL, insertion.substring(0, overlap_length1) )); diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlap_length1); diffs[pointer + 1][1] = insertion.substring(overlap_length1); pointer++; } } else { if (overlap_length2 >= deletion.length / 2 || overlap_length2 >= insertion.length / 2) { diffs.splice(pointer, 0, new diff_match_patch2.Diff( DIFF_EQUAL, deletion.substring(0, overlap_length2) )); diffs[pointer - 1][0] = DIFF_INSERT2; diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlap_length2); diffs[pointer + 1][0] = DIFF_DELETE2; diffs[pointer + 1][1] = deletion.substring(overlap_length2); pointer++; } } pointer++; } pointer++; } }; diff_match_patch2.prototype.diff_cleanupSemanticLossless = function(diffs) { function diff_cleanupSemanticScore_(one2, two) { if (!one2 || !two) { return 6; } var char1 = one2.charAt(one2.length - 1); var char2 = two.charAt(0); var nonAlphaNumeric1 = char1.match(diff_match_patch2.nonAlphaNumericRegex_); var nonAlphaNumeric2 = char2.match(diff_match_patch2.nonAlphaNumericRegex_); var whitespace1 = nonAlphaNumeric1 && char1.match(diff_match_patch2.whitespaceRegex_); var whitespace2 = nonAlphaNumeric2 && char2.match(diff_match_patch2.whitespaceRegex_); var lineBreak1 = whitespace1 && char1.match(diff_match_patch2.linebreakRegex_); var lineBreak2 = whitespace2 && char2.match(diff_match_patch2.linebreakRegex_); var blankLine1 = lineBreak1 && one2.match(diff_match_patch2.blanklineEndRegex_); var blankLine2 = lineBreak2 && two.match(diff_match_patch2.blanklineStartRegex_); if (blankLine1 || blankLine2) { return 5; } else if (lineBreak1 || lineBreak2) { return 4; } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { return 3; } else if (whitespace1 || whitespace2) { return 2; } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { return 1; } return 0; } var pointer = 1; while (pointer < diffs.length - 1) { if (diffs[pointer - 1][0] == DIFF_EQUAL && diffs[pointer + 1][0] == DIFF_EQUAL) { var equality1 = diffs[pointer - 1][1]; var edit = diffs[pointer][1]; var equality2 = diffs[pointer + 1][1]; var commonOffset = this.diff_commonSuffix(equality1, edit); if (commonOffset) { var commonString = edit.substring(edit.length - commonOffset); equality1 = equality1.substring(0, equality1.length - commonOffset); edit = commonString + edit.substring(0, edit.length - commonOffset); equality2 = commonString + equality2; } var bestEquality1 = equality1; var bestEdit = edit; var bestEquality2 = equality2; var bestScore = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); while (edit.charAt(0) === equality2.charAt(0)) { equality1 += edit.charAt(0); edit = edit.substring(1) + equality2.charAt(0); equality2 = equality2.substring(1); var score = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); if (score >= bestScore) { bestScore = score; bestEquality1 = equality1; bestEdit = edit; bestEquality2 = equality2; } } if (diffs[pointer - 1][1] != bestEquality1) { if (bestEquality1) { diffs[pointer - 1][1] = bestEquality1; } else { diffs.splice(pointer - 1, 1); pointer--; } diffs[pointer][1] = bestEdit; if (bestEquality2) { diffs[pointer + 1][1] = bestEquality2; } else { diffs.splice(pointer + 1, 1); pointer--; } } } pointer++; } }; diff_match_patch2.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/; diff_match_patch2.whitespaceRegex_ = /\s/; diff_match_patch2.linebreakRegex_ = /[\r\n]/; diff_match_patch2.blanklineEndRegex_ = /\n\r?\n$/; diff_match_patch2.blanklineStartRegex_ = /^\r?\n\r?\n/; diff_match_patch2.prototype.diff_cleanupEfficiency = function(diffs) { var changes = false; var equalities = []; var equalitiesLength = 0; var lastEquality = null; var pointer = 0; var pre_ins = false; var pre_del = false; var post_ins = false; var post_del = false; while (pointer < diffs.length) { if (diffs[pointer][0] == DIFF_EQUAL) { if (diffs[pointer][1].length < this.Diff_EditCost && (post_ins || post_del)) { equalities[equalitiesLength++] = pointer; pre_ins = post_ins; pre_del = post_del; lastEquality = diffs[pointer][1]; } else { equalitiesLength = 0; lastEquality = null; } post_ins = post_del = false; } else { if (diffs[pointer][0] == DIFF_DELETE2) { post_del = true; } else { post_ins = true; } if (lastEquality && (pre_ins && pre_del && post_ins && post_del || lastEquality.length < this.Diff_EditCost / 2 && pre_ins + pre_del + post_ins + post_del == 3)) { diffs.splice( equalities[equalitiesLength - 1], 0, new diff_match_patch2.Diff(DIFF_DELETE2, lastEquality) ); diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT2; equalitiesLength--; lastEquality = null; if (pre_ins && pre_del) { post_ins = post_del = true; equalitiesLength = 0; } else { equalitiesLength--; pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; post_ins = post_del = false; } changes = true; } } pointer++; } if (changes) { this.diff_cleanupMerge(diffs); } }; diff_match_patch2.prototype.diff_cleanupMerge = function(diffs) { diffs.push(new diff_match_patch2.Diff(DIFF_EQUAL, "")); var pointer = 0; var count_delete = 0; var count_insert = 0; var text_delete = ""; var text_insert = ""; var commonlength; while (pointer < diffs.length) { switch (diffs[pointer][0]) { case DIFF_INSERT2: count_insert++; text_insert += diffs[pointer][1]; pointer++; break; case DIFF_DELETE2: count_delete++; text_delete += diffs[pointer][1]; pointer++; break; case DIFF_EQUAL: if (count_delete + count_insert > 1) { if (count_delete !== 0 && count_insert !== 0) { commonlength = this.diff_commonPrefix(text_insert, text_delete); if (commonlength !== 0) { if (pointer - count_delete - count_insert > 0 && diffs[pointer - count_delete - count_insert - 1][0] == DIFF_EQUAL) { diffs[pointer - count_delete - count_insert - 1][1] += text_insert.substring(0, commonlength); } else { diffs.splice(0, 0, new diff_match_patch2.Diff( DIFF_EQUAL, text_insert.substring(0, commonlength) )); pointer++; } text_insert = text_insert.substring(commonlength); text_delete = text_delete.substring(commonlength); } commonlength = this.diff_commonSuffix(text_insert, text_delete); if (commonlength !== 0) { diffs[pointer][1] = text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1]; text_insert = text_insert.substring(0, text_insert.length - commonlength); text_delete = text_delete.substring(0, text_delete.length - commonlength); } } pointer -= count_delete + count_insert; diffs.splice(pointer, count_delete + count_insert); if (text_delete.length) { diffs.splice( pointer, 0, new diff_match_patch2.Diff(DIFF_DELETE2, text_delete) ); pointer++; } if (text_insert.length) { diffs.splice( pointer, 0, new diff_match_patch2.Diff(DIFF_INSERT2, text_insert) ); pointer++; } pointer++; } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) { diffs[pointer - 1][1] += diffs[pointer][1]; diffs.splice(pointer, 1); } else { pointer++; } count_insert = 0; count_delete = 0; text_delete = ""; text_insert = ""; break; } } if (diffs[diffs.length - 1][1] === "") { diffs.pop(); } var changes = false; pointer = 1; while (pointer < diffs.length - 1) { if (diffs[pointer - 1][0] == DIFF_EQUAL && diffs[pointer + 1][0] == DIFF_EQUAL) { if (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) { diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; diffs.splice(pointer - 1, 1); changes = true; } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) == diffs[pointer + 1][1]) { diffs[pointer - 1][1] += diffs[pointer + 1][1]; diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; diffs.splice(pointer + 1, 1); changes = true; } } pointer++; } if (changes) { this.diff_cleanupMerge(diffs); } }; diff_match_patch2.prototype.diff_xIndex = function(diffs, loc) { var chars1 = 0; var chars2 = 0; var last_chars1 = 0; var last_chars2 = 0; var x2; for (x2 = 0; x2 < diffs.length; x2++) { if (diffs[x2][0] !== DIFF_INSERT2) { chars1 += diffs[x2][1].length; } if (diffs[x2][0] !== DIFF_DELETE2) { chars2 += diffs[x2][1].length; } if (chars1 > loc) { break; } last_chars1 = chars1; last_chars2 = chars2; } if (diffs.length != x2 && diffs[x2][0] === DIFF_DELETE2) { return last_chars2; } return last_chars2 + (loc - last_chars1); }; diff_match_patch2.prototype.diff_prettyHtml = function(diffs) { var html = []; var pattern_amp = /&/g; var pattern_lt = //g; var pattern_para = /\n/g; for (var x2 = 0; x2 < diffs.length; x2++) { var op = diffs[x2][0]; var data = diffs[x2][1]; var text3 = data.replace(pattern_amp, "&").replace(pattern_lt, "<").replace(pattern_gt, ">").replace(pattern_para, "¶
"); switch (op) { case DIFF_INSERT2: html[x2] = '' + text3 + ""; break; case DIFF_DELETE2: html[x2] = '' + text3 + ""; break; case DIFF_EQUAL: html[x2] = "" + text3 + ""; break; } } return html.join(""); }; diff_match_patch2.prototype.diff_text1 = function(diffs) { var text3 = []; for (var x2 = 0; x2 < diffs.length; x2++) { if (diffs[x2][0] !== DIFF_INSERT2) { text3[x2] = diffs[x2][1]; } } return text3.join(""); }; diff_match_patch2.prototype.diff_text2 = function(diffs) { var text3 = []; for (var x2 = 0; x2 < diffs.length; x2++) { if (diffs[x2][0] !== DIFF_DELETE2) { text3[x2] = diffs[x2][1]; } } return text3.join(""); }; diff_match_patch2.prototype.diff_levenshtein = function(diffs) { var levenshtein = 0; var insertions = 0; var deletions = 0; for (var x2 = 0; x2 < diffs.length; x2++) { var op = diffs[x2][0]; var data = diffs[x2][1]; switch (op) { case DIFF_INSERT2: insertions += data.length; break; case DIFF_DELETE2: deletions += data.length; break; case DIFF_EQUAL: levenshtein += Math.max(insertions, deletions); insertions = 0; deletions = 0; break; } } levenshtein += Math.max(insertions, deletions); return levenshtein; }; diff_match_patch2.prototype.diff_toDelta = function(diffs) { var text3 = []; for (var x2 = 0; x2 < diffs.length; x2++) { switch (diffs[x2][0]) { case DIFF_INSERT2: text3[x2] = "+" + encodeURI(diffs[x2][1]); break; case DIFF_DELETE2: text3[x2] = "-" + diffs[x2][1].length; break; case DIFF_EQUAL: text3[x2] = "=" + diffs[x2][1].length; break; } } return text3.join(" ").replace(/%20/g, " "); }; diff_match_patch2.prototype.diff_fromDelta = function(text1, delta) { var diffs = []; var diffsLength = 0; var pointer = 0; var tokens = delta.split(/\t/g); for (var x2 = 0; x2 < tokens.length; x2++) { var param = tokens[x2].substring(1); switch (tokens[x2].charAt(0)) { case "+": try { diffs[diffsLength++] = new diff_match_patch2.Diff(DIFF_INSERT2, decodeURI(param)); } catch (ex) { throw new Error("Illegal escape in diff_fromDelta: " + param); } break; case "-": case "=": var n = parseInt(param, 10); if (isNaN(n) || n < 0) { throw new Error("Invalid number in diff_fromDelta: " + param); } var text3 = text1.substring(pointer, pointer += n); if (tokens[x2].charAt(0) == "=") { diffs[diffsLength++] = new diff_match_patch2.Diff(DIFF_EQUAL, text3); } else { diffs[diffsLength++] = new diff_match_patch2.Diff(DIFF_DELETE2, text3); } break; default: if (tokens[x2]) { throw new Error("Invalid diff operation in diff_fromDelta: " + tokens[x2]); } } } if (pointer != text1.length) { throw new Error("Delta length (" + pointer + ") does not equal source text length (" + text1.length + ")."); } return diffs; }; diff_match_patch2.prototype.match_main = function(text3, pattern, loc) { if (text3 == null || pattern == null || loc == null) { throw new Error("Null input. (match_main)"); } loc = Math.max(0, Math.min(loc, text3.length)); if (text3 == pattern) { return 0; } else if (!text3.length) { return -1; } else if (text3.substring(loc, loc + pattern.length) == pattern) { return loc; } else { return this.match_bitap_(text3, pattern, loc); } }; diff_match_patch2.prototype.match_bitap_ = function(text3, pattern, loc) { if (pattern.length > this.Match_MaxBits) { throw new Error("Pattern too long for this browser."); } var s3 = this.match_alphabet_(pattern); var dmp = this; function match_bitapScore_(e2, x2) { var accuracy = e2 / pattern.length; var proximity = Math.abs(loc - x2); if (!dmp.Match_Distance) { return proximity ? 1 : accuracy; } return accuracy + proximity / dmp.Match_Distance; } var score_threshold = this.Match_Threshold; var best_loc = text3.indexOf(pattern, loc); if (best_loc != -1) { score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold); best_loc = text3.lastIndexOf(pattern, loc + pattern.length); if (best_loc != -1) { score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold); } } var matchmask = 1 << pattern.length - 1; best_loc = -1; var bin_min, bin_mid; var bin_max = pattern.length + text3.length; var last_rd; for (var d3 = 0; d3 < pattern.length; d3++) { bin_min = 0; bin_mid = bin_max; while (bin_min < bin_mid) { if (match_bitapScore_(d3, loc + bin_mid) <= score_threshold) { bin_min = bin_mid; } else { bin_max = bin_mid; } bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min); } bin_max = bin_mid; var start = Math.max(1, loc - bin_mid + 1); var finish = Math.min(loc + bin_mid, text3.length) + pattern.length; var rd = Array(finish + 2); rd[finish + 1] = (1 << d3) - 1; for (var j = finish; j >= start; j--) { var charMatch = s3[text3.charAt(j - 1)]; if (d3 === 0) { rd[j] = (rd[j + 1] << 1 | 1) & charMatch; } else { rd[j] = (rd[j + 1] << 1 | 1) & charMatch | ((last_rd[j + 1] | last_rd[j]) << 1 | 1) | last_rd[j + 1]; } if (rd[j] & matchmask) { var score = match_bitapScore_(d3, j - 1); if (score <= score_threshold) { score_threshold = score; best_loc = j - 1; if (best_loc > loc) { start = Math.max(1, 2 * loc - best_loc); } else { break; } } } } if (match_bitapScore_(d3 + 1, loc) > score_threshold) { break; } last_rd = rd; } return best_loc; }; diff_match_patch2.prototype.match_alphabet_ = function(pattern) { var s3 = {}; for (var i2 = 0; i2 < pattern.length; i2++) { s3[pattern.charAt(i2)] = 0; } for (var i2 = 0; i2 < pattern.length; i2++) { s3[pattern.charAt(i2)] |= 1 << pattern.length - i2 - 1; } return s3; }; diff_match_patch2.prototype.patch_addContext_ = function(patch, text3) { if (text3.length == 0) { return; } if (patch.start2 === null) { throw Error("patch not initialized"); } var pattern = text3.substring(patch.start2, patch.start2 + patch.length1); var padding = 0; while (text3.indexOf(pattern) != text3.lastIndexOf(pattern) && pattern.length < this.Match_MaxBits - this.Patch_Margin - this.Patch_Margin) { padding += this.Patch_Margin; pattern = text3.substring( patch.start2 - padding, patch.start2 + patch.length1 + padding ); } padding += this.Patch_Margin; var prefix = text3.substring(patch.start2 - padding, patch.start2); if (prefix) { patch.diffs.unshift(new diff_match_patch2.Diff(DIFF_EQUAL, prefix)); } var suffix = text3.substring( patch.start2 + patch.length1, patch.start2 + patch.length1 + padding ); if (suffix) { patch.diffs.push(new diff_match_patch2.Diff(DIFF_EQUAL, suffix)); } patch.start1 -= prefix.length; patch.start2 -= prefix.length; patch.length1 += prefix.length + suffix.length; patch.length2 += prefix.length + suffix.length; }; diff_match_patch2.prototype.patch_make = function(a3, opt_b, opt_c) { var text1, diffs; if (typeof a3 == "string" && typeof opt_b == "string" && typeof opt_c == "undefined") { text1 = /** @type {string} */ a3; diffs = this.diff_main( text1, /** @type {string} */ opt_b, true ); if (diffs.length > 2) { this.diff_cleanupSemantic(diffs); this.diff_cleanupEfficiency(diffs); } } else if (a3 && typeof a3 == "object" && typeof opt_b == "undefined" && typeof opt_c == "undefined") { diffs = /** @type {!Array.} */ a3; text1 = this.diff_text1(diffs); } else if (typeof a3 == "string" && opt_b && typeof opt_b == "object" && typeof opt_c == "undefined") { text1 = /** @type {string} */ a3; diffs = /** @type {!Array.} */ opt_b; } else if (typeof a3 == "string" && typeof opt_b == "string" && opt_c && typeof opt_c == "object") { text1 = /** @type {string} */ a3; diffs = /** @type {!Array.} */ opt_c; } else { throw new Error("Unknown call format to patch_make."); } if (diffs.length === 0) { return []; } var patches = []; var patch = new diff_match_patch2.patch_obj(); var patchDiffLength = 0; var char_count1 = 0; var char_count2 = 0; var prepatch_text = text1; var postpatch_text = text1; for (var x2 = 0; x2 < diffs.length; x2++) { var diff_type = diffs[x2][0]; var diff_text = diffs[x2][1]; if (!patchDiffLength && diff_type !== DIFF_EQUAL) { patch.start1 = char_count1; patch.start2 = char_count2; } switch (diff_type) { case DIFF_INSERT2: patch.diffs[patchDiffLength++] = diffs[x2]; patch.length2 += diff_text.length; postpatch_text = postpatch_text.substring(0, char_count2) + diff_text + postpatch_text.substring(char_count2); break; case DIFF_DELETE2: patch.length1 += diff_text.length; patch.diffs[patchDiffLength++] = diffs[x2]; postpatch_text = postpatch_text.substring(0, char_count2) + postpatch_text.substring(char_count2 + diff_text.length); break; case DIFF_EQUAL: if (diff_text.length <= 2 * this.Patch_Margin && patchDiffLength && diffs.length != x2 + 1) { patch.diffs[patchDiffLength++] = diffs[x2]; patch.length1 += diff_text.length; patch.length2 += diff_text.length; } else if (diff_text.length >= 2 * this.Patch_Margin) { if (patchDiffLength) { this.patch_addContext_(patch, prepatch_text); patches.push(patch); patch = new diff_match_patch2.patch_obj(); patchDiffLength = 0; prepatch_text = postpatch_text; char_count1 = char_count2; } } break; } if (diff_type !== DIFF_INSERT2) { char_count1 += diff_text.length; } if (diff_type !== DIFF_DELETE2) { char_count2 += diff_text.length; } } if (patchDiffLength) { this.patch_addContext_(patch, prepatch_text); patches.push(patch); } return patches; }; diff_match_patch2.prototype.patch_deepCopy = function(patches) { var patchesCopy = []; for (var x2 = 0; x2 < patches.length; x2++) { var patch = patches[x2]; var patchCopy = new diff_match_patch2.patch_obj(); patchCopy.diffs = []; for (var y3 = 0; y3 < patch.diffs.length; y3++) { patchCopy.diffs[y3] = new diff_match_patch2.Diff(patch.diffs[y3][0], patch.diffs[y3][1]); } patchCopy.start1 = patch.start1; patchCopy.start2 = patch.start2; patchCopy.length1 = patch.length1; patchCopy.length2 = patch.length2; patchesCopy[x2] = patchCopy; } return patchesCopy; }; diff_match_patch2.prototype.patch_apply = function(patches, text3) { if (patches.length == 0) { return [text3, []]; } patches = this.patch_deepCopy(patches); var nullPadding = this.patch_addPadding(patches); text3 = nullPadding + text3 + nullPadding; this.patch_splitMax(patches); var delta = 0; var results = []; for (var x2 = 0; x2 < patches.length; x2++) { var expected_loc = patches[x2].start2 + delta; var text1 = this.diff_text1(patches[x2].diffs); var start_loc; var end_loc = -1; if (text1.length > this.Match_MaxBits) { start_loc = this.match_main( text3, text1.substring(0, this.Match_MaxBits), expected_loc ); if (start_loc != -1) { end_loc = this.match_main( text3, text1.substring(text1.length - this.Match_MaxBits), expected_loc + text1.length - this.Match_MaxBits ); if (end_loc == -1 || start_loc >= end_loc) { start_loc = -1; } } } else { start_loc = this.match_main(text3, text1, expected_loc); } if (start_loc == -1) { results[x2] = false; delta -= patches[x2].length2 - patches[x2].length1; } else { results[x2] = true; delta = start_loc - expected_loc; var text22; if (end_loc == -1) { text22 = text3.substring(start_loc, start_loc + text1.length); } else { text22 = text3.substring(start_loc, end_loc + this.Match_MaxBits); } if (text1 == text22) { text3 = text3.substring(0, start_loc) + this.diff_text2(patches[x2].diffs) + text3.substring(start_loc + text1.length); } else { var diffs = this.diff_main(text1, text22, false); if (text1.length > this.Match_MaxBits && this.diff_levenshtein(diffs) / text1.length > this.Patch_DeleteThreshold) { results[x2] = false; } else { this.diff_cleanupSemanticLossless(diffs); var index1 = 0; var index2; for (var y3 = 0; y3 < patches[x2].diffs.length; y3++) { var mod = patches[x2].diffs[y3]; if (mod[0] !== DIFF_EQUAL) { index2 = this.diff_xIndex(diffs, index1); } if (mod[0] === DIFF_INSERT2) { text3 = text3.substring(0, start_loc + index2) + mod[1] + text3.substring(start_loc + index2); } else if (mod[0] === DIFF_DELETE2) { text3 = text3.substring(0, start_loc + index2) + text3.substring(start_loc + this.diff_xIndex( diffs, index1 + mod[1].length )); } if (mod[0] !== DIFF_DELETE2) { index1 += mod[1].length; } } } } } } text3 = text3.substring(nullPadding.length, text3.length - nullPadding.length); return [text3, results]; }; diff_match_patch2.prototype.patch_addPadding = function(patches) { var paddingLength = this.Patch_Margin; var nullPadding = ""; for (var x2 = 1; x2 <= paddingLength; x2++) { nullPadding += String.fromCharCode(x2); } for (var x2 = 0; x2 < patches.length; x2++) { patches[x2].start1 += paddingLength; patches[x2].start2 += paddingLength; } var patch = patches[0]; var diffs = patch.diffs; if (diffs.length == 0 || diffs[0][0] != DIFF_EQUAL) { diffs.unshift(new diff_match_patch2.Diff(DIFF_EQUAL, nullPadding)); patch.start1 -= paddingLength; patch.start2 -= paddingLength; patch.length1 += paddingLength; patch.length2 += paddingLength; } else if (paddingLength > diffs[0][1].length) { var extraLength = paddingLength - diffs[0][1].length; diffs[0][1] = nullPadding.substring(diffs[0][1].length) + diffs[0][1]; patch.start1 -= extraLength; patch.start2 -= extraLength; patch.length1 += extraLength; patch.length2 += extraLength; } patch = patches[patches.length - 1]; diffs = patch.diffs; if (diffs.length == 0 || diffs[diffs.length - 1][0] != DIFF_EQUAL) { diffs.push(new diff_match_patch2.Diff(DIFF_EQUAL, nullPadding)); patch.length1 += paddingLength; patch.length2 += paddingLength; } else if (paddingLength > diffs[diffs.length - 1][1].length) { var extraLength = paddingLength - diffs[diffs.length - 1][1].length; diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength); patch.length1 += extraLength; patch.length2 += extraLength; } return nullPadding; }; diff_match_patch2.prototype.patch_splitMax = function(patches) { var patch_size = this.Match_MaxBits; for (var x2 = 0; x2 < patches.length; x2++) { if (patches[x2].length1 <= patch_size) { continue; } var bigpatch = patches[x2]; patches.splice(x2--, 1); var start1 = bigpatch.start1; var start2 = bigpatch.start2; var precontext = ""; while (bigpatch.diffs.length !== 0) { var patch = new diff_match_patch2.patch_obj(); var empty = true; patch.start1 = start1 - precontext.length; patch.start2 = start2 - precontext.length; if (precontext !== "") { patch.length1 = patch.length2 = precontext.length; patch.diffs.push(new diff_match_patch2.Diff(DIFF_EQUAL, precontext)); } while (bigpatch.diffs.length !== 0 && patch.length1 < patch_size - this.Patch_Margin) { var diff_type = bigpatch.diffs[0][0]; var diff_text = bigpatch.diffs[0][1]; if (diff_type === DIFF_INSERT2) { patch.length2 += diff_text.length; start2 += diff_text.length; patch.diffs.push(bigpatch.diffs.shift()); empty = false; } else if (diff_type === DIFF_DELETE2 && patch.diffs.length == 1 && patch.diffs[0][0] == DIFF_EQUAL && diff_text.length > 2 * patch_size) { patch.length1 += diff_text.length; start1 += diff_text.length; empty = false; patch.diffs.push(new diff_match_patch2.Diff(diff_type, diff_text)); bigpatch.diffs.shift(); } else { diff_text = diff_text.substring( 0, patch_size - patch.length1 - this.Patch_Margin ); patch.length1 += diff_text.length; start1 += diff_text.length; if (diff_type === DIFF_EQUAL) { patch.length2 += diff_text.length; start2 += diff_text.length; } else { empty = false; } patch.diffs.push(new diff_match_patch2.Diff(diff_type, diff_text)); if (diff_text == bigpatch.diffs[0][1]) { bigpatch.diffs.shift(); } else { bigpatch.diffs[0][1] = bigpatch.diffs[0][1].substring(diff_text.length); } } } precontext = this.diff_text2(patch.diffs); precontext = precontext.substring(precontext.length - this.Patch_Margin); var postcontext = this.diff_text1(bigpatch.diffs).substring(0, this.Patch_Margin); if (postcontext !== "") { patch.length1 += postcontext.length; patch.length2 += postcontext.length; if (patch.diffs.length !== 0 && patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL) { patch.diffs[patch.diffs.length - 1][1] += postcontext; } else { patch.diffs.push(new diff_match_patch2.Diff(DIFF_EQUAL, postcontext)); } } if (!empty) { patches.splice(++x2, 0, patch); } } } }; diff_match_patch2.prototype.patch_toText = function(patches) { var text3 = []; for (var x2 = 0; x2 < patches.length; x2++) { text3[x2] = patches[x2]; } return text3.join(""); }; diff_match_patch2.prototype.patch_fromText = function(textline) { var patches = []; if (!textline) { return patches; } var text3 = textline.split("\n"); var textPointer = 0; var patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/; while (textPointer < text3.length) { var m3 = text3[textPointer].match(patchHeader); if (!m3) { throw new Error("Invalid patch string: " + text3[textPointer]); } var patch = new diff_match_patch2.patch_obj(); patches.push(patch); patch.start1 = parseInt(m3[1], 10); if (m3[2] === "") { patch.start1--; patch.length1 = 1; } else if (m3[2] == "0") { patch.length1 = 0; } else { patch.start1--; patch.length1 = parseInt(m3[2], 10); } patch.start2 = parseInt(m3[3], 10); if (m3[4] === "") { patch.start2--; patch.length2 = 1; } else if (m3[4] == "0") { patch.length2 = 0; } else { patch.start2--; patch.length2 = parseInt(m3[4], 10); } textPointer++; while (textPointer < text3.length) { var sign = text3[textPointer].charAt(0); try { var line = decodeURI(text3[textPointer].substring(1)); } catch (ex) { throw new Error("Illegal escape in patch_fromText: " + line); } if (sign == "-") { patch.diffs.push(new diff_match_patch2.Diff(DIFF_DELETE2, line)); } else if (sign == "+") { patch.diffs.push(new diff_match_patch2.Diff(DIFF_INSERT2, line)); } else if (sign == " ") { patch.diffs.push(new diff_match_patch2.Diff(DIFF_EQUAL, line)); } else if (sign == "@") { break; } else if (sign === "") { } else { throw new Error('Invalid patch mode "' + sign + '" in: ' + line); } textPointer++; } } return patches; }; diff_match_patch2.patch_obj = function() { this.diffs = []; this.start1 = null; this.start2 = null; this.length1 = 0; this.length2 = 0; }; diff_match_patch2.patch_obj.prototype.toString = function() { var coords1, coords2; if (this.length1 === 0) { coords1 = this.start1 + ",0"; } else if (this.length1 == 1) { coords1 = this.start1 + 1; } else { coords1 = this.start1 + 1 + "," + this.length1; } if (this.length2 === 0) { coords2 = this.start2 + ",0"; } else if (this.length2 == 1) { coords2 = this.start2 + 1; } else { coords2 = this.start2 + 1 + "," + this.length2; } var text3 = ["@@ -" + coords1 + " +" + coords2 + " @@\n"]; var op; for (var x2 = 0; x2 < this.diffs.length; x2++) { switch (this.diffs[x2][0]) { case DIFF_INSERT2: op = "+"; break; case DIFF_DELETE2: op = "-"; break; case DIFF_EQUAL: op = " "; break; } text3[x2 + 1] = op + encodeURI(this.diffs[x2][1]) + "\n"; } return text3.join("").replace(/%20/g, " "); }; module2.exports = diff_match_patch2; module2.exports["diff_match_patch"] = diff_match_patch2; module2.exports["DIFF_DELETE"] = DIFF_DELETE2; module2.exports["DIFF_INSERT"] = DIFF_INSERT2; module2.exports["DIFF_EQUAL"] = DIFF_EQUAL; } }); // node_modules/recast/node_modules/tslib/tslib.es6.mjs var tslib_es6_exports = {}; __export(tslib_es6_exports, { __addDisposableResource: () => __addDisposableResource, __assign: () => __assign, __asyncDelegator: () => __asyncDelegator, __asyncGenerator: () => __asyncGenerator, __asyncValues: () => __asyncValues, __await: () => __await, __awaiter: () => __awaiter, __classPrivateFieldGet: () => __classPrivateFieldGet, __classPrivateFieldIn: () => __classPrivateFieldIn, __classPrivateFieldSet: () => __classPrivateFieldSet, __createBinding: () => __createBinding, __decorate: () => __decorate, __disposeResources: () => __disposeResources, __esDecorate: () => __esDecorate, __exportStar: () => __exportStar, __extends: () => __extends, __generator: () => __generator, __importDefault: () => __importDefault, __importStar: () => __importStar, __makeTemplateObject: () => __makeTemplateObject, __metadata: () => __metadata, __param: () => __param, __propKey: () => __propKey, __read: () => __read, __rest: () => __rest, __runInitializers: () => __runInitializers, __setFunctionName: () => __setFunctionName, __spread: () => __spread, __spreadArray: () => __spreadArray, __spreadArrays: () => __spreadArrays, __values: () => __values, default: () => tslib_es6_default }); function __extends(d3, b2) { if (typeof b2 !== "function" && b2 !== null) throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null"); extendStatics(d3, b2); function __() { this.constructor = d3; } d3.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __()); } function __rest(s3, e2) { var t2 = {}; for (var p in s3) if (Object.prototype.hasOwnProperty.call(s3, p) && e2.indexOf(p) < 0) t2[p] = s3[p]; if (s3 != null && typeof Object.getOwnPropertySymbols === "function") for (var i2 = 0, p = Object.getOwnPropertySymbols(s3); i2 < p.length; i2++) { if (e2.indexOf(p[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s3, p[i2])) t2[p[i2]] = s3[p[i2]]; } return t2; } function __decorate(decorators, target, key, desc) { var c2 = arguments.length, r = c2 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d3; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i2 = decorators.length - 1; i2 >= 0; i2--) if (d3 = decorators[i2]) r = (c2 < 3 ? d3(r) : c2 > 3 ? d3(target, key, r) : d3(target, key)) || r; return c2 > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function(target, key) { decorator(target, key, paramIndex); }; } function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); var _, done = false; for (var i2 = decorators.length - 1; i2 >= 0; i2--) { var context = {}; for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; for (var p in contextIn.access) context.access[p] = contextIn.access[p]; context.addInitializer = function(f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; var result = (0, decorators[i2])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); if (kind === "accessor") { if (result === void 0) continue; if (result === null || typeof result !== "object") throw new TypeError("Object expected"); if (_ = accept(result.get)) descriptor.get = _; if (_ = accept(result.set)) descriptor.set = _; if (_ = accept(result.init)) initializers.unshift(_); } else if (_ = accept(result)) { if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; } function __runInitializers(thisArg, initializers, value) { var useValue = arguments.length > 2; for (var i2 = 0; i2 < initializers.length; i2++) { value = useValue ? initializers[i2].call(thisArg, value) : initializers[i2].call(thisArg); } return useValue ? value : void 0; } function __propKey(x2) { return typeof x2 === "symbol" ? x2 : "".concat(x2); } function __setFunctionName(f, name, prefix) { if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve) { resolve(value); }); } return new (P || (P = Promise))(function(resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e2) { reject(e2); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e2) { reject(e2); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t2[0] & 1) throw t2[1]; return t2[1]; }, trys: [], ops: [] }, f, y3, t2, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function(v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y3 && (t2 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t2 = y3["return"]) && t2.call(y3), 0) : y3.next) && !(t2 = t2.call(y3, op[1])).done) return t2; if (y3 = 0, t2) op = [op[0] & 2, t2.value]; switch (op[0]) { case 0: case 1: t2 = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y3 = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t2 = _.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t2[1]) { _.label = t2[1]; t2 = op; break; } if (t2 && _.label < t2[2]) { _.label = t2[2]; _.ops.push(op); break; } if (t2[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e2) { op = [6, e2]; y3 = 0; } finally { f = t2 = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __exportStar(m3, o) { for (var p in m3) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m3, p); } function __values(o) { var s3 = typeof Symbol === "function" && Symbol.iterator, m3 = s3 && o[s3], i2 = 0; if (m3) return m3.call(o); if (o && typeof o.length === "number") return { next: function() { if (o && i2 >= o.length) o = void 0; return { value: o && o[i2++], done: !o }; } }; throw new TypeError(s3 ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m3 = typeof Symbol === "function" && o[Symbol.iterator]; if (!m3) return o; var i2 = m3.call(o), r, ar = [], e2; try { while ((n === void 0 || n-- > 0) && !(r = i2.next()).done) ar.push(r.value); } catch (error) { e2 = { error }; } finally { try { if (r && !r.done && (m3 = i2["return"])) m3.call(i2); } finally { if (e2) throw e2.error; } } return ar; } function __spread() { for (var ar = [], i2 = 0; i2 < arguments.length; i2++) ar = ar.concat(__read(arguments[i2])); return ar; } function __spreadArrays() { for (var s3 = 0, i2 = 0, il = arguments.length; i2 < il; i2++) s3 += arguments[i2].length; for (var r = Array(s3), k2 = 0, i2 = 0; i2 < il; i2++) for (var a3 = arguments[i2], j = 0, jl = a3.length; j < jl; j++, k2++) r[k2] = a3[j]; return r; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i2 = 0, l = from.length, ar; i2 < l; i2++) { if (ar || !(i2 in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i2); ar[i2] = from[i2]; } } return to.concat(ar || Array.prototype.slice.call(from)); } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i2, q2 = []; return i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() { return this; }, i2; function verb(n) { if (g[n]) i2[n] = function(v) { return new Promise(function(a3, b2) { q2.push([n, v, a3, b2]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e2) { settle(q2[0][3], e2); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q2[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q2.shift(), q2.length) resume(q2[0][0], q2[0][1]); } } function __asyncDelegator(o) { var i2, p; return i2 = {}, verb("next"), verb("throw", function(e2) { throw e2; }), verb("return"), i2[Symbol.iterator] = function() { return this; }, i2; function verb(n, f) { i2[n] = o[n] ? function(v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m3 = o[Symbol.asyncIterator], i2; return m3 ? m3.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() { return this; }, i2); function verb(n) { i2[n] = o[n] && function(v) { return new Promise(function(resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d3, v) { Promise.resolve(v).then(function(v2) { resolve({ value: v2, done: d3 }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k2 in mod) if (k2 !== "default" && Object.prototype.hasOwnProperty.call(mod, k2)) __createBinding(result, mod, k2); } __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return mod && mod.__esModule ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; } function __classPrivateFieldIn(state, receiver) { if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); return typeof state === "function" ? receiver === state : state.has(receiver); } function __addDisposableResource(env, value, async) { if (value !== null && value !== void 0) { if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); var dispose; if (async) { if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); dispose = value[Symbol.asyncDispose]; } if (dispose === void 0) { if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); dispose = value[Symbol.dispose]; } if (typeof dispose !== "function") throw new TypeError("Object not disposable."); env.stack.push({ value, dispose, async }); } else if (async) { env.stack.push({ async: true }); } return value; } function __disposeResources(env) { function fail(e2) { env.error = env.hasError ? new _SuppressedError(e2, env.error, "An error was suppressed during disposal.") : e2; env.hasError = true; } function next() { while (env.stack.length) { var rec = env.stack.pop(); try { var result = rec.dispose && rec.dispose.call(rec.value); if (rec.async) return Promise.resolve(result).then(next, function(e2) { fail(e2); return next(); }); } catch (e2) { fail(e2); } } if (env.hasError) throw env.error; } return next(); } var extendStatics, __assign, __createBinding, __setModuleDefault, _SuppressedError, tslib_es6_default; var init_tslib_es6 = __esm({ "node_modules/recast/node_modules/tslib/tslib.es6.mjs"() { extendStatics = function(d3, b2) { extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b3) { d4.__proto__ = b3; } || function(d4, b3) { for (var p in b3) if (Object.prototype.hasOwnProperty.call(b3, p)) d4[p] = b3[p]; }; return extendStatics(d3, b2); }; __assign = function() { __assign = Object.assign || function __assign3(t2) { for (var s3, i2 = 1, n = arguments.length; i2 < n; i2++) { s3 = arguments[i2]; for (var p in s3) if (Object.prototype.hasOwnProperty.call(s3, p)) t2[p] = s3[p]; } return t2; }; return __assign.apply(this, arguments); }; __createBinding = Object.create ? function(o, m3, k2, k22) { if (k22 === void 0) k22 = k2; var desc = Object.getOwnPropertyDescriptor(m3, k2); if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m3[k2]; } }; } Object.defineProperty(o, k22, desc); } : function(o, m3, k2, k22) { if (k22 === void 0) k22 = k2; o[k22] = m3[k2]; }; __setModuleDefault = Object.create ? function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); } : function(o, v) { o["default"] = v; }; _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) { var e2 = new Error(message); return e2.name = "SuppressedError", e2.error = error, e2.suppressed = suppressed, e2; }; tslib_es6_default = { __extends, __assign, __rest, __decorate, __param, __metadata, __awaiter, __generator, __createBinding, __exportStar, __values, __read, __spread, __spreadArrays, __spreadArray, __await, __asyncGenerator, __asyncDelegator, __asyncValues, __makeTemplateObject, __importStar, __importDefault, __classPrivateFieldGet, __classPrivateFieldSet, __classPrivateFieldIn, __addDisposableResource, __disposeResources }; } }); // node_modules/ast-types/node_modules/tslib/tslib.es6.mjs var tslib_es6_exports2 = {}; __export(tslib_es6_exports2, { __addDisposableResource: () => __addDisposableResource2, __assign: () => __assign2, __asyncDelegator: () => __asyncDelegator2, __asyncGenerator: () => __asyncGenerator2, __asyncValues: () => __asyncValues2, __await: () => __await2, __awaiter: () => __awaiter2, __classPrivateFieldGet: () => __classPrivateFieldGet2, __classPrivateFieldIn: () => __classPrivateFieldIn2, __classPrivateFieldSet: () => __classPrivateFieldSet2, __createBinding: () => __createBinding2, __decorate: () => __decorate2, __disposeResources: () => __disposeResources2, __esDecorate: () => __esDecorate2, __exportStar: () => __exportStar2, __extends: () => __extends2, __generator: () => __generator2, __importDefault: () => __importDefault2, __importStar: () => __importStar2, __makeTemplateObject: () => __makeTemplateObject2, __metadata: () => __metadata2, __param: () => __param2, __propKey: () => __propKey2, __read: () => __read2, __rest: () => __rest2, __runInitializers: () => __runInitializers2, __setFunctionName: () => __setFunctionName2, __spread: () => __spread2, __spreadArray: () => __spreadArray2, __spreadArrays: () => __spreadArrays2, __values: () => __values2, default: () => tslib_es6_default2 }); function __extends2(d3, b2) { if (typeof b2 !== "function" && b2 !== null) throw new TypeError("Class extends value " + String(b2) + " is not a constructor or null"); extendStatics2(d3, b2); function __() { this.constructor = d3; } d3.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __()); } function __rest2(s3, e2) { var t2 = {}; for (var p in s3) if (Object.prototype.hasOwnProperty.call(s3, p) && e2.indexOf(p) < 0) t2[p] = s3[p]; if (s3 != null && typeof Object.getOwnPropertySymbols === "function") for (var i2 = 0, p = Object.getOwnPropertySymbols(s3); i2 < p.length; i2++) { if (e2.indexOf(p[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s3, p[i2])) t2[p[i2]] = s3[p[i2]]; } return t2; } function __decorate2(decorators, target, key, desc) { var c2 = arguments.length, r = c2 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d3; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i2 = decorators.length - 1; i2 >= 0; i2--) if (d3 = decorators[i2]) r = (c2 < 3 ? d3(r) : c2 > 3 ? d3(target, key, r) : d3(target, key)) || r; return c2 > 3 && r && Object.defineProperty(target, key, r), r; } function __param2(paramIndex, decorator) { return function(target, key) { decorator(target, key, paramIndex); }; } function __esDecorate2(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); var _, done = false; for (var i2 = decorators.length - 1; i2 >= 0; i2--) { var context = {}; for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; for (var p in contextIn.access) context.access[p] = contextIn.access[p]; context.addInitializer = function(f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; var result = (0, decorators[i2])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); if (kind === "accessor") { if (result === void 0) continue; if (result === null || typeof result !== "object") throw new TypeError("Object expected"); if (_ = accept(result.get)) descriptor.get = _; if (_ = accept(result.set)) descriptor.set = _; if (_ = accept(result.init)) initializers.unshift(_); } else if (_ = accept(result)) { if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; } function __runInitializers2(thisArg, initializers, value) { var useValue = arguments.length > 2; for (var i2 = 0; i2 < initializers.length; i2++) { value = useValue ? initializers[i2].call(thisArg, value) : initializers[i2].call(thisArg); } return useValue ? value : void 0; } function __propKey2(x2) { return typeof x2 === "symbol" ? x2 : "".concat(x2); } function __setFunctionName2(f, name, prefix) { if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); } function __metadata2(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter2(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve) { resolve(value); }); } return new (P || (P = Promise))(function(resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e2) { reject(e2); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e2) { reject(e2); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator2(thisArg, body) { var _ = { label: 0, sent: function() { if (t2[0] & 1) throw t2[1]; return t2[1]; }, trys: [], ops: [] }, f, y3, t2, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function(v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y3 && (t2 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t2 = y3["return"]) && t2.call(y3), 0) : y3.next) && !(t2 = t2.call(y3, op[1])).done) return t2; if (y3 = 0, t2) op = [op[0] & 2, t2.value]; switch (op[0]) { case 0: case 1: t2 = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y3 = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t2 = _.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t2[1]) { _.label = t2[1]; t2 = op; break; } if (t2 && _.label < t2[2]) { _.label = t2[2]; _.ops.push(op); break; } if (t2[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e2) { op = [6, e2]; y3 = 0; } finally { f = t2 = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __exportStar2(m3, o) { for (var p in m3) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding2(o, m3, p); } function __values2(o) { var s3 = typeof Symbol === "function" && Symbol.iterator, m3 = s3 && o[s3], i2 = 0; if (m3) return m3.call(o); if (o && typeof o.length === "number") return { next: function() { if (o && i2 >= o.length) o = void 0; return { value: o && o[i2++], done: !o }; } }; throw new TypeError(s3 ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read2(o, n) { var m3 = typeof Symbol === "function" && o[Symbol.iterator]; if (!m3) return o; var i2 = m3.call(o), r, ar = [], e2; try { while ((n === void 0 || n-- > 0) && !(r = i2.next()).done) ar.push(r.value); } catch (error) { e2 = { error }; } finally { try { if (r && !r.done && (m3 = i2["return"])) m3.call(i2); } finally { if (e2) throw e2.error; } } return ar; } function __spread2() { for (var ar = [], i2 = 0; i2 < arguments.length; i2++) ar = ar.concat(__read2(arguments[i2])); return ar; } function __spreadArrays2() { for (var s3 = 0, i2 = 0, il = arguments.length; i2 < il; i2++) s3 += arguments[i2].length; for (var r = Array(s3), k2 = 0, i2 = 0; i2 < il; i2++) for (var a3 = arguments[i2], j = 0, jl = a3.length; j < jl; j++, k2++) r[k2] = a3[j]; return r; } function __spreadArray2(to, from, pack) { if (pack || arguments.length === 2) for (var i2 = 0, l = from.length, ar; i2 < l; i2++) { if (ar || !(i2 in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i2); ar[i2] = from[i2]; } } return to.concat(ar || Array.prototype.slice.call(from)); } function __await2(v) { return this instanceof __await2 ? (this.v = v, this) : new __await2(v); } function __asyncGenerator2(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i2, q2 = []; return i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() { return this; }, i2; function verb(n) { if (g[n]) i2[n] = function(v) { return new Promise(function(a3, b2) { q2.push([n, v, a3, b2]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e2) { settle(q2[0][3], e2); } } function step(r) { r.value instanceof __await2 ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q2[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q2.shift(), q2.length) resume(q2[0][0], q2[0][1]); } } function __asyncDelegator2(o) { var i2, p; return i2 = {}, verb("next"), verb("throw", function(e2) { throw e2; }), verb("return"), i2[Symbol.iterator] = function() { return this; }, i2; function verb(n, f) { i2[n] = o[n] ? function(v) { return (p = !p) ? { value: __await2(o[n](v)), done: false } : f ? f(v) : v; } : f; } } function __asyncValues2(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m3 = o[Symbol.asyncIterator], i2; return m3 ? m3.call(o) : (o = typeof __values2 === "function" ? __values2(o) : o[Symbol.iterator](), i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() { return this; }, i2); function verb(n) { i2[n] = o[n] && function(v) { return new Promise(function(resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d3, v) { Promise.resolve(v).then(function(v2) { resolve({ value: v2, done: d3 }); }, reject); } } function __makeTemplateObject2(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } function __importStar2(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k2 in mod) if (k2 !== "default" && Object.prototype.hasOwnProperty.call(mod, k2)) __createBinding2(result, mod, k2); } __setModuleDefault2(result, mod); return result; } function __importDefault2(mod) { return mod && mod.__esModule ? mod : { default: mod }; } function __classPrivateFieldGet2(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet2(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; } function __classPrivateFieldIn2(state, receiver) { if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); return typeof state === "function" ? receiver === state : state.has(receiver); } function __addDisposableResource2(env, value, async) { if (value !== null && value !== void 0) { if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); var dispose; if (async) { if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); dispose = value[Symbol.asyncDispose]; } if (dispose === void 0) { if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); dispose = value[Symbol.dispose]; } if (typeof dispose !== "function") throw new TypeError("Object not disposable."); env.stack.push({ value, dispose, async }); } else if (async) { env.stack.push({ async: true }); } return value; } function __disposeResources2(env) { function fail(e2) { env.error = env.hasError ? new _SuppressedError2(e2, env.error, "An error was suppressed during disposal.") : e2; env.hasError = true; } function next() { while (env.stack.length) { var rec = env.stack.pop(); try { var result = rec.dispose && rec.dispose.call(rec.value); if (rec.async) return Promise.resolve(result).then(next, function(e2) { fail(e2); return next(); }); } catch (e2) { fail(e2); } } if (env.hasError) throw env.error; } return next(); } var extendStatics2, __assign2, __createBinding2, __setModuleDefault2, _SuppressedError2, tslib_es6_default2; var init_tslib_es62 = __esm({ "node_modules/ast-types/node_modules/tslib/tslib.es6.mjs"() { extendStatics2 = function(d3, b2) { extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b3) { d4.__proto__ = b3; } || function(d4, b3) { for (var p in b3) if (Object.prototype.hasOwnProperty.call(b3, p)) d4[p] = b3[p]; }; return extendStatics2(d3, b2); }; __assign2 = function() { __assign2 = Object.assign || function __assign3(t2) { for (var s3, i2 = 1, n = arguments.length; i2 < n; i2++) { s3 = arguments[i2]; for (var p in s3) if (Object.prototype.hasOwnProperty.call(s3, p)) t2[p] = s3[p]; } return t2; }; return __assign2.apply(this, arguments); }; __createBinding2 = Object.create ? function(o, m3, k2, k22) { if (k22 === void 0) k22 = k2; var desc = Object.getOwnPropertyDescriptor(m3, k2); if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m3[k2]; } }; } Object.defineProperty(o, k22, desc); } : function(o, m3, k2, k22) { if (k22 === void 0) k22 = k2; o[k22] = m3[k2]; }; __setModuleDefault2 = Object.create ? function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); } : function(o, v) { o["default"] = v; }; _SuppressedError2 = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) { var e2 = new Error(message); return e2.name = "SuppressedError", e2.error = error, e2.suppressed = suppressed, e2; }; tslib_es6_default2 = { __extends: __extends2, __assign: __assign2, __rest: __rest2, __decorate: __decorate2, __param: __param2, __metadata: __metadata2, __awaiter: __awaiter2, __generator: __generator2, __createBinding: __createBinding2, __exportStar: __exportStar2, __values: __values2, __read: __read2, __spread: __spread2, __spreadArrays: __spreadArrays2, __spreadArray: __spreadArray2, __await: __await2, __asyncGenerator: __asyncGenerator2, __asyncDelegator: __asyncDelegator2, __asyncValues: __asyncValues2, __makeTemplateObject: __makeTemplateObject2, __importStar: __importStar2, __importDefault: __importDefault2, __classPrivateFieldGet: __classPrivateFieldGet2, __classPrivateFieldSet: __classPrivateFieldSet2, __classPrivateFieldIn: __classPrivateFieldIn2, __addDisposableResource: __addDisposableResource2, __disposeResources: __disposeResources2 }; } }); // node_modules/ast-types/lib/shared.js var require_shared = __commonJS({ "node_modules/ast-types/lib/shared.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.maybeSetModuleExports = void 0; var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var types_1 = tslib_1.__importDefault(require_types()); function default_1(fork) { var types = fork.use(types_1.default); var Type = types.Type; var builtin = types.builtInTypes; var isNumber = builtin.number; function geq(than) { return Type.from(function(value) { return isNumber.check(value) && value >= than; }, isNumber + " >= " + than); } ; var defaults = { // Functions were used because (among other reasons) that's the most // elegant way to allow for the emptyArray one always to give a new // array instance. "null": function() { return null; }, "emptyArray": function() { return []; }, "false": function() { return false; }, "true": function() { return true; }, "undefined": function() { }, "use strict": function() { return "use strict"; } }; var naiveIsPrimitive = Type.or(builtin.string, builtin.number, builtin.boolean, builtin.null, builtin.undefined); var isPrimitive = Type.from(function(value) { if (value === null) return true; var type2 = typeof value; if (type2 === "object" || type2 === "function") { return false; } return true; }, naiveIsPrimitive.toString()); return { geq, defaults, isPrimitive }; } exports.default = default_1; function maybeSetModuleExports(moduleGetter) { try { var nodeModule = moduleGetter(); var originalExports = nodeModule.exports; var defaultExport = originalExports["default"]; } catch (_a) { return; } if (defaultExport && defaultExport !== originalExports && typeof originalExports === "object") { Object.assign(defaultExport, originalExports, { "default": defaultExport }); if (originalExports.__esModule) { Object.defineProperty(defaultExport, "__esModule", { value: true }); } nodeModule.exports = defaultExport; } } exports.maybeSetModuleExports = maybeSetModuleExports; } }); // node_modules/ast-types/lib/types.js var require_types = __commonJS({ "node_modules/ast-types/lib/types.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Def = void 0; var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var shared_1 = require_shared(); var Op = Object.prototype; var objToStr = Op.toString; var hasOwn = Op.hasOwnProperty; var BaseType = ( /** @class */ function() { function BaseType2() { } BaseType2.prototype.assert = function(value, deep) { if (!this.check(value, deep)) { var str2 = shallowStringify(value); throw new Error(str2 + " does not match type " + this); } return true; }; BaseType2.prototype.arrayOf = function() { var elemType = this; return new ArrayType(elemType); }; return BaseType2; }() ); var ArrayType = ( /** @class */ function(_super) { tslib_1.__extends(ArrayType2, _super); function ArrayType2(elemType) { var _this = _super.call(this) || this; _this.elemType = elemType; _this.kind = "ArrayType"; return _this; } ArrayType2.prototype.toString = function() { return "[" + this.elemType + "]"; }; ArrayType2.prototype.check = function(value, deep) { var _this = this; return Array.isArray(value) && value.every(function(elem) { return _this.elemType.check(elem, deep); }); }; return ArrayType2; }(BaseType) ); var IdentityType = ( /** @class */ function(_super) { tslib_1.__extends(IdentityType2, _super); function IdentityType2(value) { var _this = _super.call(this) || this; _this.value = value; _this.kind = "IdentityType"; return _this; } IdentityType2.prototype.toString = function() { return String(this.value); }; IdentityType2.prototype.check = function(value, deep) { var result = value === this.value; if (!result && typeof deep === "function") { deep(this, value); } return result; }; return IdentityType2; }(BaseType) ); var ObjectType = ( /** @class */ function(_super) { tslib_1.__extends(ObjectType2, _super); function ObjectType2(fields) { var _this = _super.call(this) || this; _this.fields = fields; _this.kind = "ObjectType"; return _this; } ObjectType2.prototype.toString = function() { return "{ " + this.fields.join(", ") + " }"; }; ObjectType2.prototype.check = function(value, deep) { return objToStr.call(value) === objToStr.call({}) && this.fields.every(function(field) { return field.type.check(value[field.name], deep); }); }; return ObjectType2; }(BaseType) ); var OrType = ( /** @class */ function(_super) { tslib_1.__extends(OrType2, _super); function OrType2(types) { var _this = _super.call(this) || this; _this.types = types; _this.kind = "OrType"; return _this; } OrType2.prototype.toString = function() { return this.types.join(" | "); }; OrType2.prototype.check = function(value, deep) { if (this.types.some(function(type2) { return type2.check(value, !!deep); })) { return true; } if (typeof deep === "function") { deep(this, value); } return false; }; return OrType2; }(BaseType) ); var PredicateType = ( /** @class */ function(_super) { tslib_1.__extends(PredicateType2, _super); function PredicateType2(name, predicate) { var _this = _super.call(this) || this; _this.name = name; _this.predicate = predicate; _this.kind = "PredicateType"; return _this; } PredicateType2.prototype.toString = function() { return this.name; }; PredicateType2.prototype.check = function(value, deep) { var result = this.predicate(value, deep); if (!result && typeof deep === "function") { deep(this, value); } return result; }; return PredicateType2; }(BaseType) ); var Def = ( /** @class */ function() { function Def2(type2, typeName) { this.type = type2; this.typeName = typeName; this.baseNames = []; this.ownFields = /* @__PURE__ */ Object.create(null); this.allSupertypes = /* @__PURE__ */ Object.create(null); this.supertypeList = []; this.allFields = /* @__PURE__ */ Object.create(null); this.fieldNames = []; this.finalized = false; this.buildable = false; this.buildParams = []; } Def2.prototype.isSupertypeOf = function(that) { if (that instanceof Def2) { if (this.finalized !== true || that.finalized !== true) { throw new Error(""); } return hasOwn.call(that.allSupertypes, this.typeName); } else { throw new Error(that + " is not a Def"); } }; Def2.prototype.checkAllFields = function(value, deep) { var allFields = this.allFields; if (this.finalized !== true) { throw new Error("" + this.typeName); } function checkFieldByName(name) { var field = allFields[name]; var type2 = field.type; var child = field.getValue(value); return type2.check(child, deep); } return value !== null && typeof value === "object" && Object.keys(allFields).every(checkFieldByName); }; Def2.prototype.bases = function() { var supertypeNames = []; for (var _i = 0; _i < arguments.length; _i++) { supertypeNames[_i] = arguments[_i]; } var bases = this.baseNames; if (this.finalized) { if (supertypeNames.length !== bases.length) { throw new Error(""); } for (var i2 = 0; i2 < supertypeNames.length; i2++) { if (supertypeNames[i2] !== bases[i2]) { throw new Error(""); } } return this; } supertypeNames.forEach(function(baseName) { if (bases.indexOf(baseName) < 0) { bases.push(baseName); } }); return this; }; return Def2; }() ); exports.Def = Def; var Field = ( /** @class */ function() { function Field2(name, type2, defaultFn, hidden) { this.name = name; this.type = type2; this.defaultFn = defaultFn; this.hidden = !!hidden; } Field2.prototype.toString = function() { return JSON.stringify(this.name) + ": " + this.type; }; Field2.prototype.getValue = function(obj) { var value = obj[this.name]; if (typeof value !== "undefined") { return value; } if (typeof this.defaultFn === "function") { value = this.defaultFn.call(obj); } return value; }; return Field2; }() ); function shallowStringify(value) { if (Array.isArray(value)) { return "[" + value.map(shallowStringify).join(", ") + "]"; } if (value && typeof value === "object") { return "{ " + Object.keys(value).map(function(key) { return key + ": " + value[key]; }).join(", ") + " }"; } return JSON.stringify(value); } function typesPlugin(_fork) { var Type = { or: function() { var types = []; for (var _i = 0; _i < arguments.length; _i++) { types[_i] = arguments[_i]; } return new OrType(types.map(function(type2) { return Type.from(type2); })); }, from: function(value, name) { if (value instanceof ArrayType || value instanceof IdentityType || value instanceof ObjectType || value instanceof OrType || value instanceof PredicateType) { return value; } if (value instanceof Def) { return value.type; } if (isArray.check(value)) { if (value.length !== 1) { throw new Error("only one element type is permitted for typed arrays"); } return new ArrayType(Type.from(value[0])); } if (isObject2.check(value)) { return new ObjectType(Object.keys(value).map(function(name2) { return new Field(name2, Type.from(value[name2], name2)); })); } if (typeof value === "function") { var bicfIndex = builtInCtorFns.indexOf(value); if (bicfIndex >= 0) { return builtInCtorTypes[bicfIndex]; } if (typeof name !== "string") { throw new Error("missing name"); } return new PredicateType(name, value); } return new IdentityType(value); }, // Define a type whose name is registered in a namespace (the defCache) so // that future definitions will return the same type given the same name. // In particular, this system allows for circular and forward definitions. // The Def object d returned from Type.def may be used to configure the // type d.type by calling methods such as d.bases, d.build, and d.field. def: function(typeName) { return hasOwn.call(defCache, typeName) ? defCache[typeName] : defCache[typeName] = new DefImpl(typeName); }, hasDef: function(typeName) { return hasOwn.call(defCache, typeName); } }; var builtInCtorFns = []; var builtInCtorTypes = []; function defBuiltInType(name, example) { var objStr = objToStr.call(example); var type2 = new PredicateType(name, function(value) { return objToStr.call(value) === objStr; }); if (example && typeof example.constructor === "function") { builtInCtorFns.push(example.constructor); builtInCtorTypes.push(type2); } return type2; } var isString = defBuiltInType("string", "truthy"); var isFunction = defBuiltInType("function", function() { }); var isArray = defBuiltInType("array", []); var isObject2 = defBuiltInType("object", {}); var isRegExp = defBuiltInType("RegExp", /./); var isDate2 = defBuiltInType("Date", new Date()); var isNumber = defBuiltInType("number", 3); var isBoolean2 = defBuiltInType("boolean", true); var isNull2 = defBuiltInType("null", null); var isUndefined = defBuiltInType("undefined", void 0); var isBigInt = typeof BigInt === "function" ? defBuiltInType("BigInt", BigInt(1234)) : new PredicateType("BigInt", function() { return false; }); var builtInTypes = { string: isString, function: isFunction, array: isArray, object: isObject2, RegExp: isRegExp, Date: isDate2, number: isNumber, boolean: isBoolean2, null: isNull2, undefined: isUndefined, BigInt: isBigInt }; var defCache = /* @__PURE__ */ Object.create(null); function defFromValue(value) { if (value && typeof value === "object") { var type2 = value.type; if (typeof type2 === "string" && hasOwn.call(defCache, type2)) { var d3 = defCache[type2]; if (d3.finalized) { return d3; } } } return null; } var DefImpl = ( /** @class */ function(_super) { tslib_1.__extends(DefImpl2, _super); function DefImpl2(typeName) { var _this = _super.call(this, new PredicateType(typeName, function(value, deep) { return _this.check(value, deep); }), typeName) || this; return _this; } DefImpl2.prototype.check = function(value, deep) { if (this.finalized !== true) { throw new Error("prematurely checking unfinalized type " + this.typeName); } if (value === null || typeof value !== "object") { return false; } var vDef = defFromValue(value); if (!vDef) { if (this.typeName === "SourceLocation" || this.typeName === "Position") { return this.checkAllFields(value, deep); } return false; } if (deep && vDef === this) { return this.checkAllFields(value, deep); } if (!this.isSupertypeOf(vDef)) { return false; } if (!deep) { return true; } return vDef.checkAllFields(value, deep) && this.checkAllFields(value, false); }; DefImpl2.prototype.build = function() { var _this = this; var buildParams = []; for (var _i = 0; _i < arguments.length; _i++) { buildParams[_i] = arguments[_i]; } this.buildParams = buildParams; if (this.buildable) { return this; } this.field("type", String, function() { return _this.typeName; }); this.buildable = true; var addParam = function(built, param, arg, isArgAvailable) { if (hasOwn.call(built, param)) return; var all2 = _this.allFields; if (!hasOwn.call(all2, param)) { throw new Error("" + param); } var field = all2[param]; var type2 = field.type; var value; if (isArgAvailable) { value = arg; } else if (field.defaultFn) { value = field.defaultFn.call(built); } else { var message = "no value or default function given for field " + JSON.stringify(param) + " of " + _this.typeName + "(" + _this.buildParams.map(function(name) { return all2[name]; }).join(", ") + ")"; throw new Error(message); } if (!type2.check(value)) { throw new Error(shallowStringify(value) + " does not match field " + field + " of type " + _this.typeName); } built[param] = value; }; var builder = function() { var args = []; for (var _i2 = 0; _i2 < arguments.length; _i2++) { args[_i2] = arguments[_i2]; } var argc = args.length; if (!_this.finalized) { throw new Error("attempting to instantiate unfinalized type " + _this.typeName); } var built = Object.create(nodePrototype); _this.buildParams.forEach(function(param, i2) { if (i2 < argc) { addParam(built, param, args[i2], true); } else { addParam(built, param, null, false); } }); Object.keys(_this.allFields).forEach(function(param) { addParam(built, param, null, false); }); if (built.type !== _this.typeName) { throw new Error(""); } return built; }; builder.from = function(obj) { if (!_this.finalized) { throw new Error("attempting to instantiate unfinalized type " + _this.typeName); } var built = Object.create(nodePrototype); Object.keys(_this.allFields).forEach(function(param) { if (hasOwn.call(obj, param)) { addParam(built, param, obj[param], true); } else { addParam(built, param, null, false); } }); if (built.type !== _this.typeName) { throw new Error(""); } return built; }; Object.defineProperty(builders, getBuilderName(this.typeName), { enumerable: true, value: builder }); return this; }; DefImpl2.prototype.field = function(name, type2, defaultFn, hidden) { if (this.finalized) { console.error("Ignoring attempt to redefine field " + JSON.stringify(name) + " of finalized type " + JSON.stringify(this.typeName)); return this; } this.ownFields[name] = new Field(name, Type.from(type2), defaultFn, hidden); return this; }; DefImpl2.prototype.finalize = function() { var _this = this; if (!this.finalized) { var allFields = this.allFields; var allSupertypes = this.allSupertypes; this.baseNames.forEach(function(name) { var def = defCache[name]; if (def instanceof Def) { def.finalize(); extend3(allFields, def.allFields); extend3(allSupertypes, def.allSupertypes); } else { var message = "unknown supertype name " + JSON.stringify(name) + " for subtype " + JSON.stringify(_this.typeName); throw new Error(message); } }); extend3(allFields, this.ownFields); allSupertypes[this.typeName] = this; this.fieldNames.length = 0; for (var fieldName in allFields) { if (hasOwn.call(allFields, fieldName) && !allFields[fieldName].hidden) { this.fieldNames.push(fieldName); } } Object.defineProperty(namedTypes, this.typeName, { enumerable: true, value: this.type }); this.finalized = true; populateSupertypeList(this.typeName, this.supertypeList); if (this.buildable && this.supertypeList.lastIndexOf("Expression") >= 0) { wrapExpressionBuilderWithStatement(this.typeName); } } }; return DefImpl2; }(Def) ); function getSupertypeNames(typeName) { if (!hasOwn.call(defCache, typeName)) { throw new Error(""); } var d3 = defCache[typeName]; if (d3.finalized !== true) { throw new Error(""); } return d3.supertypeList.slice(1); } function computeSupertypeLookupTable(candidates) { var table = {}; var typeNames = Object.keys(defCache); var typeNameCount = typeNames.length; for (var i2 = 0; i2 < typeNameCount; ++i2) { var typeName = typeNames[i2]; var d3 = defCache[typeName]; if (d3.finalized !== true) { throw new Error("" + typeName); } for (var j = 0; j < d3.supertypeList.length; ++j) { var superTypeName = d3.supertypeList[j]; if (hasOwn.call(candidates, superTypeName)) { table[typeName] = superTypeName; break; } } } return table; } var builders = /* @__PURE__ */ Object.create(null); var nodePrototype = {}; function defineMethod(name, func) { var old = nodePrototype[name]; if (isUndefined.check(func)) { delete nodePrototype[name]; } else { isFunction.assert(func); Object.defineProperty(nodePrototype, name, { enumerable: true, configurable: true, value: func }); } return old; } function getBuilderName(typeName) { return typeName.replace(/^[A-Z]+/, function(upperCasePrefix) { var len = upperCasePrefix.length; switch (len) { case 0: return ""; case 1: return upperCasePrefix.toLowerCase(); default: return upperCasePrefix.slice(0, len - 1).toLowerCase() + upperCasePrefix.charAt(len - 1); } }); } function getStatementBuilderName(typeName) { typeName = getBuilderName(typeName); return typeName.replace(/(Expression)?$/, "Statement"); } var namedTypes = {}; function getFieldNames(object) { var d3 = defFromValue(object); if (d3) { return d3.fieldNames.slice(0); } if ("type" in object) { throw new Error("did not recognize object of type " + JSON.stringify(object.type)); } return Object.keys(object); } function getFieldValue(object, fieldName) { var d3 = defFromValue(object); if (d3) { var field = d3.allFields[fieldName]; if (field) { return field.getValue(object); } } return object && object[fieldName]; } function eachField(object, callback, context) { getFieldNames(object).forEach(function(name) { callback.call(this, name, getFieldValue(object, name)); }, context); } function someField(object, callback, context) { return getFieldNames(object).some(function(name) { return callback.call(this, name, getFieldValue(object, name)); }, context); } function wrapExpressionBuilderWithStatement(typeName) { var wrapperName = getStatementBuilderName(typeName); if (builders[wrapperName]) return; var wrapped = builders[getBuilderName(typeName)]; if (!wrapped) return; var builder = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return builders.expressionStatement(wrapped.apply(builders, args)); }; builder.from = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return builders.expressionStatement(wrapped.from.apply(builders, args)); }; builders[wrapperName] = builder; } function populateSupertypeList(typeName, list2) { list2.length = 0; list2.push(typeName); var lastSeen = /* @__PURE__ */ Object.create(null); for (var pos = 0; pos < list2.length; ++pos) { typeName = list2[pos]; var d3 = defCache[typeName]; if (d3.finalized !== true) { throw new Error(""); } if (hasOwn.call(lastSeen, typeName)) { delete list2[lastSeen[typeName]]; } lastSeen[typeName] = pos; list2.push.apply(list2, d3.baseNames); } for (var to = 0, from = to, len = list2.length; from < len; ++from) { if (hasOwn.call(list2, from)) { list2[to++] = list2[from]; } } list2.length = to; } function extend3(into, from) { Object.keys(from).forEach(function(name) { into[name] = from[name]; }); return into; } function finalize() { Object.keys(defCache).forEach(function(name) { defCache[name].finalize(); }); } return { Type, builtInTypes, getSupertypeNames, computeSupertypeLookupTable, builders, defineMethod, getBuilderName, getStatementBuilderName, namedTypes, getFieldNames, getFieldValue, eachField, someField, finalize }; } exports.default = typesPlugin; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/path.js var require_path = __commonJS({ "node_modules/ast-types/lib/path.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var shared_1 = require_shared(); var types_1 = tslib_1.__importDefault(require_types()); var Op = Object.prototype; var hasOwn = Op.hasOwnProperty; function pathPlugin(fork) { var types = fork.use(types_1.default); var isArray = types.builtInTypes.array; var isNumber = types.builtInTypes.number; var Path = function Path2(value, parentPath, name) { if (!(this instanceof Path2)) { throw new Error("Path constructor cannot be invoked without 'new'"); } if (parentPath) { if (!(parentPath instanceof Path2)) { throw new Error(""); } } else { parentPath = null; name = null; } this.value = value; this.parentPath = parentPath; this.name = name; this.__childCache = null; }; var Pp = Path.prototype; function getChildCache(path) { return path.__childCache || (path.__childCache = /* @__PURE__ */ Object.create(null)); } function getChildPath(path, name) { var cache = getChildCache(path); var actualChildValue = path.getValueProperty(name); var childPath = cache[name]; if (!hasOwn.call(cache, name) || // Ensure consistency between cache and reality. childPath.value !== actualChildValue) { childPath = cache[name] = new path.constructor(actualChildValue, path, name); } return childPath; } Pp.getValueProperty = function getValueProperty(name) { return this.value[name]; }; Pp.get = function get() { var names = []; for (var _i = 0; _i < arguments.length; _i++) { names[_i] = arguments[_i]; } var path = this; var count = names.length; for (var i2 = 0; i2 < count; ++i2) { path = getChildPath(path, names[i2]); } return path; }; Pp.each = function each(callback, context) { var childPaths = []; var len = this.value.length; var i2 = 0; for (var i2 = 0; i2 < len; ++i2) { if (hasOwn.call(this.value, i2)) { childPaths[i2] = this.get(i2); } } context = context || this; for (i2 = 0; i2 < len; ++i2) { if (hasOwn.call(childPaths, i2)) { callback.call(context, childPaths[i2]); } } }; Pp.map = function map2(callback, context) { var result = []; this.each(function(childPath) { result.push(callback.call(this, childPath)); }, context); return result; }; Pp.filter = function filter(callback, context) { var result = []; this.each(function(childPath) { if (callback.call(this, childPath)) { result.push(childPath); } }, context); return result; }; function emptyMoves() { } function getMoves(path, offset, start, end) { isArray.assert(path.value); if (offset === 0) { return emptyMoves; } var length = path.value.length; if (length < 1) { return emptyMoves; } var argc = arguments.length; if (argc === 2) { start = 0; end = length; } else if (argc === 3) { start = Math.max(start, 0); end = length; } else { start = Math.max(start, 0); end = Math.min(end, length); } isNumber.assert(start); isNumber.assert(end); var moves = /* @__PURE__ */ Object.create(null); var cache = getChildCache(path); for (var i2 = start; i2 < end; ++i2) { if (hasOwn.call(path.value, i2)) { var childPath = path.get(i2); if (childPath.name !== i2) { throw new Error(""); } var newIndex = i2 + offset; childPath.name = newIndex; moves[newIndex] = childPath; delete cache[i2]; } } delete cache.length; return function() { for (var newIndex2 in moves) { var childPath2 = moves[newIndex2]; if (childPath2.name !== +newIndex2) { throw new Error(""); } cache[newIndex2] = childPath2; path.value[newIndex2] = childPath2.value; } }; } Pp.shift = function shift() { var move = getMoves(this, -1); var result = this.value.shift(); move(); return result; }; Pp.unshift = function unshift() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var move = getMoves(this, args.length); var result = this.value.unshift.apply(this.value, args); move(); return result; }; Pp.push = function push2() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } isArray.assert(this.value); delete getChildCache(this).length; return this.value.push.apply(this.value, args); }; Pp.pop = function pop() { isArray.assert(this.value); var cache = getChildCache(this); delete cache[this.value.length - 1]; delete cache.length; return this.value.pop(); }; Pp.insertAt = function insertAt(index2) { var argc = arguments.length; var move = getMoves(this, argc - 1, index2); if (move === emptyMoves && argc <= 1) { return this; } index2 = Math.max(index2, 0); for (var i2 = 1; i2 < argc; ++i2) { this.value[index2 + i2 - 1] = arguments[i2]; } move(); return this; }; Pp.insertBefore = function insertBefore() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var pp = this.parentPath; var argc = args.length; var insertAtArgs = [this.name]; for (var i2 = 0; i2 < argc; ++i2) { insertAtArgs.push(args[i2]); } return pp.insertAt.apply(pp, insertAtArgs); }; Pp.insertAfter = function insertAfter() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var pp = this.parentPath; var argc = args.length; var insertAtArgs = [this.name + 1]; for (var i2 = 0; i2 < argc; ++i2) { insertAtArgs.push(args[i2]); } return pp.insertAt.apply(pp, insertAtArgs); }; function repairRelationshipWithParent(path) { if (!(path instanceof Path)) { throw new Error(""); } var pp = path.parentPath; if (!pp) { return path; } var parentValue = pp.value; var parentCache = getChildCache(pp); if (parentValue[path.name] === path.value) { parentCache[path.name] = path; } else if (isArray.check(parentValue)) { var i2 = parentValue.indexOf(path.value); if (i2 >= 0) { parentCache[path.name = i2] = path; } } else { parentValue[path.name] = path.value; parentCache[path.name] = path; } if (parentValue[path.name] !== path.value) { throw new Error(""); } if (path.parentPath.get(path.name) !== path) { throw new Error(""); } return path; } Pp.replace = function replace(replacement) { var results = []; var parentValue = this.parentPath.value; var parentCache = getChildCache(this.parentPath); var count = arguments.length; repairRelationshipWithParent(this); if (isArray.check(parentValue)) { var originalLength = parentValue.length; var move = getMoves(this.parentPath, count - 1, this.name + 1); var spliceArgs = [this.name, 1]; for (var i2 = 0; i2 < count; ++i2) { spliceArgs.push(arguments[i2]); } var splicedOut = parentValue.splice.apply(parentValue, spliceArgs); if (splicedOut[0] !== this.value) { throw new Error(""); } if (parentValue.length !== originalLength - 1 + count) { throw new Error(""); } move(); if (count === 0) { delete this.value; delete parentCache[this.name]; this.__childCache = null; } else { if (parentValue[this.name] !== replacement) { throw new Error(""); } if (this.value !== replacement) { this.value = replacement; this.__childCache = null; } for (i2 = 0; i2 < count; ++i2) { results.push(this.parentPath.get(this.name + i2)); } if (results[0] !== this) { throw new Error(""); } } } else if (count === 1) { if (this.value !== replacement) { this.__childCache = null; } this.value = parentValue[this.name] = replacement; results.push(this); } else if (count === 0) { delete parentValue[this.name]; delete this.value; this.__childCache = null; } else { throw new Error("Could not replace path"); } return results; }; return Path; } exports.default = pathPlugin; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/scope.js var require_scope = __commonJS({ "node_modules/ast-types/lib/scope.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var shared_1 = require_shared(); var types_1 = tslib_1.__importDefault(require_types()); var hasOwn = Object.prototype.hasOwnProperty; function scopePlugin(fork) { var types = fork.use(types_1.default); var Type = types.Type; var namedTypes = types.namedTypes; var Node = namedTypes.Node; var Expression = namedTypes.Expression; var isArray = types.builtInTypes.array; var b2 = types.builders; var Scope = function Scope2(path, parentScope) { if (!(this instanceof Scope2)) { throw new Error("Scope constructor cannot be invoked without 'new'"); } if (!TypeParameterScopeType.check(path.value)) { ScopeType.assert(path.value); } var depth; if (parentScope) { if (!(parentScope instanceof Scope2)) { throw new Error(""); } depth = parentScope.depth + 1; } else { parentScope = null; depth = 0; } Object.defineProperties(this, { path: { value: path }, node: { value: path.value }, isGlobal: { value: !parentScope, enumerable: true }, depth: { value: depth }, parent: { value: parentScope }, bindings: { value: {} }, types: { value: {} } }); }; var ScopeType = Type.or( // Program nodes introduce global scopes. namedTypes.Program, // Function is the supertype of FunctionExpression, // FunctionDeclaration, ArrowExpression, etc. namedTypes.Function, // In case you didn't know, the caught parameter shadows any variable // of the same name in an outer scope. namedTypes.CatchClause ); var TypeParameterScopeType = Type.or(namedTypes.Function, namedTypes.ClassDeclaration, namedTypes.ClassExpression, namedTypes.InterfaceDeclaration, namedTypes.TSInterfaceDeclaration, namedTypes.TypeAlias, namedTypes.TSTypeAliasDeclaration); var FlowOrTSTypeParameterType = Type.or(namedTypes.TypeParameter, namedTypes.TSTypeParameter); Scope.isEstablishedBy = function(node2) { return ScopeType.check(node2) || TypeParameterScopeType.check(node2); }; var Sp = Scope.prototype; Sp.didScan = false; Sp.declares = function(name) { this.scan(); return hasOwn.call(this.bindings, name); }; Sp.declaresType = function(name) { this.scan(); return hasOwn.call(this.types, name); }; Sp.declareTemporary = function(prefix) { if (prefix) { if (!/^[a-z$_]/i.test(prefix)) { throw new Error(""); } } else { prefix = "t$"; } prefix += this.depth.toString(36) + "$"; this.scan(); var index2 = 0; while (this.declares(prefix + index2)) { ++index2; } var name = prefix + index2; return this.bindings[name] = types.builders.identifier(name); }; Sp.injectTemporary = function(identifier, init) { identifier || (identifier = this.declareTemporary()); var bodyPath = this.path.get("body"); if (namedTypes.BlockStatement.check(bodyPath.value)) { bodyPath = bodyPath.get("body"); } bodyPath.unshift(b2.variableDeclaration("var", [b2.variableDeclarator(identifier, init || null)])); return identifier; }; Sp.scan = function(force) { if (force || !this.didScan) { for (var name in this.bindings) { delete this.bindings[name]; } for (var name in this.types) { delete this.types[name]; } scanScope(this.path, this.bindings, this.types); this.didScan = true; } }; Sp.getBindings = function() { this.scan(); return this.bindings; }; Sp.getTypes = function() { this.scan(); return this.types; }; function scanScope(path, bindings, scopeTypes) { var node2 = path.value; if (TypeParameterScopeType.check(node2)) { var params = path.get("typeParameters", "params"); if (isArray.check(params.value)) { params.each(function(childPath) { addTypeParameter(childPath, scopeTypes); }); } } if (ScopeType.check(node2)) { if (namedTypes.CatchClause.check(node2)) { addPattern(path.get("param"), bindings); } else { recursiveScanScope(path, bindings, scopeTypes); } } } function recursiveScanScope(path, bindings, scopeTypes) { var node2 = path.value; if (path.parent && namedTypes.FunctionExpression.check(path.parent.node) && path.parent.node.id) { addPattern(path.parent.get("id"), bindings); } if (!node2) { } else if (isArray.check(node2)) { path.each(function(childPath) { recursiveScanChild(childPath, bindings, scopeTypes); }); } else if (namedTypes.Function.check(node2)) { path.get("params").each(function(paramPath) { addPattern(paramPath, bindings); }); recursiveScanChild(path.get("body"), bindings, scopeTypes); recursiveScanScope(path.get("typeParameters"), bindings, scopeTypes); } else if (namedTypes.TypeAlias && namedTypes.TypeAlias.check(node2) || namedTypes.InterfaceDeclaration && namedTypes.InterfaceDeclaration.check(node2) || namedTypes.TSTypeAliasDeclaration && namedTypes.TSTypeAliasDeclaration.check(node2) || namedTypes.TSInterfaceDeclaration && namedTypes.TSInterfaceDeclaration.check(node2)) { addTypePattern(path.get("id"), scopeTypes); } else if (namedTypes.VariableDeclarator.check(node2)) { addPattern(path.get("id"), bindings); recursiveScanChild(path.get("init"), bindings, scopeTypes); } else if (node2.type === "ImportSpecifier" || node2.type === "ImportNamespaceSpecifier" || node2.type === "ImportDefaultSpecifier") { addPattern( // Esprima used to use the .name field to refer to the local // binding identifier for ImportSpecifier nodes, but .id for // ImportNamespaceSpecifier and ImportDefaultSpecifier nodes. // ESTree/Acorn/ESpree use .local for all three node types. path.get(node2.local ? "local" : node2.name ? "name" : "id"), bindings ); } else if (Node.check(node2) && !Expression.check(node2)) { types.eachField(node2, function(name, child) { var childPath = path.get(name); if (!pathHasValue(childPath, child)) { throw new Error(""); } recursiveScanChild(childPath, bindings, scopeTypes); }); } } function pathHasValue(path, value) { if (path.value === value) { return true; } if (Array.isArray(path.value) && path.value.length === 0 && Array.isArray(value) && value.length === 0) { return true; } return false; } function recursiveScanChild(path, bindings, scopeTypes) { var node2 = path.value; if (!node2 || Expression.check(node2)) { } else if (namedTypes.FunctionDeclaration.check(node2) && node2.id !== null) { addPattern(path.get("id"), bindings); } else if (namedTypes.ClassDeclaration && namedTypes.ClassDeclaration.check(node2) && node2.id !== null) { addPattern(path.get("id"), bindings); recursiveScanScope(path.get("typeParameters"), bindings, scopeTypes); } else if (namedTypes.InterfaceDeclaration && namedTypes.InterfaceDeclaration.check(node2) || namedTypes.TSInterfaceDeclaration && namedTypes.TSInterfaceDeclaration.check(node2)) { addTypePattern(path.get("id"), scopeTypes); } else if (ScopeType.check(node2)) { if (namedTypes.CatchClause.check(node2) && // TODO Broaden this to accept any pattern. namedTypes.Identifier.check(node2.param)) { var catchParamName = node2.param.name; var hadBinding = hasOwn.call(bindings, catchParamName); recursiveScanScope(path.get("body"), bindings, scopeTypes); if (!hadBinding) { delete bindings[catchParamName]; } } } else { recursiveScanScope(path, bindings, scopeTypes); } } function addPattern(patternPath, bindings) { var pattern = patternPath.value; namedTypes.Pattern.assert(pattern); if (namedTypes.Identifier.check(pattern)) { if (hasOwn.call(bindings, pattern.name)) { bindings[pattern.name].push(patternPath); } else { bindings[pattern.name] = [patternPath]; } } else if (namedTypes.AssignmentPattern && namedTypes.AssignmentPattern.check(pattern)) { addPattern(patternPath.get("left"), bindings); } else if (namedTypes.ObjectPattern && namedTypes.ObjectPattern.check(pattern)) { patternPath.get("properties").each(function(propertyPath) { var property = propertyPath.value; if (namedTypes.Pattern.check(property)) { addPattern(propertyPath, bindings); } else if (namedTypes.Property.check(property) || namedTypes.ObjectProperty && namedTypes.ObjectProperty.check(property)) { addPattern(propertyPath.get("value"), bindings); } else if (namedTypes.SpreadProperty && namedTypes.SpreadProperty.check(property)) { addPattern(propertyPath.get("argument"), bindings); } }); } else if (namedTypes.ArrayPattern && namedTypes.ArrayPattern.check(pattern)) { patternPath.get("elements").each(function(elementPath) { var element2 = elementPath.value; if (namedTypes.Pattern.check(element2)) { addPattern(elementPath, bindings); } else if (namedTypes.SpreadElement && namedTypes.SpreadElement.check(element2)) { addPattern(elementPath.get("argument"), bindings); } }); } else if (namedTypes.PropertyPattern && namedTypes.PropertyPattern.check(pattern)) { addPattern(patternPath.get("pattern"), bindings); } else if (namedTypes.SpreadElementPattern && namedTypes.SpreadElementPattern.check(pattern) || namedTypes.RestElement && namedTypes.RestElement.check(pattern) || namedTypes.SpreadPropertyPattern && namedTypes.SpreadPropertyPattern.check(pattern)) { addPattern(patternPath.get("argument"), bindings); } } function addTypePattern(patternPath, types2) { var pattern = patternPath.value; namedTypes.Pattern.assert(pattern); if (namedTypes.Identifier.check(pattern)) { if (hasOwn.call(types2, pattern.name)) { types2[pattern.name].push(patternPath); } else { types2[pattern.name] = [patternPath]; } } } function addTypeParameter(parameterPath, types2) { var parameter = parameterPath.value; FlowOrTSTypeParameterType.assert(parameter); if (hasOwn.call(types2, parameter.name)) { types2[parameter.name].push(parameterPath); } else { types2[parameter.name] = [parameterPath]; } } Sp.lookup = function(name) { for (var scope = this; scope; scope = scope.parent) if (scope.declares(name)) break; return scope; }; Sp.lookupType = function(name) { for (var scope = this; scope; scope = scope.parent) if (scope.declaresType(name)) break; return scope; }; Sp.getGlobalScope = function() { var scope = this; while (!scope.isGlobal) scope = scope.parent; return scope; }; return Scope; } exports.default = scopePlugin; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/node-path.js var require_node_path = __commonJS({ "node_modules/ast-types/lib/node-path.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var types_1 = tslib_1.__importDefault(require_types()); var path_1 = tslib_1.__importDefault(require_path()); var scope_1 = tslib_1.__importDefault(require_scope()); var shared_1 = require_shared(); function nodePathPlugin(fork) { var types = fork.use(types_1.default); var n = types.namedTypes; var b2 = types.builders; var isNumber = types.builtInTypes.number; var isArray = types.builtInTypes.array; var Path = fork.use(path_1.default); var Scope = fork.use(scope_1.default); var NodePath = function NodePath2(value, parentPath, name) { if (!(this instanceof NodePath2)) { throw new Error("NodePath constructor cannot be invoked without 'new'"); } Path.call(this, value, parentPath, name); }; var NPp = NodePath.prototype = Object.create(Path.prototype, { constructor: { value: NodePath, enumerable: false, writable: true, configurable: true } }); Object.defineProperties(NPp, { node: { get: function() { Object.defineProperty(this, "node", { configurable: true, value: this._computeNode() }); return this.node; } }, parent: { get: function() { Object.defineProperty(this, "parent", { configurable: true, value: this._computeParent() }); return this.parent; } }, scope: { get: function() { Object.defineProperty(this, "scope", { configurable: true, value: this._computeScope() }); return this.scope; } } }); NPp.replace = function() { delete this.node; delete this.parent; delete this.scope; return Path.prototype.replace.apply(this, arguments); }; NPp.prune = function() { var remainingNodePath = this.parent; this.replace(); return cleanUpNodesAfterPrune(remainingNodePath); }; NPp._computeNode = function() { var value = this.value; if (n.Node.check(value)) { return value; } var pp = this.parentPath; return pp && pp.node || null; }; NPp._computeParent = function() { var value = this.value; var pp = this.parentPath; if (!n.Node.check(value)) { while (pp && !n.Node.check(pp.value)) { pp = pp.parentPath; } if (pp) { pp = pp.parentPath; } } while (pp && !n.Node.check(pp.value)) { pp = pp.parentPath; } return pp || null; }; NPp._computeScope = function() { var value = this.value; var pp = this.parentPath; var scope = pp && pp.scope; if (n.Node.check(value) && Scope.isEstablishedBy(value)) { scope = new Scope(this, scope); } return scope || null; }; NPp.getValueProperty = function(name) { return types.getFieldValue(this.value, name); }; NPp.needsParens = function(assumeExpressionContext) { var pp = this.parentPath; if (!pp) { return false; } var node2 = this.value; if (!n.Expression.check(node2)) { return false; } if (node2.type === "Identifier") { return false; } while (!n.Node.check(pp.value)) { pp = pp.parentPath; if (!pp) { return false; } } var parent = pp.value; switch (node2.type) { case "UnaryExpression": case "SpreadElement": case "SpreadProperty": return parent.type === "MemberExpression" && this.name === "object" && parent.object === node2; case "BinaryExpression": case "LogicalExpression": switch (parent.type) { case "CallExpression": return this.name === "callee" && parent.callee === node2; case "UnaryExpression": case "SpreadElement": case "SpreadProperty": return true; case "MemberExpression": return this.name === "object" && parent.object === node2; case "BinaryExpression": case "LogicalExpression": { var n_1 = node2; var po = parent.operator; var pp_1 = PRECEDENCE[po]; var no = n_1.operator; var np = PRECEDENCE[no]; if (pp_1 > np) { return true; } if (pp_1 === np && this.name === "right") { if (parent.right !== n_1) { throw new Error("Nodes must be equal"); } return true; } } default: return false; } case "SequenceExpression": switch (parent.type) { case "ForStatement": return false; case "ExpressionStatement": return this.name !== "expression"; default: return true; } case "YieldExpression": switch (parent.type) { case "BinaryExpression": case "LogicalExpression": case "UnaryExpression": case "SpreadElement": case "SpreadProperty": case "CallExpression": case "MemberExpression": case "NewExpression": case "ConditionalExpression": case "YieldExpression": return true; default: return false; } case "Literal": return parent.type === "MemberExpression" && isNumber.check(node2.value) && this.name === "object" && parent.object === node2; case "AssignmentExpression": case "ConditionalExpression": switch (parent.type) { case "UnaryExpression": case "SpreadElement": case "SpreadProperty": case "BinaryExpression": case "LogicalExpression": return true; case "CallExpression": return this.name === "callee" && parent.callee === node2; case "ConditionalExpression": return this.name === "test" && parent.test === node2; case "MemberExpression": return this.name === "object" && parent.object === node2; default: return false; } default: if (parent.type === "NewExpression" && this.name === "callee" && parent.callee === node2) { return containsCallExpression(node2); } } if (assumeExpressionContext !== true && !this.canBeFirstInStatement() && this.firstInStatement()) return true; return false; }; function isBinary2(node2) { return n.BinaryExpression.check(node2) || n.LogicalExpression.check(node2); } function isUnaryLike(node2) { return n.UnaryExpression.check(node2) || n.SpreadElement && n.SpreadElement.check(node2) || n.SpreadProperty && n.SpreadProperty.check(node2); } var PRECEDENCE = {}; [ ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"] ].forEach(function(tier, i2) { tier.forEach(function(op) { PRECEDENCE[op] = i2; }); }); function containsCallExpression(node2) { if (n.CallExpression.check(node2)) { return true; } if (isArray.check(node2)) { return node2.some(containsCallExpression); } if (n.Node.check(node2)) { return types.someField(node2, function(_name, child) { return containsCallExpression(child); }); } return false; } NPp.canBeFirstInStatement = function() { var node2 = this.node; return !n.FunctionExpression.check(node2) && !n.ObjectExpression.check(node2); }; NPp.firstInStatement = function() { return firstInStatement(this); }; function firstInStatement(path) { for (var node2, parent; path.parent; path = path.parent) { node2 = path.node; parent = path.parent.node; if (n.BlockStatement.check(parent) && path.parent.name === "body" && path.name === 0) { if (parent.body[0] !== node2) { throw new Error("Nodes must be equal"); } return true; } if (n.ExpressionStatement.check(parent) && path.name === "expression") { if (parent.expression !== node2) { throw new Error("Nodes must be equal"); } return true; } if (n.SequenceExpression.check(parent) && path.parent.name === "expressions" && path.name === 0) { if (parent.expressions[0] !== node2) { throw new Error("Nodes must be equal"); } continue; } if (n.CallExpression.check(parent) && path.name === "callee") { if (parent.callee !== node2) { throw new Error("Nodes must be equal"); } continue; } if (n.MemberExpression.check(parent) && path.name === "object") { if (parent.object !== node2) { throw new Error("Nodes must be equal"); } continue; } if (n.ConditionalExpression.check(parent) && path.name === "test") { if (parent.test !== node2) { throw new Error("Nodes must be equal"); } continue; } if (isBinary2(parent) && path.name === "left") { if (parent.left !== node2) { throw new Error("Nodes must be equal"); } continue; } if (n.UnaryExpression.check(parent) && !parent.prefix && path.name === "argument") { if (parent.argument !== node2) { throw new Error("Nodes must be equal"); } continue; } return false; } return true; } function cleanUpNodesAfterPrune(remainingNodePath) { if (n.VariableDeclaration.check(remainingNodePath.node)) { var declarations = remainingNodePath.get("declarations").value; if (!declarations || declarations.length === 0) { return remainingNodePath.prune(); } } else if (n.ExpressionStatement.check(remainingNodePath.node)) { if (!remainingNodePath.get("expression").value) { return remainingNodePath.prune(); } } else if (n.IfStatement.check(remainingNodePath.node)) { cleanUpIfStatementAfterPrune(remainingNodePath); } return remainingNodePath; } function cleanUpIfStatementAfterPrune(ifStatement) { var testExpression = ifStatement.get("test").value; var alternate = ifStatement.get("alternate").value; var consequent = ifStatement.get("consequent").value; if (!consequent && !alternate) { var testExpressionStatement = b2.expressionStatement(testExpression); ifStatement.replace(testExpressionStatement); } else if (!consequent && alternate) { var negatedTestExpression = b2.unaryExpression("!", testExpression, true); if (n.UnaryExpression.check(testExpression) && testExpression.operator === "!") { negatedTestExpression = testExpression.argument; } ifStatement.get("test").replace(negatedTestExpression); ifStatement.get("consequent").replace(alternate); ifStatement.get("alternate").replace(); } } return NodePath; } exports.default = nodePathPlugin; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/path-visitor.js var require_path_visitor = __commonJS({ "node_modules/ast-types/lib/path-visitor.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var types_1 = tslib_1.__importDefault(require_types()); var node_path_1 = tslib_1.__importDefault(require_node_path()); var shared_1 = require_shared(); var hasOwn = Object.prototype.hasOwnProperty; function pathVisitorPlugin(fork) { var types = fork.use(types_1.default); var NodePath = fork.use(node_path_1.default); var isArray = types.builtInTypes.array; var isObject2 = types.builtInTypes.object; var isFunction = types.builtInTypes.function; var undefined2; var PathVisitor = function PathVisitor2() { if (!(this instanceof PathVisitor2)) { throw new Error("PathVisitor constructor cannot be invoked without 'new'"); } this._reusableContextStack = []; this._methodNameTable = computeMethodNameTable(this); this._shouldVisitComments = hasOwn.call(this._methodNameTable, "Block") || hasOwn.call(this._methodNameTable, "Line"); this.Context = makeContextConstructor(this); this._visiting = false; this._changeReported = false; }; function computeMethodNameTable(visitor) { var typeNames = /* @__PURE__ */ Object.create(null); for (var methodName in visitor) { if (/^visit[A-Z]/.test(methodName)) { typeNames[methodName.slice("visit".length)] = true; } } var supertypeTable = types.computeSupertypeLookupTable(typeNames); var methodNameTable = /* @__PURE__ */ Object.create(null); var typeNameKeys = Object.keys(supertypeTable); var typeNameCount = typeNameKeys.length; for (var i2 = 0; i2 < typeNameCount; ++i2) { var typeName = typeNameKeys[i2]; methodName = "visit" + supertypeTable[typeName]; if (isFunction.check(visitor[methodName])) { methodNameTable[typeName] = methodName; } } return methodNameTable; } PathVisitor.fromMethodsObject = function fromMethodsObject(methods) { if (methods instanceof PathVisitor) { return methods; } if (!isObject2.check(methods)) { return new PathVisitor(); } var Visitor = function Visitor2() { if (!(this instanceof Visitor2)) { throw new Error("Visitor constructor cannot be invoked without 'new'"); } PathVisitor.call(this); }; var Vp = Visitor.prototype = Object.create(PVp); Vp.constructor = Visitor; extend3(Vp, methods); extend3(Visitor, PathVisitor); isFunction.assert(Visitor.fromMethodsObject); isFunction.assert(Visitor.visit); return new Visitor(); }; function extend3(target, source) { for (var property in source) { if (hasOwn.call(source, property)) { target[property] = source[property]; } } return target; } PathVisitor.visit = function visit(node2, methods) { return PathVisitor.fromMethodsObject(methods).visit(node2); }; var PVp = PathVisitor.prototype; PVp.visit = function() { if (this._visiting) { throw new Error("Recursively calling visitor.visit(path) resets visitor state. Try this.visit(path) or this.traverse(path) instead."); } this._visiting = true; this._changeReported = false; this._abortRequested = false; var argc = arguments.length; var args = new Array(argc); for (var i2 = 0; i2 < argc; ++i2) { args[i2] = arguments[i2]; } if (!(args[0] instanceof NodePath)) { args[0] = new NodePath({ root: args[0] }).get("root"); } this.reset.apply(this, args); var didNotThrow; try { var root = this.visitWithoutReset(args[0]); didNotThrow = true; } finally { this._visiting = false; if (!didNotThrow && this._abortRequested) { return args[0].value; } } return root; }; PVp.AbortRequest = function AbortRequest() { }; PVp.abort = function() { var visitor = this; visitor._abortRequested = true; var request = new visitor.AbortRequest(); request.cancel = function() { visitor._abortRequested = false; }; throw request; }; PVp.reset = function(_path) { }; PVp.visitWithoutReset = function(path) { if (this instanceof this.Context) { return this.visitor.visitWithoutReset(path); } if (!(path instanceof NodePath)) { throw new Error(""); } var value = path.value; var methodName = value && typeof value === "object" && typeof value.type === "string" && this._methodNameTable[value.type]; if (methodName) { var context = this.acquireContext(path); try { return context.invokeVisitorMethod(methodName); } finally { this.releaseContext(context); } } else { return visitChildren(path, this); } }; function visitChildren(path, visitor) { if (!(path instanceof NodePath)) { throw new Error(""); } if (!(visitor instanceof PathVisitor)) { throw new Error(""); } var value = path.value; if (isArray.check(value)) { path.each(visitor.visitWithoutReset, visitor); } else if (!isObject2.check(value)) { } else { var childNames = types.getFieldNames(value); if (visitor._shouldVisitComments && value.comments && childNames.indexOf("comments") < 0) { childNames.push("comments"); } var childCount = childNames.length; var childPaths = []; for (var i2 = 0; i2 < childCount; ++i2) { var childName = childNames[i2]; if (!hasOwn.call(value, childName)) { value[childName] = types.getFieldValue(value, childName); } childPaths.push(path.get(childName)); } for (var i2 = 0; i2 < childCount; ++i2) { visitor.visitWithoutReset(childPaths[i2]); } } return path.value; } PVp.acquireContext = function(path) { if (this._reusableContextStack.length === 0) { return new this.Context(path); } return this._reusableContextStack.pop().reset(path); }; PVp.releaseContext = function(context) { if (!(context instanceof this.Context)) { throw new Error(""); } this._reusableContextStack.push(context); context.currentPath = null; }; PVp.reportChanged = function() { this._changeReported = true; }; PVp.wasChangeReported = function() { return this._changeReported; }; function makeContextConstructor(visitor) { function Context(path) { if (!(this instanceof Context)) { throw new Error(""); } if (!(this instanceof PathVisitor)) { throw new Error(""); } if (!(path instanceof NodePath)) { throw new Error(""); } Object.defineProperty(this, "visitor", { value: visitor, writable: false, enumerable: true, configurable: false }); this.currentPath = path; this.needToCallTraverse = true; Object.seal(this); } if (!(visitor instanceof PathVisitor)) { throw new Error(""); } var Cp = Context.prototype = Object.create(visitor); Cp.constructor = Context; extend3(Cp, sharedContextProtoMethods); return Context; } var sharedContextProtoMethods = /* @__PURE__ */ Object.create(null); sharedContextProtoMethods.reset = function reset(path) { if (!(this instanceof this.Context)) { throw new Error(""); } if (!(path instanceof NodePath)) { throw new Error(""); } this.currentPath = path; this.needToCallTraverse = true; return this; }; sharedContextProtoMethods.invokeVisitorMethod = function invokeVisitorMethod(methodName) { if (!(this instanceof this.Context)) { throw new Error(""); } if (!(this.currentPath instanceof NodePath)) { throw new Error(""); } var result = this.visitor[methodName].call(this, this.currentPath); if (result === false) { this.needToCallTraverse = false; } else if (result !== undefined2) { this.currentPath = this.currentPath.replace(result)[0]; if (this.needToCallTraverse) { this.traverse(this.currentPath); } } if (this.needToCallTraverse !== false) { throw new Error("Must either call this.traverse or return false in " + methodName); } var path = this.currentPath; return path && path.value; }; sharedContextProtoMethods.traverse = function traverse(path, newVisitor) { if (!(this instanceof this.Context)) { throw new Error(""); } if (!(path instanceof NodePath)) { throw new Error(""); } if (!(this.currentPath instanceof NodePath)) { throw new Error(""); } this.needToCallTraverse = false; return visitChildren(path, PathVisitor.fromMethodsObject(newVisitor || this.visitor)); }; sharedContextProtoMethods.visit = function visit(path, newVisitor) { if (!(this instanceof this.Context)) { throw new Error(""); } if (!(path instanceof NodePath)) { throw new Error(""); } if (!(this.currentPath instanceof NodePath)) { throw new Error(""); } this.needToCallTraverse = false; return PathVisitor.fromMethodsObject(newVisitor || this.visitor).visitWithoutReset(path); }; sharedContextProtoMethods.reportChanged = function reportChanged() { this.visitor.reportChanged(); }; sharedContextProtoMethods.abort = function abort() { this.needToCallTraverse = false; this.visitor.abort(); }; return PathVisitor; } exports.default = pathVisitorPlugin; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/equiv.js var require_equiv = __commonJS({ "node_modules/ast-types/lib/equiv.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var shared_1 = require_shared(); var types_1 = tslib_1.__importDefault(require_types()); function default_1(fork) { var types = fork.use(types_1.default); var getFieldNames = types.getFieldNames; var getFieldValue = types.getFieldValue; var isArray = types.builtInTypes.array; var isObject2 = types.builtInTypes.object; var isDate2 = types.builtInTypes.Date; var isRegExp = types.builtInTypes.RegExp; var hasOwn = Object.prototype.hasOwnProperty; function astNodesAreEquivalent(a3, b2, problemPath) { if (isArray.check(problemPath)) { problemPath.length = 0; } else { problemPath = null; } return areEquivalent(a3, b2, problemPath); } astNodesAreEquivalent.assert = function(a3, b2) { var problemPath = []; if (!astNodesAreEquivalent(a3, b2, problemPath)) { if (problemPath.length === 0) { if (a3 !== b2) { throw new Error("Nodes must be equal"); } } else { throw new Error("Nodes differ in the following path: " + problemPath.map(subscriptForProperty).join("")); } } }; function subscriptForProperty(property) { if (/[_$a-z][_$a-z0-9]*/i.test(property)) { return "." + property; } return "[" + JSON.stringify(property) + "]"; } function areEquivalent(a3, b2, problemPath) { if (a3 === b2) { return true; } if (isArray.check(a3)) { return arraysAreEquivalent(a3, b2, problemPath); } if (isObject2.check(a3)) { return objectsAreEquivalent(a3, b2, problemPath); } if (isDate2.check(a3)) { return isDate2.check(b2) && +a3 === +b2; } if (isRegExp.check(a3)) { return isRegExp.check(b2) && (a3.source === b2.source && a3.global === b2.global && a3.multiline === b2.multiline && a3.ignoreCase === b2.ignoreCase); } return a3 == b2; } function arraysAreEquivalent(a3, b2, problemPath) { isArray.assert(a3); var aLength = a3.length; if (!isArray.check(b2) || b2.length !== aLength) { if (problemPath) { problemPath.push("length"); } return false; } for (var i2 = 0; i2 < aLength; ++i2) { if (problemPath) { problemPath.push(i2); } if (i2 in a3 !== i2 in b2) { return false; } if (!areEquivalent(a3[i2], b2[i2], problemPath)) { return false; } if (problemPath) { var problemPathTail = problemPath.pop(); if (problemPathTail !== i2) { throw new Error("" + problemPathTail); } } } return true; } function objectsAreEquivalent(a3, b2, problemPath) { isObject2.assert(a3); if (!isObject2.check(b2)) { return false; } if (a3.type !== b2.type) { if (problemPath) { problemPath.push("type"); } return false; } var aNames = getFieldNames(a3); var aNameCount = aNames.length; var bNames = getFieldNames(b2); var bNameCount = bNames.length; if (aNameCount === bNameCount) { for (var i2 = 0; i2 < aNameCount; ++i2) { var name = aNames[i2]; var aChild = getFieldValue(a3, name); var bChild = getFieldValue(b2, name); if (problemPath) { problemPath.push(name); } if (!areEquivalent(aChild, bChild, problemPath)) { return false; } if (problemPath) { var problemPathTail = problemPath.pop(); if (problemPathTail !== name) { throw new Error("" + problemPathTail); } } } return true; } if (!problemPath) { return false; } var seenNames = /* @__PURE__ */ Object.create(null); for (i2 = 0; i2 < aNameCount; ++i2) { seenNames[aNames[i2]] = true; } for (i2 = 0; i2 < bNameCount; ++i2) { name = bNames[i2]; if (!hasOwn.call(seenNames, name)) { problemPath.push(name); return false; } delete seenNames[name]; } for (name in seenNames) { problemPath.push(name); break; } return false; } return astNodesAreEquivalent; } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/fork.js var require_fork = __commonJS({ "node_modules/ast-types/lib/fork.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var types_1 = tslib_1.__importDefault(require_types()); var path_visitor_1 = tslib_1.__importDefault(require_path_visitor()); var equiv_1 = tslib_1.__importDefault(require_equiv()); var path_1 = tslib_1.__importDefault(require_path()); var node_path_1 = tslib_1.__importDefault(require_node_path()); var shared_1 = require_shared(); function default_1(plugins) { var fork = createFork(); var types = fork.use(types_1.default); plugins.forEach(fork.use); types.finalize(); var PathVisitor = fork.use(path_visitor_1.default); return { Type: types.Type, builtInTypes: types.builtInTypes, namedTypes: types.namedTypes, builders: types.builders, defineMethod: types.defineMethod, getFieldNames: types.getFieldNames, getFieldValue: types.getFieldValue, eachField: types.eachField, someField: types.someField, getSupertypeNames: types.getSupertypeNames, getBuilderName: types.getBuilderName, astNodesAreEquivalent: fork.use(equiv_1.default), finalize: types.finalize, Path: fork.use(path_1.default), NodePath: fork.use(node_path_1.default), PathVisitor, use: fork.use, visit: PathVisitor.visit }; } exports.default = default_1; function createFork() { var used = []; var usedResult = []; function use(plugin) { var idx = used.indexOf(plugin); if (idx === -1) { idx = used.length; used.push(plugin); usedResult[idx] = plugin(fork); } return usedResult[idx]; } var fork = { use }; return fork; } (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/operators/core.js var require_core = __commonJS({ "node_modules/ast-types/lib/def/operators/core.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var shared_1 = require_shared(); function default_1() { return { BinaryOperators: [ "==", "!=", "===", "!==", "<", "<=", ">", ">=", "<<", ">>", ">>>", "+", "-", "*", "/", "%", "&", "|", "^", "in", "instanceof" ], AssignmentOperators: [ "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&=" ], LogicalOperators: [ "||", "&&" ] }; } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/operators/es2016.js var require_es2016 = __commonJS({ "node_modules/ast-types/lib/def/operators/es2016.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var shared_1 = require_shared(); var core_1 = tslib_1.__importDefault(require_core()); function default_1(fork) { var result = fork.use(core_1.default); if (result.BinaryOperators.indexOf("**") < 0) { result.BinaryOperators.push("**"); } if (result.AssignmentOperators.indexOf("**=") < 0) { result.AssignmentOperators.push("**="); } return result; } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/operators/es2020.js var require_es2020 = __commonJS({ "node_modules/ast-types/lib/def/operators/es2020.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var shared_1 = require_shared(); var es2016_1 = tslib_1.__importDefault(require_es2016()); function default_1(fork) { var result = fork.use(es2016_1.default); if (result.LogicalOperators.indexOf("??") < 0) { result.LogicalOperators.push("??"); } return result; } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/operators/es2021.js var require_es2021 = __commonJS({ "node_modules/ast-types/lib/def/operators/es2021.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var shared_1 = require_shared(); var es2020_1 = tslib_1.__importDefault(require_es2020()); function default_1(fork) { var result = fork.use(es2020_1.default); result.LogicalOperators.forEach(function(op) { var assignOp = op + "="; if (result.AssignmentOperators.indexOf(assignOp) < 0) { result.AssignmentOperators.push(assignOp); } }); return result; } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/core.js var require_core2 = __commonJS({ "node_modules/ast-types/lib/def/core.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var core_1 = tslib_1.__importDefault(require_core()); var types_1 = tslib_1.__importDefault(require_types()); var shared_1 = tslib_1.__importStar(require_shared()); function default_1(fork) { var types = fork.use(types_1.default); var Type = types.Type; var def = Type.def; var or = Type.or; var shared = fork.use(shared_1.default); var defaults = shared.defaults; var geq = shared.geq; var _a = fork.use(core_1.default), BinaryOperators = _a.BinaryOperators, AssignmentOperators = _a.AssignmentOperators, LogicalOperators = _a.LogicalOperators; def("Printable").field("loc", or(def("SourceLocation"), null), defaults["null"], true); def("Node").bases("Printable").field("type", String).field("comments", or([def("Comment")], null), defaults["null"], true); def("SourceLocation").field("start", def("Position")).field("end", def("Position")).field("source", or(String, null), defaults["null"]); def("Position").field("line", geq(1)).field("column", geq(0)); def("File").bases("Node").build("program", "name").field("program", def("Program")).field("name", or(String, null), defaults["null"]); def("Program").bases("Node").build("body").field("body", [def("Statement")]); def("Function").bases("Node").field("id", or(def("Identifier"), null), defaults["null"]).field("params", [def("Pattern")]).field("body", def("BlockStatement")).field("generator", Boolean, defaults["false"]).field("async", Boolean, defaults["false"]); def("Statement").bases("Node"); def("EmptyStatement").bases("Statement").build(); def("BlockStatement").bases("Statement").build("body").field("body", [def("Statement")]); def("ExpressionStatement").bases("Statement").build("expression").field("expression", def("Expression")); def("IfStatement").bases("Statement").build("test", "consequent", "alternate").field("test", def("Expression")).field("consequent", def("Statement")).field("alternate", or(def("Statement"), null), defaults["null"]); def("LabeledStatement").bases("Statement").build("label", "body").field("label", def("Identifier")).field("body", def("Statement")); def("BreakStatement").bases("Statement").build("label").field("label", or(def("Identifier"), null), defaults["null"]); def("ContinueStatement").bases("Statement").build("label").field("label", or(def("Identifier"), null), defaults["null"]); def("WithStatement").bases("Statement").build("object", "body").field("object", def("Expression")).field("body", def("Statement")); def("SwitchStatement").bases("Statement").build("discriminant", "cases", "lexical").field("discriminant", def("Expression")).field("cases", [def("SwitchCase")]).field("lexical", Boolean, defaults["false"]); def("ReturnStatement").bases("Statement").build("argument").field("argument", or(def("Expression"), null)); def("ThrowStatement").bases("Statement").build("argument").field("argument", def("Expression")); def("TryStatement").bases("Statement").build("block", "handler", "finalizer").field("block", def("BlockStatement")).field("handler", or(def("CatchClause"), null), function() { return this.handlers && this.handlers[0] || null; }).field("handlers", [def("CatchClause")], function() { return this.handler ? [this.handler] : []; }, true).field("guardedHandlers", [def("CatchClause")], defaults.emptyArray).field("finalizer", or(def("BlockStatement"), null), defaults["null"]); def("CatchClause").bases("Node").build("param", "guard", "body").field("param", def("Pattern")).field("guard", or(def("Expression"), null), defaults["null"]).field("body", def("BlockStatement")); def("WhileStatement").bases("Statement").build("test", "body").field("test", def("Expression")).field("body", def("Statement")); def("DoWhileStatement").bases("Statement").build("body", "test").field("body", def("Statement")).field("test", def("Expression")); def("ForStatement").bases("Statement").build("init", "test", "update", "body").field("init", or(def("VariableDeclaration"), def("Expression"), null)).field("test", or(def("Expression"), null)).field("update", or(def("Expression"), null)).field("body", def("Statement")); def("ForInStatement").bases("Statement").build("left", "right", "body").field("left", or(def("VariableDeclaration"), def("Expression"))).field("right", def("Expression")).field("body", def("Statement")); def("DebuggerStatement").bases("Statement").build(); def("Declaration").bases("Statement"); def("FunctionDeclaration").bases("Function", "Declaration").build("id", "params", "body").field("id", def("Identifier")); def("FunctionExpression").bases("Function", "Expression").build("id", "params", "body"); def("VariableDeclaration").bases("Declaration").build("kind", "declarations").field("kind", or("var", "let", "const")).field("declarations", [def("VariableDeclarator")]); def("VariableDeclarator").bases("Node").build("id", "init").field("id", def("Pattern")).field("init", or(def("Expression"), null), defaults["null"]); def("Expression").bases("Node"); def("ThisExpression").bases("Expression").build(); def("ArrayExpression").bases("Expression").build("elements").field("elements", [or(def("Expression"), null)]); def("ObjectExpression").bases("Expression").build("properties").field("properties", [def("Property")]); def("Property").bases("Node").build("kind", "key", "value").field("kind", or("init", "get", "set")).field("key", or(def("Literal"), def("Identifier"))).field("value", def("Expression")); def("SequenceExpression").bases("Expression").build("expressions").field("expressions", [def("Expression")]); var UnaryOperator = or("-", "+", "!", "~", "typeof", "void", "delete"); def("UnaryExpression").bases("Expression").build("operator", "argument", "prefix").field("operator", UnaryOperator).field("argument", def("Expression")).field("prefix", Boolean, defaults["true"]); var BinaryOperator = or.apply(void 0, BinaryOperators); def("BinaryExpression").bases("Expression").build("operator", "left", "right").field("operator", BinaryOperator).field("left", def("Expression")).field("right", def("Expression")); var AssignmentOperator = or.apply(void 0, AssignmentOperators); def("AssignmentExpression").bases("Expression").build("operator", "left", "right").field("operator", AssignmentOperator).field("left", or(def("Pattern"), def("MemberExpression"))).field("right", def("Expression")); var UpdateOperator = or("++", "--"); def("UpdateExpression").bases("Expression").build("operator", "argument", "prefix").field("operator", UpdateOperator).field("argument", def("Expression")).field("prefix", Boolean); var LogicalOperator = or.apply(void 0, LogicalOperators); def("LogicalExpression").bases("Expression").build("operator", "left", "right").field("operator", LogicalOperator).field("left", def("Expression")).field("right", def("Expression")); def("ConditionalExpression").bases("Expression").build("test", "consequent", "alternate").field("test", def("Expression")).field("consequent", def("Expression")).field("alternate", def("Expression")); def("NewExpression").bases("Expression").build("callee", "arguments").field("callee", def("Expression")).field("arguments", [def("Expression")]); def("CallExpression").bases("Expression").build("callee", "arguments").field("callee", def("Expression")).field("arguments", [def("Expression")]); def("MemberExpression").bases("Expression").build("object", "property", "computed").field("object", def("Expression")).field("property", or(def("Identifier"), def("Expression"))).field("computed", Boolean, function() { var type2 = this.property.type; if (type2 === "Literal" || type2 === "MemberExpression" || type2 === "BinaryExpression") { return true; } return false; }); def("Pattern").bases("Node"); def("SwitchCase").bases("Node").build("test", "consequent").field("test", or(def("Expression"), null)).field("consequent", [def("Statement")]); def("Identifier").bases("Expression", "Pattern").build("name").field("name", String).field("optional", Boolean, defaults["false"]); def("Literal").bases("Expression").build("value").field("value", or(String, Boolean, null, Number, RegExp, BigInt)); def("Comment").bases("Printable").field("value", String).field("leading", Boolean, defaults["true"]).field("trailing", Boolean, defaults["false"]); } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/es6.js var require_es6 = __commonJS({ "node_modules/ast-types/lib/def/es6.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var core_1 = tslib_1.__importDefault(require_core2()); var types_1 = tslib_1.__importDefault(require_types()); var shared_1 = tslib_1.__importStar(require_shared()); function default_1(fork) { fork.use(core_1.default); var types = fork.use(types_1.default); var def = types.Type.def; var or = types.Type.or; var defaults = fork.use(shared_1.default).defaults; def("Function").field("generator", Boolean, defaults["false"]).field("expression", Boolean, defaults["false"]).field("defaults", [or(def("Expression"), null)], defaults.emptyArray).field("rest", or(def("Identifier"), null), defaults["null"]); def("RestElement").bases("Pattern").build("argument").field("argument", def("Pattern")).field( "typeAnnotation", // for Babylon. Flow parser puts it on the identifier or(def("TypeAnnotation"), def("TSTypeAnnotation"), null), defaults["null"] ); def("SpreadElementPattern").bases("Pattern").build("argument").field("argument", def("Pattern")); def("FunctionDeclaration").build("id", "params", "body", "generator", "expression").field("id", or(def("Identifier"), null)); def("FunctionExpression").build("id", "params", "body", "generator", "expression"); def("ArrowFunctionExpression").bases("Function", "Expression").build("params", "body", "expression").field("id", null, defaults["null"]).field("body", or(def("BlockStatement"), def("Expression"))).field("generator", false, defaults["false"]); def("ForOfStatement").bases("Statement").build("left", "right", "body").field("left", or(def("VariableDeclaration"), def("Pattern"))).field("right", def("Expression")).field("body", def("Statement")); def("YieldExpression").bases("Expression").build("argument", "delegate").field("argument", or(def("Expression"), null)).field("delegate", Boolean, defaults["false"]); def("GeneratorExpression").bases("Expression").build("body", "blocks", "filter").field("body", def("Expression")).field("blocks", [def("ComprehensionBlock")]).field("filter", or(def("Expression"), null)); def("ComprehensionExpression").bases("Expression").build("body", "blocks", "filter").field("body", def("Expression")).field("blocks", [def("ComprehensionBlock")]).field("filter", or(def("Expression"), null)); def("ComprehensionBlock").bases("Node").build("left", "right", "each").field("left", def("Pattern")).field("right", def("Expression")).field("each", Boolean); def("Property").field("key", or(def("Literal"), def("Identifier"), def("Expression"))).field("value", or(def("Expression"), def("Pattern"))).field("method", Boolean, defaults["false"]).field("shorthand", Boolean, defaults["false"]).field("computed", Boolean, defaults["false"]); def("ObjectProperty").field("shorthand", Boolean, defaults["false"]); def("PropertyPattern").bases("Pattern").build("key", "pattern").field("key", or(def("Literal"), def("Identifier"), def("Expression"))).field("pattern", def("Pattern")).field("computed", Boolean, defaults["false"]); def("ObjectPattern").bases("Pattern").build("properties").field("properties", [or(def("PropertyPattern"), def("Property"))]); def("ArrayPattern").bases("Pattern").build("elements").field("elements", [or(def("Pattern"), null)]); def("SpreadElement").bases("Node").build("argument").field("argument", def("Expression")); def("ArrayExpression").field("elements", [or(def("Expression"), def("SpreadElement"), def("RestElement"), null)]); def("NewExpression").field("arguments", [or(def("Expression"), def("SpreadElement"))]); def("CallExpression").field("arguments", [or(def("Expression"), def("SpreadElement"))]); def("AssignmentPattern").bases("Pattern").build("left", "right").field("left", def("Pattern")).field("right", def("Expression")); def("MethodDefinition").bases("Declaration").build("kind", "key", "value", "static").field("kind", or("constructor", "method", "get", "set")).field("key", def("Expression")).field("value", def("Function")).field("computed", Boolean, defaults["false"]).field("static", Boolean, defaults["false"]); var ClassBodyElement = or(def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty"), def("StaticBlock")); def("ClassProperty").bases("Declaration").build("key").field("key", or(def("Literal"), def("Identifier"), def("Expression"))).field("computed", Boolean, defaults["false"]); def("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition", ClassBodyElement); def("ClassBody").bases("Declaration").build("body").field("body", [ClassBodyElement]); def("ClassDeclaration").bases("Declaration").build("id", "body", "superClass").field("id", or(def("Identifier"), null)).field("body", def("ClassBody")).field("superClass", or(def("Expression"), null), defaults["null"]); def("ClassExpression").bases("Expression").build("id", "body", "superClass").field("id", or(def("Identifier"), null), defaults["null"]).field("body", def("ClassBody")).field("superClass", or(def("Expression"), null), defaults["null"]); def("Super").bases("Expression").build(); def("Specifier").bases("Node"); def("ModuleSpecifier").bases("Specifier").field("local", or(def("Identifier"), null), defaults["null"]).field("id", or(def("Identifier"), null), defaults["null"]).field("name", or(def("Identifier"), null), defaults["null"]); def("ImportSpecifier").bases("ModuleSpecifier").build("imported", "local").field("imported", def("Identifier")); def("ImportDefaultSpecifier").bases("ModuleSpecifier").build("local"); def("ImportNamespaceSpecifier").bases("ModuleSpecifier").build("local"); def("ImportDeclaration").bases("Declaration").build("specifiers", "source", "importKind").field("specifiers", [or(def("ImportSpecifier"), def("ImportNamespaceSpecifier"), def("ImportDefaultSpecifier"))], defaults.emptyArray).field("source", def("Literal")).field("importKind", or("value", "type"), function() { return "value"; }); def("ExportNamedDeclaration").bases("Declaration").build("declaration", "specifiers", "source").field("declaration", or(def("Declaration"), null)).field("specifiers", [def("ExportSpecifier")], defaults.emptyArray).field("source", or(def("Literal"), null), defaults["null"]); def("ExportSpecifier").bases("ModuleSpecifier").build("local", "exported").field("exported", def("Identifier")); def("ExportDefaultDeclaration").bases("Declaration").build("declaration").field("declaration", or(def("Declaration"), def("Expression"))); def("ExportAllDeclaration").bases("Declaration").build("source").field("source", def("Literal")); def("TaggedTemplateExpression").bases("Expression").build("tag", "quasi").field("tag", def("Expression")).field("quasi", def("TemplateLiteral")); def("TemplateLiteral").bases("Expression").build("quasis", "expressions").field("quasis", [def("TemplateElement")]).field("expressions", [def("Expression")]); def("TemplateElement").bases("Node").build("value", "tail").field("value", { "cooked": String, "raw": String }).field("tail", Boolean); def("MetaProperty").bases("Expression").build("meta", "property").field("meta", def("Identifier")).field("property", def("Identifier")); } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/es2016.js var require_es20162 = __commonJS({ "node_modules/ast-types/lib/def/es2016.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var es2016_1 = tslib_1.__importDefault(require_es2016()); var es6_1 = tslib_1.__importDefault(require_es6()); var shared_1 = require_shared(); function default_1(fork) { fork.use(es2016_1.default); fork.use(es6_1.default); } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/es2017.js var require_es2017 = __commonJS({ "node_modules/ast-types/lib/def/es2017.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var es2016_1 = tslib_1.__importDefault(require_es20162()); var types_1 = tslib_1.__importDefault(require_types()); var shared_1 = tslib_1.__importStar(require_shared()); function default_1(fork) { fork.use(es2016_1.default); var types = fork.use(types_1.default); var def = types.Type.def; var defaults = fork.use(shared_1.default).defaults; def("Function").field("async", Boolean, defaults["false"]); def("AwaitExpression").bases("Expression").build("argument").field("argument", def("Expression")); } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/es2018.js var require_es2018 = __commonJS({ "node_modules/ast-types/lib/def/es2018.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var es2017_1 = tslib_1.__importDefault(require_es2017()); var types_1 = tslib_1.__importDefault(require_types()); var shared_1 = tslib_1.__importStar(require_shared()); function default_1(fork) { fork.use(es2017_1.default); var types = fork.use(types_1.default); var def = types.Type.def; var or = types.Type.or; var defaults = fork.use(shared_1.default).defaults; def("ForOfStatement").field("await", Boolean, defaults["false"]); def("SpreadProperty").bases("Node").build("argument").field("argument", def("Expression")); def("ObjectExpression").field("properties", [or( def("Property"), def("SpreadProperty"), // Legacy def("SpreadElement") )]); def("TemplateElement").field("value", { "cooked": or(String, null), "raw": String }); def("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument", def("Pattern")); def("ObjectPattern").field("properties", [or(def("PropertyPattern"), def("Property"), def("RestElement"), def("SpreadPropertyPattern"))]); } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/es2019.js var require_es2019 = __commonJS({ "node_modules/ast-types/lib/def/es2019.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var es2018_1 = tslib_1.__importDefault(require_es2018()); var types_1 = tslib_1.__importDefault(require_types()); var shared_1 = tslib_1.__importStar(require_shared()); function default_1(fork) { fork.use(es2018_1.default); var types = fork.use(types_1.default); var def = types.Type.def; var or = types.Type.or; var defaults = fork.use(shared_1.default).defaults; def("CatchClause").field("param", or(def("Pattern"), null), defaults["null"]); } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/es2020.js var require_es20202 = __commonJS({ "node_modules/ast-types/lib/def/es2020.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var es2020_1 = tslib_1.__importDefault(require_es2020()); var es2019_1 = tslib_1.__importDefault(require_es2019()); var types_1 = tslib_1.__importDefault(require_types()); var shared_1 = tslib_1.__importStar(require_shared()); function default_1(fork) { fork.use(es2020_1.default); fork.use(es2019_1.default); var types = fork.use(types_1.default); var def = types.Type.def; var or = types.Type.or; var shared = fork.use(shared_1.default); var defaults = shared.defaults; def("ImportExpression").bases("Expression").build("source").field("source", def("Expression")); def("ExportAllDeclaration").bases("Declaration").build("source", "exported").field("source", def("Literal")).field("exported", or(def("Identifier"), null, void 0), defaults["null"]); def("ChainElement").bases("Node").field("optional", Boolean, defaults["false"]); def("CallExpression").bases("Expression", "ChainElement"); def("MemberExpression").bases("Expression", "ChainElement"); def("ChainExpression").bases("Expression").build("expression").field("expression", def("ChainElement")); def("OptionalCallExpression").bases("CallExpression").build("callee", "arguments", "optional").field("optional", Boolean, defaults["true"]); def("OptionalMemberExpression").bases("MemberExpression").build("object", "property", "computed", "optional").field("optional", Boolean, defaults["true"]); } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/es2021.js var require_es20212 = __commonJS({ "node_modules/ast-types/lib/def/es2021.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var es2021_1 = tslib_1.__importDefault(require_es2021()); var es2020_1 = tslib_1.__importDefault(require_es20202()); var shared_1 = require_shared(); function default_1(fork) { fork.use(es2021_1.default); fork.use(es2020_1.default); } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/es2022.js var require_es2022 = __commonJS({ "node_modules/ast-types/lib/def/es2022.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var es2021_1 = tslib_1.__importDefault(require_es20212()); var types_1 = tslib_1.__importDefault(require_types()); var shared_1 = require_shared(); function default_1(fork) { fork.use(es2021_1.default); var types = fork.use(types_1.default); var def = types.Type.def; def("StaticBlock").bases("Declaration").build("body").field("body", [def("Statement")]); } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/es-proposals.js var require_es_proposals = __commonJS({ "node_modules/ast-types/lib/def/es-proposals.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var types_1 = tslib_1.__importDefault(require_types()); var shared_1 = tslib_1.__importStar(require_shared()); var es2022_1 = tslib_1.__importDefault(require_es2022()); function default_1(fork) { fork.use(es2022_1.default); var types = fork.use(types_1.default); var Type = types.Type; var def = types.Type.def; var or = Type.or; var shared = fork.use(shared_1.default); var defaults = shared.defaults; def("AwaitExpression").build("argument", "all").field("argument", or(def("Expression"), null)).field("all", Boolean, defaults["false"]); def("Decorator").bases("Node").build("expression").field("expression", def("Expression")); def("Property").field("decorators", or([def("Decorator")], null), defaults["null"]); def("MethodDefinition").field("decorators", or([def("Decorator")], null), defaults["null"]); def("PrivateName").bases("Expression", "Pattern").build("id").field("id", def("Identifier")); def("ClassPrivateProperty").bases("ClassProperty").build("key", "value").field("key", def("PrivateName")).field("value", or(def("Expression"), null), defaults["null"]); def("ImportAttribute").bases("Node").build("key", "value").field("key", or(def("Identifier"), def("Literal"))).field("value", def("Expression")); [ "ImportDeclaration", "ExportAllDeclaration", "ExportNamedDeclaration" ].forEach(function(decl) { def(decl).field("assertions", [def("ImportAttribute")], defaults.emptyArray); }); def("RecordExpression").bases("Expression").build("properties").field("properties", [or(def("ObjectProperty"), def("ObjectMethod"), def("SpreadElement"))]); def("TupleExpression").bases("Expression").build("elements").field("elements", [or(def("Expression"), def("SpreadElement"), null)]); def("ModuleExpression").bases("Node").build("body").field("body", def("Program")); } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/jsx.js var require_jsx = __commonJS({ "node_modules/ast-types/lib/def/jsx.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var es_proposals_1 = tslib_1.__importDefault(require_es_proposals()); var types_1 = tslib_1.__importDefault(require_types()); var shared_1 = tslib_1.__importStar(require_shared()); function default_1(fork) { fork.use(es_proposals_1.default); var types = fork.use(types_1.default); var def = types.Type.def; var or = types.Type.or; var defaults = fork.use(shared_1.default).defaults; def("JSXAttribute").bases("Node").build("name", "value").field("name", or(def("JSXIdentifier"), def("JSXNamespacedName"))).field("value", or( def("Literal"), // attr="value" def("JSXExpressionContainer"), // attr={value} def("JSXElement"), // attr=
def("JSXFragment"), // attr=<> null // attr= or just attr ), defaults["null"]); def("JSXIdentifier").bases("Identifier").build("name").field("name", String); def("JSXNamespacedName").bases("Node").build("namespace", "name").field("namespace", def("JSXIdentifier")).field("name", def("JSXIdentifier")); def("JSXMemberExpression").bases("MemberExpression").build("object", "property").field("object", or(def("JSXIdentifier"), def("JSXMemberExpression"))).field("property", def("JSXIdentifier")).field("computed", Boolean, defaults.false); var JSXElementName = or(def("JSXIdentifier"), def("JSXNamespacedName"), def("JSXMemberExpression")); def("JSXSpreadAttribute").bases("Node").build("argument").field("argument", def("Expression")); var JSXAttributes = [or(def("JSXAttribute"), def("JSXSpreadAttribute"))]; def("JSXExpressionContainer").bases("Expression").build("expression").field("expression", or(def("Expression"), def("JSXEmptyExpression"))); var JSXChildren = [or( def("JSXText"), def("JSXExpressionContainer"), def("JSXSpreadChild"), def("JSXElement"), def("JSXFragment"), def("Literal") // Legacy: Esprima should return JSXText instead. )]; def("JSXElement").bases("Expression").build("openingElement", "closingElement", "children").field("openingElement", def("JSXOpeningElement")).field("closingElement", or(def("JSXClosingElement"), null), defaults["null"]).field("children", JSXChildren, defaults.emptyArray).field("name", JSXElementName, function() { return this.openingElement.name; }, true).field("selfClosing", Boolean, function() { return this.openingElement.selfClosing; }, true).field("attributes", JSXAttributes, function() { return this.openingElement.attributes; }, true); def("JSXOpeningElement").bases("Node").build("name", "attributes", "selfClosing").field("name", JSXElementName).field("attributes", JSXAttributes, defaults.emptyArray).field("selfClosing", Boolean, defaults["false"]); def("JSXClosingElement").bases("Node").build("name").field("name", JSXElementName); def("JSXFragment").bases("Expression").build("openingFragment", "closingFragment", "children").field("openingFragment", def("JSXOpeningFragment")).field("closingFragment", def("JSXClosingFragment")).field("children", JSXChildren, defaults.emptyArray); def("JSXOpeningFragment").bases("Node").build(); def("JSXClosingFragment").bases("Node").build(); def("JSXText").bases("Literal").build("value", "raw").field("value", String).field("raw", String, function() { return this.value; }); def("JSXEmptyExpression").bases("Node").build(); def("JSXSpreadChild").bases("Node").build("expression").field("expression", def("Expression")); } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/type-annotations.js var require_type_annotations = __commonJS({ "node_modules/ast-types/lib/def/type-annotations.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var types_1 = tslib_1.__importDefault(require_types()); var shared_1 = tslib_1.__importStar(require_shared()); function default_1(fork) { var types = fork.use(types_1.default); var def = types.Type.def; var or = types.Type.or; var defaults = fork.use(shared_1.default).defaults; var TypeAnnotation = or(def("TypeAnnotation"), def("TSTypeAnnotation"), null); var TypeParamDecl = or(def("TypeParameterDeclaration"), def("TSTypeParameterDeclaration"), null); def("Identifier").field("typeAnnotation", TypeAnnotation, defaults["null"]); def("ObjectPattern").field("typeAnnotation", TypeAnnotation, defaults["null"]); def("Function").field("returnType", TypeAnnotation, defaults["null"]).field("typeParameters", TypeParamDecl, defaults["null"]); def("ClassProperty").build("key", "value", "typeAnnotation", "static").field("value", or(def("Expression"), null)).field("static", Boolean, defaults["false"]).field("typeAnnotation", TypeAnnotation, defaults["null"]); [ "ClassDeclaration", "ClassExpression" ].forEach(function(typeName) { def(typeName).field("typeParameters", TypeParamDecl, defaults["null"]).field("superTypeParameters", or(def("TypeParameterInstantiation"), def("TSTypeParameterInstantiation"), null), defaults["null"]).field("implements", or([def("ClassImplements")], [def("TSExpressionWithTypeArguments")]), defaults.emptyArray); }); } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/flow.js var require_flow = __commonJS({ "node_modules/ast-types/lib/def/flow.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var es_proposals_1 = tslib_1.__importDefault(require_es_proposals()); var type_annotations_1 = tslib_1.__importDefault(require_type_annotations()); var types_1 = tslib_1.__importDefault(require_types()); var shared_1 = tslib_1.__importStar(require_shared()); function default_1(fork) { fork.use(es_proposals_1.default); fork.use(type_annotations_1.default); var types = fork.use(types_1.default); var def = types.Type.def; var or = types.Type.or; var defaults = fork.use(shared_1.default).defaults; def("Flow").bases("Node"); def("FlowType").bases("Flow"); def("AnyTypeAnnotation").bases("FlowType").build(); def("EmptyTypeAnnotation").bases("FlowType").build(); def("MixedTypeAnnotation").bases("FlowType").build(); def("VoidTypeAnnotation").bases("FlowType").build(); def("SymbolTypeAnnotation").bases("FlowType").build(); def("NumberTypeAnnotation").bases("FlowType").build(); def("BigIntTypeAnnotation").bases("FlowType").build(); def("NumberLiteralTypeAnnotation").bases("FlowType").build("value", "raw").field("value", Number).field("raw", String); def("NumericLiteralTypeAnnotation").bases("FlowType").build("value", "raw").field("value", Number).field("raw", String); def("BigIntLiteralTypeAnnotation").bases("FlowType").build("value", "raw").field("value", null).field("raw", String); def("StringTypeAnnotation").bases("FlowType").build(); def("StringLiteralTypeAnnotation").bases("FlowType").build("value", "raw").field("value", String).field("raw", String); def("BooleanTypeAnnotation").bases("FlowType").build(); def("BooleanLiteralTypeAnnotation").bases("FlowType").build("value", "raw").field("value", Boolean).field("raw", String); def("TypeAnnotation").bases("Node").build("typeAnnotation").field("typeAnnotation", def("FlowType")); def("NullableTypeAnnotation").bases("FlowType").build("typeAnnotation").field("typeAnnotation", def("FlowType")); def("NullLiteralTypeAnnotation").bases("FlowType").build(); def("NullTypeAnnotation").bases("FlowType").build(); def("ThisTypeAnnotation").bases("FlowType").build(); def("ExistsTypeAnnotation").bases("FlowType").build(); def("ExistentialTypeParam").bases("FlowType").build(); def("FunctionTypeAnnotation").bases("FlowType").build("params", "returnType", "rest", "typeParameters").field("params", [def("FunctionTypeParam")]).field("returnType", def("FlowType")).field("rest", or(def("FunctionTypeParam"), null)).field("typeParameters", or(def("TypeParameterDeclaration"), null)); def("FunctionTypeParam").bases("Node").build("name", "typeAnnotation", "optional").field("name", or(def("Identifier"), null)).field("typeAnnotation", def("FlowType")).field("optional", Boolean); def("ArrayTypeAnnotation").bases("FlowType").build("elementType").field("elementType", def("FlowType")); def("ObjectTypeAnnotation").bases("FlowType").build("properties", "indexers", "callProperties").field("properties", [ or(def("ObjectTypeProperty"), def("ObjectTypeSpreadProperty")) ]).field("indexers", [def("ObjectTypeIndexer")], defaults.emptyArray).field("callProperties", [def("ObjectTypeCallProperty")], defaults.emptyArray).field("inexact", or(Boolean, void 0), defaults["undefined"]).field("exact", Boolean, defaults["false"]).field("internalSlots", [def("ObjectTypeInternalSlot")], defaults.emptyArray); def("Variance").bases("Node").build("kind").field("kind", or("plus", "minus")); var LegacyVariance = or(def("Variance"), "plus", "minus", null); def("ObjectTypeProperty").bases("Node").build("key", "value", "optional").field("key", or(def("Literal"), def("Identifier"))).field("value", def("FlowType")).field("optional", Boolean).field("variance", LegacyVariance, defaults["null"]); def("ObjectTypeIndexer").bases("Node").build("id", "key", "value").field("id", def("Identifier")).field("key", def("FlowType")).field("value", def("FlowType")).field("variance", LegacyVariance, defaults["null"]).field("static", Boolean, defaults["false"]); def("ObjectTypeCallProperty").bases("Node").build("value").field("value", def("FunctionTypeAnnotation")).field("static", Boolean, defaults["false"]); def("QualifiedTypeIdentifier").bases("Node").build("qualification", "id").field("qualification", or(def("Identifier"), def("QualifiedTypeIdentifier"))).field("id", def("Identifier")); def("GenericTypeAnnotation").bases("FlowType").build("id", "typeParameters").field("id", or(def("Identifier"), def("QualifiedTypeIdentifier"))).field("typeParameters", or(def("TypeParameterInstantiation"), null)); def("MemberTypeAnnotation").bases("FlowType").build("object", "property").field("object", def("Identifier")).field("property", or(def("MemberTypeAnnotation"), def("GenericTypeAnnotation"))); def("IndexedAccessType").bases("FlowType").build("objectType", "indexType").field("objectType", def("FlowType")).field("indexType", def("FlowType")); def("OptionalIndexedAccessType").bases("FlowType").build("objectType", "indexType", "optional").field("objectType", def("FlowType")).field("indexType", def("FlowType")).field("optional", Boolean); def("UnionTypeAnnotation").bases("FlowType").build("types").field("types", [def("FlowType")]); def("IntersectionTypeAnnotation").bases("FlowType").build("types").field("types", [def("FlowType")]); def("TypeofTypeAnnotation").bases("FlowType").build("argument").field("argument", def("FlowType")); def("ObjectTypeSpreadProperty").bases("Node").build("argument").field("argument", def("FlowType")); def("ObjectTypeInternalSlot").bases("Node").build("id", "value", "optional", "static", "method").field("id", def("Identifier")).field("value", def("FlowType")).field("optional", Boolean).field("static", Boolean).field("method", Boolean); def("TypeParameterDeclaration").bases("Node").build("params").field("params", [def("TypeParameter")]); def("TypeParameterInstantiation").bases("Node").build("params").field("params", [def("FlowType")]); def("TypeParameter").bases("FlowType").build("name", "variance", "bound", "default").field("name", String).field("variance", LegacyVariance, defaults["null"]).field("bound", or(def("TypeAnnotation"), null), defaults["null"]).field("default", or(def("FlowType"), null), defaults["null"]); def("ClassProperty").field("variance", LegacyVariance, defaults["null"]); def("ClassImplements").bases("Node").build("id").field("id", def("Identifier")).field("superClass", or(def("Expression"), null), defaults["null"]).field("typeParameters", or(def("TypeParameterInstantiation"), null), defaults["null"]); def("InterfaceTypeAnnotation").bases("FlowType").build("body", "extends").field("body", def("ObjectTypeAnnotation")).field("extends", or([def("InterfaceExtends")], null), defaults["null"]); def("InterfaceDeclaration").bases("Declaration").build("id", "body", "extends").field("id", def("Identifier")).field("typeParameters", or(def("TypeParameterDeclaration"), null), defaults["null"]).field("body", def("ObjectTypeAnnotation")).field("extends", [def("InterfaceExtends")]); def("DeclareInterface").bases("InterfaceDeclaration").build("id", "body", "extends"); def("InterfaceExtends").bases("Node").build("id").field("id", def("Identifier")).field("typeParameters", or(def("TypeParameterInstantiation"), null), defaults["null"]); def("TypeAlias").bases("Declaration").build("id", "typeParameters", "right").field("id", def("Identifier")).field("typeParameters", or(def("TypeParameterDeclaration"), null)).field("right", def("FlowType")); def("DeclareTypeAlias").bases("TypeAlias").build("id", "typeParameters", "right"); def("OpaqueType").bases("Declaration").build("id", "typeParameters", "impltype", "supertype").field("id", def("Identifier")).field("typeParameters", or(def("TypeParameterDeclaration"), null)).field("impltype", def("FlowType")).field("supertype", or(def("FlowType"), null)); def("DeclareOpaqueType").bases("OpaqueType").build("id", "typeParameters", "supertype").field("impltype", or(def("FlowType"), null)); def("TypeCastExpression").bases("Expression").build("expression", "typeAnnotation").field("expression", def("Expression")).field("typeAnnotation", def("TypeAnnotation")); def("TupleTypeAnnotation").bases("FlowType").build("types").field("types", [def("FlowType")]); def("DeclareVariable").bases("Statement").build("id").field("id", def("Identifier")); def("DeclareFunction").bases("Statement").build("id").field("id", def("Identifier")).field("predicate", or(def("FlowPredicate"), null), defaults["null"]); def("DeclareClass").bases("InterfaceDeclaration").build("id"); def("DeclareModule").bases("Statement").build("id", "body").field("id", or(def("Identifier"), def("Literal"))).field("body", def("BlockStatement")); def("DeclareModuleExports").bases("Statement").build("typeAnnotation").field("typeAnnotation", def("TypeAnnotation")); def("DeclareExportDeclaration").bases("Declaration").build("default", "declaration", "specifiers", "source").field("default", Boolean).field("declaration", or( def("DeclareVariable"), def("DeclareFunction"), def("DeclareClass"), def("FlowType"), // Implies default. def("TypeAlias"), // Implies named type def("DeclareOpaqueType"), // Implies named opaque type def("InterfaceDeclaration"), null )).field("specifiers", [or(def("ExportSpecifier"), def("ExportBatchSpecifier"))], defaults.emptyArray).field("source", or(def("Literal"), null), defaults["null"]); def("DeclareExportAllDeclaration").bases("Declaration").build("source").field("source", or(def("Literal"), null), defaults["null"]); def("ImportDeclaration").field("importKind", or("value", "type", "typeof"), function() { return "value"; }); def("FlowPredicate").bases("Flow"); def("InferredPredicate").bases("FlowPredicate").build(); def("DeclaredPredicate").bases("FlowPredicate").build("value").field("value", def("Expression")); def("Function").field("predicate", or(def("FlowPredicate"), null), defaults["null"]); def("CallExpression").field("typeArguments", or(null, def("TypeParameterInstantiation")), defaults["null"]); def("NewExpression").field("typeArguments", or(null, def("TypeParameterInstantiation")), defaults["null"]); def("EnumDeclaration").bases("Declaration").build("id", "body").field("id", def("Identifier")).field("body", or(def("EnumBooleanBody"), def("EnumNumberBody"), def("EnumStringBody"), def("EnumSymbolBody"))); def("EnumBooleanBody").build("members", "explicitType").field("members", [def("EnumBooleanMember")]).field("explicitType", Boolean); def("EnumNumberBody").build("members", "explicitType").field("members", [def("EnumNumberMember")]).field("explicitType", Boolean); def("EnumStringBody").build("members", "explicitType").field("members", or([def("EnumStringMember")], [def("EnumDefaultedMember")])).field("explicitType", Boolean); def("EnumSymbolBody").build("members").field("members", [def("EnumDefaultedMember")]); def("EnumBooleanMember").build("id", "init").field("id", def("Identifier")).field("init", or(def("Literal"), Boolean)); def("EnumNumberMember").build("id", "init").field("id", def("Identifier")).field("init", def("Literal")); def("EnumStringMember").build("id", "init").field("id", def("Identifier")).field("init", def("Literal")); def("EnumDefaultedMember").build("id").field("id", def("Identifier")); } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/esprima.js var require_esprima = __commonJS({ "node_modules/ast-types/lib/def/esprima.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var es_proposals_1 = tslib_1.__importDefault(require_es_proposals()); var types_1 = tslib_1.__importDefault(require_types()); var shared_1 = tslib_1.__importStar(require_shared()); function default_1(fork) { fork.use(es_proposals_1.default); var types = fork.use(types_1.default); var defaults = fork.use(shared_1.default).defaults; var def = types.Type.def; var or = types.Type.or; def("VariableDeclaration").field("declarations", [or( def("VariableDeclarator"), def("Identifier") // Esprima deviation. )]); def("Property").field("value", or( def("Expression"), def("Pattern") // Esprima deviation. )); def("ArrayPattern").field("elements", [or(def("Pattern"), def("SpreadElement"), null)]); def("ObjectPattern").field("properties", [or( def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern"), def("SpreadProperty") // Used by Esprima. )]); def("ExportSpecifier").bases("ModuleSpecifier").build("id", "name"); def("ExportBatchSpecifier").bases("Specifier").build(); def("ExportDeclaration").bases("Declaration").build("default", "declaration", "specifiers", "source").field("default", Boolean).field("declaration", or( def("Declaration"), def("Expression"), // Implies default. null )).field("specifiers", [or(def("ExportSpecifier"), def("ExportBatchSpecifier"))], defaults.emptyArray).field("source", or(def("Literal"), null), defaults["null"]); def("Block").bases("Comment").build( "value", /*optional:*/ "leading", "trailing" ); def("Line").bases("Comment").build( "value", /*optional:*/ "leading", "trailing" ); } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/babel-core.js var require_babel_core = __commonJS({ "node_modules/ast-types/lib/def/babel-core.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var es_proposals_1 = tslib_1.__importDefault(require_es_proposals()); var types_1 = tslib_1.__importDefault(require_types()); var shared_1 = tslib_1.__importStar(require_shared()); function default_1(fork) { var _a, _b, _c, _d, _e; fork.use(es_proposals_1.default); var types = fork.use(types_1.default); var defaults = fork.use(shared_1.default).defaults; var def = types.Type.def; var or = types.Type.or; var isUndefined = types.builtInTypes.undefined; def("Noop").bases("Statement").build(); def("DoExpression").bases("Expression").build("body").field("body", [def("Statement")]); def("BindExpression").bases("Expression").build("object", "callee").field("object", or(def("Expression"), null)).field("callee", def("Expression")); def("ParenthesizedExpression").bases("Expression").build("expression").field("expression", def("Expression")); def("ExportNamespaceSpecifier").bases("Specifier").build("exported").field("exported", def("Identifier")); def("ExportDefaultSpecifier").bases("Specifier").build("exported").field("exported", def("Identifier")); def("CommentBlock").bases("Comment").build( "value", /*optional:*/ "leading", "trailing" ); def("CommentLine").bases("Comment").build( "value", /*optional:*/ "leading", "trailing" ); def("Directive").bases("Node").build("value").field("value", def("DirectiveLiteral")); def("DirectiveLiteral").bases("Node", "Expression").build("value").field("value", String, defaults["use strict"]); def("InterpreterDirective").bases("Node").build("value").field("value", String); def("BlockStatement").bases("Statement").build("body").field("body", [def("Statement")]).field("directives", [def("Directive")], defaults.emptyArray); def("Program").bases("Node").build("body").field("body", [def("Statement")]).field("directives", [def("Directive")], defaults.emptyArray).field("interpreter", or(def("InterpreterDirective"), null), defaults["null"]); function makeLiteralExtra(rawValueType, toRaw) { if (rawValueType === void 0) { rawValueType = String; } return [ "extra", { rawValue: rawValueType, raw: String }, function getDefault() { var value = types.getFieldValue(this, "value"); return { rawValue: value, raw: toRaw ? toRaw(value) : String(value) }; } ]; } (_a = def("StringLiteral").bases("Literal").build("value").field("value", String)).field.apply(_a, makeLiteralExtra(String, function(val) { return JSON.stringify(val); })); (_b = def("NumericLiteral").bases("Literal").build("value").field("value", Number).field("raw", or(String, null), defaults["null"])).field.apply(_b, makeLiteralExtra(Number)); (_c = def("BigIntLiteral").bases("Literal").build("value").field("value", or(String, Number))).field.apply(_c, makeLiteralExtra(String, function(val) { return val + "n"; })); (_d = def("DecimalLiteral").bases("Literal").build("value").field("value", String)).field.apply(_d, makeLiteralExtra(String, function(val) { return val + "m"; })); def("NullLiteral").bases("Literal").build().field("value", null, defaults["null"]); def("BooleanLiteral").bases("Literal").build("value").field("value", Boolean); (_e = def("RegExpLiteral").bases("Literal").build("pattern", "flags").field("pattern", String).field("flags", String).field("value", RegExp, function() { return new RegExp(this.pattern, this.flags); })).field.apply(_e, makeLiteralExtra(or(RegExp, isUndefined), function(exp) { return "/".concat(exp.pattern, "/").concat(exp.flags || ""); })).field("regex", { pattern: String, flags: String }, function() { return { pattern: this.pattern, flags: this.flags }; }); var ObjectExpressionProperty = or(def("Property"), def("ObjectMethod"), def("ObjectProperty"), def("SpreadProperty"), def("SpreadElement")); def("ObjectExpression").bases("Expression").build("properties").field("properties", [ObjectExpressionProperty]); def("ObjectMethod").bases("Node", "Function").build("kind", "key", "params", "body", "computed").field("kind", or("method", "get", "set")).field("key", or(def("Literal"), def("Identifier"), def("Expression"))).field("params", [def("Pattern")]).field("body", def("BlockStatement")).field("computed", Boolean, defaults["false"]).field("generator", Boolean, defaults["false"]).field("async", Boolean, defaults["false"]).field( "accessibility", // TypeScript or(def("Literal"), null), defaults["null"] ).field("decorators", or([def("Decorator")], null), defaults["null"]); def("ObjectProperty").bases("Node").build("key", "value").field("key", or(def("Literal"), def("Identifier"), def("Expression"))).field("value", or(def("Expression"), def("Pattern"))).field( "accessibility", // TypeScript or(def("Literal"), null), defaults["null"] ).field("computed", Boolean, defaults["false"]); var ClassBodyElement = or(def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty"), def("ClassPrivateProperty"), def("ClassMethod"), def("ClassPrivateMethod"), def("ClassAccessorProperty"), def("StaticBlock")); def("ClassBody").bases("Declaration").build("body").field("body", [ClassBodyElement]); def("ClassMethod").bases("Declaration", "Function").build("kind", "key", "params", "body", "computed", "static").field("key", or(def("Literal"), def("Identifier"), def("Expression"))); def("ClassPrivateMethod").bases("Declaration", "Function").build("key", "params", "body", "kind", "computed", "static").field("key", def("PrivateName")); def("ClassAccessorProperty").bases("Declaration").build("key", "value", "decorators", "computed", "static").field("key", or( def("Literal"), def("Identifier"), def("PrivateName"), // Only when .computed is true (TODO enforce this) def("Expression") )).field("value", or(def("Expression"), null), defaults["null"]); [ "ClassMethod", "ClassPrivateMethod" ].forEach(function(typeName) { def(typeName).field("kind", or("get", "set", "method", "constructor"), function() { return "method"; }).field("body", def("BlockStatement")).field("access", or("public", "private", "protected", null), defaults["null"]); }); [ "ClassMethod", "ClassPrivateMethod", "ClassAccessorProperty" ].forEach(function(typeName) { def(typeName).field("computed", Boolean, defaults["false"]).field("static", Boolean, defaults["false"]).field("abstract", Boolean, defaults["false"]).field("accessibility", or("public", "private", "protected", null), defaults["null"]).field("decorators", or([def("Decorator")], null), defaults["null"]).field("definite", Boolean, defaults["false"]).field("optional", Boolean, defaults["false"]).field("override", Boolean, defaults["false"]).field("readonly", Boolean, defaults["false"]); }); var ObjectPatternProperty = or( def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern"), def("SpreadProperty"), // Used by Esprima def("ObjectProperty"), // Babel 6 def("RestProperty"), // Babel 6 def("RestElement") ); def("ObjectPattern").bases("Pattern").build("properties").field("properties", [ObjectPatternProperty]).field("decorators", or([def("Decorator")], null), defaults["null"]); def("SpreadProperty").bases("Node").build("argument").field("argument", def("Expression")); def("RestProperty").bases("Node").build("argument").field("argument", def("Expression")); def("ForAwaitStatement").bases("Statement").build("left", "right", "body").field("left", or(def("VariableDeclaration"), def("Expression"))).field("right", def("Expression")).field("body", def("Statement")); def("Import").bases("Expression").build(); } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/babel.js var require_babel = __commonJS({ "node_modules/ast-types/lib/def/babel.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var types_1 = tslib_1.__importDefault(require_types()); var babel_core_1 = tslib_1.__importDefault(require_babel_core()); var flow_1 = tslib_1.__importDefault(require_flow()); var shared_1 = require_shared(); function default_1(fork) { var types = fork.use(types_1.default); var def = types.Type.def; fork.use(babel_core_1.default); fork.use(flow_1.default); def("V8IntrinsicIdentifier").bases("Expression").build("name").field("name", String); def("TopicReference").bases("Expression").build(); } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/def/typescript.js var require_typescript = __commonJS({ "node_modules/ast-types/lib/def/typescript.js"(exports, module2) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var babel_core_1 = tslib_1.__importDefault(require_babel_core()); var type_annotations_1 = tslib_1.__importDefault(require_type_annotations()); var types_1 = tslib_1.__importDefault(require_types()); var shared_1 = tslib_1.__importStar(require_shared()); function default_1(fork) { fork.use(babel_core_1.default); fork.use(type_annotations_1.default); var types = fork.use(types_1.default); var n = types.namedTypes; var def = types.Type.def; var or = types.Type.or; var defaults = fork.use(shared_1.default).defaults; var StringLiteral = types.Type.from(function(value, deep) { if (n.StringLiteral && n.StringLiteral.check(value, deep)) { return true; } if (n.Literal && n.Literal.check(value, deep) && typeof value.value === "string") { return true; } return false; }, "StringLiteral"); def("TSType").bases("Node"); var TSEntityName = or(def("Identifier"), def("TSQualifiedName")); def("TSTypeReference").bases("TSType", "TSHasOptionalTypeParameterInstantiation").build("typeName", "typeParameters").field("typeName", TSEntityName); def("TSHasOptionalTypeParameterInstantiation").field("typeParameters", or(def("TSTypeParameterInstantiation"), null), defaults["null"]); def("TSHasOptionalTypeParameters").field("typeParameters", or(def("TSTypeParameterDeclaration"), null, void 0), defaults["null"]); def("TSHasOptionalTypeAnnotation").field("typeAnnotation", or(def("TSTypeAnnotation"), null), defaults["null"]); def("TSQualifiedName").bases("Node").build("left", "right").field("left", TSEntityName).field("right", TSEntityName); def("TSAsExpression").bases("Expression", "Pattern").build("expression", "typeAnnotation").field("expression", def("Expression")).field("typeAnnotation", def("TSType")).field("extra", or({ parenthesized: Boolean }, null), defaults["null"]); def("TSTypeCastExpression").bases("Expression").build("expression", "typeAnnotation").field("expression", def("Expression")).field("typeAnnotation", def("TSType")); def("TSSatisfiesExpression").bases("Expression", "Pattern").build("expression", "typeAnnotation").field("expression", def("Expression")).field("typeAnnotation", def("TSType")); def("TSNonNullExpression").bases("Expression", "Pattern").build("expression").field("expression", def("Expression")); [ "TSAnyKeyword", "TSBigIntKeyword", "TSBooleanKeyword", "TSNeverKeyword", "TSNullKeyword", "TSNumberKeyword", "TSObjectKeyword", "TSStringKeyword", "TSSymbolKeyword", "TSUndefinedKeyword", "TSUnknownKeyword", "TSVoidKeyword", "TSIntrinsicKeyword", "TSThisType" ].forEach(function(keywordType) { def(keywordType).bases("TSType").build(); }); def("TSArrayType").bases("TSType").build("elementType").field("elementType", def("TSType")); def("TSLiteralType").bases("TSType").build("literal").field("literal", or(def("NumericLiteral"), def("StringLiteral"), def("BooleanLiteral"), def("TemplateLiteral"), def("UnaryExpression"), def("BigIntLiteral"))); def("TemplateLiteral").field("expressions", or([def("Expression")], [def("TSType")])); [ "TSUnionType", "TSIntersectionType" ].forEach(function(typeName) { def(typeName).bases("TSType").build("types").field("types", [def("TSType")]); }); def("TSConditionalType").bases("TSType").build("checkType", "extendsType", "trueType", "falseType").field("checkType", def("TSType")).field("extendsType", def("TSType")).field("trueType", def("TSType")).field("falseType", def("TSType")); def("TSInferType").bases("TSType").build("typeParameter").field("typeParameter", def("TSTypeParameter")); def("TSParenthesizedType").bases("TSType").build("typeAnnotation").field("typeAnnotation", def("TSType")); var ParametersType = [or(def("Identifier"), def("RestElement"), def("ArrayPattern"), def("ObjectPattern"))]; [ "TSFunctionType", "TSConstructorType" ].forEach(function(typeName) { def(typeName).bases("TSType", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation").build("parameters").field("parameters", ParametersType); }); def("TSDeclareFunction").bases("Declaration", "TSHasOptionalTypeParameters").build("id", "params", "returnType").field("declare", Boolean, defaults["false"]).field("async", Boolean, defaults["false"]).field("generator", Boolean, defaults["false"]).field("id", or(def("Identifier"), null), defaults["null"]).field("params", [def("Pattern")]).field("returnType", or( def("TSTypeAnnotation"), def("Noop"), // Still used? null ), defaults["null"]); def("TSDeclareMethod").bases("Declaration", "TSHasOptionalTypeParameters").build("key", "params", "returnType").field("async", Boolean, defaults["false"]).field("generator", Boolean, defaults["false"]).field("params", [def("Pattern")]).field("abstract", Boolean, defaults["false"]).field("accessibility", or("public", "private", "protected", void 0), defaults["undefined"]).field("static", Boolean, defaults["false"]).field("computed", Boolean, defaults["false"]).field("optional", Boolean, defaults["false"]).field("key", or( def("Identifier"), def("StringLiteral"), def("NumericLiteral"), // Only allowed if .computed is true. def("Expression") )).field("kind", or("get", "set", "method", "constructor"), function getDefault() { return "method"; }).field( "access", // Not "accessibility"? or("public", "private", "protected", void 0), defaults["undefined"] ).field("decorators", or([def("Decorator")], null), defaults["null"]).field("returnType", or( def("TSTypeAnnotation"), def("Noop"), // Still used? null ), defaults["null"]); def("TSMappedType").bases("TSType").build("typeParameter", "typeAnnotation").field("readonly", or(Boolean, "+", "-"), defaults["false"]).field("typeParameter", def("TSTypeParameter")).field("optional", or(Boolean, "+", "-"), defaults["false"]).field("typeAnnotation", or(def("TSType"), null), defaults["null"]); def("TSTupleType").bases("TSType").build("elementTypes").field("elementTypes", [or(def("TSType"), def("TSNamedTupleMember"))]); def("TSNamedTupleMember").bases("TSType").build("label", "elementType", "optional").field("label", def("Identifier")).field("optional", Boolean, defaults["false"]).field("elementType", def("TSType")); def("TSRestType").bases("TSType").build("typeAnnotation").field("typeAnnotation", def("TSType")); def("TSOptionalType").bases("TSType").build("typeAnnotation").field("typeAnnotation", def("TSType")); def("TSIndexedAccessType").bases("TSType").build("objectType", "indexType").field("objectType", def("TSType")).field("indexType", def("TSType")); def("TSTypeOperator").bases("TSType").build("operator").field("operator", String).field("typeAnnotation", def("TSType")); def("TSTypeAnnotation").bases("Node").build("typeAnnotation").field("typeAnnotation", or(def("TSType"), def("TSTypeAnnotation"))); def("TSIndexSignature").bases("Declaration", "TSHasOptionalTypeAnnotation").build("parameters", "typeAnnotation").field("parameters", [def("Identifier")]).field("readonly", Boolean, defaults["false"]); def("TSPropertySignature").bases("Declaration", "TSHasOptionalTypeAnnotation").build("key", "typeAnnotation", "optional").field("key", def("Expression")).field("computed", Boolean, defaults["false"]).field("readonly", Boolean, defaults["false"]).field("optional", Boolean, defaults["false"]).field("initializer", or(def("Expression"), null), defaults["null"]); def("TSMethodSignature").bases("Declaration", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation").build("key", "parameters", "typeAnnotation").field("key", def("Expression")).field("computed", Boolean, defaults["false"]).field("optional", Boolean, defaults["false"]).field("parameters", ParametersType); def("TSTypePredicate").bases("TSTypeAnnotation", "TSType").build("parameterName", "typeAnnotation", "asserts").field("parameterName", or(def("Identifier"), def("TSThisType"))).field("typeAnnotation", or(def("TSTypeAnnotation"), null), defaults["null"]).field("asserts", Boolean, defaults["false"]); [ "TSCallSignatureDeclaration", "TSConstructSignatureDeclaration" ].forEach(function(typeName) { def(typeName).bases("Declaration", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation").build("parameters", "typeAnnotation").field("parameters", ParametersType); }); def("TSEnumMember").bases("Node").build("id", "initializer").field("id", or(def("Identifier"), StringLiteral)).field("initializer", or(def("Expression"), null), defaults["null"]); def("TSTypeQuery").bases("TSType").build("exprName").field("exprName", or(TSEntityName, def("TSImportType"))); var TSTypeMember = or(def("TSCallSignatureDeclaration"), def("TSConstructSignatureDeclaration"), def("TSIndexSignature"), def("TSMethodSignature"), def("TSPropertySignature")); def("TSTypeLiteral").bases("TSType").build("members").field("members", [TSTypeMember]); def("TSTypeParameter").bases("Identifier").build("name", "constraint", "default").field("name", or(def("Identifier"), String)).field("constraint", or(def("TSType"), void 0), defaults["undefined"]).field("default", or(def("TSType"), void 0), defaults["undefined"]); def("TSTypeAssertion").bases("Expression", "Pattern").build("typeAnnotation", "expression").field("typeAnnotation", def("TSType")).field("expression", def("Expression")).field("extra", or({ parenthesized: Boolean }, null), defaults["null"]); def("TSTypeParameterDeclaration").bases("Declaration").build("params").field("params", [def("TSTypeParameter")]); def("TSInstantiationExpression").bases("Expression", "TSHasOptionalTypeParameterInstantiation").build("expression", "typeParameters").field("expression", def("Expression")); def("TSTypeParameterInstantiation").bases("Node").build("params").field("params", [def("TSType")]); def("TSEnumDeclaration").bases("Declaration").build("id", "members").field("id", def("Identifier")).field("const", Boolean, defaults["false"]).field("declare", Boolean, defaults["false"]).field("members", [def("TSEnumMember")]).field("initializer", or(def("Expression"), null), defaults["null"]); def("TSTypeAliasDeclaration").bases("Declaration", "TSHasOptionalTypeParameters").build("id", "typeAnnotation").field("id", def("Identifier")).field("declare", Boolean, defaults["false"]).field("typeAnnotation", def("TSType")); def("TSModuleBlock").bases("Node").build("body").field("body", [def("Statement")]); def("TSModuleDeclaration").bases("Declaration").build("id", "body").field("id", or(StringLiteral, TSEntityName)).field("declare", Boolean, defaults["false"]).field("global", Boolean, defaults["false"]).field("body", or(def("TSModuleBlock"), def("TSModuleDeclaration"), null), defaults["null"]); def("TSImportType").bases("TSType", "TSHasOptionalTypeParameterInstantiation").build("argument", "qualifier", "typeParameters").field("argument", StringLiteral).field("qualifier", or(TSEntityName, void 0), defaults["undefined"]); def("TSImportEqualsDeclaration").bases("Declaration").build("id", "moduleReference").field("id", def("Identifier")).field("isExport", Boolean, defaults["false"]).field("moduleReference", or(TSEntityName, def("TSExternalModuleReference"))); def("TSExternalModuleReference").bases("Declaration").build("expression").field("expression", StringLiteral); def("TSExportAssignment").bases("Statement").build("expression").field("expression", def("Expression")); def("TSNamespaceExportDeclaration").bases("Declaration").build("id").field("id", def("Identifier")); def("TSInterfaceBody").bases("Node").build("body").field("body", [TSTypeMember]); def("TSExpressionWithTypeArguments").bases("TSType", "TSHasOptionalTypeParameterInstantiation").build("expression", "typeParameters").field("expression", TSEntityName); def("TSInterfaceDeclaration").bases("Declaration", "TSHasOptionalTypeParameters").build("id", "body").field("id", TSEntityName).field("declare", Boolean, defaults["false"]).field("extends", or([def("TSExpressionWithTypeArguments")], null), defaults["null"]).field("body", def("TSInterfaceBody")); def("TSParameterProperty").bases("Pattern").build("parameter").field("accessibility", or("public", "private", "protected", void 0), defaults["undefined"]).field("readonly", Boolean, defaults["false"]).field("parameter", or(def("Identifier"), def("AssignmentPattern"))); def("ClassProperty").field( "access", // Not "accessibility"? or("public", "private", "protected", void 0), defaults["undefined"] ); def("ClassAccessorProperty").bases("Declaration", "TSHasOptionalTypeAnnotation"); def("ClassBody").field("body", [or( def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty"), def("ClassPrivateProperty"), def("ClassAccessorProperty"), def("ClassMethod"), def("ClassPrivateMethod"), def("StaticBlock"), // Just need to add these types: def("TSDeclareMethod"), TSTypeMember )]); } exports.default = default_1; (0, shared_1.maybeSetModuleExports)(function() { return module2; }); } }); // node_modules/ast-types/lib/gen/namedTypes.js var require_namedTypes = __commonJS({ "node_modules/ast-types/lib/gen/namedTypes.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.namedTypes = void 0; var namedTypes; (function(namedTypes2) { })(namedTypes = exports.namedTypes || (exports.namedTypes = {})); } }); // node_modules/ast-types/lib/main.js var require_main = __commonJS({ "node_modules/ast-types/lib/main.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.visit = exports.use = exports.Type = exports.someField = exports.PathVisitor = exports.Path = exports.NodePath = exports.namedTypes = exports.getSupertypeNames = exports.getFieldValue = exports.getFieldNames = exports.getBuilderName = exports.finalize = exports.eachField = exports.defineMethod = exports.builtInTypes = exports.builders = exports.astNodesAreEquivalent = void 0; var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); var fork_1 = tslib_1.__importDefault(require_fork()); var es_proposals_1 = tslib_1.__importDefault(require_es_proposals()); var jsx_1 = tslib_1.__importDefault(require_jsx()); var flow_1 = tslib_1.__importDefault(require_flow()); var esprima_1 = tslib_1.__importDefault(require_esprima()); var babel_1 = tslib_1.__importDefault(require_babel()); var typescript_1 = tslib_1.__importDefault(require_typescript()); var namedTypes_1 = require_namedTypes(); Object.defineProperty(exports, "namedTypes", { enumerable: true, get: function() { return namedTypes_1.namedTypes; } }); var _a = (0, fork_1.default)([ // Feel free to add to or remove from this list of extension modules to // configure the precise type hierarchy that you need. es_proposals_1.default, jsx_1.default, flow_1.default, esprima_1.default, babel_1.default, typescript_1.default ]); var astNodesAreEquivalent = _a.astNodesAreEquivalent; var builders = _a.builders; var builtInTypes = _a.builtInTypes; var defineMethod = _a.defineMethod; var eachField = _a.eachField; var finalize = _a.finalize; var getBuilderName = _a.getBuilderName; var getFieldNames = _a.getFieldNames; var getFieldValue = _a.getFieldValue; var getSupertypeNames = _a.getSupertypeNames; var n = _a.namedTypes; var NodePath = _a.NodePath; var Path = _a.Path; var PathVisitor = _a.PathVisitor; var someField = _a.someField; var Type = _a.Type; var use = _a.use; var visit = _a.visit; exports.astNodesAreEquivalent = astNodesAreEquivalent; exports.builders = builders; exports.builtInTypes = builtInTypes; exports.defineMethod = defineMethod; exports.eachField = eachField; exports.finalize = finalize; exports.getBuilderName = getBuilderName; exports.getFieldNames = getFieldNames; exports.getFieldValue = getFieldValue; exports.getSupertypeNames = getSupertypeNames; exports.NodePath = NodePath; exports.Path = Path; exports.PathVisitor = PathVisitor; exports.someField = someField; exports.Type = Type; exports.use = use; exports.visit = visit; Object.assign(namedTypes_1.namedTypes, n); } }); // node_modules/source-map/lib/base64.js var require_base64 = __commonJS({ "node_modules/source-map/lib/base64.js"(exports) { var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); exports.encode = function(number) { if (0 <= number && number < intToCharMap.length) { return intToCharMap[number]; } throw new TypeError("Must be between 0 and 63: " + number); }; exports.decode = function(charCode) { var bigA = 65; var bigZ = 90; var littleA = 97; var littleZ = 122; var zero = 48; var nine = 57; var plus = 43; var slash = 47; var littleOffset = 26; var numberOffset = 52; if (bigA <= charCode && charCode <= bigZ) { return charCode - bigA; } if (littleA <= charCode && charCode <= littleZ) { return charCode - littleA + littleOffset; } if (zero <= charCode && charCode <= nine) { return charCode - zero + numberOffset; } if (charCode == plus) { return 62; } if (charCode == slash) { return 63; } return -1; }; } }); // node_modules/source-map/lib/base64-vlq.js var require_base64_vlq = __commonJS({ "node_modules/source-map/lib/base64-vlq.js"(exports) { var base64 = require_base64(); var VLQ_BASE_SHIFT = 5; var VLQ_BASE = 1 << VLQ_BASE_SHIFT; var VLQ_BASE_MASK = VLQ_BASE - 1; var VLQ_CONTINUATION_BIT = VLQ_BASE; function toVLQSigned(aValue) { return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0; } function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } exports.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { var strLen = aStr.length; var result = 0; var shift = 0; var continuation, digit; do { if (aIndex >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base64.decode(aStr.charCodeAt(aIndex++)); if (digit === -1) { throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); } continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift += VLQ_BASE_SHIFT; } while (continuation); aOutParam.value = fromVLQSigned(result); aOutParam.rest = aIndex; }; } }); // node_modules/source-map/lib/util.js var require_util = __commonJS({ "node_modules/source-map/lib/util.js"(exports) { function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match2 = aUrl.match(urlRegexp); if (!match2) { return null; } return { scheme: match2[1], auth: match2[2], host: match2[3], port: match2[4], path: match2[5] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ""; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ":"; } url += "//"; if (aParsedUrl.auth) { url += aParsedUrl.auth + "@"; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port; } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; function normalize(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = exports.isAbsolute(path); var parts = path.split(/\/+/); for (var part, up = 0, i2 = parts.length - 1; i2 >= 0; i2--) { part = parts[i2]; if (part === ".") { parts.splice(i2, 1); } else if (part === "..") { up++; } else if (up > 0) { if (part === "") { parts.splice(i2 + 1, up); up = 0; } else { parts.splice(i2, 2); up--; } } } path = parts.join("/"); if (path === "") { path = isAbsolute ? "/" : "."; } if (url) { url.path = path; return urlGenerate(url); } return path; } exports.normalize = normalize; function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || "/"; } if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === "/" ? aPath : normalize(aRoot.replace(/\/+$/, "") + "/" + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports.join = join; exports.isAbsolute = function(aPath) { return aPath.charAt(0) === "/" || urlRegexp.test(aPath); }; function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ""); var level = 0; while (aPath.indexOf(aRoot + "/") !== 0) { var index2 = aRoot.lastIndexOf("/"); if (index2 < 0) { return aPath; } aRoot = aRoot.slice(0, index2); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports.relative = relative; var supportsNullProto = function() { var obj = /* @__PURE__ */ Object.create(null); return !("__proto__" in obj); }(); function identity(s3) { return s3; } function toSetString(aStr) { if (isProtoString(aStr)) { return "$" + aStr; } return aStr; } exports.toSetString = supportsNullProto ? identity : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports.fromSetString = supportsNullProto ? identity : fromSetString; function isProtoString(s3) { if (!s3) { return false; } var length = s3.length; if (length < 9) { return false; } if (s3.charCodeAt(length - 1) !== 95 || s3.charCodeAt(length - 2) !== 95 || s3.charCodeAt(length - 3) !== 111 || s3.charCodeAt(length - 4) !== 116 || s3.charCodeAt(length - 5) !== 111 || s3.charCodeAt(length - 6) !== 114 || s3.charCodeAt(length - 7) !== 112 || s3.charCodeAt(length - 8) !== 95 || s3.charCodeAt(length - 9) !== 95) { return false; } for (var i2 = length - 10; i2 >= 0; i2--) { if (s3.charCodeAt(i2) !== 36) { return false; } } return true; } function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByOriginalPositions = compareByOriginalPositions; function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 === null) { return 1; } if (aStr2 === null) { return -1; } if (aStr1 > aStr2) { return 1; } return -1; } function compareByGeneratedPositionsInflated(mappingA, mappingB) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; function parseSourceMapInput(str2) { return JSON.parse(str2.replace(/^\)]}'[^\n]*\n/, "")); } exports.parseSourceMapInput = parseSourceMapInput; function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { sourceURL = sourceURL || ""; if (sourceRoot) { if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") { sourceRoot += "/"; } sourceURL = sourceRoot + sourceURL; } if (sourceMapURL) { var parsed = urlParse(sourceMapURL); if (!parsed) { throw new Error("sourceMapURL could not be parsed"); } if (parsed.path) { var index2 = parsed.path.lastIndexOf("/"); if (index2 >= 0) { parsed.path = parsed.path.substring(0, index2 + 1); } } sourceURL = join(urlGenerate(parsed), sourceURL); } return normalize(sourceURL); } exports.computeSourceURL = computeSourceURL; } }); // node_modules/source-map/lib/array-set.js var require_array_set = __commonJS({ "node_modules/source-map/lib/array-set.js"(exports) { var util2 = require_util(); var has = Object.prototype.hasOwnProperty; var hasNativeMap = typeof Map !== "undefined"; function ArraySet() { this._array = []; this._set = hasNativeMap ? /* @__PURE__ */ new Map() : /* @__PURE__ */ Object.create(null); } ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set2 = new ArraySet(); for (var i2 = 0, len = aArray.length; i2 < len; i2++) { set2.add(aArray[i2], aAllowDuplicates); } return set2; }; ArraySet.prototype.size = function ArraySet_size() { return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; }; ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var sStr = hasNativeMap ? aStr : util2.toSetString(aStr); var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); var idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { if (hasNativeMap) { this._set.set(aStr, idx); } else { this._set[sStr] = idx; } } }; ArraySet.prototype.has = function ArraySet_has(aStr) { if (hasNativeMap) { return this._set.has(aStr); } else { var sStr = util2.toSetString(aStr); return has.call(this._set, sStr); } }; ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { if (hasNativeMap) { var idx = this._set.get(aStr); if (idx >= 0) { return idx; } } else { var sStr = util2.toSetString(aStr); if (has.call(this._set, sStr)) { return this._set[sStr]; } } throw new Error('"' + aStr + '" is not in the set.'); }; ArraySet.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error("No element indexed by " + aIdx); }; ArraySet.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; exports.ArraySet = ArraySet; } }); // node_modules/source-map/lib/mapping-list.js var require_mapping_list = __commonJS({ "node_modules/source-map/lib/mapping-list.js"(exports) { var util2 = require_util(); function generatedPositionAfter(mappingA, mappingB) { var lineA = mappingA.generatedLine; var lineB = mappingB.generatedLine; var columnA = mappingA.generatedColumn; var columnB = mappingB.generatedColumn; return lineB > lineA || lineB == lineA && columnB >= columnA || util2.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; } function MappingList() { this._array = []; this._sorted = true; this._last = { generatedLine: -1, generatedColumn: 0 }; } MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) { this._array.forEach(aCallback, aThisArg); }; MappingList.prototype.add = function MappingList_add(aMapping) { if (generatedPositionAfter(this._last, aMapping)) { this._last = aMapping; this._array.push(aMapping); } else { this._sorted = false; this._array.push(aMapping); } }; MappingList.prototype.toArray = function MappingList_toArray() { if (!this._sorted) { this._array.sort(util2.compareByGeneratedPositionsInflated); this._sorted = true; } return this._array; }; exports.MappingList = MappingList; } }); // node_modules/source-map/lib/source-map-generator.js var require_source_map_generator = __commonJS({ "node_modules/source-map/lib/source-map-generator.js"(exports) { var base64VLQ = require_base64_vlq(); var util2 = require_util(); var ArraySet = require_array_set().ArraySet; var MappingList = require_mapping_list().MappingList; function SourceMapGenerator(aArgs) { if (!aArgs) { aArgs = {}; } this._file = util2.getArg(aArgs, "file", null); this._sourceRoot = util2.getArg(aArgs, "sourceRoot", null); this._skipValidation = util2.getArg(aArgs, "skipValidation", false); this._sources = new ArraySet(); this._names = new ArraySet(); this._mappings = new MappingList(); this._sourcesContents = null; } SourceMapGenerator.prototype._version = 3; SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { var sourceRoot = aSourceMapConsumer.sourceRoot; var generator = new SourceMapGenerator({ file: aSourceMapConsumer.file, sourceRoot }); aSourceMapConsumer.eachMapping(function(mapping) { var newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } }; if (mapping.source != null) { newMapping.source = mapping.source; if (sourceRoot != null) { newMapping.source = util2.relative(sourceRoot, newMapping.source); } newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn }; if (mapping.name != null) { newMapping.name = mapping.name; } } generator.addMapping(newMapping); }); aSourceMapConsumer.sources.forEach(function(sourceFile) { var sourceRelative = sourceFile; if (sourceRoot !== null) { sourceRelative = util2.relative(sourceRoot, sourceFile); } if (!generator._sources.has(sourceRelative)) { generator._sources.add(sourceRelative); } var content3 = aSourceMapConsumer.sourceContentFor(sourceFile); if (content3 != null) { generator.setSourceContent(sourceFile, content3); } }); return generator; }; SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { var generated = util2.getArg(aArgs, "generated"); var original = util2.getArg(aArgs, "original", null); var source = util2.getArg(aArgs, "source", null); var name = util2.getArg(aArgs, "name", null); if (!this._skipValidation) { this._validateMapping(generated, original, source, name); } if (source != null) { source = String(source); if (!this._sources.has(source)) { this._sources.add(source); } } if (name != null) { name = String(name); if (!this._names.has(name)) { this._names.add(name); } } this._mappings.add({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, originalColumn: original != null && original.column, source, name }); }; SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { var source = aSourceFile; if (this._sourceRoot != null) { source = util2.relative(this._sourceRoot, source); } if (aSourceContent != null) { if (!this._sourcesContents) { this._sourcesContents = /* @__PURE__ */ Object.create(null); } this._sourcesContents[util2.toSetString(source)] = aSourceContent; } else if (this._sourcesContents) { delete this._sourcesContents[util2.toSetString(source)]; if (Object.keys(this._sourcesContents).length === 0) { this._sourcesContents = null; } } }; SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { var sourceFile = aSourceFile; if (aSourceFile == null) { if (aSourceMapConsumer.file == null) { throw new Error( `SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.` ); } sourceFile = aSourceMapConsumer.file; } var sourceRoot = this._sourceRoot; if (sourceRoot != null) { sourceFile = util2.relative(sourceRoot, sourceFile); } var newSources = new ArraySet(); var newNames = new ArraySet(); this._mappings.unsortedForEach(function(mapping) { if (mapping.source === sourceFile && mapping.originalLine != null) { var original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); if (original.source != null) { mapping.source = original.source; if (aSourceMapPath != null) { mapping.source = util2.join(aSourceMapPath, mapping.source); } if (sourceRoot != null) { mapping.source = util2.relative(sourceRoot, mapping.source); } mapping.originalLine = original.line; mapping.originalColumn = original.column; if (original.name != null) { mapping.name = original.name; } } } var source = mapping.source; if (source != null && !newSources.has(source)) { newSources.add(source); } var name = mapping.name; if (name != null && !newNames.has(name)) { newNames.add(name); } }, this); this._sources = newSources; this._names = newNames; aSourceMapConsumer.sources.forEach(function(sourceFile2) { var content3 = aSourceMapConsumer.sourceContentFor(sourceFile2); if (content3 != null) { if (aSourceMapPath != null) { sourceFile2 = util2.join(aSourceMapPath, sourceFile2); } if (sourceRoot != null) { sourceFile2 = util2.relative(sourceRoot, sourceFile2); } this.setSourceContent(sourceFile2, content3); } }, this); }; SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") { throw new Error( "original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values." ); } if (aGenerated && "line" in aGenerated && "column" in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { return; } else if (aGenerated && "line" in aGenerated && "column" in aGenerated && aOriginal && "line" in aOriginal && "column" in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { return; } else { throw new Error("Invalid mapping: " + JSON.stringify({ generated: aGenerated, source: aSource, original: aOriginal, name: aName })); } }; SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { var previousGeneratedColumn = 0; var previousGeneratedLine = 1; var previousOriginalColumn = 0; var previousOriginalLine = 0; var previousName = 0; var previousSource = 0; var result = ""; var next; var mapping; var nameIdx; var sourceIdx; var mappings = this._mappings.toArray(); for (var i2 = 0, len = mappings.length; i2 < len; i2++) { mapping = mappings[i2]; next = ""; if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { next += ";"; previousGeneratedLine++; } } else { if (i2 > 0) { if (!util2.compareByGeneratedPositionsInflated(mapping, mappings[i2 - 1])) { continue; } next += ","; } } next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source != null) { sourceIdx = this._sources.indexOf(mapping.source); next += base64VLQ.encode(sourceIdx - previousSource); previousSource = sourceIdx; next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); previousOriginalLine = mapping.originalLine - 1; next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); previousOriginalColumn = mapping.originalColumn; if (mapping.name != null) { nameIdx = this._names.indexOf(mapping.name); next += base64VLQ.encode(nameIdx - previousName); previousName = nameIdx; } } result += next; } return result; }; SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { return aSources.map(function(source) { if (!this._sourcesContents) { return null; } if (aSourceRoot != null) { source = util2.relative(aSourceRoot, source); } var key = util2.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; }, this); }; SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { var map2 = { version: this._version, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._file != null) { map2.file = this._file; } if (this._sourceRoot != null) { map2.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map2.sourcesContent = this._generateSourcesContent(map2.sources, map2.sourceRoot); } return map2; }; SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { return JSON.stringify(this.toJSON()); }; exports.SourceMapGenerator = SourceMapGenerator; } }); // node_modules/source-map/lib/binary-search.js var require_binary_search = __commonJS({ "node_modules/source-map/lib/binary-search.js"(exports) { exports.GREATEST_LOWER_BOUND = 1; exports.LEAST_UPPER_BOUND = 2; function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); if (cmp === 0) { return mid; } else if (cmp > 0) { if (aHigh - mid > 1) { return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); } if (aBias == exports.LEAST_UPPER_BOUND) { return aHigh < aHaystack.length ? aHigh : -1; } else { return mid; } } else { if (mid - aLow > 1) { return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); } if (aBias == exports.LEAST_UPPER_BOUND) { return mid; } else { return aLow < 0 ? -1 : aLow; } } } exports.search = function search2(aNeedle, aHaystack, aCompare, aBias) { if (aHaystack.length === 0) { return -1; } var index2 = recursiveSearch( -1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports.GREATEST_LOWER_BOUND ); if (index2 < 0) { return -1; } while (index2 - 1 >= 0) { if (aCompare(aHaystack[index2], aHaystack[index2 - 1], true) !== 0) { break; } --index2; } return index2; }; } }); // node_modules/source-map/lib/quick-sort.js var require_quick_sort = __commonJS({ "node_modules/source-map/lib/quick-sort.js"(exports) { function swap(ary, x2, y3) { var temp = ary[x2]; ary[x2] = ary[y3]; ary[y3] = temp; } function randomIntInRange(low, high) { return Math.round(low + Math.random() * (high - low)); } function doQuickSort(ary, comparator, p, r) { if (p < r) { var pivotIndex = randomIntInRange(p, r); var i2 = p - 1; swap(ary, pivotIndex, r); var pivot = ary[r]; for (var j = p; j < r; j++) { if (comparator(ary[j], pivot) <= 0) { i2 += 1; swap(ary, i2, j); } } swap(ary, i2 + 1, j); var q2 = i2 + 1; doQuickSort(ary, comparator, p, q2 - 1); doQuickSort(ary, comparator, q2 + 1, r); } } exports.quickSort = function(ary, comparator) { doQuickSort(ary, comparator, 0, ary.length - 1); }; } }); // node_modules/source-map/lib/source-map-consumer.js var require_source_map_consumer = __commonJS({ "node_modules/source-map/lib/source-map-consumer.js"(exports) { var util2 = require_util(); var binarySearch = require_binary_search(); var ArraySet = require_array_set().ArraySet; var base64VLQ = require_base64_vlq(); var quickSort = require_quick_sort().quickSort; function SourceMapConsumer(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === "string") { sourceMap = util2.parseSourceMapInput(aSourceMap); } return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); } SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); }; SourceMapConsumer.prototype._version = 3; SourceMapConsumer.prototype.__generatedMappings = null; Object.defineProperty(SourceMapConsumer.prototype, "_generatedMappings", { configurable: true, enumerable: true, get: function() { if (!this.__generatedMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__generatedMappings; } }); SourceMapConsumer.prototype.__originalMappings = null; Object.defineProperty(SourceMapConsumer.prototype, "_originalMappings", { configurable: true, enumerable: true, get: function() { if (!this.__originalMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__originalMappings; } }); SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index2) { var c2 = aStr.charAt(index2); return c2 === ";" || c2 === ","; }; SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { throw new Error("Subclasses must implement _parseMappings"); }; SourceMapConsumer.GENERATED_ORDER = 1; SourceMapConsumer.ORIGINAL_ORDER = 2; SourceMapConsumer.GREATEST_LOWER_BOUND = 1; SourceMapConsumer.LEAST_UPPER_BOUND = 2; SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { var context = aContext || null; var order = aOrder || SourceMapConsumer.GENERATED_ORDER; var mappings; switch (order) { case SourceMapConsumer.GENERATED_ORDER: mappings = this._generatedMappings; break; case SourceMapConsumer.ORIGINAL_ORDER: mappings = this._originalMappings; break; default: throw new Error("Unknown order of iteration."); } var sourceRoot = this.sourceRoot; mappings.map(function(mapping) { var source = mapping.source === null ? null : this._sources.at(mapping.source); source = util2.computeSourceURL(sourceRoot, source, this._sourceMapURL); return { source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name === null ? null : this._names.at(mapping.name) }; }, this).forEach(aCallback, context); }; SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { var line = util2.getArg(aArgs, "line"); var needle = { source: util2.getArg(aArgs, "source"), originalLine: line, originalColumn: util2.getArg(aArgs, "column", 0) }; needle.source = this._findSourceIndex(needle.source); if (needle.source < 0) { return []; } var mappings = []; var index2 = this._findMapping( needle, this._originalMappings, "originalLine", "originalColumn", util2.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND ); if (index2 >= 0) { var mapping = this._originalMappings[index2]; if (aArgs.column === void 0) { var originalLine = mapping.originalLine; while (mapping && mapping.originalLine === originalLine) { mappings.push({ line: util2.getArg(mapping, "generatedLine", null), column: util2.getArg(mapping, "generatedColumn", null), lastColumn: util2.getArg(mapping, "lastGeneratedColumn", null) }); mapping = this._originalMappings[++index2]; } } else { var originalColumn = mapping.originalColumn; while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) { mappings.push({ line: util2.getArg(mapping, "generatedLine", null), column: util2.getArg(mapping, "generatedColumn", null), lastColumn: util2.getArg(mapping, "lastGeneratedColumn", null) }); mapping = this._originalMappings[++index2]; } } } return mappings; }; exports.SourceMapConsumer = SourceMapConsumer; function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === "string") { sourceMap = util2.parseSourceMapInput(aSourceMap); } var version = util2.getArg(sourceMap, "version"); var sources = util2.getArg(sourceMap, "sources"); var names = util2.getArg(sourceMap, "names", []); var sourceRoot = util2.getArg(sourceMap, "sourceRoot", null); var sourcesContent = util2.getArg(sourceMap, "sourcesContent", null); var mappings = util2.getArg(sourceMap, "mappings"); var file = util2.getArg(sourceMap, "file", null); if (version != this._version) { throw new Error("Unsupported version: " + version); } if (sourceRoot) { sourceRoot = util2.normalize(sourceRoot); } sources = sources.map(String).map(util2.normalize).map(function(source) { return sourceRoot && util2.isAbsolute(sourceRoot) && util2.isAbsolute(source) ? util2.relative(sourceRoot, source) : source; }); this._names = ArraySet.fromArray(names.map(String), true); this._sources = ArraySet.fromArray(sources, true); this._absoluteSources = this._sources.toArray().map(function(s3) { return util2.computeSourceURL(sourceRoot, s3, aSourceMapURL); }); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this._sourceMapURL = aSourceMapURL; this.file = file; } BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { var relativeSource = aSource; if (this.sourceRoot != null) { relativeSource = util2.relative(this.sourceRoot, relativeSource); } if (this._sources.has(relativeSource)) { return this._sources.indexOf(relativeSource); } var i2; for (i2 = 0; i2 < this._absoluteSources.length; ++i2) { if (this._absoluteSources[i2] == aSource) { return i2; } } return -1; }; BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { var smc = Object.create(BasicSourceMapConsumer.prototype); var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); smc.sourceRoot = aSourceMap._sourceRoot; smc.sourcesContent = aSourceMap._generateSourcesContent( smc._sources.toArray(), smc.sourceRoot ); smc.file = aSourceMap._file; smc._sourceMapURL = aSourceMapURL; smc._absoluteSources = smc._sources.toArray().map(function(s3) { return util2.computeSourceURL(smc.sourceRoot, s3, aSourceMapURL); }); var generatedMappings = aSourceMap._mappings.toArray().slice(); var destGeneratedMappings = smc.__generatedMappings = []; var destOriginalMappings = smc.__originalMappings = []; for (var i2 = 0, length = generatedMappings.length; i2 < length; i2++) { var srcMapping = generatedMappings[i2]; var destMapping = new Mapping(); destMapping.generatedLine = srcMapping.generatedLine; destMapping.generatedColumn = srcMapping.generatedColumn; if (srcMapping.source) { destMapping.source = sources.indexOf(srcMapping.source); destMapping.originalLine = srcMapping.originalLine; destMapping.originalColumn = srcMapping.originalColumn; if (srcMapping.name) { destMapping.name = names.indexOf(srcMapping.name); } destOriginalMappings.push(destMapping); } destGeneratedMappings.push(destMapping); } quickSort(smc.__originalMappings, util2.compareByOriginalPositions); return smc; }; BasicSourceMapConsumer.prototype._version = 3; Object.defineProperty(BasicSourceMapConsumer.prototype, "sources", { get: function() { return this._absoluteSources.slice(); } }); function Mapping() { this.generatedLine = 0; this.generatedColumn = 0; this.source = null; this.originalLine = null; this.originalColumn = null; this.name = null; } BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { var generatedLine = 1; var previousGeneratedColumn = 0; var previousOriginalLine = 0; var previousOriginalColumn = 0; var previousSource = 0; var previousName = 0; var length = aStr.length; var index2 = 0; var cachedSegments = {}; var temp = {}; var originalMappings = []; var generatedMappings = []; var mapping, str2, segment, end, value; while (index2 < length) { if (aStr.charAt(index2) === ";") { generatedLine++; index2++; previousGeneratedColumn = 0; } else if (aStr.charAt(index2) === ",") { index2++; } else { mapping = new Mapping(); mapping.generatedLine = generatedLine; for (end = index2; end < length; end++) { if (this._charIsMappingSeparator(aStr, end)) { break; } } str2 = aStr.slice(index2, end); segment = cachedSegments[str2]; if (segment) { index2 += str2.length; } else { segment = []; while (index2 < end) { base64VLQ.decode(aStr, index2, temp); value = temp.value; index2 = temp.rest; segment.push(value); } if (segment.length === 2) { throw new Error("Found a source, but no line and column"); } if (segment.length === 3) { throw new Error("Found a source and line, but no column"); } cachedSegments[str2] = segment; } mapping.generatedColumn = previousGeneratedColumn + segment[0]; previousGeneratedColumn = mapping.generatedColumn; if (segment.length > 1) { mapping.source = previousSource + segment[1]; previousSource += segment[1]; mapping.originalLine = previousOriginalLine + segment[2]; previousOriginalLine = mapping.originalLine; mapping.originalLine += 1; mapping.originalColumn = previousOriginalColumn + segment[3]; previousOriginalColumn = mapping.originalColumn; if (segment.length > 4) { mapping.name = previousName + segment[4]; previousName += segment[4]; } } generatedMappings.push(mapping); if (typeof mapping.originalLine === "number") { originalMappings.push(mapping); } } } quickSort(generatedMappings, util2.compareByGeneratedPositionsDeflated); this.__generatedMappings = generatedMappings; quickSort(originalMappings, util2.compareByOriginalPositions); this.__originalMappings = originalMappings; }; BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) { if (aNeedle[aLineName] <= 0) { throw new TypeError("Line must be greater than or equal to 1, got " + aNeedle[aLineName]); } if (aNeedle[aColumnName] < 0) { throw new TypeError("Column must be greater than or equal to 0, got " + aNeedle[aColumnName]); } return binarySearch.search(aNeedle, aMappings, aComparator, aBias); }; BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() { for (var index2 = 0; index2 < this._generatedMappings.length; ++index2) { var mapping = this._generatedMappings[index2]; if (index2 + 1 < this._generatedMappings.length) { var nextMapping = this._generatedMappings[index2 + 1]; if (mapping.generatedLine === nextMapping.generatedLine) { mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; continue; } } mapping.lastGeneratedColumn = Infinity; } }; BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util2.getArg(aArgs, "line"), generatedColumn: util2.getArg(aArgs, "column") }; var index2 = this._findMapping( needle, this._generatedMappings, "generatedLine", "generatedColumn", util2.compareByGeneratedPositionsDeflated, util2.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index2 >= 0) { var mapping = this._generatedMappings[index2]; if (mapping.generatedLine === needle.generatedLine) { var source = util2.getArg(mapping, "source", null); if (source !== null) { source = this._sources.at(source); source = util2.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); } var name = util2.getArg(mapping, "name", null); if (name !== null) { name = this._names.at(name); } return { source, line: util2.getArg(mapping, "originalLine", null), column: util2.getArg(mapping, "originalColumn", null), name }; } } return { source: null, line: null, column: null, name: null }; }; BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() { if (!this.sourcesContent) { return false; } return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function(sc) { return sc == null; }); }; BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { if (!this.sourcesContent) { return null; } var index2 = this._findSourceIndex(aSource); if (index2 >= 0) { return this.sourcesContent[index2]; } var relativeSource = aSource; if (this.sourceRoot != null) { relativeSource = util2.relative(this.sourceRoot, relativeSource); } var url; if (this.sourceRoot != null && (url = util2.urlParse(this.sourceRoot))) { var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) { return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]; } if ((!url.path || url.path == "/") && this._sources.has("/" + relativeSource)) { return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; } } if (nullOnMissing) { return null; } else { throw new Error('"' + relativeSource + '" is not in the SourceMap.'); } }; BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { var source = util2.getArg(aArgs, "source"); source = this._findSourceIndex(source); if (source < 0) { return { line: null, column: null, lastColumn: null }; } var needle = { source, originalLine: util2.getArg(aArgs, "line"), originalColumn: util2.getArg(aArgs, "column") }; var index2 = this._findMapping( needle, this._originalMappings, "originalLine", "originalColumn", util2.compareByOriginalPositions, util2.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index2 >= 0) { var mapping = this._originalMappings[index2]; if (mapping.source === needle.source) { return { line: util2.getArg(mapping, "generatedLine", null), column: util2.getArg(mapping, "generatedColumn", null), lastColumn: util2.getArg(mapping, "lastGeneratedColumn", null) }; } } return { line: null, column: null, lastColumn: null }; }; exports.BasicSourceMapConsumer = BasicSourceMapConsumer; function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === "string") { sourceMap = util2.parseSourceMapInput(aSourceMap); } var version = util2.getArg(sourceMap, "version"); var sections = util2.getArg(sourceMap, "sections"); if (version != this._version) { throw new Error("Unsupported version: " + version); } this._sources = new ArraySet(); this._names = new ArraySet(); var lastOffset = { line: -1, column: 0 }; this._sections = sections.map(function(s3) { if (s3.url) { throw new Error("Support for url field in sections not implemented."); } var offset = util2.getArg(s3, "offset"); var offsetLine = util2.getArg(offset, "line"); var offsetColumn = util2.getArg(offset, "column"); if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) { throw new Error("Section offsets must be ordered and non-overlapping."); } lastOffset = offset; return { generatedOffset: { // The offset fields are 0-based, but we use 1-based indices when // encoding/decoding from VLQ. generatedLine: offsetLine + 1, generatedColumn: offsetColumn + 1 }, consumer: new SourceMapConsumer(util2.getArg(s3, "map"), aSourceMapURL) }; }); } IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; IndexedSourceMapConsumer.prototype._version = 3; Object.defineProperty(IndexedSourceMapConsumer.prototype, "sources", { get: function() { var sources = []; for (var i2 = 0; i2 < this._sections.length; i2++) { for (var j = 0; j < this._sections[i2].consumer.sources.length; j++) { sources.push(this._sections[i2].consumer.sources[j]); } } return sources; } }); IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util2.getArg(aArgs, "line"), generatedColumn: util2.getArg(aArgs, "column") }; var sectionIndex = binarySearch.search( needle, this._sections, function(needle2, section2) { var cmp = needle2.generatedLine - section2.generatedOffset.generatedLine; if (cmp) { return cmp; } return needle2.generatedColumn - section2.generatedOffset.generatedColumn; } ); var section = this._sections[sectionIndex]; if (!section) { return { source: null, line: null, column: null, name: null }; } return section.consumer.originalPositionFor({ line: needle.generatedLine - (section.generatedOffset.generatedLine - 1), column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), bias: aArgs.bias }); }; IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() { return this._sections.every(function(s3) { return s3.consumer.hasContentsOfAllSources(); }); }; IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { for (var i2 = 0; i2 < this._sections.length; i2++) { var section = this._sections[i2]; var content3 = section.consumer.sourceContentFor(aSource, true); if (content3) { return content3; } } if (nullOnMissing) { return null; } else { throw new Error('"' + aSource + '" is not in the SourceMap.'); } }; IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { for (var i2 = 0; i2 < this._sections.length; i2++) { var section = this._sections[i2]; if (section.consumer._findSourceIndex(util2.getArg(aArgs, "source")) === -1) { continue; } var generatedPosition = section.consumer.generatedPositionFor(aArgs); if (generatedPosition) { var ret = { line: generatedPosition.line + (section.generatedOffset.generatedLine - 1), column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0) }; return ret; } } return { line: null, column: null }; }; IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { this.__generatedMappings = []; this.__originalMappings = []; for (var i2 = 0; i2 < this._sections.length; i2++) { var section = this._sections[i2]; var sectionMappings = section.consumer._generatedMappings; for (var j = 0; j < sectionMappings.length; j++) { var mapping = sectionMappings[j]; var source = section.consumer._sources.at(mapping.source); source = util2.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); this._sources.add(source); source = this._sources.indexOf(source); var name = null; if (mapping.name) { name = section.consumer._names.at(mapping.name); this._names.add(name); name = this._names.indexOf(name); } var adjustedMapping = { source, generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1), generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name }; this.__generatedMappings.push(adjustedMapping); if (typeof adjustedMapping.originalLine === "number") { this.__originalMappings.push(adjustedMapping); } } } quickSort(this.__generatedMappings, util2.compareByGeneratedPositionsDeflated); quickSort(this.__originalMappings, util2.compareByOriginalPositions); }; exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; } }); // node_modules/source-map/lib/source-node.js var require_source_node = __commonJS({ "node_modules/source-map/lib/source-node.js"(exports) { var SourceMapGenerator = require_source_map_generator().SourceMapGenerator; var util2 = require_util(); var REGEX_NEWLINE = /(\r?\n)/; var NEWLINE_CODE = 10; var isSourceNode = "$$$isSourceNode$$$"; function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; this.line = aLine == null ? null : aLine; this.column = aColumn == null ? null : aColumn; this.source = aSource == null ? null : aSource; this.name = aName == null ? null : aName; this[isSourceNode] = true; if (aChunks != null) this.add(aChunks); } SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { var node2 = new SourceNode(); var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); var remainingLinesIndex = 0; var shiftNextLine = function() { var lineContents = getNextLine(); var newLine = getNextLine() || ""; return lineContents + newLine; function getNextLine() { return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : void 0; } }; var lastGeneratedLine = 1, lastGeneratedColumn = 0; var lastMapping = null; aSourceMapConsumer.eachMapping(function(mapping) { if (lastMapping !== null) { if (lastGeneratedLine < mapping.generatedLine) { addMappingWithCode(lastMapping, shiftNextLine()); lastGeneratedLine++; lastGeneratedColumn = 0; } else { var nextLine = remainingLines[remainingLinesIndex] || ""; var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); lastMapping = mapping; return; } } while (lastGeneratedLine < mapping.generatedLine) { node2.add(shiftNextLine()); lastGeneratedLine++; } if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[remainingLinesIndex] || ""; node2.add(nextLine.substr(0, mapping.generatedColumn)); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } lastMapping = mapping; }, this); if (remainingLinesIndex < remainingLines.length) { if (lastMapping) { addMappingWithCode(lastMapping, shiftNextLine()); } node2.add(remainingLines.splice(remainingLinesIndex).join("")); } aSourceMapConsumer.sources.forEach(function(sourceFile) { var content3 = aSourceMapConsumer.sourceContentFor(sourceFile); if (content3 != null) { if (aRelativePath != null) { sourceFile = util2.join(aRelativePath, sourceFile); } node2.setSourceContent(sourceFile, content3); } }); return node2; function addMappingWithCode(mapping, code) { if (mapping === null || mapping.source === void 0) { node2.add(code); } else { var source = aRelativePath ? util2.join(aRelativePath, mapping.source) : mapping.source; node2.add(new SourceNode( mapping.originalLine, mapping.originalColumn, source, code, mapping.name )); } } }; SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function(chunk) { this.add(chunk); }, this); } else if (aChunk[isSourceNode] || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { for (var i2 = aChunk.length - 1; i2 >= 0; i2--) { this.prepend(aChunk[i2]); } } else if (aChunk[isSourceNode] || typeof aChunk === "string") { this.children.unshift(aChunk); } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; for (var i2 = 0, len = this.children.length; i2 < len; i2++) { chunk = this.children[i2]; if (chunk[isSourceNode]) { chunk.walk(aFn); } else { if (chunk !== "") { aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name }); } } } }; SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i2; var len = this.children.length; if (len > 0) { newChildren = []; for (i2 = 0; i2 < len - 1; i2++) { newChildren.push(this.children[i2]); newChildren.push(aSep); } newChildren.push(this.children[i2]); this.children = newChildren; } return this; }; SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; if (lastChild[isSourceNode]) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === "string") { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); } else { this.children.push("".replace(aPattern, aReplacement)); } return this; }; SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { this.sourceContents[util2.toSetString(aSourceFile)] = aSourceContent; }; SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { for (var i2 = 0, len = this.children.length; i2 < len; i2++) { if (this.children[i2][isSourceNode]) { this.children[i2].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i2 = 0, len = sources.length; i2 < len; i2++) { aFn(util2.fromSetString(sources[i2]), this.sourceContents[sources[i2]]); } }; SourceNode.prototype.toString = function SourceNode_toString() { var str2 = ""; this.walk(function(chunk) { str2 += chunk; }); return str2; }; SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", line: 1, column: 0 }; var map2 = new SourceMapGenerator(aArgs); var sourceMappingActive = false; var lastOriginalSource = null; var lastOriginalLine = null; var lastOriginalColumn = null; var lastOriginalName = null; this.walk(function(chunk, original) { generated.code += chunk; if (original.source !== null && original.line !== null && original.column !== null) { if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map2.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; lastOriginalName = original.name; sourceMappingActive = true; } else if (sourceMappingActive) { map2.addMapping({ generated: { line: generated.line, column: generated.column } }); lastOriginalSource = null; sourceMappingActive = false; } for (var idx = 0, length = chunk.length; idx < length; idx++) { if (chunk.charCodeAt(idx) === NEWLINE_CODE) { generated.line++; generated.column = 0; if (idx + 1 === length) { lastOriginalSource = null; sourceMappingActive = false; } else if (sourceMappingActive) { map2.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } } else { generated.column++; } } }); this.walkSourceContents(function(sourceFile, sourceContent) { map2.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map2 }; }; exports.SourceNode = SourceNode; } }); // node_modules/source-map/source-map.js var require_source_map = __commonJS({ "node_modules/source-map/source-map.js"(exports) { exports.SourceMapGenerator = require_source_map_generator().SourceMapGenerator; exports.SourceMapConsumer = require_source_map_consumer().SourceMapConsumer; exports.SourceNode = require_source_node().SourceNode; } }); // node_modules/recast/lib/util.js var require_util2 = __commonJS({ "node_modules/recast/lib/util.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isTrailingCommaEnabled = exports.getParentExportDeclaration = exports.isExportDeclaration = exports.fixFaultyLocations = exports.getTrueLoc = exports.composeSourceMaps = exports.copyPos = exports.comparePos = exports.getUnionOfKeys = exports.getOption = exports.isBrowser = exports.getLineTerminator = void 0; var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); var assert_1 = tslib_1.__importDefault(require("assert")); var types = tslib_1.__importStar(require_main()); var n = types.namedTypes; var source_map_1 = tslib_1.__importDefault(require_source_map()); var SourceMapConsumer = source_map_1.default.SourceMapConsumer; var SourceMapGenerator = source_map_1.default.SourceMapGenerator; var hasOwn = Object.prototype.hasOwnProperty; function getLineTerminator() { return isBrowser() ? "\n" : require("os").EOL || "\n"; } exports.getLineTerminator = getLineTerminator; function isBrowser() { return typeof window !== "undefined" && typeof window.document !== "undefined"; } exports.isBrowser = isBrowser; function getOption(options, key, defaultValue) { if (options && hasOwn.call(options, key)) { return options[key]; } return defaultValue; } exports.getOption = getOption; function getUnionOfKeys() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var result = {}; var argc = args.length; for (var i2 = 0; i2 < argc; ++i2) { var keys = Object.keys(args[i2]); var keyCount = keys.length; for (var j = 0; j < keyCount; ++j) { result[keys[j]] = true; } } return result; } exports.getUnionOfKeys = getUnionOfKeys; function comparePos(pos1, pos2) { return pos1.line - pos2.line || pos1.column - pos2.column; } exports.comparePos = comparePos; function copyPos(pos) { return { line: pos.line, column: pos.column }; } exports.copyPos = copyPos; function composeSourceMaps(formerMap, latterMap) { if (formerMap) { if (!latterMap) { return formerMap; } } else { return latterMap || null; } var smcFormer = new SourceMapConsumer(formerMap); var smcLatter = new SourceMapConsumer(latterMap); var smg = new SourceMapGenerator({ file: latterMap.file, sourceRoot: latterMap.sourceRoot }); var sourcesToContents = {}; smcLatter.eachMapping(function(mapping) { var origPos = smcFormer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); var sourceName = origPos.source; if (sourceName === null) { return; } smg.addMapping({ source: sourceName, original: copyPos(origPos), generated: { line: mapping.generatedLine, column: mapping.generatedColumn }, name: mapping.name }); var sourceContent = smcFormer.sourceContentFor(sourceName); if (sourceContent && !hasOwn.call(sourcesToContents, sourceName)) { sourcesToContents[sourceName] = sourceContent; smg.setSourceContent(sourceName, sourceContent); } }); return smg.toJSON(); } exports.composeSourceMaps = composeSourceMaps; function getTrueLoc(node2, lines) { if (!node2.loc) { return null; } var result = { start: node2.loc.start, end: node2.loc.end }; function include(node3) { expandLoc(result, node3.loc); } if (node2.declaration && node2.declaration.decorators && isExportDeclaration(node2)) { node2.declaration.decorators.forEach(include); } if (comparePos(result.start, result.end) < 0) { result.start = copyPos(result.start); lines.skipSpaces(result.start, false, true); if (comparePos(result.start, result.end) < 0) { result.end = copyPos(result.end); lines.skipSpaces(result.end, true, true); } } if (node2.comments) { node2.comments.forEach(include); } return result; } exports.getTrueLoc = getTrueLoc; function expandLoc(parentLoc, childLoc) { if (parentLoc && childLoc) { if (comparePos(childLoc.start, parentLoc.start) < 0) { parentLoc.start = childLoc.start; } if (comparePos(parentLoc.end, childLoc.end) < 0) { parentLoc.end = childLoc.end; } } } function fixFaultyLocations(node2, lines) { var loc = node2.loc; if (loc) { if (loc.start.line < 1) { loc.start.line = 1; } if (loc.end.line < 1) { loc.end.line = 1; } } if (node2.type === "File") { loc.start = lines.firstPos(); loc.end = lines.lastPos(); } fixForLoopHead(node2, lines); fixTemplateLiteral(node2, lines); if (loc && node2.decorators) { node2.decorators.forEach(function(decorator) { expandLoc(loc, decorator.loc); }); } else if (node2.declaration && isExportDeclaration(node2)) { node2.declaration.loc = null; var decorators = node2.declaration.decorators; if (decorators) { decorators.forEach(function(decorator) { expandLoc(loc, decorator.loc); }); } } else if (n.MethodDefinition && n.MethodDefinition.check(node2) || n.Property.check(node2) && (node2.method || node2.shorthand)) { node2.value.loc = null; if (n.FunctionExpression.check(node2.value)) { node2.value.id = null; } } else if (node2.type === "ObjectTypeProperty") { var loc_1 = node2.loc; var end = loc_1 && loc_1.end; if (end) { end = copyPos(end); if (lines.prevPos(end) && lines.charAt(end) === ",") { if (end = lines.skipSpaces(end, true, true)) { loc_1.end = end; } } } } } exports.fixFaultyLocations = fixFaultyLocations; function fixForLoopHead(node2, lines) { if (node2.type !== "ForStatement") { return; } function fix(child) { var loc = child && child.loc; var start = loc && loc.start; var end = loc && copyPos(loc.end); while (start && end && comparePos(start, end) < 0) { lines.prevPos(end); if (lines.charAt(end) === ";") { loc.end.line = end.line; loc.end.column = end.column; } else { break; } } } fix(node2.init); fix(node2.test); fix(node2.update); } function fixTemplateLiteral(node2, lines) { if (node2.type !== "TemplateLiteral") { return; } if (node2.quasis.length === 0) { return; } if (node2.loc) { var afterLeftBackTickPos = copyPos(node2.loc.start); assert_1.default.strictEqual(lines.charAt(afterLeftBackTickPos), "`"); assert_1.default.ok(lines.nextPos(afterLeftBackTickPos)); var firstQuasi = node2.quasis[0]; if (comparePos(firstQuasi.loc.start, afterLeftBackTickPos) < 0) { firstQuasi.loc.start = afterLeftBackTickPos; } var rightBackTickPos = copyPos(node2.loc.end); assert_1.default.ok(lines.prevPos(rightBackTickPos)); assert_1.default.strictEqual(lines.charAt(rightBackTickPos), "`"); var lastQuasi = node2.quasis[node2.quasis.length - 1]; if (comparePos(rightBackTickPos, lastQuasi.loc.end) < 0) { lastQuasi.loc.end = rightBackTickPos; } } node2.expressions.forEach(function(expr, i2) { var dollarCurlyPos = lines.skipSpaces(expr.loc.start, true, false); if (lines.prevPos(dollarCurlyPos) && lines.charAt(dollarCurlyPos) === "{" && lines.prevPos(dollarCurlyPos) && lines.charAt(dollarCurlyPos) === "$") { var quasiBefore = node2.quasis[i2]; if (comparePos(dollarCurlyPos, quasiBefore.loc.end) < 0) { quasiBefore.loc.end = dollarCurlyPos; } } var rightCurlyPos = lines.skipSpaces(expr.loc.end, false, false); if (lines.charAt(rightCurlyPos) === "}") { assert_1.default.ok(lines.nextPos(rightCurlyPos)); var quasiAfter = node2.quasis[i2 + 1]; if (comparePos(quasiAfter.loc.start, rightCurlyPos) < 0) { quasiAfter.loc.start = rightCurlyPos; } } }); } function isExportDeclaration(node2) { if (node2) switch (node2.type) { case "ExportDeclaration": case "ExportDefaultDeclaration": case "ExportDefaultSpecifier": case "DeclareExportDeclaration": case "ExportNamedDeclaration": case "ExportAllDeclaration": return true; } return false; } exports.isExportDeclaration = isExportDeclaration; function getParentExportDeclaration(path) { var parentNode = path.getParentNode(); if (path.getName() === "declaration" && isExportDeclaration(parentNode)) { return parentNode; } return null; } exports.getParentExportDeclaration = getParentExportDeclaration; function isTrailingCommaEnabled(options, context) { var trailingComma = options.trailingComma; if (typeof trailingComma === "object") { return !!trailingComma[context]; } return !!trailingComma; } exports.isTrailingCommaEnabled = isTrailingCommaEnabled; } }); // node_modules/esprima/dist/esprima.js var require_esprima2 = __commonJS({ "node_modules/esprima/dist/esprima.js"(exports, module2) { (function webpackUniversalModuleDefinition(root, factory) { if (typeof exports === "object" && typeof module2 === "object") module2.exports = factory(); else if (typeof define === "function" && define.amd) define([], factory); else if (typeof exports === "object") exports["esprima"] = factory(); else root["esprima"] = factory(); })(exports, function() { return ( /******/ function(modules) { var installedModules = {}; function __webpack_require__(moduleId) { if (installedModules[moduleId]) return installedModules[moduleId].exports; var module3 = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; modules[moduleId].call(module3.exports, module3, module3.exports, __webpack_require__); module3.loaded = true; return module3.exports; } __webpack_require__.m = modules; __webpack_require__.c = installedModules; __webpack_require__.p = ""; return __webpack_require__(0); }([ /* 0 */ /***/ function(module3, exports2, __webpack_require__) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var comment_handler_1 = __webpack_require__(1); var jsx_parser_1 = __webpack_require__(3); var parser_1 = __webpack_require__(8); var tokenizer_1 = __webpack_require__(15); function parse3(code, options, delegate) { var commentHandler = null; var proxyDelegate = function(node2, metadata) { if (delegate) { delegate(node2, metadata); } if (commentHandler) { commentHandler.visit(node2, metadata); } }; var parserDelegate = typeof delegate === "function" ? proxyDelegate : null; var collectComment = false; if (options) { collectComment = typeof options.comment === "boolean" && options.comment; var attachComment = typeof options.attachComment === "boolean" && options.attachComment; if (collectComment || attachComment) { commentHandler = new comment_handler_1.CommentHandler(); commentHandler.attach = attachComment; options.comment = true; parserDelegate = proxyDelegate; } } var isModule = false; if (options && typeof options.sourceType === "string") { isModule = options.sourceType === "module"; } var parser; if (options && typeof options.jsx === "boolean" && options.jsx) { parser = new jsx_parser_1.JSXParser(code, options, parserDelegate); } else { parser = new parser_1.Parser(code, options, parserDelegate); } var program = isModule ? parser.parseModule() : parser.parseScript(); var ast = program; if (collectComment && commentHandler) { ast.comments = commentHandler.comments; } if (parser.config.tokens) { ast.tokens = parser.tokens; } if (parser.config.tolerant) { ast.errors = parser.errorHandler.errors; } return ast; } exports2.parse = parse3; function parseModule(code, options, delegate) { var parsingOptions = options || {}; parsingOptions.sourceType = "module"; return parse3(code, parsingOptions, delegate); } exports2.parseModule = parseModule; function parseScript(code, options, delegate) { var parsingOptions = options || {}; parsingOptions.sourceType = "script"; return parse3(code, parsingOptions, delegate); } exports2.parseScript = parseScript; function tokenize(code, options, delegate) { var tokenizer = new tokenizer_1.Tokenizer(code, options); var tokens; tokens = []; try { while (true) { var token = tokenizer.getNextToken(); if (!token) { break; } if (delegate) { token = delegate(token); } tokens.push(token); } } catch (e2) { tokenizer.errorHandler.tolerate(e2); } if (tokenizer.errorHandler.tolerant) { tokens.errors = tokenizer.errors(); } return tokens; } exports2.tokenize = tokenize; var syntax_1 = __webpack_require__(2); exports2.Syntax = syntax_1.Syntax; exports2.version = "4.0.1"; }, /* 1 */ /***/ function(module3, exports2, __webpack_require__) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var syntax_1 = __webpack_require__(2); var CommentHandler = function() { function CommentHandler2() { this.attach = false; this.comments = []; this.stack = []; this.leading = []; this.trailing = []; } CommentHandler2.prototype.insertInnerComments = function(node2, metadata) { if (node2.type === syntax_1.Syntax.BlockStatement && node2.body.length === 0) { var innerComments = []; for (var i2 = this.leading.length - 1; i2 >= 0; --i2) { var entry = this.leading[i2]; if (metadata.end.offset >= entry.start) { innerComments.unshift(entry.comment); this.leading.splice(i2, 1); this.trailing.splice(i2, 1); } } if (innerComments.length) { node2.innerComments = innerComments; } } }; CommentHandler2.prototype.findTrailingComments = function(metadata) { var trailingComments = []; if (this.trailing.length > 0) { for (var i2 = this.trailing.length - 1; i2 >= 0; --i2) { var entry_1 = this.trailing[i2]; if (entry_1.start >= metadata.end.offset) { trailingComments.unshift(entry_1.comment); } } this.trailing.length = 0; return trailingComments; } var entry = this.stack[this.stack.length - 1]; if (entry && entry.node.trailingComments) { var firstComment = entry.node.trailingComments[0]; if (firstComment && firstComment.range[0] >= metadata.end.offset) { trailingComments = entry.node.trailingComments; delete entry.node.trailingComments; } } return trailingComments; }; CommentHandler2.prototype.findLeadingComments = function(metadata) { var leadingComments = []; var target; while (this.stack.length > 0) { var entry = this.stack[this.stack.length - 1]; if (entry && entry.start >= metadata.start.offset) { target = entry.node; this.stack.pop(); } else { break; } } if (target) { var count = target.leadingComments ? target.leadingComments.length : 0; for (var i2 = count - 1; i2 >= 0; --i2) { var comment = target.leadingComments[i2]; if (comment.range[1] <= metadata.start.offset) { leadingComments.unshift(comment); target.leadingComments.splice(i2, 1); } } if (target.leadingComments && target.leadingComments.length === 0) { delete target.leadingComments; } return leadingComments; } for (var i2 = this.leading.length - 1; i2 >= 0; --i2) { var entry = this.leading[i2]; if (entry.start <= metadata.start.offset) { leadingComments.unshift(entry.comment); this.leading.splice(i2, 1); } } return leadingComments; }; CommentHandler2.prototype.visitNode = function(node2, metadata) { if (node2.type === syntax_1.Syntax.Program && node2.body.length > 0) { return; } this.insertInnerComments(node2, metadata); var trailingComments = this.findTrailingComments(metadata); var leadingComments = this.findLeadingComments(metadata); if (leadingComments.length > 0) { node2.leadingComments = leadingComments; } if (trailingComments.length > 0) { node2.trailingComments = trailingComments; } this.stack.push({ node: node2, start: metadata.start.offset }); }; CommentHandler2.prototype.visitComment = function(node2, metadata) { var type2 = node2.type[0] === "L" ? "Line" : "Block"; var comment = { type: type2, value: node2.value }; if (node2.range) { comment.range = node2.range; } if (node2.loc) { comment.loc = node2.loc; } this.comments.push(comment); if (this.attach) { var entry = { comment: { type: type2, value: node2.value, range: [metadata.start.offset, metadata.end.offset] }, start: metadata.start.offset }; if (node2.loc) { entry.comment.loc = node2.loc; } node2.type = type2; this.leading.push(entry); this.trailing.push(entry); } }; CommentHandler2.prototype.visit = function(node2, metadata) { if (node2.type === "LineComment") { this.visitComment(node2, metadata); } else if (node2.type === "BlockComment") { this.visitComment(node2, metadata); } else if (this.attach) { this.visitNode(node2, metadata); } }; return CommentHandler2; }(); exports2.CommentHandler = CommentHandler; }, /* 2 */ /***/ function(module3, exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.Syntax = { AssignmentExpression: "AssignmentExpression", AssignmentPattern: "AssignmentPattern", ArrayExpression: "ArrayExpression", ArrayPattern: "ArrayPattern", ArrowFunctionExpression: "ArrowFunctionExpression", AwaitExpression: "AwaitExpression", BlockStatement: "BlockStatement", BinaryExpression: "BinaryExpression", BreakStatement: "BreakStatement", CallExpression: "CallExpression", CatchClause: "CatchClause", ClassBody: "ClassBody", ClassDeclaration: "ClassDeclaration", ClassExpression: "ClassExpression", ConditionalExpression: "ConditionalExpression", ContinueStatement: "ContinueStatement", DoWhileStatement: "DoWhileStatement", DebuggerStatement: "DebuggerStatement", EmptyStatement: "EmptyStatement", ExportAllDeclaration: "ExportAllDeclaration", ExportDefaultDeclaration: "ExportDefaultDeclaration", ExportNamedDeclaration: "ExportNamedDeclaration", ExportSpecifier: "ExportSpecifier", ExpressionStatement: "ExpressionStatement", ForStatement: "ForStatement", ForOfStatement: "ForOfStatement", ForInStatement: "ForInStatement", FunctionDeclaration: "FunctionDeclaration", FunctionExpression: "FunctionExpression", Identifier: "Identifier", IfStatement: "IfStatement", ImportDeclaration: "ImportDeclaration", ImportDefaultSpecifier: "ImportDefaultSpecifier", ImportNamespaceSpecifier: "ImportNamespaceSpecifier", ImportSpecifier: "ImportSpecifier", Literal: "Literal", LabeledStatement: "LabeledStatement", LogicalExpression: "LogicalExpression", MemberExpression: "MemberExpression", MetaProperty: "MetaProperty", MethodDefinition: "MethodDefinition", NewExpression: "NewExpression", ObjectExpression: "ObjectExpression", ObjectPattern: "ObjectPattern", Program: "Program", Property: "Property", RestElement: "RestElement", ReturnStatement: "ReturnStatement", SequenceExpression: "SequenceExpression", SpreadElement: "SpreadElement", Super: "Super", SwitchCase: "SwitchCase", SwitchStatement: "SwitchStatement", TaggedTemplateExpression: "TaggedTemplateExpression", TemplateElement: "TemplateElement", TemplateLiteral: "TemplateLiteral", ThisExpression: "ThisExpression", ThrowStatement: "ThrowStatement", TryStatement: "TryStatement", UnaryExpression: "UnaryExpression", UpdateExpression: "UpdateExpression", VariableDeclaration: "VariableDeclaration", VariableDeclarator: "VariableDeclarator", WhileStatement: "WhileStatement", WithStatement: "WithStatement", YieldExpression: "YieldExpression" }; }, /* 3 */ /***/ function(module3, exports2, __webpack_require__) { "use strict"; var __extends3 = this && this.__extends || function() { var extendStatics3 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b2) { d3.__proto__ = b2; } || function(d3, b2) { for (var p in b2) if (b2.hasOwnProperty(p)) d3[p] = b2[p]; }; return function(d3, b2) { extendStatics3(d3, b2); function __() { this.constructor = d3; } d3.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __()); }; }(); Object.defineProperty(exports2, "__esModule", { value: true }); var character_1 = __webpack_require__(4); var JSXNode = __webpack_require__(5); var jsx_syntax_1 = __webpack_require__(6); var Node = __webpack_require__(7); var parser_1 = __webpack_require__(8); var token_1 = __webpack_require__(13); var xhtml_entities_1 = __webpack_require__(14); token_1.TokenName[ 100 /* Identifier */ ] = "JSXIdentifier"; token_1.TokenName[ 101 /* Text */ ] = "JSXText"; function getQualifiedElementName(elementName) { var qualifiedName; switch (elementName.type) { case jsx_syntax_1.JSXSyntax.JSXIdentifier: var id = elementName; qualifiedName = id.name; break; case jsx_syntax_1.JSXSyntax.JSXNamespacedName: var ns = elementName; qualifiedName = getQualifiedElementName(ns.namespace) + ":" + getQualifiedElementName(ns.name); break; case jsx_syntax_1.JSXSyntax.JSXMemberExpression: var expr = elementName; qualifiedName = getQualifiedElementName(expr.object) + "." + getQualifiedElementName(expr.property); break; default: break; } return qualifiedName; } var JSXParser = function(_super) { __extends3(JSXParser2, _super); function JSXParser2(code, options, delegate) { return _super.call(this, code, options, delegate) || this; } JSXParser2.prototype.parsePrimaryExpression = function() { return this.match("<") ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this); }; JSXParser2.prototype.startJSX = function() { this.scanner.index = this.startMarker.index; this.scanner.lineNumber = this.startMarker.line; this.scanner.lineStart = this.startMarker.index - this.startMarker.column; }; JSXParser2.prototype.finishJSX = function() { this.nextToken(); }; JSXParser2.prototype.reenterJSX = function() { this.startJSX(); this.expectJSX("}"); if (this.config.tokens) { this.tokens.pop(); } }; JSXParser2.prototype.createJSXNode = function() { this.collectComments(); return { index: this.scanner.index, line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart }; }; JSXParser2.prototype.createJSXChildNode = function() { return { index: this.scanner.index, line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart }; }; JSXParser2.prototype.scanXHTMLEntity = function(quote) { var result = "&"; var valid = true; var terminated = false; var numeric = false; var hex = false; while (!this.scanner.eof() && valid && !terminated) { var ch = this.scanner.source[this.scanner.index]; if (ch === quote) { break; } terminated = ch === ";"; result += ch; ++this.scanner.index; if (!terminated) { switch (result.length) { case 2: numeric = ch === "#"; break; case 3: if (numeric) { hex = ch === "x"; valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0)); numeric = numeric && !hex; } break; default: valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0))); valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0))); break; } } } if (valid && terminated && result.length > 2) { var str2 = result.substr(1, result.length - 2); if (numeric && str2.length > 1) { result = String.fromCharCode(parseInt(str2.substr(1), 10)); } else if (hex && str2.length > 2) { result = String.fromCharCode(parseInt("0" + str2.substr(1), 16)); } else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str2]) { result = xhtml_entities_1.XHTMLEntities[str2]; } } return result; }; JSXParser2.prototype.lexJSX = function() { var cp = this.scanner.source.charCodeAt(this.scanner.index); if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) { var value = this.scanner.source[this.scanner.index++]; return { type: 7, value, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: this.scanner.index - 1, end: this.scanner.index }; } if (cp === 34 || cp === 39) { var start = this.scanner.index; var quote = this.scanner.source[this.scanner.index++]; var str2 = ""; while (!this.scanner.eof()) { var ch = this.scanner.source[this.scanner.index++]; if (ch === quote) { break; } else if (ch === "&") { str2 += this.scanXHTMLEntity(quote); } else { str2 += ch; } } return { type: 8, value: str2, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start, end: this.scanner.index }; } if (cp === 46) { var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1); var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2); var value = n1 === 46 && n2 === 46 ? "..." : "."; var start = this.scanner.index; this.scanner.index += value.length; return { type: 7, value, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start, end: this.scanner.index }; } if (cp === 96) { return { type: 10, value: "", lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start: this.scanner.index, end: this.scanner.index }; } if (character_1.Character.isIdentifierStart(cp) && cp !== 92) { var start = this.scanner.index; ++this.scanner.index; while (!this.scanner.eof()) { var ch = this.scanner.source.charCodeAt(this.scanner.index); if (character_1.Character.isIdentifierPart(ch) && ch !== 92) { ++this.scanner.index; } else if (ch === 45) { ++this.scanner.index; } else { break; } } var id = this.scanner.source.slice(start, this.scanner.index); return { type: 100, value: id, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start, end: this.scanner.index }; } return this.scanner.lex(); }; JSXParser2.prototype.nextJSXToken = function() { this.collectComments(); this.startMarker.index = this.scanner.index; this.startMarker.line = this.scanner.lineNumber; this.startMarker.column = this.scanner.index - this.scanner.lineStart; var token = this.lexJSX(); this.lastMarker.index = this.scanner.index; this.lastMarker.line = this.scanner.lineNumber; this.lastMarker.column = this.scanner.index - this.scanner.lineStart; if (this.config.tokens) { this.tokens.push(this.convertToken(token)); } return token; }; JSXParser2.prototype.nextJSXText = function() { this.startMarker.index = this.scanner.index; this.startMarker.line = this.scanner.lineNumber; this.startMarker.column = this.scanner.index - this.scanner.lineStart; var start = this.scanner.index; var text3 = ""; while (!this.scanner.eof()) { var ch = this.scanner.source[this.scanner.index]; if (ch === "{" || ch === "<") { break; } ++this.scanner.index; text3 += ch; if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { ++this.scanner.lineNumber; if (ch === "\r" && this.scanner.source[this.scanner.index] === "\n") { ++this.scanner.index; } this.scanner.lineStart = this.scanner.index; } } this.lastMarker.index = this.scanner.index; this.lastMarker.line = this.scanner.lineNumber; this.lastMarker.column = this.scanner.index - this.scanner.lineStart; var token = { type: 101, value: text3, lineNumber: this.scanner.lineNumber, lineStart: this.scanner.lineStart, start, end: this.scanner.index }; if (text3.length > 0 && this.config.tokens) { this.tokens.push(this.convertToken(token)); } return token; }; JSXParser2.prototype.peekJSXToken = function() { var state = this.scanner.saveState(); this.scanner.scanComments(); var next = this.lexJSX(); this.scanner.restoreState(state); return next; }; JSXParser2.prototype.expectJSX = function(value) { var token = this.nextJSXToken(); if (token.type !== 7 || token.value !== value) { this.throwUnexpectedToken(token); } }; JSXParser2.prototype.matchJSX = function(value) { var next = this.peekJSXToken(); return next.type === 7 && next.value === value; }; JSXParser2.prototype.parseJSXIdentifier = function() { var node2 = this.createJSXNode(); var token = this.nextJSXToken(); if (token.type !== 100) { this.throwUnexpectedToken(token); } return this.finalize(node2, new JSXNode.JSXIdentifier(token.value)); }; JSXParser2.prototype.parseJSXElementName = function() { var node2 = this.createJSXNode(); var elementName = this.parseJSXIdentifier(); if (this.matchJSX(":")) { var namespace = elementName; this.expectJSX(":"); var name_1 = this.parseJSXIdentifier(); elementName = this.finalize(node2, new JSXNode.JSXNamespacedName(namespace, name_1)); } else if (this.matchJSX(".")) { while (this.matchJSX(".")) { var object = elementName; this.expectJSX("."); var property = this.parseJSXIdentifier(); elementName = this.finalize(node2, new JSXNode.JSXMemberExpression(object, property)); } } return elementName; }; JSXParser2.prototype.parseJSXAttributeName = function() { var node2 = this.createJSXNode(); var attributeName; var identifier = this.parseJSXIdentifier(); if (this.matchJSX(":")) { var namespace = identifier; this.expectJSX(":"); var name_2 = this.parseJSXIdentifier(); attributeName = this.finalize(node2, new JSXNode.JSXNamespacedName(namespace, name_2)); } else { attributeName = identifier; } return attributeName; }; JSXParser2.prototype.parseJSXStringLiteralAttribute = function() { var node2 = this.createJSXNode(); var token = this.nextJSXToken(); if (token.type !== 8) { this.throwUnexpectedToken(token); } var raw = this.getTokenRaw(token); return this.finalize(node2, new Node.Literal(token.value, raw)); }; JSXParser2.prototype.parseJSXExpressionAttribute = function() { var node2 = this.createJSXNode(); this.expectJSX("{"); this.finishJSX(); if (this.match("}")) { this.tolerateError("JSX attributes must only be assigned a non-empty expression"); } var expression = this.parseAssignmentExpression(); this.reenterJSX(); return this.finalize(node2, new JSXNode.JSXExpressionContainer(expression)); }; JSXParser2.prototype.parseJSXAttributeValue = function() { return this.matchJSX("{") ? this.parseJSXExpressionAttribute() : this.matchJSX("<") ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute(); }; JSXParser2.prototype.parseJSXNameValueAttribute = function() { var node2 = this.createJSXNode(); var name = this.parseJSXAttributeName(); var value = null; if (this.matchJSX("=")) { this.expectJSX("="); value = this.parseJSXAttributeValue(); } return this.finalize(node2, new JSXNode.JSXAttribute(name, value)); }; JSXParser2.prototype.parseJSXSpreadAttribute = function() { var node2 = this.createJSXNode(); this.expectJSX("{"); this.expectJSX("..."); this.finishJSX(); var argument = this.parseAssignmentExpression(); this.reenterJSX(); return this.finalize(node2, new JSXNode.JSXSpreadAttribute(argument)); }; JSXParser2.prototype.parseJSXAttributes = function() { var attributes = []; while (!this.matchJSX("/") && !this.matchJSX(">")) { var attribute = this.matchJSX("{") ? this.parseJSXSpreadAttribute() : this.parseJSXNameValueAttribute(); attributes.push(attribute); } return attributes; }; JSXParser2.prototype.parseJSXOpeningElement = function() { var node2 = this.createJSXNode(); this.expectJSX("<"); var name = this.parseJSXElementName(); var attributes = this.parseJSXAttributes(); var selfClosing = this.matchJSX("/"); if (selfClosing) { this.expectJSX("/"); } this.expectJSX(">"); return this.finalize(node2, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); }; JSXParser2.prototype.parseJSXBoundaryElement = function() { var node2 = this.createJSXNode(); this.expectJSX("<"); if (this.matchJSX("/")) { this.expectJSX("/"); var name_3 = this.parseJSXElementName(); this.expectJSX(">"); return this.finalize(node2, new JSXNode.JSXClosingElement(name_3)); } var name = this.parseJSXElementName(); var attributes = this.parseJSXAttributes(); var selfClosing = this.matchJSX("/"); if (selfClosing) { this.expectJSX("/"); } this.expectJSX(">"); return this.finalize(node2, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); }; JSXParser2.prototype.parseJSXEmptyExpression = function() { var node2 = this.createJSXChildNode(); this.collectComments(); this.lastMarker.index = this.scanner.index; this.lastMarker.line = this.scanner.lineNumber; this.lastMarker.column = this.scanner.index - this.scanner.lineStart; return this.finalize(node2, new JSXNode.JSXEmptyExpression()); }; JSXParser2.prototype.parseJSXExpressionContainer = function() { var node2 = this.createJSXNode(); this.expectJSX("{"); var expression; if (this.matchJSX("}")) { expression = this.parseJSXEmptyExpression(); this.expectJSX("}"); } else { this.finishJSX(); expression = this.parseAssignmentExpression(); this.reenterJSX(); } return this.finalize(node2, new JSXNode.JSXExpressionContainer(expression)); }; JSXParser2.prototype.parseJSXChildren = function() { var children = []; while (!this.scanner.eof()) { var node2 = this.createJSXChildNode(); var token = this.nextJSXText(); if (token.start < token.end) { var raw = this.getTokenRaw(token); var child = this.finalize(node2, new JSXNode.JSXText(token.value, raw)); children.push(child); } if (this.scanner.source[this.scanner.index] === "{") { var container = this.parseJSXExpressionContainer(); children.push(container); } else { break; } } return children; }; JSXParser2.prototype.parseComplexJSXElement = function(el) { var stack = []; while (!this.scanner.eof()) { el.children = el.children.concat(this.parseJSXChildren()); var node2 = this.createJSXChildNode(); var element2 = this.parseJSXBoundaryElement(); if (element2.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) { var opening = element2; if (opening.selfClosing) { var child = this.finalize(node2, new JSXNode.JSXElement(opening, [], null)); el.children.push(child); } else { stack.push(el); el = { node: node2, opening, closing: null, children: [] }; } } if (element2.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) { el.closing = element2; var open_1 = getQualifiedElementName(el.opening.name); var close_1 = getQualifiedElementName(el.closing.name); if (open_1 !== close_1) { this.tolerateError("Expected corresponding JSX closing tag for %0", open_1); } if (stack.length > 0) { var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing)); el = stack[stack.length - 1]; el.children.push(child); stack.pop(); } else { break; } } } return el; }; JSXParser2.prototype.parseJSXElement = function() { var node2 = this.createJSXNode(); var opening = this.parseJSXOpeningElement(); var children = []; var closing = null; if (!opening.selfClosing) { var el = this.parseComplexJSXElement({ node: node2, opening, closing, children }); children = el.children; closing = el.closing; } return this.finalize(node2, new JSXNode.JSXElement(opening, children, closing)); }; JSXParser2.prototype.parseJSXRoot = function() { if (this.config.tokens) { this.tokens.pop(); } this.startJSX(); var element2 = this.parseJSXElement(); this.finishJSX(); return element2; }; JSXParser2.prototype.isStartOfExpression = function() { return _super.prototype.isStartOfExpression.call(this) || this.match("<"); }; return JSXParser2; }(parser_1.Parser); exports2.JSXParser = JSXParser; }, /* 4 */ /***/ function(module3, exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var Regex = { // Unicode v8.0.0 NonAsciiIdentifierStart: NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, // Unicode v8.0.0 NonAsciiIdentifierPart: NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ }; exports2.Character = { /* tslint:disable:no-bitwise */ fromCodePoint: function(cp) { return cp < 65536 ? String.fromCharCode(cp) : String.fromCharCode(55296 + (cp - 65536 >> 10)) + String.fromCharCode(56320 + (cp - 65536 & 1023)); }, // https://tc39.github.io/ecma262/#sec-white-space isWhiteSpace: function(cp) { return cp === 32 || cp === 9 || cp === 11 || cp === 12 || cp === 160 || cp >= 5760 && [5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8239, 8287, 12288, 65279].indexOf(cp) >= 0; }, // https://tc39.github.io/ecma262/#sec-line-terminators isLineTerminator: function(cp) { return cp === 10 || cp === 13 || cp === 8232 || cp === 8233; }, // https://tc39.github.io/ecma262/#sec-names-and-keywords isIdentifierStart: function(cp) { return cp === 36 || cp === 95 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 92 || cp >= 128 && Regex.NonAsciiIdentifierStart.test(exports2.Character.fromCodePoint(cp)); }, isIdentifierPart: function(cp) { return cp === 36 || cp === 95 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp >= 48 && cp <= 57 || cp === 92 || cp >= 128 && Regex.NonAsciiIdentifierPart.test(exports2.Character.fromCodePoint(cp)); }, // https://tc39.github.io/ecma262/#sec-literals-numeric-literals isDecimalDigit: function(cp) { return cp >= 48 && cp <= 57; }, isHexDigit: function(cp) { return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 70 || cp >= 97 && cp <= 102; }, isOctalDigit: function(cp) { return cp >= 48 && cp <= 55; } }; }, /* 5 */ /***/ function(module3, exports2, __webpack_require__) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var jsx_syntax_1 = __webpack_require__(6); var JSXClosingElement = function() { function JSXClosingElement2(name) { this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement; this.name = name; } return JSXClosingElement2; }(); exports2.JSXClosingElement = JSXClosingElement; var JSXElement = function() { function JSXElement2(openingElement, children, closingElement) { this.type = jsx_syntax_1.JSXSyntax.JSXElement; this.openingElement = openingElement; this.children = children; this.closingElement = closingElement; } return JSXElement2; }(); exports2.JSXElement = JSXElement; var JSXEmptyExpression = function() { function JSXEmptyExpression2() { this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression; } return JSXEmptyExpression2; }(); exports2.JSXEmptyExpression = JSXEmptyExpression; var JSXExpressionContainer = function() { function JSXExpressionContainer2(expression) { this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer; this.expression = expression; } return JSXExpressionContainer2; }(); exports2.JSXExpressionContainer = JSXExpressionContainer; var JSXIdentifier = function() { function JSXIdentifier2(name) { this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier; this.name = name; } return JSXIdentifier2; }(); exports2.JSXIdentifier = JSXIdentifier; var JSXMemberExpression = function() { function JSXMemberExpression2(object, property) { this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression; this.object = object; this.property = property; } return JSXMemberExpression2; }(); exports2.JSXMemberExpression = JSXMemberExpression; var JSXAttribute = function() { function JSXAttribute2(name, value) { this.type = jsx_syntax_1.JSXSyntax.JSXAttribute; this.name = name; this.value = value; } return JSXAttribute2; }(); exports2.JSXAttribute = JSXAttribute; var JSXNamespacedName = function() { function JSXNamespacedName2(namespace, name) { this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName; this.namespace = namespace; this.name = name; } return JSXNamespacedName2; }(); exports2.JSXNamespacedName = JSXNamespacedName; var JSXOpeningElement = function() { function JSXOpeningElement2(name, selfClosing, attributes) { this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement; this.name = name; this.selfClosing = selfClosing; this.attributes = attributes; } return JSXOpeningElement2; }(); exports2.JSXOpeningElement = JSXOpeningElement; var JSXSpreadAttribute = function() { function JSXSpreadAttribute2(argument) { this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute; this.argument = argument; } return JSXSpreadAttribute2; }(); exports2.JSXSpreadAttribute = JSXSpreadAttribute; var JSXText = function() { function JSXText2(value, raw) { this.type = jsx_syntax_1.JSXSyntax.JSXText; this.value = value; this.raw = raw; } return JSXText2; }(); exports2.JSXText = JSXText; }, /* 6 */ /***/ function(module3, exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.JSXSyntax = { JSXAttribute: "JSXAttribute", JSXClosingElement: "JSXClosingElement", JSXElement: "JSXElement", JSXEmptyExpression: "JSXEmptyExpression", JSXExpressionContainer: "JSXExpressionContainer", JSXIdentifier: "JSXIdentifier", JSXMemberExpression: "JSXMemberExpression", JSXNamespacedName: "JSXNamespacedName", JSXOpeningElement: "JSXOpeningElement", JSXSpreadAttribute: "JSXSpreadAttribute", JSXText: "JSXText" }; }, /* 7 */ /***/ function(module3, exports2, __webpack_require__) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var syntax_1 = __webpack_require__(2); var ArrayExpression = function() { function ArrayExpression2(elements) { this.type = syntax_1.Syntax.ArrayExpression; this.elements = elements; } return ArrayExpression2; }(); exports2.ArrayExpression = ArrayExpression; var ArrayPattern = function() { function ArrayPattern2(elements) { this.type = syntax_1.Syntax.ArrayPattern; this.elements = elements; } return ArrayPattern2; }(); exports2.ArrayPattern = ArrayPattern; var ArrowFunctionExpression = function() { function ArrowFunctionExpression2(params, body, expression) { this.type = syntax_1.Syntax.ArrowFunctionExpression; this.id = null; this.params = params; this.body = body; this.generator = false; this.expression = expression; this.async = false; } return ArrowFunctionExpression2; }(); exports2.ArrowFunctionExpression = ArrowFunctionExpression; var AssignmentExpression = function() { function AssignmentExpression2(operator, left, right) { this.type = syntax_1.Syntax.AssignmentExpression; this.operator = operator; this.left = left; this.right = right; } return AssignmentExpression2; }(); exports2.AssignmentExpression = AssignmentExpression; var AssignmentPattern = function() { function AssignmentPattern2(left, right) { this.type = syntax_1.Syntax.AssignmentPattern; this.left = left; this.right = right; } return AssignmentPattern2; }(); exports2.AssignmentPattern = AssignmentPattern; var AsyncArrowFunctionExpression = function() { function AsyncArrowFunctionExpression2(params, body, expression) { this.type = syntax_1.Syntax.ArrowFunctionExpression; this.id = null; this.params = params; this.body = body; this.generator = false; this.expression = expression; this.async = true; } return AsyncArrowFunctionExpression2; }(); exports2.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression; var AsyncFunctionDeclaration = function() { function AsyncFunctionDeclaration2(id, params, body) { this.type = syntax_1.Syntax.FunctionDeclaration; this.id = id; this.params = params; this.body = body; this.generator = false; this.expression = false; this.async = true; } return AsyncFunctionDeclaration2; }(); exports2.AsyncFunctionDeclaration = AsyncFunctionDeclaration; var AsyncFunctionExpression = function() { function AsyncFunctionExpression2(id, params, body) { this.type = syntax_1.Syntax.FunctionExpression; this.id = id; this.params = params; this.body = body; this.generator = false; this.expression = false; this.async = true; } return AsyncFunctionExpression2; }(); exports2.AsyncFunctionExpression = AsyncFunctionExpression; var AwaitExpression = function() { function AwaitExpression2(argument) { this.type = syntax_1.Syntax.AwaitExpression; this.argument = argument; } return AwaitExpression2; }(); exports2.AwaitExpression = AwaitExpression; var BinaryExpression = function() { function BinaryExpression2(operator, left, right) { var logical = operator === "||" || operator === "&&"; this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression; this.operator = operator; this.left = left; this.right = right; } return BinaryExpression2; }(); exports2.BinaryExpression = BinaryExpression; var BlockStatement = function() { function BlockStatement2(body) { this.type = syntax_1.Syntax.BlockStatement; this.body = body; } return BlockStatement2; }(); exports2.BlockStatement = BlockStatement; var BreakStatement = function() { function BreakStatement2(label) { this.type = syntax_1.Syntax.BreakStatement; this.label = label; } return BreakStatement2; }(); exports2.BreakStatement = BreakStatement; var CallExpression = function() { function CallExpression2(callee, args) { this.type = syntax_1.Syntax.CallExpression; this.callee = callee; this.arguments = args; } return CallExpression2; }(); exports2.CallExpression = CallExpression; var CatchClause = function() { function CatchClause2(param, body) { this.type = syntax_1.Syntax.CatchClause; this.param = param; this.body = body; } return CatchClause2; }(); exports2.CatchClause = CatchClause; var ClassBody = function() { function ClassBody2(body) { this.type = syntax_1.Syntax.ClassBody; this.body = body; } return ClassBody2; }(); exports2.ClassBody = ClassBody; var ClassDeclaration = function() { function ClassDeclaration2(id, superClass, body) { this.type = syntax_1.Syntax.ClassDeclaration; this.id = id; this.superClass = superClass; this.body = body; } return ClassDeclaration2; }(); exports2.ClassDeclaration = ClassDeclaration; var ClassExpression = function() { function ClassExpression2(id, superClass, body) { this.type = syntax_1.Syntax.ClassExpression; this.id = id; this.superClass = superClass; this.body = body; } return ClassExpression2; }(); exports2.ClassExpression = ClassExpression; var ComputedMemberExpression = function() { function ComputedMemberExpression2(object, property) { this.type = syntax_1.Syntax.MemberExpression; this.computed = true; this.object = object; this.property = property; } return ComputedMemberExpression2; }(); exports2.ComputedMemberExpression = ComputedMemberExpression; var ConditionalExpression = function() { function ConditionalExpression2(test, consequent, alternate) { this.type = syntax_1.Syntax.ConditionalExpression; this.test = test; this.consequent = consequent; this.alternate = alternate; } return ConditionalExpression2; }(); exports2.ConditionalExpression = ConditionalExpression; var ContinueStatement = function() { function ContinueStatement2(label) { this.type = syntax_1.Syntax.ContinueStatement; this.label = label; } return ContinueStatement2; }(); exports2.ContinueStatement = ContinueStatement; var DebuggerStatement = function() { function DebuggerStatement2() { this.type = syntax_1.Syntax.DebuggerStatement; } return DebuggerStatement2; }(); exports2.DebuggerStatement = DebuggerStatement; var Directive = function() { function Directive2(expression, directive) { this.type = syntax_1.Syntax.ExpressionStatement; this.expression = expression; this.directive = directive; } return Directive2; }(); exports2.Directive = Directive; var DoWhileStatement = function() { function DoWhileStatement2(body, test) { this.type = syntax_1.Syntax.DoWhileStatement; this.body = body; this.test = test; } return DoWhileStatement2; }(); exports2.DoWhileStatement = DoWhileStatement; var EmptyStatement = function() { function EmptyStatement2() { this.type = syntax_1.Syntax.EmptyStatement; } return EmptyStatement2; }(); exports2.EmptyStatement = EmptyStatement; var ExportAllDeclaration = function() { function ExportAllDeclaration2(source) { this.type = syntax_1.Syntax.ExportAllDeclaration; this.source = source; } return ExportAllDeclaration2; }(); exports2.ExportAllDeclaration = ExportAllDeclaration; var ExportDefaultDeclaration = function() { function ExportDefaultDeclaration2(declaration) { this.type = syntax_1.Syntax.ExportDefaultDeclaration; this.declaration = declaration; } return ExportDefaultDeclaration2; }(); exports2.ExportDefaultDeclaration = ExportDefaultDeclaration; var ExportNamedDeclaration = function() { function ExportNamedDeclaration2(declaration, specifiers, source) { this.type = syntax_1.Syntax.ExportNamedDeclaration; this.declaration = declaration; this.specifiers = specifiers; this.source = source; } return ExportNamedDeclaration2; }(); exports2.ExportNamedDeclaration = ExportNamedDeclaration; var ExportSpecifier = function() { function ExportSpecifier2(local, exported) { this.type = syntax_1.Syntax.ExportSpecifier; this.exported = exported; this.local = local; } return ExportSpecifier2; }(); exports2.ExportSpecifier = ExportSpecifier; var ExpressionStatement = function() { function ExpressionStatement2(expression) { this.type = syntax_1.Syntax.ExpressionStatement; this.expression = expression; } return ExpressionStatement2; }(); exports2.ExpressionStatement = ExpressionStatement; var ForInStatement = function() { function ForInStatement2(left, right, body) { this.type = syntax_1.Syntax.ForInStatement; this.left = left; this.right = right; this.body = body; this.each = false; } return ForInStatement2; }(); exports2.ForInStatement = ForInStatement; var ForOfStatement = function() { function ForOfStatement2(left, right, body) { this.type = syntax_1.Syntax.ForOfStatement; this.left = left; this.right = right; this.body = body; } return ForOfStatement2; }(); exports2.ForOfStatement = ForOfStatement; var ForStatement = function() { function ForStatement2(init, test, update, body) { this.type = syntax_1.Syntax.ForStatement; this.init = init; this.test = test; this.update = update; this.body = body; } return ForStatement2; }(); exports2.ForStatement = ForStatement; var FunctionDeclaration = function() { function FunctionDeclaration2(id, params, body, generator) { this.type = syntax_1.Syntax.FunctionDeclaration; this.id = id; this.params = params; this.body = body; this.generator = generator; this.expression = false; this.async = false; } return FunctionDeclaration2; }(); exports2.FunctionDeclaration = FunctionDeclaration; var FunctionExpression = function() { function FunctionExpression2(id, params, body, generator) { this.type = syntax_1.Syntax.FunctionExpression; this.id = id; this.params = params; this.body = body; this.generator = generator; this.expression = false; this.async = false; } return FunctionExpression2; }(); exports2.FunctionExpression = FunctionExpression; var Identifier = function() { function Identifier2(name) { this.type = syntax_1.Syntax.Identifier; this.name = name; } return Identifier2; }(); exports2.Identifier = Identifier; var IfStatement = function() { function IfStatement2(test, consequent, alternate) { this.type = syntax_1.Syntax.IfStatement; this.test = test; this.consequent = consequent; this.alternate = alternate; } return IfStatement2; }(); exports2.IfStatement = IfStatement; var ImportDeclaration = function() { function ImportDeclaration2(specifiers, source) { this.type = syntax_1.Syntax.ImportDeclaration; this.specifiers = specifiers; this.source = source; } return ImportDeclaration2; }(); exports2.ImportDeclaration = ImportDeclaration; var ImportDefaultSpecifier = function() { function ImportDefaultSpecifier2(local) { this.type = syntax_1.Syntax.ImportDefaultSpecifier; this.local = local; } return ImportDefaultSpecifier2; }(); exports2.ImportDefaultSpecifier = ImportDefaultSpecifier; var ImportNamespaceSpecifier = function() { function ImportNamespaceSpecifier2(local) { this.type = syntax_1.Syntax.ImportNamespaceSpecifier; this.local = local; } return ImportNamespaceSpecifier2; }(); exports2.ImportNamespaceSpecifier = ImportNamespaceSpecifier; var ImportSpecifier = function() { function ImportSpecifier2(local, imported) { this.type = syntax_1.Syntax.ImportSpecifier; this.local = local; this.imported = imported; } return ImportSpecifier2; }(); exports2.ImportSpecifier = ImportSpecifier; var LabeledStatement = function() { function LabeledStatement2(label, body) { this.type = syntax_1.Syntax.LabeledStatement; this.label = label; this.body = body; } return LabeledStatement2; }(); exports2.LabeledStatement = LabeledStatement; var Literal = function() { function Literal2(value, raw) { this.type = syntax_1.Syntax.Literal; this.value = value; this.raw = raw; } return Literal2; }(); exports2.Literal = Literal; var MetaProperty = function() { function MetaProperty2(meta, property) { this.type = syntax_1.Syntax.MetaProperty; this.meta = meta; this.property = property; } return MetaProperty2; }(); exports2.MetaProperty = MetaProperty; var MethodDefinition = function() { function MethodDefinition2(key, computed, value, kind, isStatic) { this.type = syntax_1.Syntax.MethodDefinition; this.key = key; this.computed = computed; this.value = value; this.kind = kind; this.static = isStatic; } return MethodDefinition2; }(); exports2.MethodDefinition = MethodDefinition; var Module = function() { function Module2(body) { this.type = syntax_1.Syntax.Program; this.body = body; this.sourceType = "module"; } return Module2; }(); exports2.Module = Module; var NewExpression = function() { function NewExpression2(callee, args) { this.type = syntax_1.Syntax.NewExpression; this.callee = callee; this.arguments = args; } return NewExpression2; }(); exports2.NewExpression = NewExpression; var ObjectExpression = function() { function ObjectExpression2(properties) { this.type = syntax_1.Syntax.ObjectExpression; this.properties = properties; } return ObjectExpression2; }(); exports2.ObjectExpression = ObjectExpression; var ObjectPattern = function() { function ObjectPattern2(properties) { this.type = syntax_1.Syntax.ObjectPattern; this.properties = properties; } return ObjectPattern2; }(); exports2.ObjectPattern = ObjectPattern; var Property = function() { function Property2(kind, key, computed, value, method, shorthand) { this.type = syntax_1.Syntax.Property; this.key = key; this.computed = computed; this.value = value; this.kind = kind; this.method = method; this.shorthand = shorthand; } return Property2; }(); exports2.Property = Property; var RegexLiteral = function() { function RegexLiteral2(value, raw, pattern, flags) { this.type = syntax_1.Syntax.Literal; this.value = value; this.raw = raw; this.regex = { pattern, flags }; } return RegexLiteral2; }(); exports2.RegexLiteral = RegexLiteral; var RestElement = function() { function RestElement2(argument) { this.type = syntax_1.Syntax.RestElement; this.argument = argument; } return RestElement2; }(); exports2.RestElement = RestElement; var ReturnStatement = function() { function ReturnStatement2(argument) { this.type = syntax_1.Syntax.ReturnStatement; this.argument = argument; } return ReturnStatement2; }(); exports2.ReturnStatement = ReturnStatement; var Script = function() { function Script2(body) { this.type = syntax_1.Syntax.Program; this.body = body; this.sourceType = "script"; } return Script2; }(); exports2.Script = Script; var SequenceExpression = function() { function SequenceExpression2(expressions) { this.type = syntax_1.Syntax.SequenceExpression; this.expressions = expressions; } return SequenceExpression2; }(); exports2.SequenceExpression = SequenceExpression; var SpreadElement = function() { function SpreadElement2(argument) { this.type = syntax_1.Syntax.SpreadElement; this.argument = argument; } return SpreadElement2; }(); exports2.SpreadElement = SpreadElement; var StaticMemberExpression = function() { function StaticMemberExpression2(object, property) { this.type = syntax_1.Syntax.MemberExpression; this.computed = false; this.object = object; this.property = property; } return StaticMemberExpression2; }(); exports2.StaticMemberExpression = StaticMemberExpression; var Super = function() { function Super2() { this.type = syntax_1.Syntax.Super; } return Super2; }(); exports2.Super = Super; var SwitchCase = function() { function SwitchCase2(test, consequent) { this.type = syntax_1.Syntax.SwitchCase; this.test = test; this.consequent = consequent; } return SwitchCase2; }(); exports2.SwitchCase = SwitchCase; var SwitchStatement = function() { function SwitchStatement2(discriminant, cases) { this.type = syntax_1.Syntax.SwitchStatement; this.discriminant = discriminant; this.cases = cases; } return SwitchStatement2; }(); exports2.SwitchStatement = SwitchStatement; var TaggedTemplateExpression = function() { function TaggedTemplateExpression2(tag, quasi) { this.type = syntax_1.Syntax.TaggedTemplateExpression; this.tag = tag; this.quasi = quasi; } return TaggedTemplateExpression2; }(); exports2.TaggedTemplateExpression = TaggedTemplateExpression; var TemplateElement = function() { function TemplateElement2(value, tail) { this.type = syntax_1.Syntax.TemplateElement; this.value = value; this.tail = tail; } return TemplateElement2; }(); exports2.TemplateElement = TemplateElement; var TemplateLiteral = function() { function TemplateLiteral2(quasis, expressions) { this.type = syntax_1.Syntax.TemplateLiteral; this.quasis = quasis; this.expressions = expressions; } return TemplateLiteral2; }(); exports2.TemplateLiteral = TemplateLiteral; var ThisExpression = function() { function ThisExpression2() { this.type = syntax_1.Syntax.ThisExpression; } return ThisExpression2; }(); exports2.ThisExpression = ThisExpression; var ThrowStatement = function() { function ThrowStatement2(argument) { this.type = syntax_1.Syntax.ThrowStatement; this.argument = argument; } return ThrowStatement2; }(); exports2.ThrowStatement = ThrowStatement; var TryStatement = function() { function TryStatement2(block, handler, finalizer) { this.type = syntax_1.Syntax.TryStatement; this.block = block; this.handler = handler; this.finalizer = finalizer; } return TryStatement2; }(); exports2.TryStatement = TryStatement; var UnaryExpression = function() { function UnaryExpression2(operator, argument) { this.type = syntax_1.Syntax.UnaryExpression; this.operator = operator; this.argument = argument; this.prefix = true; } return UnaryExpression2; }(); exports2.UnaryExpression = UnaryExpression; var UpdateExpression = function() { function UpdateExpression2(operator, argument, prefix) { this.type = syntax_1.Syntax.UpdateExpression; this.operator = operator; this.argument = argument; this.prefix = prefix; } return UpdateExpression2; }(); exports2.UpdateExpression = UpdateExpression; var VariableDeclaration = function() { function VariableDeclaration2(declarations, kind) { this.type = syntax_1.Syntax.VariableDeclaration; this.declarations = declarations; this.kind = kind; } return VariableDeclaration2; }(); exports2.VariableDeclaration = VariableDeclaration; var VariableDeclarator = function() { function VariableDeclarator2(id, init) { this.type = syntax_1.Syntax.VariableDeclarator; this.id = id; this.init = init; } return VariableDeclarator2; }(); exports2.VariableDeclarator = VariableDeclarator; var WhileStatement = function() { function WhileStatement2(test, body) { this.type = syntax_1.Syntax.WhileStatement; this.test = test; this.body = body; } return WhileStatement2; }(); exports2.WhileStatement = WhileStatement; var WithStatement = function() { function WithStatement2(object, body) { this.type = syntax_1.Syntax.WithStatement; this.object = object; this.body = body; } return WithStatement2; }(); exports2.WithStatement = WithStatement; var YieldExpression = function() { function YieldExpression2(argument, delegate) { this.type = syntax_1.Syntax.YieldExpression; this.argument = argument; this.delegate = delegate; } return YieldExpression2; }(); exports2.YieldExpression = YieldExpression; }, /* 8 */ /***/ function(module3, exports2, __webpack_require__) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var assert_1 = __webpack_require__(9); var error_handler_1 = __webpack_require__(10); var messages_1 = __webpack_require__(11); var Node = __webpack_require__(7); var scanner_1 = __webpack_require__(12); var syntax_1 = __webpack_require__(2); var token_1 = __webpack_require__(13); var ArrowParameterPlaceHolder = "ArrowParameterPlaceHolder"; var Parser = function() { function Parser2(code, options, delegate) { if (options === void 0) { options = {}; } this.config = { range: typeof options.range === "boolean" && options.range, loc: typeof options.loc === "boolean" && options.loc, source: null, tokens: typeof options.tokens === "boolean" && options.tokens, comment: typeof options.comment === "boolean" && options.comment, tolerant: typeof options.tolerant === "boolean" && options.tolerant }; if (this.config.loc && options.source && options.source !== null) { this.config.source = String(options.source); } this.delegate = delegate; this.errorHandler = new error_handler_1.ErrorHandler(); this.errorHandler.tolerant = this.config.tolerant; this.scanner = new scanner_1.Scanner(code, this.errorHandler); this.scanner.trackComment = this.config.comment; this.operatorPrecedence = { ")": 0, ";": 0, ",": 0, "=": 0, "]": 0, "||": 1, "&&": 2, "|": 3, "^": 4, "&": 5, "==": 6, "!=": 6, "===": 6, "!==": 6, "<": 7, ">": 7, "<=": 7, ">=": 7, "<<": 8, ">>": 8, ">>>": 8, "+": 9, "-": 9, "*": 11, "/": 11, "%": 11 }; this.lookahead = { type: 2, value: "", lineNumber: this.scanner.lineNumber, lineStart: 0, start: 0, end: 0 }; this.hasLineTerminator = false; this.context = { isModule: false, await: false, allowIn: true, allowStrictDirective: true, allowYield: true, firstCoverInitializedNameError: null, isAssignmentTarget: false, isBindingElement: false, inFunctionBody: false, inIteration: false, inSwitch: false, labelSet: {}, strict: false }; this.tokens = []; this.startMarker = { index: 0, line: this.scanner.lineNumber, column: 0 }; this.lastMarker = { index: 0, line: this.scanner.lineNumber, column: 0 }; this.nextToken(); this.lastMarker = { index: this.scanner.index, line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart }; } Parser2.prototype.throwError = function(messageFormat) { var values = []; for (var _i = 1; _i < arguments.length; _i++) { values[_i - 1] = arguments[_i]; } var args = Array.prototype.slice.call(arguments, 1); var msg = messageFormat.replace(/%(\d)/g, function(whole, idx) { assert_1.assert(idx < args.length, "Message reference must be in range"); return args[idx]; }); var index2 = this.lastMarker.index; var line = this.lastMarker.line; var column = this.lastMarker.column + 1; throw this.errorHandler.createError(index2, line, column, msg); }; Parser2.prototype.tolerateError = function(messageFormat) { var values = []; for (var _i = 1; _i < arguments.length; _i++) { values[_i - 1] = arguments[_i]; } var args = Array.prototype.slice.call(arguments, 1); var msg = messageFormat.replace(/%(\d)/g, function(whole, idx) { assert_1.assert(idx < args.length, "Message reference must be in range"); return args[idx]; }); var index2 = this.lastMarker.index; var line = this.scanner.lineNumber; var column = this.lastMarker.column + 1; this.errorHandler.tolerateError(index2, line, column, msg); }; Parser2.prototype.unexpectedTokenError = function(token, message) { var msg = message || messages_1.Messages.UnexpectedToken; var value; if (token) { if (!message) { msg = token.type === 2 ? messages_1.Messages.UnexpectedEOS : token.type === 3 ? messages_1.Messages.UnexpectedIdentifier : token.type === 6 ? messages_1.Messages.UnexpectedNumber : token.type === 8 ? messages_1.Messages.UnexpectedString : token.type === 10 ? messages_1.Messages.UnexpectedTemplate : messages_1.Messages.UnexpectedToken; if (token.type === 4) { if (this.scanner.isFutureReservedWord(token.value)) { msg = messages_1.Messages.UnexpectedReserved; } else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) { msg = messages_1.Messages.StrictReservedWord; } } } value = token.value; } else { value = "ILLEGAL"; } msg = msg.replace("%0", value); if (token && typeof token.lineNumber === "number") { var index2 = token.start; var line = token.lineNumber; var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column; var column = token.start - lastMarkerLineStart + 1; return this.errorHandler.createError(index2, line, column, msg); } else { var index2 = this.lastMarker.index; var line = this.lastMarker.line; var column = this.lastMarker.column + 1; return this.errorHandler.createError(index2, line, column, msg); } }; Parser2.prototype.throwUnexpectedToken = function(token, message) { throw this.unexpectedTokenError(token, message); }; Parser2.prototype.tolerateUnexpectedToken = function(token, message) { this.errorHandler.tolerate(this.unexpectedTokenError(token, message)); }; Parser2.prototype.collectComments = function() { if (!this.config.comment) { this.scanner.scanComments(); } else { var comments = this.scanner.scanComments(); if (comments.length > 0 && this.delegate) { for (var i2 = 0; i2 < comments.length; ++i2) { var e2 = comments[i2]; var node2 = void 0; node2 = { type: e2.multiLine ? "BlockComment" : "LineComment", value: this.scanner.source.slice(e2.slice[0], e2.slice[1]) }; if (this.config.range) { node2.range = e2.range; } if (this.config.loc) { node2.loc = e2.loc; } var metadata = { start: { line: e2.loc.start.line, column: e2.loc.start.column, offset: e2.range[0] }, end: { line: e2.loc.end.line, column: e2.loc.end.column, offset: e2.range[1] } }; this.delegate(node2, metadata); } } } }; Parser2.prototype.getTokenRaw = function(token) { return this.scanner.source.slice(token.start, token.end); }; Parser2.prototype.convertToken = function(token) { var t2 = { type: token_1.TokenName[token.type], value: this.getTokenRaw(token) }; if (this.config.range) { t2.range = [token.start, token.end]; } if (this.config.loc) { t2.loc = { start: { line: this.startMarker.line, column: this.startMarker.column }, end: { line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart } }; } if (token.type === 9) { var pattern = token.pattern; var flags = token.flags; t2.regex = { pattern, flags }; } return t2; }; Parser2.prototype.nextToken = function() { var token = this.lookahead; this.lastMarker.index = this.scanner.index; this.lastMarker.line = this.scanner.lineNumber; this.lastMarker.column = this.scanner.index - this.scanner.lineStart; this.collectComments(); if (this.scanner.index !== this.startMarker.index) { this.startMarker.index = this.scanner.index; this.startMarker.line = this.scanner.lineNumber; this.startMarker.column = this.scanner.index - this.scanner.lineStart; } var next = this.scanner.lex(); this.hasLineTerminator = token.lineNumber !== next.lineNumber; if (next && this.context.strict && next.type === 3) { if (this.scanner.isStrictModeReservedWord(next.value)) { next.type = 4; } } this.lookahead = next; if (this.config.tokens && next.type !== 2) { this.tokens.push(this.convertToken(next)); } return token; }; Parser2.prototype.nextRegexToken = function() { this.collectComments(); var token = this.scanner.scanRegExp(); if (this.config.tokens) { this.tokens.pop(); this.tokens.push(this.convertToken(token)); } this.lookahead = token; this.nextToken(); return token; }; Parser2.prototype.createNode = function() { return { index: this.startMarker.index, line: this.startMarker.line, column: this.startMarker.column }; }; Parser2.prototype.startNode = function(token, lastLineStart) { if (lastLineStart === void 0) { lastLineStart = 0; } var column = token.start - token.lineStart; var line = token.lineNumber; if (column < 0) { column += lastLineStart; line--; } return { index: token.start, line, column }; }; Parser2.prototype.finalize = function(marker, node2) { if (this.config.range) { node2.range = [marker.index, this.lastMarker.index]; } if (this.config.loc) { node2.loc = { start: { line: marker.line, column: marker.column }, end: { line: this.lastMarker.line, column: this.lastMarker.column } }; if (this.config.source) { node2.loc.source = this.config.source; } } if (this.delegate) { var metadata = { start: { line: marker.line, column: marker.column, offset: marker.index }, end: { line: this.lastMarker.line, column: this.lastMarker.column, offset: this.lastMarker.index } }; this.delegate(node2, metadata); } return node2; }; Parser2.prototype.expect = function(value) { var token = this.nextToken(); if (token.type !== 7 || token.value !== value) { this.throwUnexpectedToken(token); } }; Parser2.prototype.expectCommaSeparator = function() { if (this.config.tolerant) { var token = this.lookahead; if (token.type === 7 && token.value === ",") { this.nextToken(); } else if (token.type === 7 && token.value === ";") { this.nextToken(); this.tolerateUnexpectedToken(token); } else { this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken); } } else { this.expect(","); } }; Parser2.prototype.expectKeyword = function(keyword) { var token = this.nextToken(); if (token.type !== 4 || token.value !== keyword) { this.throwUnexpectedToken(token); } }; Parser2.prototype.match = function(value) { return this.lookahead.type === 7 && this.lookahead.value === value; }; Parser2.prototype.matchKeyword = function(keyword) { return this.lookahead.type === 4 && this.lookahead.value === keyword; }; Parser2.prototype.matchContextualKeyword = function(keyword) { return this.lookahead.type === 3 && this.lookahead.value === keyword; }; Parser2.prototype.matchAssign = function() { if (this.lookahead.type !== 7) { return false; } var op = this.lookahead.value; return op === "=" || op === "*=" || op === "**=" || op === "/=" || op === "%=" || op === "+=" || op === "-=" || op === "<<=" || op === ">>=" || op === ">>>=" || op === "&=" || op === "^=" || op === "|="; }; Parser2.prototype.isolateCoverGrammar = function(parseFunction) { var previousIsBindingElement = this.context.isBindingElement; var previousIsAssignmentTarget = this.context.isAssignmentTarget; var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; this.context.isBindingElement = true; this.context.isAssignmentTarget = true; this.context.firstCoverInitializedNameError = null; var result = parseFunction.call(this); if (this.context.firstCoverInitializedNameError !== null) { this.throwUnexpectedToken(this.context.firstCoverInitializedNameError); } this.context.isBindingElement = previousIsBindingElement; this.context.isAssignmentTarget = previousIsAssignmentTarget; this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError; return result; }; Parser2.prototype.inheritCoverGrammar = function(parseFunction) { var previousIsBindingElement = this.context.isBindingElement; var previousIsAssignmentTarget = this.context.isAssignmentTarget; var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; this.context.isBindingElement = true; this.context.isAssignmentTarget = true; this.context.firstCoverInitializedNameError = null; var result = parseFunction.call(this); this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement; this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget; this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError; return result; }; Parser2.prototype.consumeSemicolon = function() { if (this.match(";")) { this.nextToken(); } else if (!this.hasLineTerminator) { if (this.lookahead.type !== 2 && !this.match("}")) { this.throwUnexpectedToken(this.lookahead); } this.lastMarker.index = this.startMarker.index; this.lastMarker.line = this.startMarker.line; this.lastMarker.column = this.startMarker.column; } }; Parser2.prototype.parsePrimaryExpression = function() { var node2 = this.createNode(); var expr; var token, raw; switch (this.lookahead.type) { case 3: if ((this.context.isModule || this.context.await) && this.lookahead.value === "await") { this.tolerateUnexpectedToken(this.lookahead); } expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node2, new Node.Identifier(this.nextToken().value)); break; case 6: case 8: if (this.context.strict && this.lookahead.octal) { this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral); } this.context.isAssignmentTarget = false; this.context.isBindingElement = false; token = this.nextToken(); raw = this.getTokenRaw(token); expr = this.finalize(node2, new Node.Literal(token.value, raw)); break; case 1: this.context.isAssignmentTarget = false; this.context.isBindingElement = false; token = this.nextToken(); raw = this.getTokenRaw(token); expr = this.finalize(node2, new Node.Literal(token.value === "true", raw)); break; case 5: this.context.isAssignmentTarget = false; this.context.isBindingElement = false; token = this.nextToken(); raw = this.getTokenRaw(token); expr = this.finalize(node2, new Node.Literal(null, raw)); break; case 10: expr = this.parseTemplateLiteral(); break; case 7: switch (this.lookahead.value) { case "(": this.context.isBindingElement = false; expr = this.inheritCoverGrammar(this.parseGroupExpression); break; case "[": expr = this.inheritCoverGrammar(this.parseArrayInitializer); break; case "{": expr = this.inheritCoverGrammar(this.parseObjectInitializer); break; case "/": case "/=": this.context.isAssignmentTarget = false; this.context.isBindingElement = false; this.scanner.index = this.startMarker.index; token = this.nextRegexToken(); raw = this.getTokenRaw(token); expr = this.finalize(node2, new Node.RegexLiteral(token.regex, raw, token.pattern, token.flags)); break; default: expr = this.throwUnexpectedToken(this.nextToken()); } break; case 4: if (!this.context.strict && this.context.allowYield && this.matchKeyword("yield")) { expr = this.parseIdentifierName(); } else if (!this.context.strict && this.matchKeyword("let")) { expr = this.finalize(node2, new Node.Identifier(this.nextToken().value)); } else { this.context.isAssignmentTarget = false; this.context.isBindingElement = false; if (this.matchKeyword("function")) { expr = this.parseFunctionExpression(); } else if (this.matchKeyword("this")) { this.nextToken(); expr = this.finalize(node2, new Node.ThisExpression()); } else if (this.matchKeyword("class")) { expr = this.parseClassExpression(); } else { expr = this.throwUnexpectedToken(this.nextToken()); } } break; default: expr = this.throwUnexpectedToken(this.nextToken()); } return expr; }; Parser2.prototype.parseSpreadElement = function() { var node2 = this.createNode(); this.expect("..."); var arg = this.inheritCoverGrammar(this.parseAssignmentExpression); return this.finalize(node2, new Node.SpreadElement(arg)); }; Parser2.prototype.parseArrayInitializer = function() { var node2 = this.createNode(); var elements = []; this.expect("["); while (!this.match("]")) { if (this.match(",")) { this.nextToken(); elements.push(null); } else if (this.match("...")) { var element2 = this.parseSpreadElement(); if (!this.match("]")) { this.context.isAssignmentTarget = false; this.context.isBindingElement = false; this.expect(","); } elements.push(element2); } else { elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); if (!this.match("]")) { this.expect(","); } } } this.expect("]"); return this.finalize(node2, new Node.ArrayExpression(elements)); }; Parser2.prototype.parsePropertyMethod = function(params) { this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var previousStrict = this.context.strict; var previousAllowStrictDirective = this.context.allowStrictDirective; this.context.allowStrictDirective = params.simple; var body = this.isolateCoverGrammar(this.parseFunctionSourceElements); if (this.context.strict && params.firstRestricted) { this.tolerateUnexpectedToken(params.firstRestricted, params.message); } if (this.context.strict && params.stricted) { this.tolerateUnexpectedToken(params.stricted, params.message); } this.context.strict = previousStrict; this.context.allowStrictDirective = previousAllowStrictDirective; return body; }; Parser2.prototype.parsePropertyMethodFunction = function() { var isGenerator = false; var node2 = this.createNode(); var previousAllowYield = this.context.allowYield; this.context.allowYield = true; var params = this.parseFormalParameters(); var method = this.parsePropertyMethod(params); this.context.allowYield = previousAllowYield; return this.finalize(node2, new Node.FunctionExpression(null, params.params, method, isGenerator)); }; Parser2.prototype.parsePropertyMethodAsyncFunction = function() { var node2 = this.createNode(); var previousAllowYield = this.context.allowYield; var previousAwait = this.context.await; this.context.allowYield = false; this.context.await = true; var params = this.parseFormalParameters(); var method = this.parsePropertyMethod(params); this.context.allowYield = previousAllowYield; this.context.await = previousAwait; return this.finalize(node2, new Node.AsyncFunctionExpression(null, params.params, method)); }; Parser2.prototype.parseObjectPropertyKey = function() { var node2 = this.createNode(); var token = this.nextToken(); var key; switch (token.type) { case 8: case 6: if (this.context.strict && token.octal) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral); } var raw = this.getTokenRaw(token); key = this.finalize(node2, new Node.Literal(token.value, raw)); break; case 3: case 1: case 5: case 4: key = this.finalize(node2, new Node.Identifier(token.value)); break; case 7: if (token.value === "[") { key = this.isolateCoverGrammar(this.parseAssignmentExpression); this.expect("]"); } else { key = this.throwUnexpectedToken(token); } break; default: key = this.throwUnexpectedToken(token); } return key; }; Parser2.prototype.isPropertyKey = function(key, value) { return key.type === syntax_1.Syntax.Identifier && key.name === value || key.type === syntax_1.Syntax.Literal && key.value === value; }; Parser2.prototype.parseObjectProperty = function(hasProto) { var node2 = this.createNode(); var token = this.lookahead; var kind; var key = null; var value = null; var computed = false; var method = false; var shorthand = false; var isAsync2 = false; if (token.type === 3) { var id = token.value; this.nextToken(); computed = this.match("["); isAsync2 = !this.hasLineTerminator && id === "async" && !this.match(":") && !this.match("(") && !this.match("*") && !this.match(","); key = isAsync2 ? this.parseObjectPropertyKey() : this.finalize(node2, new Node.Identifier(id)); } else if (this.match("*")) { this.nextToken(); } else { computed = this.match("["); key = this.parseObjectPropertyKey(); } var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); if (token.type === 3 && !isAsync2 && token.value === "get" && lookaheadPropertyKey) { kind = "get"; computed = this.match("["); key = this.parseObjectPropertyKey(); this.context.allowYield = false; value = this.parseGetterMethod(); } else if (token.type === 3 && !isAsync2 && token.value === "set" && lookaheadPropertyKey) { kind = "set"; computed = this.match("["); key = this.parseObjectPropertyKey(); value = this.parseSetterMethod(); } else if (token.type === 7 && token.value === "*" && lookaheadPropertyKey) { kind = "init"; computed = this.match("["); key = this.parseObjectPropertyKey(); value = this.parseGeneratorMethod(); method = true; } else { if (!key) { this.throwUnexpectedToken(this.lookahead); } kind = "init"; if (this.match(":") && !isAsync2) { if (!computed && this.isPropertyKey(key, "__proto__")) { if (hasProto.value) { this.tolerateError(messages_1.Messages.DuplicateProtoProperty); } hasProto.value = true; } this.nextToken(); value = this.inheritCoverGrammar(this.parseAssignmentExpression); } else if (this.match("(")) { value = isAsync2 ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); method = true; } else if (token.type === 3) { var id = this.finalize(node2, new Node.Identifier(token.value)); if (this.match("=")) { this.context.firstCoverInitializedNameError = this.lookahead; this.nextToken(); shorthand = true; var init = this.isolateCoverGrammar(this.parseAssignmentExpression); value = this.finalize(node2, new Node.AssignmentPattern(id, init)); } else { shorthand = true; value = id; } } else { this.throwUnexpectedToken(this.nextToken()); } } return this.finalize(node2, new Node.Property(kind, key, computed, value, method, shorthand)); }; Parser2.prototype.parseObjectInitializer = function() { var node2 = this.createNode(); this.expect("{"); var properties = []; var hasProto = { value: false }; while (!this.match("}")) { properties.push(this.parseObjectProperty(hasProto)); if (!this.match("}")) { this.expectCommaSeparator(); } } this.expect("}"); return this.finalize(node2, new Node.ObjectExpression(properties)); }; Parser2.prototype.parseTemplateHead = function() { assert_1.assert(this.lookahead.head, "Template literal must start with a template head"); var node2 = this.createNode(); var token = this.nextToken(); var raw = token.value; var cooked = token.cooked; return this.finalize(node2, new Node.TemplateElement({ raw, cooked }, token.tail)); }; Parser2.prototype.parseTemplateElement = function() { if (this.lookahead.type !== 10) { this.throwUnexpectedToken(); } var node2 = this.createNode(); var token = this.nextToken(); var raw = token.value; var cooked = token.cooked; return this.finalize(node2, new Node.TemplateElement({ raw, cooked }, token.tail)); }; Parser2.prototype.parseTemplateLiteral = function() { var node2 = this.createNode(); var expressions = []; var quasis = []; var quasi = this.parseTemplateHead(); quasis.push(quasi); while (!quasi.tail) { expressions.push(this.parseExpression()); quasi = this.parseTemplateElement(); quasis.push(quasi); } return this.finalize(node2, new Node.TemplateLiteral(quasis, expressions)); }; Parser2.prototype.reinterpretExpressionAsPattern = function(expr) { switch (expr.type) { case syntax_1.Syntax.Identifier: case syntax_1.Syntax.MemberExpression: case syntax_1.Syntax.RestElement: case syntax_1.Syntax.AssignmentPattern: break; case syntax_1.Syntax.SpreadElement: expr.type = syntax_1.Syntax.RestElement; this.reinterpretExpressionAsPattern(expr.argument); break; case syntax_1.Syntax.ArrayExpression: expr.type = syntax_1.Syntax.ArrayPattern; for (var i2 = 0; i2 < expr.elements.length; i2++) { if (expr.elements[i2] !== null) { this.reinterpretExpressionAsPattern(expr.elements[i2]); } } break; case syntax_1.Syntax.ObjectExpression: expr.type = syntax_1.Syntax.ObjectPattern; for (var i2 = 0; i2 < expr.properties.length; i2++) { this.reinterpretExpressionAsPattern(expr.properties[i2].value); } break; case syntax_1.Syntax.AssignmentExpression: expr.type = syntax_1.Syntax.AssignmentPattern; delete expr.operator; this.reinterpretExpressionAsPattern(expr.left); break; default: break; } }; Parser2.prototype.parseGroupExpression = function() { var expr; this.expect("("); if (this.match(")")) { this.nextToken(); if (!this.match("=>")) { this.expect("=>"); } expr = { type: ArrowParameterPlaceHolder, params: [], async: false }; } else { var startToken = this.lookahead; var params = []; if (this.match("...")) { expr = this.parseRestElement(params); this.expect(")"); if (!this.match("=>")) { this.expect("=>"); } expr = { type: ArrowParameterPlaceHolder, params: [expr], async: false }; } else { var arrow = false; this.context.isBindingElement = true; expr = this.inheritCoverGrammar(this.parseAssignmentExpression); if (this.match(",")) { var expressions = []; this.context.isAssignmentTarget = false; expressions.push(expr); while (this.lookahead.type !== 2) { if (!this.match(",")) { break; } this.nextToken(); if (this.match(")")) { this.nextToken(); for (var i2 = 0; i2 < expressions.length; i2++) { this.reinterpretExpressionAsPattern(expressions[i2]); } arrow = true; expr = { type: ArrowParameterPlaceHolder, params: expressions, async: false }; } else if (this.match("...")) { if (!this.context.isBindingElement) { this.throwUnexpectedToken(this.lookahead); } expressions.push(this.parseRestElement(params)); this.expect(")"); if (!this.match("=>")) { this.expect("=>"); } this.context.isBindingElement = false; for (var i2 = 0; i2 < expressions.length; i2++) { this.reinterpretExpressionAsPattern(expressions[i2]); } arrow = true; expr = { type: ArrowParameterPlaceHolder, params: expressions, async: false }; } else { expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); } if (arrow) { break; } } if (!arrow) { expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); } } if (!arrow) { this.expect(")"); if (this.match("=>")) { if (expr.type === syntax_1.Syntax.Identifier && expr.name === "yield") { arrow = true; expr = { type: ArrowParameterPlaceHolder, params: [expr], async: false }; } if (!arrow) { if (!this.context.isBindingElement) { this.throwUnexpectedToken(this.lookahead); } if (expr.type === syntax_1.Syntax.SequenceExpression) { for (var i2 = 0; i2 < expr.expressions.length; i2++) { this.reinterpretExpressionAsPattern(expr.expressions[i2]); } } else { this.reinterpretExpressionAsPattern(expr); } var parameters = expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]; expr = { type: ArrowParameterPlaceHolder, params: parameters, async: false }; } } this.context.isBindingElement = false; } } } return expr; }; Parser2.prototype.parseArguments = function() { this.expect("("); var args = []; if (!this.match(")")) { while (true) { var expr = this.match("...") ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAssignmentExpression); args.push(expr); if (this.match(")")) { break; } this.expectCommaSeparator(); if (this.match(")")) { break; } } } this.expect(")"); return args; }; Parser2.prototype.isIdentifierName = function(token) { return token.type === 3 || token.type === 4 || token.type === 1 || token.type === 5; }; Parser2.prototype.parseIdentifierName = function() { var node2 = this.createNode(); var token = this.nextToken(); if (!this.isIdentifierName(token)) { this.throwUnexpectedToken(token); } return this.finalize(node2, new Node.Identifier(token.value)); }; Parser2.prototype.parseNewExpression = function() { var node2 = this.createNode(); var id = this.parseIdentifierName(); assert_1.assert(id.name === "new", "New expression must start with `new`"); var expr; if (this.match(".")) { this.nextToken(); if (this.lookahead.type === 3 && this.context.inFunctionBody && this.lookahead.value === "target") { var property = this.parseIdentifierName(); expr = new Node.MetaProperty(id, property); } else { this.throwUnexpectedToken(this.lookahead); } } else { var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression); var args = this.match("(") ? this.parseArguments() : []; expr = new Node.NewExpression(callee, args); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } return this.finalize(node2, expr); }; Parser2.prototype.parseAsyncArgument = function() { var arg = this.parseAssignmentExpression(); this.context.firstCoverInitializedNameError = null; return arg; }; Parser2.prototype.parseAsyncArguments = function() { this.expect("("); var args = []; if (!this.match(")")) { while (true) { var expr = this.match("...") ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAsyncArgument); args.push(expr); if (this.match(")")) { break; } this.expectCommaSeparator(); if (this.match(")")) { break; } } } this.expect(")"); return args; }; Parser2.prototype.parseLeftHandSideExpressionAllowCall = function() { var startToken = this.lookahead; var maybeAsync = this.matchContextualKeyword("async"); var previousAllowIn = this.context.allowIn; this.context.allowIn = true; var expr; if (this.matchKeyword("super") && this.context.inFunctionBody) { expr = this.createNode(); this.nextToken(); expr = this.finalize(expr, new Node.Super()); if (!this.match("(") && !this.match(".") && !this.match("[")) { this.throwUnexpectedToken(this.lookahead); } } else { expr = this.inheritCoverGrammar(this.matchKeyword("new") ? this.parseNewExpression : this.parsePrimaryExpression); } while (true) { if (this.match(".")) { this.context.isBindingElement = false; this.context.isAssignmentTarget = true; this.expect("."); var property = this.parseIdentifierName(); expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property)); } else if (this.match("(")) { var asyncArrow = maybeAsync && startToken.lineNumber === this.lookahead.lineNumber; this.context.isBindingElement = false; this.context.isAssignmentTarget = false; var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments(); expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args)); if (asyncArrow && this.match("=>")) { for (var i2 = 0; i2 < args.length; ++i2) { this.reinterpretExpressionAsPattern(args[i2]); } expr = { type: ArrowParameterPlaceHolder, params: args, async: true }; } } else if (this.match("[")) { this.context.isBindingElement = false; this.context.isAssignmentTarget = true; this.expect("["); var property = this.isolateCoverGrammar(this.parseExpression); this.expect("]"); expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property)); } else if (this.lookahead.type === 10 && this.lookahead.head) { var quasi = this.parseTemplateLiteral(); expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi)); } else { break; } } this.context.allowIn = previousAllowIn; return expr; }; Parser2.prototype.parseSuper = function() { var node2 = this.createNode(); this.expectKeyword("super"); if (!this.match("[") && !this.match(".")) { this.throwUnexpectedToken(this.lookahead); } return this.finalize(node2, new Node.Super()); }; Parser2.prototype.parseLeftHandSideExpression = function() { assert_1.assert(this.context.allowIn, "callee of new expression always allow in keyword."); var node2 = this.startNode(this.lookahead); var expr = this.matchKeyword("super") && this.context.inFunctionBody ? this.parseSuper() : this.inheritCoverGrammar(this.matchKeyword("new") ? this.parseNewExpression : this.parsePrimaryExpression); while (true) { if (this.match("[")) { this.context.isBindingElement = false; this.context.isAssignmentTarget = true; this.expect("["); var property = this.isolateCoverGrammar(this.parseExpression); this.expect("]"); expr = this.finalize(node2, new Node.ComputedMemberExpression(expr, property)); } else if (this.match(".")) { this.context.isBindingElement = false; this.context.isAssignmentTarget = true; this.expect("."); var property = this.parseIdentifierName(); expr = this.finalize(node2, new Node.StaticMemberExpression(expr, property)); } else if (this.lookahead.type === 10 && this.lookahead.head) { var quasi = this.parseTemplateLiteral(); expr = this.finalize(node2, new Node.TaggedTemplateExpression(expr, quasi)); } else { break; } } return expr; }; Parser2.prototype.parseUpdateExpression = function() { var expr; var startToken = this.lookahead; if (this.match("++") || this.match("--")) { var node2 = this.startNode(startToken); var token = this.nextToken(); expr = this.inheritCoverGrammar(this.parseUnaryExpression); if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { this.tolerateError(messages_1.Messages.StrictLHSPrefix); } if (!this.context.isAssignmentTarget) { this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); } var prefix = true; expr = this.finalize(node2, new Node.UpdateExpression(token.value, expr, prefix)); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } else { expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall); if (!this.hasLineTerminator && this.lookahead.type === 7) { if (this.match("++") || this.match("--")) { if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { this.tolerateError(messages_1.Messages.StrictLHSPostfix); } if (!this.context.isAssignmentTarget) { this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); } this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var operator = this.nextToken().value; var prefix = false; expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix)); } } } return expr; }; Parser2.prototype.parseAwaitExpression = function() { var node2 = this.createNode(); this.nextToken(); var argument = this.parseUnaryExpression(); return this.finalize(node2, new Node.AwaitExpression(argument)); }; Parser2.prototype.parseUnaryExpression = function() { var expr; if (this.match("+") || this.match("-") || this.match("~") || this.match("!") || this.matchKeyword("delete") || this.matchKeyword("void") || this.matchKeyword("typeof")) { var node2 = this.startNode(this.lookahead); var token = this.nextToken(); expr = this.inheritCoverGrammar(this.parseUnaryExpression); expr = this.finalize(node2, new Node.UnaryExpression(token.value, expr)); if (this.context.strict && expr.operator === "delete" && expr.argument.type === syntax_1.Syntax.Identifier) { this.tolerateError(messages_1.Messages.StrictDelete); } this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } else if (this.context.await && this.matchContextualKeyword("await")) { expr = this.parseAwaitExpression(); } else { expr = this.parseUpdateExpression(); } return expr; }; Parser2.prototype.parseExponentiationExpression = function() { var startToken = this.lookahead; var expr = this.inheritCoverGrammar(this.parseUnaryExpression); if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match("**")) { this.nextToken(); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var left = expr; var right = this.isolateCoverGrammar(this.parseExponentiationExpression); expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression("**", left, right)); } return expr; }; Parser2.prototype.binaryPrecedence = function(token) { var op = token.value; var precedence; if (token.type === 7) { precedence = this.operatorPrecedence[op] || 0; } else if (token.type === 4) { precedence = op === "instanceof" || this.context.allowIn && op === "in" ? 7 : 0; } else { precedence = 0; } return precedence; }; Parser2.prototype.parseBinaryExpression = function() { var startToken = this.lookahead; var expr = this.inheritCoverGrammar(this.parseExponentiationExpression); var token = this.lookahead; var prec = this.binaryPrecedence(token); if (prec > 0) { this.nextToken(); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var markers = [startToken, this.lookahead]; var left = expr; var right = this.isolateCoverGrammar(this.parseExponentiationExpression); var stack = [left, token.value, right]; var precedences = [prec]; while (true) { prec = this.binaryPrecedence(this.lookahead); if (prec <= 0) { break; } while (stack.length > 2 && prec <= precedences[precedences.length - 1]) { right = stack.pop(); var operator = stack.pop(); precedences.pop(); left = stack.pop(); markers.pop(); var node2 = this.startNode(markers[markers.length - 1]); stack.push(this.finalize(node2, new Node.BinaryExpression(operator, left, right))); } stack.push(this.nextToken().value); precedences.push(prec); markers.push(this.lookahead); stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression)); } var i2 = stack.length - 1; expr = stack[i2]; var lastMarker = markers.pop(); while (i2 > 1) { var marker = markers.pop(); var lastLineStart = lastMarker && lastMarker.lineStart; var node2 = this.startNode(marker, lastLineStart); var operator = stack[i2 - 1]; expr = this.finalize(node2, new Node.BinaryExpression(operator, stack[i2 - 2], expr)); i2 -= 2; lastMarker = marker; } } return expr; }; Parser2.prototype.parseConditionalExpression = function() { var startToken = this.lookahead; var expr = this.inheritCoverGrammar(this.parseBinaryExpression); if (this.match("?")) { this.nextToken(); var previousAllowIn = this.context.allowIn; this.context.allowIn = true; var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression); this.context.allowIn = previousAllowIn; this.expect(":"); var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression); expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate)); this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } return expr; }; Parser2.prototype.checkPatternParam = function(options, param) { switch (param.type) { case syntax_1.Syntax.Identifier: this.validateParam(options, param, param.name); break; case syntax_1.Syntax.RestElement: this.checkPatternParam(options, param.argument); break; case syntax_1.Syntax.AssignmentPattern: this.checkPatternParam(options, param.left); break; case syntax_1.Syntax.ArrayPattern: for (var i2 = 0; i2 < param.elements.length; i2++) { if (param.elements[i2] !== null) { this.checkPatternParam(options, param.elements[i2]); } } break; case syntax_1.Syntax.ObjectPattern: for (var i2 = 0; i2 < param.properties.length; i2++) { this.checkPatternParam(options, param.properties[i2].value); } break; default: break; } options.simple = options.simple && param instanceof Node.Identifier; }; Parser2.prototype.reinterpretAsCoverFormalsList = function(expr) { var params = [expr]; var options; var asyncArrow = false; switch (expr.type) { case syntax_1.Syntax.Identifier: break; case ArrowParameterPlaceHolder: params = expr.params; asyncArrow = expr.async; break; default: return null; } options = { simple: true, paramSet: {} }; for (var i2 = 0; i2 < params.length; ++i2) { var param = params[i2]; if (param.type === syntax_1.Syntax.AssignmentPattern) { if (param.right.type === syntax_1.Syntax.YieldExpression) { if (param.right.argument) { this.throwUnexpectedToken(this.lookahead); } param.right.type = syntax_1.Syntax.Identifier; param.right.name = "yield"; delete param.right.argument; delete param.right.delegate; } } else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === "await") { this.throwUnexpectedToken(this.lookahead); } this.checkPatternParam(options, param); params[i2] = param; } if (this.context.strict || !this.context.allowYield) { for (var i2 = 0; i2 < params.length; ++i2) { var param = params[i2]; if (param.type === syntax_1.Syntax.YieldExpression) { this.throwUnexpectedToken(this.lookahead); } } } if (options.message === messages_1.Messages.StrictParamDupe) { var token = this.context.strict ? options.stricted : options.firstRestricted; this.throwUnexpectedToken(token, options.message); } return { simple: options.simple, params, stricted: options.stricted, firstRestricted: options.firstRestricted, message: options.message }; }; Parser2.prototype.parseAssignmentExpression = function() { var expr; if (!this.context.allowYield && this.matchKeyword("yield")) { expr = this.parseYieldExpression(); } else { var startToken = this.lookahead; var token = startToken; expr = this.parseConditionalExpression(); if (token.type === 3 && token.lineNumber === this.lookahead.lineNumber && token.value === "async") { if (this.lookahead.type === 3 || this.matchKeyword("yield")) { var arg = this.parsePrimaryExpression(); this.reinterpretExpressionAsPattern(arg); expr = { type: ArrowParameterPlaceHolder, params: [arg], async: true }; } } if (expr.type === ArrowParameterPlaceHolder || this.match("=>")) { this.context.isAssignmentTarget = false; this.context.isBindingElement = false; var isAsync2 = expr.async; var list2 = this.reinterpretAsCoverFormalsList(expr); if (list2) { if (this.hasLineTerminator) { this.tolerateUnexpectedToken(this.lookahead); } this.context.firstCoverInitializedNameError = null; var previousStrict = this.context.strict; var previousAllowStrictDirective = this.context.allowStrictDirective; this.context.allowStrictDirective = list2.simple; var previousAllowYield = this.context.allowYield; var previousAwait = this.context.await; this.context.allowYield = true; this.context.await = isAsync2; var node2 = this.startNode(startToken); this.expect("=>"); var body = void 0; if (this.match("{")) { var previousAllowIn = this.context.allowIn; this.context.allowIn = true; body = this.parseFunctionSourceElements(); this.context.allowIn = previousAllowIn; } else { body = this.isolateCoverGrammar(this.parseAssignmentExpression); } var expression = body.type !== syntax_1.Syntax.BlockStatement; if (this.context.strict && list2.firstRestricted) { this.throwUnexpectedToken(list2.firstRestricted, list2.message); } if (this.context.strict && list2.stricted) { this.tolerateUnexpectedToken(list2.stricted, list2.message); } expr = isAsync2 ? this.finalize(node2, new Node.AsyncArrowFunctionExpression(list2.params, body, expression)) : this.finalize(node2, new Node.ArrowFunctionExpression(list2.params, body, expression)); this.context.strict = previousStrict; this.context.allowStrictDirective = previousAllowStrictDirective; this.context.allowYield = previousAllowYield; this.context.await = previousAwait; } } else { if (this.matchAssign()) { if (!this.context.isAssignmentTarget) { this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); } if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) { var id = expr; if (this.scanner.isRestrictedWord(id.name)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment); } if (this.scanner.isStrictModeReservedWord(id.name)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); } } if (!this.match("=")) { this.context.isAssignmentTarget = false; this.context.isBindingElement = false; } else { this.reinterpretExpressionAsPattern(expr); } token = this.nextToken(); var operator = token.value; var right = this.isolateCoverGrammar(this.parseAssignmentExpression); expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right)); this.context.firstCoverInitializedNameError = null; } } } return expr; }; Parser2.prototype.parseExpression = function() { var startToken = this.lookahead; var expr = this.isolateCoverGrammar(this.parseAssignmentExpression); if (this.match(",")) { var expressions = []; expressions.push(expr); while (this.lookahead.type !== 2) { if (!this.match(",")) { break; } this.nextToken(); expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); } expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); } return expr; }; Parser2.prototype.parseStatementListItem = function() { var statement; this.context.isAssignmentTarget = true; this.context.isBindingElement = true; if (this.lookahead.type === 4) { switch (this.lookahead.value) { case "export": if (!this.context.isModule) { this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration); } statement = this.parseExportDeclaration(); break; case "import": if (!this.context.isModule) { this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration); } statement = this.parseImportDeclaration(); break; case "const": statement = this.parseLexicalDeclaration({ inFor: false }); break; case "function": statement = this.parseFunctionDeclaration(); break; case "class": statement = this.parseClassDeclaration(); break; case "let": statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement(); break; default: statement = this.parseStatement(); break; } } else { statement = this.parseStatement(); } return statement; }; Parser2.prototype.parseBlock = function() { var node2 = this.createNode(); this.expect("{"); var block = []; while (true) { if (this.match("}")) { break; } block.push(this.parseStatementListItem()); } this.expect("}"); return this.finalize(node2, new Node.BlockStatement(block)); }; Parser2.prototype.parseLexicalBinding = function(kind, options) { var node2 = this.createNode(); var params = []; var id = this.parsePattern(params, kind); if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { if (this.scanner.isRestrictedWord(id.name)) { this.tolerateError(messages_1.Messages.StrictVarName); } } var init = null; if (kind === "const") { if (!this.matchKeyword("in") && !this.matchContextualKeyword("of")) { if (this.match("=")) { this.nextToken(); init = this.isolateCoverGrammar(this.parseAssignmentExpression); } else { this.throwError(messages_1.Messages.DeclarationMissingInitializer, "const"); } } } else if (!options.inFor && id.type !== syntax_1.Syntax.Identifier || this.match("=")) { this.expect("="); init = this.isolateCoverGrammar(this.parseAssignmentExpression); } return this.finalize(node2, new Node.VariableDeclarator(id, init)); }; Parser2.prototype.parseBindingList = function(kind, options) { var list2 = [this.parseLexicalBinding(kind, options)]; while (this.match(",")) { this.nextToken(); list2.push(this.parseLexicalBinding(kind, options)); } return list2; }; Parser2.prototype.isLexicalDeclaration = function() { var state = this.scanner.saveState(); this.scanner.scanComments(); var next = this.scanner.lex(); this.scanner.restoreState(state); return next.type === 3 || next.type === 7 && next.value === "[" || next.type === 7 && next.value === "{" || next.type === 4 && next.value === "let" || next.type === 4 && next.value === "yield"; }; Parser2.prototype.parseLexicalDeclaration = function(options) { var node2 = this.createNode(); var kind = this.nextToken().value; assert_1.assert(kind === "let" || kind === "const", "Lexical declaration must be either let or const"); var declarations = this.parseBindingList(kind, options); this.consumeSemicolon(); return this.finalize(node2, new Node.VariableDeclaration(declarations, kind)); }; Parser2.prototype.parseBindingRestElement = function(params, kind) { var node2 = this.createNode(); this.expect("..."); var arg = this.parsePattern(params, kind); return this.finalize(node2, new Node.RestElement(arg)); }; Parser2.prototype.parseArrayPattern = function(params, kind) { var node2 = this.createNode(); this.expect("["); var elements = []; while (!this.match("]")) { if (this.match(",")) { this.nextToken(); elements.push(null); } else { if (this.match("...")) { elements.push(this.parseBindingRestElement(params, kind)); break; } else { elements.push(this.parsePatternWithDefault(params, kind)); } if (!this.match("]")) { this.expect(","); } } } this.expect("]"); return this.finalize(node2, new Node.ArrayPattern(elements)); }; Parser2.prototype.parsePropertyPattern = function(params, kind) { var node2 = this.createNode(); var computed = false; var shorthand = false; var method = false; var key; var value; if (this.lookahead.type === 3) { var keyToken = this.lookahead; key = this.parseVariableIdentifier(); var init = this.finalize(node2, new Node.Identifier(keyToken.value)); if (this.match("=")) { params.push(keyToken); shorthand = true; this.nextToken(); var expr = this.parseAssignmentExpression(); value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init, expr)); } else if (!this.match(":")) { params.push(keyToken); shorthand = true; value = init; } else { this.expect(":"); value = this.parsePatternWithDefault(params, kind); } } else { computed = this.match("["); key = this.parseObjectPropertyKey(); this.expect(":"); value = this.parsePatternWithDefault(params, kind); } return this.finalize(node2, new Node.Property("init", key, computed, value, method, shorthand)); }; Parser2.prototype.parseObjectPattern = function(params, kind) { var node2 = this.createNode(); var properties = []; this.expect("{"); while (!this.match("}")) { properties.push(this.parsePropertyPattern(params, kind)); if (!this.match("}")) { this.expect(","); } } this.expect("}"); return this.finalize(node2, new Node.ObjectPattern(properties)); }; Parser2.prototype.parsePattern = function(params, kind) { var pattern; if (this.match("[")) { pattern = this.parseArrayPattern(params, kind); } else if (this.match("{")) { pattern = this.parseObjectPattern(params, kind); } else { if (this.matchKeyword("let") && (kind === "const" || kind === "let")) { this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding); } params.push(this.lookahead); pattern = this.parseVariableIdentifier(kind); } return pattern; }; Parser2.prototype.parsePatternWithDefault = function(params, kind) { var startToken = this.lookahead; var pattern = this.parsePattern(params, kind); if (this.match("=")) { this.nextToken(); var previousAllowYield = this.context.allowYield; this.context.allowYield = true; var right = this.isolateCoverGrammar(this.parseAssignmentExpression); this.context.allowYield = previousAllowYield; pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right)); } return pattern; }; Parser2.prototype.parseVariableIdentifier = function(kind) { var node2 = this.createNode(); var token = this.nextToken(); if (token.type === 4 && token.value === "yield") { if (this.context.strict) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); } else if (!this.context.allowYield) { this.throwUnexpectedToken(token); } } else if (token.type !== 3) { if (this.context.strict && token.type === 4 && this.scanner.isStrictModeReservedWord(token.value)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); } else { if (this.context.strict || token.value !== "let" || kind !== "var") { this.throwUnexpectedToken(token); } } } else if ((this.context.isModule || this.context.await) && token.type === 3 && token.value === "await") { this.tolerateUnexpectedToken(token); } return this.finalize(node2, new Node.Identifier(token.value)); }; Parser2.prototype.parseVariableDeclaration = function(options) { var node2 = this.createNode(); var params = []; var id = this.parsePattern(params, "var"); if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { if (this.scanner.isRestrictedWord(id.name)) { this.tolerateError(messages_1.Messages.StrictVarName); } } var init = null; if (this.match("=")) { this.nextToken(); init = this.isolateCoverGrammar(this.parseAssignmentExpression); } else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) { this.expect("="); } return this.finalize(node2, new Node.VariableDeclarator(id, init)); }; Parser2.prototype.parseVariableDeclarationList = function(options) { var opt = { inFor: options.inFor }; var list2 = []; list2.push(this.parseVariableDeclaration(opt)); while (this.match(",")) { this.nextToken(); list2.push(this.parseVariableDeclaration(opt)); } return list2; }; Parser2.prototype.parseVariableStatement = function() { var node2 = this.createNode(); this.expectKeyword("var"); var declarations = this.parseVariableDeclarationList({ inFor: false }); this.consumeSemicolon(); return this.finalize(node2, new Node.VariableDeclaration(declarations, "var")); }; Parser2.prototype.parseEmptyStatement = function() { var node2 = this.createNode(); this.expect(";"); return this.finalize(node2, new Node.EmptyStatement()); }; Parser2.prototype.parseExpressionStatement = function() { var node2 = this.createNode(); var expr = this.parseExpression(); this.consumeSemicolon(); return this.finalize(node2, new Node.ExpressionStatement(expr)); }; Parser2.prototype.parseIfClause = function() { if (this.context.strict && this.matchKeyword("function")) { this.tolerateError(messages_1.Messages.StrictFunction); } return this.parseStatement(); }; Parser2.prototype.parseIfStatement = function() { var node2 = this.createNode(); var consequent; var alternate = null; this.expectKeyword("if"); this.expect("("); var test = this.parseExpression(); if (!this.match(")") && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); consequent = this.finalize(this.createNode(), new Node.EmptyStatement()); } else { this.expect(")"); consequent = this.parseIfClause(); if (this.matchKeyword("else")) { this.nextToken(); alternate = this.parseIfClause(); } } return this.finalize(node2, new Node.IfStatement(test, consequent, alternate)); }; Parser2.prototype.parseDoWhileStatement = function() { var node2 = this.createNode(); this.expectKeyword("do"); var previousInIteration = this.context.inIteration; this.context.inIteration = true; var body = this.parseStatement(); this.context.inIteration = previousInIteration; this.expectKeyword("while"); this.expect("("); var test = this.parseExpression(); if (!this.match(")") && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); } else { this.expect(")"); if (this.match(";")) { this.nextToken(); } } return this.finalize(node2, new Node.DoWhileStatement(body, test)); }; Parser2.prototype.parseWhileStatement = function() { var node2 = this.createNode(); var body; this.expectKeyword("while"); this.expect("("); var test = this.parseExpression(); if (!this.match(")") && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); body = this.finalize(this.createNode(), new Node.EmptyStatement()); } else { this.expect(")"); var previousInIteration = this.context.inIteration; this.context.inIteration = true; body = this.parseStatement(); this.context.inIteration = previousInIteration; } return this.finalize(node2, new Node.WhileStatement(test, body)); }; Parser2.prototype.parseForStatement = function() { var init = null; var test = null; var update = null; var forIn = true; var left, right; var node2 = this.createNode(); this.expectKeyword("for"); this.expect("("); if (this.match(";")) { this.nextToken(); } else { if (this.matchKeyword("var")) { init = this.createNode(); this.nextToken(); var previousAllowIn = this.context.allowIn; this.context.allowIn = false; var declarations = this.parseVariableDeclarationList({ inFor: true }); this.context.allowIn = previousAllowIn; if (declarations.length === 1 && this.matchKeyword("in")) { var decl = declarations[0]; if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) { this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, "for-in"); } init = this.finalize(init, new Node.VariableDeclaration(declarations, "var")); this.nextToken(); left = init; right = this.parseExpression(); init = null; } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword("of")) { init = this.finalize(init, new Node.VariableDeclaration(declarations, "var")); this.nextToken(); left = init; right = this.parseAssignmentExpression(); init = null; forIn = false; } else { init = this.finalize(init, new Node.VariableDeclaration(declarations, "var")); this.expect(";"); } } else if (this.matchKeyword("const") || this.matchKeyword("let")) { init = this.createNode(); var kind = this.nextToken().value; if (!this.context.strict && this.lookahead.value === "in") { init = this.finalize(init, new Node.Identifier(kind)); this.nextToken(); left = init; right = this.parseExpression(); init = null; } else { var previousAllowIn = this.context.allowIn; this.context.allowIn = false; var declarations = this.parseBindingList(kind, { inFor: true }); this.context.allowIn = previousAllowIn; if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword("in")) { init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); this.nextToken(); left = init; right = this.parseExpression(); init = null; } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword("of")) { init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); this.nextToken(); left = init; right = this.parseAssignmentExpression(); init = null; forIn = false; } else { this.consumeSemicolon(); init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); } } } else { var initStartToken = this.lookahead; var previousAllowIn = this.context.allowIn; this.context.allowIn = false; init = this.inheritCoverGrammar(this.parseAssignmentExpression); this.context.allowIn = previousAllowIn; if (this.matchKeyword("in")) { if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { this.tolerateError(messages_1.Messages.InvalidLHSInForIn); } this.nextToken(); this.reinterpretExpressionAsPattern(init); left = init; right = this.parseExpression(); init = null; } else if (this.matchContextualKeyword("of")) { if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { this.tolerateError(messages_1.Messages.InvalidLHSInForLoop); } this.nextToken(); this.reinterpretExpressionAsPattern(init); left = init; right = this.parseAssignmentExpression(); init = null; forIn = false; } else { if (this.match(",")) { var initSeq = [init]; while (this.match(",")) { this.nextToken(); initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); } init = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq)); } this.expect(";"); } } } if (typeof left === "undefined") { if (!this.match(";")) { test = this.parseExpression(); } this.expect(";"); if (!this.match(")")) { update = this.parseExpression(); } } var body; if (!this.match(")") && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); body = this.finalize(this.createNode(), new Node.EmptyStatement()); } else { this.expect(")"); var previousInIteration = this.context.inIteration; this.context.inIteration = true; body = this.isolateCoverGrammar(this.parseStatement); this.context.inIteration = previousInIteration; } return typeof left === "undefined" ? this.finalize(node2, new Node.ForStatement(init, test, update, body)) : forIn ? this.finalize(node2, new Node.ForInStatement(left, right, body)) : this.finalize(node2, new Node.ForOfStatement(left, right, body)); }; Parser2.prototype.parseContinueStatement = function() { var node2 = this.createNode(); this.expectKeyword("continue"); var label = null; if (this.lookahead.type === 3 && !this.hasLineTerminator) { var id = this.parseVariableIdentifier(); label = id; var key = "$" + id.name; if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { this.throwError(messages_1.Messages.UnknownLabel, id.name); } } this.consumeSemicolon(); if (label === null && !this.context.inIteration) { this.throwError(messages_1.Messages.IllegalContinue); } return this.finalize(node2, new Node.ContinueStatement(label)); }; Parser2.prototype.parseBreakStatement = function() { var node2 = this.createNode(); this.expectKeyword("break"); var label = null; if (this.lookahead.type === 3 && !this.hasLineTerminator) { var id = this.parseVariableIdentifier(); var key = "$" + id.name; if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { this.throwError(messages_1.Messages.UnknownLabel, id.name); } label = id; } this.consumeSemicolon(); if (label === null && !this.context.inIteration && !this.context.inSwitch) { this.throwError(messages_1.Messages.IllegalBreak); } return this.finalize(node2, new Node.BreakStatement(label)); }; Parser2.prototype.parseReturnStatement = function() { if (!this.context.inFunctionBody) { this.tolerateError(messages_1.Messages.IllegalReturn); } var node2 = this.createNode(); this.expectKeyword("return"); var hasArgument = !this.match(";") && !this.match("}") && !this.hasLineTerminator && this.lookahead.type !== 2 || this.lookahead.type === 8 || this.lookahead.type === 10; var argument = hasArgument ? this.parseExpression() : null; this.consumeSemicolon(); return this.finalize(node2, new Node.ReturnStatement(argument)); }; Parser2.prototype.parseWithStatement = function() { if (this.context.strict) { this.tolerateError(messages_1.Messages.StrictModeWith); } var node2 = this.createNode(); var body; this.expectKeyword("with"); this.expect("("); var object = this.parseExpression(); if (!this.match(")") && this.config.tolerant) { this.tolerateUnexpectedToken(this.nextToken()); body = this.finalize(this.createNode(), new Node.EmptyStatement()); } else { this.expect(")"); body = this.parseStatement(); } return this.finalize(node2, new Node.WithStatement(object, body)); }; Parser2.prototype.parseSwitchCase = function() { var node2 = this.createNode(); var test; if (this.matchKeyword("default")) { this.nextToken(); test = null; } else { this.expectKeyword("case"); test = this.parseExpression(); } this.expect(":"); var consequent = []; while (true) { if (this.match("}") || this.matchKeyword("default") || this.matchKeyword("case")) { break; } consequent.push(this.parseStatementListItem()); } return this.finalize(node2, new Node.SwitchCase(test, consequent)); }; Parser2.prototype.parseSwitchStatement = function() { var node2 = this.createNode(); this.expectKeyword("switch"); this.expect("("); var discriminant = this.parseExpression(); this.expect(")"); var previousInSwitch = this.context.inSwitch; this.context.inSwitch = true; var cases = []; var defaultFound = false; this.expect("{"); while (true) { if (this.match("}")) { break; } var clause = this.parseSwitchCase(); if (clause.test === null) { if (defaultFound) { this.throwError(messages_1.Messages.MultipleDefaultsInSwitch); } defaultFound = true; } cases.push(clause); } this.expect("}"); this.context.inSwitch = previousInSwitch; return this.finalize(node2, new Node.SwitchStatement(discriminant, cases)); }; Parser2.prototype.parseLabelledStatement = function() { var node2 = this.createNode(); var expr = this.parseExpression(); var statement; if (expr.type === syntax_1.Syntax.Identifier && this.match(":")) { this.nextToken(); var id = expr; var key = "$" + id.name; if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { this.throwError(messages_1.Messages.Redeclaration, "Label", id.name); } this.context.labelSet[key] = true; var body = void 0; if (this.matchKeyword("class")) { this.tolerateUnexpectedToken(this.lookahead); body = this.parseClassDeclaration(); } else if (this.matchKeyword("function")) { var token = this.lookahead; var declaration = this.parseFunctionDeclaration(); if (this.context.strict) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction); } else if (declaration.generator) { this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext); } body = declaration; } else { body = this.parseStatement(); } delete this.context.labelSet[key]; statement = new Node.LabeledStatement(id, body); } else { this.consumeSemicolon(); statement = new Node.ExpressionStatement(expr); } return this.finalize(node2, statement); }; Parser2.prototype.parseThrowStatement = function() { var node2 = this.createNode(); this.expectKeyword("throw"); if (this.hasLineTerminator) { this.throwError(messages_1.Messages.NewlineAfterThrow); } var argument = this.parseExpression(); this.consumeSemicolon(); return this.finalize(node2, new Node.ThrowStatement(argument)); }; Parser2.prototype.parseCatchClause = function() { var node2 = this.createNode(); this.expectKeyword("catch"); this.expect("("); if (this.match(")")) { this.throwUnexpectedToken(this.lookahead); } var params = []; var param = this.parsePattern(params); var paramMap = {}; for (var i2 = 0; i2 < params.length; i2++) { var key = "$" + params[i2].value; if (Object.prototype.hasOwnProperty.call(paramMap, key)) { this.tolerateError(messages_1.Messages.DuplicateBinding, params[i2].value); } paramMap[key] = true; } if (this.context.strict && param.type === syntax_1.Syntax.Identifier) { if (this.scanner.isRestrictedWord(param.name)) { this.tolerateError(messages_1.Messages.StrictCatchVariable); } } this.expect(")"); var body = this.parseBlock(); return this.finalize(node2, new Node.CatchClause(param, body)); }; Parser2.prototype.parseFinallyClause = function() { this.expectKeyword("finally"); return this.parseBlock(); }; Parser2.prototype.parseTryStatement = function() { var node2 = this.createNode(); this.expectKeyword("try"); var block = this.parseBlock(); var handler = this.matchKeyword("catch") ? this.parseCatchClause() : null; var finalizer = this.matchKeyword("finally") ? this.parseFinallyClause() : null; if (!handler && !finalizer) { this.throwError(messages_1.Messages.NoCatchOrFinally); } return this.finalize(node2, new Node.TryStatement(block, handler, finalizer)); }; Parser2.prototype.parseDebuggerStatement = function() { var node2 = this.createNode(); this.expectKeyword("debugger"); this.consumeSemicolon(); return this.finalize(node2, new Node.DebuggerStatement()); }; Parser2.prototype.parseStatement = function() { var statement; switch (this.lookahead.type) { case 1: case 5: case 6: case 8: case 10: case 9: statement = this.parseExpressionStatement(); break; case 7: var value = this.lookahead.value; if (value === "{") { statement = this.parseBlock(); } else if (value === "(") { statement = this.parseExpressionStatement(); } else if (value === ";") { statement = this.parseEmptyStatement(); } else { statement = this.parseExpressionStatement(); } break; case 3: statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement(); break; case 4: switch (this.lookahead.value) { case "break": statement = this.parseBreakStatement(); break; case "continue": statement = this.parseContinueStatement(); break; case "debugger": statement = this.parseDebuggerStatement(); break; case "do": statement = this.parseDoWhileStatement(); break; case "for": statement = this.parseForStatement(); break; case "function": statement = this.parseFunctionDeclaration(); break; case "if": statement = this.parseIfStatement(); break; case "return": statement = this.parseReturnStatement(); break; case "switch": statement = this.parseSwitchStatement(); break; case "throw": statement = this.parseThrowStatement(); break; case "try": statement = this.parseTryStatement(); break; case "var": statement = this.parseVariableStatement(); break; case "while": statement = this.parseWhileStatement(); break; case "with": statement = this.parseWithStatement(); break; default: statement = this.parseExpressionStatement(); break; } break; default: statement = this.throwUnexpectedToken(this.lookahead); } return statement; }; Parser2.prototype.parseFunctionSourceElements = function() { var node2 = this.createNode(); this.expect("{"); var body = this.parseDirectivePrologues(); var previousLabelSet = this.context.labelSet; var previousInIteration = this.context.inIteration; var previousInSwitch = this.context.inSwitch; var previousInFunctionBody = this.context.inFunctionBody; this.context.labelSet = {}; this.context.inIteration = false; this.context.inSwitch = false; this.context.inFunctionBody = true; while (this.lookahead.type !== 2) { if (this.match("}")) { break; } body.push(this.parseStatementListItem()); } this.expect("}"); this.context.labelSet = previousLabelSet; this.context.inIteration = previousInIteration; this.context.inSwitch = previousInSwitch; this.context.inFunctionBody = previousInFunctionBody; return this.finalize(node2, new Node.BlockStatement(body)); }; Parser2.prototype.validateParam = function(options, param, name) { var key = "$" + name; if (this.context.strict) { if (this.scanner.isRestrictedWord(name)) { options.stricted = param; options.message = messages_1.Messages.StrictParamName; } if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { options.stricted = param; options.message = messages_1.Messages.StrictParamDupe; } } else if (!options.firstRestricted) { if (this.scanner.isRestrictedWord(name)) { options.firstRestricted = param; options.message = messages_1.Messages.StrictParamName; } else if (this.scanner.isStrictModeReservedWord(name)) { options.firstRestricted = param; options.message = messages_1.Messages.StrictReservedWord; } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { options.stricted = param; options.message = messages_1.Messages.StrictParamDupe; } } if (typeof Object.defineProperty === "function") { Object.defineProperty(options.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true }); } else { options.paramSet[key] = true; } }; Parser2.prototype.parseRestElement = function(params) { var node2 = this.createNode(); this.expect("..."); var arg = this.parsePattern(params); if (this.match("=")) { this.throwError(messages_1.Messages.DefaultRestParameter); } if (!this.match(")")) { this.throwError(messages_1.Messages.ParameterAfterRestParameter); } return this.finalize(node2, new Node.RestElement(arg)); }; Parser2.prototype.parseFormalParameter = function(options) { var params = []; var param = this.match("...") ? this.parseRestElement(params) : this.parsePatternWithDefault(params); for (var i2 = 0; i2 < params.length; i2++) { this.validateParam(options, params[i2], params[i2].value); } options.simple = options.simple && param instanceof Node.Identifier; options.params.push(param); }; Parser2.prototype.parseFormalParameters = function(firstRestricted) { var options; options = { simple: true, params: [], firstRestricted }; this.expect("("); if (!this.match(")")) { options.paramSet = {}; while (this.lookahead.type !== 2) { this.parseFormalParameter(options); if (this.match(")")) { break; } this.expect(","); if (this.match(")")) { break; } } } this.expect(")"); return { simple: options.simple, params: options.params, stricted: options.stricted, firstRestricted: options.firstRestricted, message: options.message }; }; Parser2.prototype.matchAsyncFunction = function() { var match2 = this.matchContextualKeyword("async"); if (match2) { var state = this.scanner.saveState(); this.scanner.scanComments(); var next = this.scanner.lex(); this.scanner.restoreState(state); match2 = state.lineNumber === next.lineNumber && next.type === 4 && next.value === "function"; } return match2; }; Parser2.prototype.parseFunctionDeclaration = function(identifierIsOptional) { var node2 = this.createNode(); var isAsync2 = this.matchContextualKeyword("async"); if (isAsync2) { this.nextToken(); } this.expectKeyword("function"); var isGenerator = isAsync2 ? false : this.match("*"); if (isGenerator) { this.nextToken(); } var message; var id = null; var firstRestricted = null; if (!identifierIsOptional || !this.match("(")) { var token = this.lookahead; id = this.parseVariableIdentifier(); if (this.context.strict) { if (this.scanner.isRestrictedWord(token.value)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); } } else { if (this.scanner.isRestrictedWord(token.value)) { firstRestricted = token; message = messages_1.Messages.StrictFunctionName; } else if (this.scanner.isStrictModeReservedWord(token.value)) { firstRestricted = token; message = messages_1.Messages.StrictReservedWord; } } } var previousAllowAwait = this.context.await; var previousAllowYield = this.context.allowYield; this.context.await = isAsync2; this.context.allowYield = !isGenerator; var formalParameters = this.parseFormalParameters(firstRestricted); var params = formalParameters.params; var stricted = formalParameters.stricted; firstRestricted = formalParameters.firstRestricted; if (formalParameters.message) { message = formalParameters.message; } var previousStrict = this.context.strict; var previousAllowStrictDirective = this.context.allowStrictDirective; this.context.allowStrictDirective = formalParameters.simple; var body = this.parseFunctionSourceElements(); if (this.context.strict && firstRestricted) { this.throwUnexpectedToken(firstRestricted, message); } if (this.context.strict && stricted) { this.tolerateUnexpectedToken(stricted, message); } this.context.strict = previousStrict; this.context.allowStrictDirective = previousAllowStrictDirective; this.context.await = previousAllowAwait; this.context.allowYield = previousAllowYield; return isAsync2 ? this.finalize(node2, new Node.AsyncFunctionDeclaration(id, params, body)) : this.finalize(node2, new Node.FunctionDeclaration(id, params, body, isGenerator)); }; Parser2.prototype.parseFunctionExpression = function() { var node2 = this.createNode(); var isAsync2 = this.matchContextualKeyword("async"); if (isAsync2) { this.nextToken(); } this.expectKeyword("function"); var isGenerator = isAsync2 ? false : this.match("*"); if (isGenerator) { this.nextToken(); } var message; var id = null; var firstRestricted; var previousAllowAwait = this.context.await; var previousAllowYield = this.context.allowYield; this.context.await = isAsync2; this.context.allowYield = !isGenerator; if (!this.match("(")) { var token = this.lookahead; id = !this.context.strict && !isGenerator && this.matchKeyword("yield") ? this.parseIdentifierName() : this.parseVariableIdentifier(); if (this.context.strict) { if (this.scanner.isRestrictedWord(token.value)) { this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); } } else { if (this.scanner.isRestrictedWord(token.value)) { firstRestricted = token; message = messages_1.Messages.StrictFunctionName; } else if (this.scanner.isStrictModeReservedWord(token.value)) { firstRestricted = token; message = messages_1.Messages.StrictReservedWord; } } } var formalParameters = this.parseFormalParameters(firstRestricted); var params = formalParameters.params; var stricted = formalParameters.stricted; firstRestricted = formalParameters.firstRestricted; if (formalParameters.message) { message = formalParameters.message; } var previousStrict = this.context.strict; var previousAllowStrictDirective = this.context.allowStrictDirective; this.context.allowStrictDirective = formalParameters.simple; var body = this.parseFunctionSourceElements(); if (this.context.strict && firstRestricted) { this.throwUnexpectedToken(firstRestricted, message); } if (this.context.strict && stricted) { this.tolerateUnexpectedToken(stricted, message); } this.context.strict = previousStrict; this.context.allowStrictDirective = previousAllowStrictDirective; this.context.await = previousAllowAwait; this.context.allowYield = previousAllowYield; return isAsync2 ? this.finalize(node2, new Node.AsyncFunctionExpression(id, params, body)) : this.finalize(node2, new Node.FunctionExpression(id, params, body, isGenerator)); }; Parser2.prototype.parseDirective = function() { var token = this.lookahead; var node2 = this.createNode(); var expr = this.parseExpression(); var directive = expr.type === syntax_1.Syntax.Literal ? this.getTokenRaw(token).slice(1, -1) : null; this.consumeSemicolon(); return this.finalize(node2, directive ? new Node.Directive(expr, directive) : new Node.ExpressionStatement(expr)); }; Parser2.prototype.parseDirectivePrologues = function() { var firstRestricted = null; var body = []; while (true) { var token = this.lookahead; if (token.type !== 8) { break; } var statement = this.parseDirective(); body.push(statement); var directive = statement.directive; if (typeof directive !== "string") { break; } if (directive === "use strict") { this.context.strict = true; if (firstRestricted) { this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral); } if (!this.context.allowStrictDirective) { this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } return body; }; Parser2.prototype.qualifiedPropertyName = function(token) { switch (token.type) { case 3: case 8: case 1: case 5: case 6: case 4: return true; case 7: return token.value === "["; default: break; } return false; }; Parser2.prototype.parseGetterMethod = function() { var node2 = this.createNode(); var isGenerator = false; var previousAllowYield = this.context.allowYield; this.context.allowYield = !isGenerator; var formalParameters = this.parseFormalParameters(); if (formalParameters.params.length > 0) { this.tolerateError(messages_1.Messages.BadGetterArity); } var method = this.parsePropertyMethod(formalParameters); this.context.allowYield = previousAllowYield; return this.finalize(node2, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); }; Parser2.prototype.parseSetterMethod = function() { var node2 = this.createNode(); var isGenerator = false; var previousAllowYield = this.context.allowYield; this.context.allowYield = !isGenerator; var formalParameters = this.parseFormalParameters(); if (formalParameters.params.length !== 1) { this.tolerateError(messages_1.Messages.BadSetterArity); } else if (formalParameters.params[0] instanceof Node.RestElement) { this.tolerateError(messages_1.Messages.BadSetterRestParameter); } var method = this.parsePropertyMethod(formalParameters); this.context.allowYield = previousAllowYield; return this.finalize(node2, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); }; Parser2.prototype.parseGeneratorMethod = function() { var node2 = this.createNode(); var isGenerator = true; var previousAllowYield = this.context.allowYield; this.context.allowYield = true; var params = this.parseFormalParameters(); this.context.allowYield = false; var method = this.parsePropertyMethod(params); this.context.allowYield = previousAllowYield; return this.finalize(node2, new Node.FunctionExpression(null, params.params, method, isGenerator)); }; Parser2.prototype.isStartOfExpression = function() { var start = true; var value = this.lookahead.value; switch (this.lookahead.type) { case 7: start = value === "[" || value === "(" || value === "{" || value === "+" || value === "-" || value === "!" || value === "~" || value === "++" || value === "--" || value === "/" || value === "/="; break; case 4: start = value === "class" || value === "delete" || value === "function" || value === "let" || value === "new" || value === "super" || value === "this" || value === "typeof" || value === "void" || value === "yield"; break; default: break; } return start; }; Parser2.prototype.parseYieldExpression = function() { var node2 = this.createNode(); this.expectKeyword("yield"); var argument = null; var delegate = false; if (!this.hasLineTerminator) { var previousAllowYield = this.context.allowYield; this.context.allowYield = false; delegate = this.match("*"); if (delegate) { this.nextToken(); argument = this.parseAssignmentExpression(); } else if (this.isStartOfExpression()) { argument = this.parseAssignmentExpression(); } this.context.allowYield = previousAllowYield; } return this.finalize(node2, new Node.YieldExpression(argument, delegate)); }; Parser2.prototype.parseClassElement = function(hasConstructor) { var token = this.lookahead; var node2 = this.createNode(); var kind = ""; var key = null; var value = null; var computed = false; var method = false; var isStatic = false; var isAsync2 = false; if (this.match("*")) { this.nextToken(); } else { computed = this.match("["); key = this.parseObjectPropertyKey(); var id = key; if (id.name === "static" && (this.qualifiedPropertyName(this.lookahead) || this.match("*"))) { token = this.lookahead; isStatic = true; computed = this.match("["); if (this.match("*")) { this.nextToken(); } else { key = this.parseObjectPropertyKey(); } } if (token.type === 3 && !this.hasLineTerminator && token.value === "async") { var punctuator = this.lookahead.value; if (punctuator !== ":" && punctuator !== "(" && punctuator !== "*") { isAsync2 = true; token = this.lookahead; key = this.parseObjectPropertyKey(); if (token.type === 3 && token.value === "constructor") { this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync); } } } } var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); if (token.type === 3) { if (token.value === "get" && lookaheadPropertyKey) { kind = "get"; computed = this.match("["); key = this.parseObjectPropertyKey(); this.context.allowYield = false; value = this.parseGetterMethod(); } else if (token.value === "set" && lookaheadPropertyKey) { kind = "set"; computed = this.match("["); key = this.parseObjectPropertyKey(); value = this.parseSetterMethod(); } } else if (token.type === 7 && token.value === "*" && lookaheadPropertyKey) { kind = "init"; computed = this.match("["); key = this.parseObjectPropertyKey(); value = this.parseGeneratorMethod(); method = true; } if (!kind && key && this.match("(")) { kind = "init"; value = isAsync2 ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); method = true; } if (!kind) { this.throwUnexpectedToken(this.lookahead); } if (kind === "init") { kind = "method"; } if (!computed) { if (isStatic && this.isPropertyKey(key, "prototype")) { this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype); } if (!isStatic && this.isPropertyKey(key, "constructor")) { if (kind !== "method" || !method || value && value.generator) { this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod); } if (hasConstructor.value) { this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor); } else { hasConstructor.value = true; } kind = "constructor"; } } return this.finalize(node2, new Node.MethodDefinition(key, computed, value, kind, isStatic)); }; Parser2.prototype.parseClassElementList = function() { var body = []; var hasConstructor = { value: false }; this.expect("{"); while (!this.match("}")) { if (this.match(";")) { this.nextToken(); } else { body.push(this.parseClassElement(hasConstructor)); } } this.expect("}"); return body; }; Parser2.prototype.parseClassBody = function() { var node2 = this.createNode(); var elementList = this.parseClassElementList(); return this.finalize(node2, new Node.ClassBody(elementList)); }; Parser2.prototype.parseClassDeclaration = function(identifierIsOptional) { var node2 = this.createNode(); var previousStrict = this.context.strict; this.context.strict = true; this.expectKeyword("class"); var id = identifierIsOptional && this.lookahead.type !== 3 ? null : this.parseVariableIdentifier(); var superClass = null; if (this.matchKeyword("extends")) { this.nextToken(); superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); } var classBody = this.parseClassBody(); this.context.strict = previousStrict; return this.finalize(node2, new Node.ClassDeclaration(id, superClass, classBody)); }; Parser2.prototype.parseClassExpression = function() { var node2 = this.createNode(); var previousStrict = this.context.strict; this.context.strict = true; this.expectKeyword("class"); var id = this.lookahead.type === 3 ? this.parseVariableIdentifier() : null; var superClass = null; if (this.matchKeyword("extends")) { this.nextToken(); superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); } var classBody = this.parseClassBody(); this.context.strict = previousStrict; return this.finalize(node2, new Node.ClassExpression(id, superClass, classBody)); }; Parser2.prototype.parseModule = function() { this.context.strict = true; this.context.isModule = true; this.scanner.isModule = true; var node2 = this.createNode(); var body = this.parseDirectivePrologues(); while (this.lookahead.type !== 2) { body.push(this.parseStatementListItem()); } return this.finalize(node2, new Node.Module(body)); }; Parser2.prototype.parseScript = function() { var node2 = this.createNode(); var body = this.parseDirectivePrologues(); while (this.lookahead.type !== 2) { body.push(this.parseStatementListItem()); } return this.finalize(node2, new Node.Script(body)); }; Parser2.prototype.parseModuleSpecifier = function() { var node2 = this.createNode(); if (this.lookahead.type !== 8) { this.throwError(messages_1.Messages.InvalidModuleSpecifier); } var token = this.nextToken(); var raw = this.getTokenRaw(token); return this.finalize(node2, new Node.Literal(token.value, raw)); }; Parser2.prototype.parseImportSpecifier = function() { var node2 = this.createNode(); var imported; var local; if (this.lookahead.type === 3) { imported = this.parseVariableIdentifier(); local = imported; if (this.matchContextualKeyword("as")) { this.nextToken(); local = this.parseVariableIdentifier(); } } else { imported = this.parseIdentifierName(); local = imported; if (this.matchContextualKeyword("as")) { this.nextToken(); local = this.parseVariableIdentifier(); } else { this.throwUnexpectedToken(this.nextToken()); } } return this.finalize(node2, new Node.ImportSpecifier(local, imported)); }; Parser2.prototype.parseNamedImports = function() { this.expect("{"); var specifiers = []; while (!this.match("}")) { specifiers.push(this.parseImportSpecifier()); if (!this.match("}")) { this.expect(","); } } this.expect("}"); return specifiers; }; Parser2.prototype.parseImportDefaultSpecifier = function() { var node2 = this.createNode(); var local = this.parseIdentifierName(); return this.finalize(node2, new Node.ImportDefaultSpecifier(local)); }; Parser2.prototype.parseImportNamespaceSpecifier = function() { var node2 = this.createNode(); this.expect("*"); if (!this.matchContextualKeyword("as")) { this.throwError(messages_1.Messages.NoAsAfterImportNamespace); } this.nextToken(); var local = this.parseIdentifierName(); return this.finalize(node2, new Node.ImportNamespaceSpecifier(local)); }; Parser2.prototype.parseImportDeclaration = function() { if (this.context.inFunctionBody) { this.throwError(messages_1.Messages.IllegalImportDeclaration); } var node2 = this.createNode(); this.expectKeyword("import"); var src; var specifiers = []; if (this.lookahead.type === 8) { src = this.parseModuleSpecifier(); } else { if (this.match("{")) { specifiers = specifiers.concat(this.parseNamedImports()); } else if (this.match("*")) { specifiers.push(this.parseImportNamespaceSpecifier()); } else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword("default")) { specifiers.push(this.parseImportDefaultSpecifier()); if (this.match(",")) { this.nextToken(); if (this.match("*")) { specifiers.push(this.parseImportNamespaceSpecifier()); } else if (this.match("{")) { specifiers = specifiers.concat(this.parseNamedImports()); } else { this.throwUnexpectedToken(this.lookahead); } } } else { this.throwUnexpectedToken(this.nextToken()); } if (!this.matchContextualKeyword("from")) { var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; this.throwError(message, this.lookahead.value); } this.nextToken(); src = this.parseModuleSpecifier(); } this.consumeSemicolon(); return this.finalize(node2, new Node.ImportDeclaration(specifiers, src)); }; Parser2.prototype.parseExportSpecifier = function() { var node2 = this.createNode(); var local = this.parseIdentifierName(); var exported = local; if (this.matchContextualKeyword("as")) { this.nextToken(); exported = this.parseIdentifierName(); } return this.finalize(node2, new Node.ExportSpecifier(local, exported)); }; Parser2.prototype.parseExportDeclaration = function() { if (this.context.inFunctionBody) { this.throwError(messages_1.Messages.IllegalExportDeclaration); } var node2 = this.createNode(); this.expectKeyword("export"); var exportDeclaration; if (this.matchKeyword("default")) { this.nextToken(); if (this.matchKeyword("function")) { var declaration = this.parseFunctionDeclaration(true); exportDeclaration = this.finalize(node2, new Node.ExportDefaultDeclaration(declaration)); } else if (this.matchKeyword("class")) { var declaration = this.parseClassDeclaration(true); exportDeclaration = this.finalize(node2, new Node.ExportDefaultDeclaration(declaration)); } else if (this.matchContextualKeyword("async")) { var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression(); exportDeclaration = this.finalize(node2, new Node.ExportDefaultDeclaration(declaration)); } else { if (this.matchContextualKeyword("from")) { this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value); } var declaration = this.match("{") ? this.parseObjectInitializer() : this.match("[") ? this.parseArrayInitializer() : this.parseAssignmentExpression(); this.consumeSemicolon(); exportDeclaration = this.finalize(node2, new Node.ExportDefaultDeclaration(declaration)); } } else if (this.match("*")) { this.nextToken(); if (!this.matchContextualKeyword("from")) { var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; this.throwError(message, this.lookahead.value); } this.nextToken(); var src = this.parseModuleSpecifier(); this.consumeSemicolon(); exportDeclaration = this.finalize(node2, new Node.ExportAllDeclaration(src)); } else if (this.lookahead.type === 4) { var declaration = void 0; switch (this.lookahead.value) { case "let": case "const": declaration = this.parseLexicalDeclaration({ inFor: false }); break; case "var": case "class": case "function": declaration = this.parseStatementListItem(); break; default: this.throwUnexpectedToken(this.lookahead); } exportDeclaration = this.finalize(node2, new Node.ExportNamedDeclaration(declaration, [], null)); } else if (this.matchAsyncFunction()) { var declaration = this.parseFunctionDeclaration(); exportDeclaration = this.finalize(node2, new Node.ExportNamedDeclaration(declaration, [], null)); } else { var specifiers = []; var source = null; var isExportFromIdentifier = false; this.expect("{"); while (!this.match("}")) { isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword("default"); specifiers.push(this.parseExportSpecifier()); if (!this.match("}")) { this.expect(","); } } this.expect("}"); if (this.matchContextualKeyword("from")) { this.nextToken(); source = this.parseModuleSpecifier(); this.consumeSemicolon(); } else if (isExportFromIdentifier) { var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; this.throwError(message, this.lookahead.value); } else { this.consumeSemicolon(); } exportDeclaration = this.finalize(node2, new Node.ExportNamedDeclaration(null, specifiers, source)); } return exportDeclaration; }; return Parser2; }(); exports2.Parser = Parser; }, /* 9 */ /***/ function(module3, exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); function assert(condition, message) { if (!condition) { throw new Error("ASSERT: " + message); } } exports2.assert = assert; }, /* 10 */ /***/ function(module3, exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var ErrorHandler = function() { function ErrorHandler2() { this.errors = []; this.tolerant = false; } ErrorHandler2.prototype.recordError = function(error) { this.errors.push(error); }; ErrorHandler2.prototype.tolerate = function(error) { if (this.tolerant) { this.recordError(error); } else { throw error; } }; ErrorHandler2.prototype.constructError = function(msg, column) { var error = new Error(msg); try { throw error; } catch (base) { if (Object.create && Object.defineProperty) { error = Object.create(base); Object.defineProperty(error, "column", { value: column }); } } return error; }; ErrorHandler2.prototype.createError = function(index2, line, col, description) { var msg = "Line " + line + ": " + description; var error = this.constructError(msg, col); error.index = index2; error.lineNumber = line; error.description = description; return error; }; ErrorHandler2.prototype.throwError = function(index2, line, col, description) { throw this.createError(index2, line, col, description); }; ErrorHandler2.prototype.tolerateError = function(index2, line, col, description) { var error = this.createError(index2, line, col, description); if (this.tolerant) { this.recordError(error); } else { throw error; } }; return ErrorHandler2; }(); exports2.ErrorHandler = ErrorHandler; }, /* 11 */ /***/ function(module3, exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.Messages = { BadGetterArity: "Getter must not have any formal parameters", BadSetterArity: "Setter must have exactly one formal parameter", BadSetterRestParameter: "Setter function argument must not be a rest parameter", ConstructorIsAsync: "Class constructor may not be an async method", ConstructorSpecialMethod: "Class constructor may not be an accessor", DeclarationMissingInitializer: "Missing initializer in %0 declaration", DefaultRestParameter: "Unexpected token =", DuplicateBinding: "Duplicate binding %0", DuplicateConstructor: "A class may only have one constructor", DuplicateProtoProperty: "Duplicate __proto__ fields are not allowed in object literals", ForInOfLoopInitializer: "%0 loop variable declaration may not have an initializer", GeneratorInLegacyContext: "Generator declarations are not allowed in legacy contexts", IllegalBreak: "Illegal break statement", IllegalContinue: "Illegal continue statement", IllegalExportDeclaration: "Unexpected token", IllegalImportDeclaration: "Unexpected token", IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list", IllegalReturn: "Illegal return statement", InvalidEscapedReservedWord: "Keyword must not contain escaped characters", InvalidHexEscapeSequence: "Invalid hexadecimal escape sequence", InvalidLHSInAssignment: "Invalid left-hand side in assignment", InvalidLHSInForIn: "Invalid left-hand side in for-in", InvalidLHSInForLoop: "Invalid left-hand side in for-loop", InvalidModuleSpecifier: "Unexpected token", InvalidRegExp: "Invalid regular expression", LetInLexicalBinding: "let is disallowed as a lexically bound name", MissingFromClause: "Unexpected token", MultipleDefaultsInSwitch: "More than one default clause in switch statement", NewlineAfterThrow: "Illegal newline after throw", NoAsAfterImportNamespace: "Unexpected token", NoCatchOrFinally: "Missing catch or finally after try", ParameterAfterRestParameter: "Rest parameter must be last formal parameter", Redeclaration: "%0 '%1' has already been declared", StaticPrototype: "Classes may not have static property named prototype", StrictCatchVariable: "Catch variable may not be eval or arguments in strict mode", StrictDelete: "Delete of an unqualified identifier in strict mode.", StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block", StrictFunctionName: "Function name may not be eval or arguments in strict mode", StrictLHSAssignment: "Assignment to eval or arguments is not allowed in strict mode", StrictLHSPostfix: "Postfix increment/decrement may not have eval or arguments operand in strict mode", StrictLHSPrefix: "Prefix increment/decrement may not have eval or arguments operand in strict mode", StrictModeWith: "Strict mode code may not include a with statement", StrictOctalLiteral: "Octal literals are not allowed in strict mode.", StrictParamDupe: "Strict mode function may not have duplicate parameter names", StrictParamName: "Parameter name eval or arguments is not allowed in strict mode", StrictReservedWord: "Use of future reserved word in strict mode", StrictVarName: "Variable name may not be eval or arguments in strict mode", TemplateOctalLiteral: "Octal literals are not allowed in template strings.", UnexpectedEOS: "Unexpected end of input", UnexpectedIdentifier: "Unexpected identifier", UnexpectedNumber: "Unexpected number", UnexpectedReserved: "Unexpected reserved word", UnexpectedString: "Unexpected string", UnexpectedTemplate: "Unexpected quasi %0", UnexpectedToken: "Unexpected token %0", UnexpectedTokenIllegal: "Unexpected token ILLEGAL", UnknownLabel: "Undefined label '%0'", UnterminatedRegExp: "Invalid regular expression: missing /" }; }, /* 12 */ /***/ function(module3, exports2, __webpack_require__) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var assert_1 = __webpack_require__(9); var character_1 = __webpack_require__(4); var messages_1 = __webpack_require__(11); function hexValue(ch) { return "0123456789abcdef".indexOf(ch.toLowerCase()); } function octalValue(ch) { return "01234567".indexOf(ch); } var Scanner = function() { function Scanner2(code, handler) { this.source = code; this.errorHandler = handler; this.trackComment = false; this.isModule = false; this.length = code.length; this.index = 0; this.lineNumber = code.length > 0 ? 1 : 0; this.lineStart = 0; this.curlyStack = []; } Scanner2.prototype.saveState = function() { return { index: this.index, lineNumber: this.lineNumber, lineStart: this.lineStart }; }; Scanner2.prototype.restoreState = function(state) { this.index = state.index; this.lineNumber = state.lineNumber; this.lineStart = state.lineStart; }; Scanner2.prototype.eof = function() { return this.index >= this.length; }; Scanner2.prototype.throwUnexpectedToken = function(message) { if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); }; Scanner2.prototype.tolerateUnexpectedToken = function(message) { if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); }; Scanner2.prototype.skipSingleLineComment = function(offset) { var comments = []; var start, loc; if (this.trackComment) { comments = []; start = this.index - offset; loc = { start: { line: this.lineNumber, column: this.index - this.lineStart - offset }, end: {} }; } while (!this.eof()) { var ch = this.source.charCodeAt(this.index); ++this.index; if (character_1.Character.isLineTerminator(ch)) { if (this.trackComment) { loc.end = { line: this.lineNumber, column: this.index - this.lineStart - 1 }; var entry = { multiLine: false, slice: [start + offset, this.index - 1], range: [start, this.index - 1], loc }; comments.push(entry); } if (ch === 13 && this.source.charCodeAt(this.index) === 10) { ++this.index; } ++this.lineNumber; this.lineStart = this.index; return comments; } } if (this.trackComment) { loc.end = { line: this.lineNumber, column: this.index - this.lineStart }; var entry = { multiLine: false, slice: [start + offset, this.index], range: [start, this.index], loc }; comments.push(entry); } return comments; }; Scanner2.prototype.skipMultiLineComment = function() { var comments = []; var start, loc; if (this.trackComment) { comments = []; start = this.index - 2; loc = { start: { line: this.lineNumber, column: this.index - this.lineStart - 2 }, end: {} }; } while (!this.eof()) { var ch = this.source.charCodeAt(this.index); if (character_1.Character.isLineTerminator(ch)) { if (ch === 13 && this.source.charCodeAt(this.index + 1) === 10) { ++this.index; } ++this.lineNumber; ++this.index; this.lineStart = this.index; } else if (ch === 42) { if (this.source.charCodeAt(this.index + 1) === 47) { this.index += 2; if (this.trackComment) { loc.end = { line: this.lineNumber, column: this.index - this.lineStart }; var entry = { multiLine: true, slice: [start + 2, this.index - 2], range: [start, this.index], loc }; comments.push(entry); } return comments; } ++this.index; } else { ++this.index; } } if (this.trackComment) { loc.end = { line: this.lineNumber, column: this.index - this.lineStart }; var entry = { multiLine: true, slice: [start + 2, this.index], range: [start, this.index], loc }; comments.push(entry); } this.tolerateUnexpectedToken(); return comments; }; Scanner2.prototype.scanComments = function() { var comments; if (this.trackComment) { comments = []; } var start = this.index === 0; while (!this.eof()) { var ch = this.source.charCodeAt(this.index); if (character_1.Character.isWhiteSpace(ch)) { ++this.index; } else if (character_1.Character.isLineTerminator(ch)) { ++this.index; if (ch === 13 && this.source.charCodeAt(this.index) === 10) { ++this.index; } ++this.lineNumber; this.lineStart = this.index; start = true; } else if (ch === 47) { ch = this.source.charCodeAt(this.index + 1); if (ch === 47) { this.index += 2; var comment = this.skipSingleLineComment(2); if (this.trackComment) { comments = comments.concat(comment); } start = true; } else if (ch === 42) { this.index += 2; var comment = this.skipMultiLineComment(); if (this.trackComment) { comments = comments.concat(comment); } } else { break; } } else if (start && ch === 45) { if (this.source.charCodeAt(this.index + 1) === 45 && this.source.charCodeAt(this.index + 2) === 62) { this.index += 3; var comment = this.skipSingleLineComment(3); if (this.trackComment) { comments = comments.concat(comment); } } else { break; } } else if (ch === 60 && !this.isModule) { if (this.source.slice(this.index + 1, this.index + 4) === "!--") { this.index += 4; var comment = this.skipSingleLineComment(4); if (this.trackComment) { comments = comments.concat(comment); } } else { break; } } else { break; } } return comments; }; Scanner2.prototype.isFutureReservedWord = function(id) { switch (id) { case "enum": case "export": case "import": case "super": return true; default: return false; } }; Scanner2.prototype.isStrictModeReservedWord = function(id) { switch (id) { case "implements": case "interface": case "package": case "private": case "protected": case "public": case "static": case "yield": case "let": return true; default: return false; } }; Scanner2.prototype.isRestrictedWord = function(id) { return id === "eval" || id === "arguments"; }; Scanner2.prototype.isKeyword = function(id) { switch (id.length) { case 2: return id === "if" || id === "in" || id === "do"; case 3: return id === "var" || id === "for" || id === "new" || id === "try" || id === "let"; case 4: return id === "this" || id === "else" || id === "case" || id === "void" || id === "with" || id === "enum"; case 5: return id === "while" || id === "break" || id === "catch" || id === "throw" || id === "const" || id === "yield" || id === "class" || id === "super"; case 6: return id === "return" || id === "typeof" || id === "delete" || id === "switch" || id === "export" || id === "import"; case 7: return id === "default" || id === "finally" || id === "extends"; case 8: return id === "function" || id === "continue" || id === "debugger"; case 10: return id === "instanceof"; default: return false; } }; Scanner2.prototype.codePointAt = function(i2) { var cp = this.source.charCodeAt(i2); if (cp >= 55296 && cp <= 56319) { var second = this.source.charCodeAt(i2 + 1); if (second >= 56320 && second <= 57343) { var first = cp; cp = (first - 55296) * 1024 + second - 56320 + 65536; } } return cp; }; Scanner2.prototype.scanHexEscape = function(prefix) { var len = prefix === "u" ? 4 : 2; var code = 0; for (var i2 = 0; i2 < len; ++i2) { if (!this.eof() && character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) { code = code * 16 + hexValue(this.source[this.index++]); } else { return null; } } return String.fromCharCode(code); }; Scanner2.prototype.scanUnicodeCodePointEscape = function() { var ch = this.source[this.index]; var code = 0; if (ch === "}") { this.throwUnexpectedToken(); } while (!this.eof()) { ch = this.source[this.index++]; if (!character_1.Character.isHexDigit(ch.charCodeAt(0))) { break; } code = code * 16 + hexValue(ch); } if (code > 1114111 || ch !== "}") { this.throwUnexpectedToken(); } return character_1.Character.fromCodePoint(code); }; Scanner2.prototype.getIdentifier = function() { var start = this.index++; while (!this.eof()) { var ch = this.source.charCodeAt(this.index); if (ch === 92) { this.index = start; return this.getComplexIdentifier(); } else if (ch >= 55296 && ch < 57343) { this.index = start; return this.getComplexIdentifier(); } if (character_1.Character.isIdentifierPart(ch)) { ++this.index; } else { break; } } return this.source.slice(start, this.index); }; Scanner2.prototype.getComplexIdentifier = function() { var cp = this.codePointAt(this.index); var id = character_1.Character.fromCodePoint(cp); this.index += id.length; var ch; if (cp === 92) { if (this.source.charCodeAt(this.index) !== 117) { this.throwUnexpectedToken(); } ++this.index; if (this.source[this.index] === "{") { ++this.index; ch = this.scanUnicodeCodePointEscape(); } else { ch = this.scanHexEscape("u"); if (ch === null || ch === "\\" || !character_1.Character.isIdentifierStart(ch.charCodeAt(0))) { this.throwUnexpectedToken(); } } id = ch; } while (!this.eof()) { cp = this.codePointAt(this.index); if (!character_1.Character.isIdentifierPart(cp)) { break; } ch = character_1.Character.fromCodePoint(cp); id += ch; this.index += ch.length; if (cp === 92) { id = id.substr(0, id.length - 1); if (this.source.charCodeAt(this.index) !== 117) { this.throwUnexpectedToken(); } ++this.index; if (this.source[this.index] === "{") { ++this.index; ch = this.scanUnicodeCodePointEscape(); } else { ch = this.scanHexEscape("u"); if (ch === null || ch === "\\" || !character_1.Character.isIdentifierPart(ch.charCodeAt(0))) { this.throwUnexpectedToken(); } } id += ch; } } return id; }; Scanner2.prototype.octalToDecimal = function(ch) { var octal = ch !== "0"; var code = octalValue(ch); if (!this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) { octal = true; code = code * 8 + octalValue(this.source[this.index++]); if ("0123".indexOf(ch) >= 0 && !this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) { code = code * 8 + octalValue(this.source[this.index++]); } } return { code, octal }; }; Scanner2.prototype.scanIdentifier = function() { var type2; var start = this.index; var id = this.source.charCodeAt(start) === 92 ? this.getComplexIdentifier() : this.getIdentifier(); if (id.length === 1) { type2 = 3; } else if (this.isKeyword(id)) { type2 = 4; } else if (id === "null") { type2 = 5; } else if (id === "true" || id === "false") { type2 = 1; } else { type2 = 3; } if (type2 !== 3 && start + id.length !== this.index) { var restore = this.index; this.index = start; this.tolerateUnexpectedToken(messages_1.Messages.InvalidEscapedReservedWord); this.index = restore; } return { type: type2, value: id, lineNumber: this.lineNumber, lineStart: this.lineStart, start, end: this.index }; }; Scanner2.prototype.scanPunctuator = function() { var start = this.index; var str2 = this.source[this.index]; switch (str2) { case "(": case "{": if (str2 === "{") { this.curlyStack.push("{"); } ++this.index; break; case ".": ++this.index; if (this.source[this.index] === "." && this.source[this.index + 1] === ".") { this.index += 2; str2 = "..."; } break; case "}": ++this.index; this.curlyStack.pop(); break; case ")": case ";": case ",": case "[": case "]": case ":": case "?": case "~": ++this.index; break; default: str2 = this.source.substr(this.index, 4); if (str2 === ">>>=") { this.index += 4; } else { str2 = str2.substr(0, 3); if (str2 === "===" || str2 === "!==" || str2 === ">>>" || str2 === "<<=" || str2 === ">>=" || str2 === "**=") { this.index += 3; } else { str2 = str2.substr(0, 2); if (str2 === "&&" || str2 === "||" || str2 === "==" || str2 === "!=" || str2 === "+=" || str2 === "-=" || str2 === "*=" || str2 === "/=" || str2 === "++" || str2 === "--" || str2 === "<<" || str2 === ">>" || str2 === "&=" || str2 === "|=" || str2 === "^=" || str2 === "%=" || str2 === "<=" || str2 === ">=" || str2 === "=>" || str2 === "**") { this.index += 2; } else { str2 = this.source[this.index]; if ("<>=!+-*%&|^/".indexOf(str2) >= 0) { ++this.index; } } } } } if (this.index === start) { this.throwUnexpectedToken(); } return { type: 7, value: str2, lineNumber: this.lineNumber, lineStart: this.lineStart, start, end: this.index }; }; Scanner2.prototype.scanHexLiteral = function(start) { var num = ""; while (!this.eof()) { if (!character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) { break; } num += this.source[this.index++]; } if (num.length === 0) { this.throwUnexpectedToken(); } if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) { this.throwUnexpectedToken(); } return { type: 6, value: parseInt("0x" + num, 16), lineNumber: this.lineNumber, lineStart: this.lineStart, start, end: this.index }; }; Scanner2.prototype.scanBinaryLiteral = function(start) { var num = ""; var ch; while (!this.eof()) { ch = this.source[this.index]; if (ch !== "0" && ch !== "1") { break; } num += this.source[this.index++]; } if (num.length === 0) { this.throwUnexpectedToken(); } if (!this.eof()) { ch = this.source.charCodeAt(this.index); if (character_1.Character.isIdentifierStart(ch) || character_1.Character.isDecimalDigit(ch)) { this.throwUnexpectedToken(); } } return { type: 6, value: parseInt(num, 2), lineNumber: this.lineNumber, lineStart: this.lineStart, start, end: this.index }; }; Scanner2.prototype.scanOctalLiteral = function(prefix, start) { var num = ""; var octal = false; if (character_1.Character.isOctalDigit(prefix.charCodeAt(0))) { octal = true; num = "0" + this.source[this.index++]; } else { ++this.index; } while (!this.eof()) { if (!character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) { break; } num += this.source[this.index++]; } if (!octal && num.length === 0) { this.throwUnexpectedToken(); } if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index)) || character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { this.throwUnexpectedToken(); } return { type: 6, value: parseInt(num, 8), octal, lineNumber: this.lineNumber, lineStart: this.lineStart, start, end: this.index }; }; Scanner2.prototype.isImplicitOctalLiteral = function() { for (var i2 = this.index + 1; i2 < this.length; ++i2) { var ch = this.source[i2]; if (ch === "8" || ch === "9") { return false; } if (!character_1.Character.isOctalDigit(ch.charCodeAt(0))) { return true; } } return true; }; Scanner2.prototype.scanNumericLiteral = function() { var start = this.index; var ch = this.source[start]; assert_1.assert(character_1.Character.isDecimalDigit(ch.charCodeAt(0)) || ch === ".", "Numeric literal must start with a decimal digit or a decimal point"); var num = ""; if (ch !== ".") { num = this.source[this.index++]; ch = this.source[this.index]; if (num === "0") { if (ch === "x" || ch === "X") { ++this.index; return this.scanHexLiteral(start); } if (ch === "b" || ch === "B") { ++this.index; return this.scanBinaryLiteral(start); } if (ch === "o" || ch === "O") { return this.scanOctalLiteral(ch, start); } if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) { if (this.isImplicitOctalLiteral()) { return this.scanOctalLiteral(ch, start); } } } while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { num += this.source[this.index++]; } ch = this.source[this.index]; } if (ch === ".") { num += this.source[this.index++]; while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { num += this.source[this.index++]; } ch = this.source[this.index]; } if (ch === "e" || ch === "E") { num += this.source[this.index++]; ch = this.source[this.index]; if (ch === "+" || ch === "-") { num += this.source[this.index++]; } if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { num += this.source[this.index++]; } } else { this.throwUnexpectedToken(); } } if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) { this.throwUnexpectedToken(); } return { type: 6, value: parseFloat(num), lineNumber: this.lineNumber, lineStart: this.lineStart, start, end: this.index }; }; Scanner2.prototype.scanStringLiteral = function() { var start = this.index; var quote = this.source[start]; assert_1.assert(quote === "'" || quote === '"', "String literal must starts with a quote"); ++this.index; var octal = false; var str2 = ""; while (!this.eof()) { var ch = this.source[this.index++]; if (ch === quote) { quote = ""; break; } else if (ch === "\\") { ch = this.source[this.index++]; if (!ch || !character_1.Character.isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case "u": if (this.source[this.index] === "{") { ++this.index; str2 += this.scanUnicodeCodePointEscape(); } else { var unescaped_1 = this.scanHexEscape(ch); if (unescaped_1 === null) { this.throwUnexpectedToken(); } str2 += unescaped_1; } break; case "x": var unescaped = this.scanHexEscape(ch); if (unescaped === null) { this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence); } str2 += unescaped; break; case "n": str2 += "\n"; break; case "r": str2 += "\r"; break; case "t": str2 += " "; break; case "b": str2 += "\b"; break; case "f": str2 += "\f"; break; case "v": str2 += "\v"; break; case "8": case "9": str2 += ch; this.tolerateUnexpectedToken(); break; default: if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) { var octToDec = this.octalToDecimal(ch); octal = octToDec.octal || octal; str2 += String.fromCharCode(octToDec.code); } else { str2 += ch; } break; } } else { ++this.lineNumber; if (ch === "\r" && this.source[this.index] === "\n") { ++this.index; } this.lineStart = this.index; } } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { break; } else { str2 += ch; } } if (quote !== "") { this.index = start; this.throwUnexpectedToken(); } return { type: 8, value: str2, octal, lineNumber: this.lineNumber, lineStart: this.lineStart, start, end: this.index }; }; Scanner2.prototype.scanTemplate = function() { var cooked = ""; var terminated = false; var start = this.index; var head = this.source[start] === "`"; var tail = false; var rawOffset = 2; ++this.index; while (!this.eof()) { var ch = this.source[this.index++]; if (ch === "`") { rawOffset = 1; tail = true; terminated = true; break; } else if (ch === "$") { if (this.source[this.index] === "{") { this.curlyStack.push("${"); ++this.index; terminated = true; break; } cooked += ch; } else if (ch === "\\") { ch = this.source[this.index++]; if (!character_1.Character.isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case "n": cooked += "\n"; break; case "r": cooked += "\r"; break; case "t": cooked += " "; break; case "u": if (this.source[this.index] === "{") { ++this.index; cooked += this.scanUnicodeCodePointEscape(); } else { var restore = this.index; var unescaped_2 = this.scanHexEscape(ch); if (unescaped_2 !== null) { cooked += unescaped_2; } else { this.index = restore; cooked += ch; } } break; case "x": var unescaped = this.scanHexEscape(ch); if (unescaped === null) { this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence); } cooked += unescaped; break; case "b": cooked += "\b"; break; case "f": cooked += "\f"; break; case "v": cooked += "\v"; break; default: if (ch === "0") { if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral); } cooked += "\0"; } else if (character_1.Character.isOctalDigit(ch.charCodeAt(0))) { this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral); } else { cooked += ch; } break; } } else { ++this.lineNumber; if (ch === "\r" && this.source[this.index] === "\n") { ++this.index; } this.lineStart = this.index; } } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { ++this.lineNumber; if (ch === "\r" && this.source[this.index] === "\n") { ++this.index; } this.lineStart = this.index; cooked += "\n"; } else { cooked += ch; } } if (!terminated) { this.throwUnexpectedToken(); } if (!head) { this.curlyStack.pop(); } return { type: 10, value: this.source.slice(start + 1, this.index - rawOffset), cooked, head, tail, lineNumber: this.lineNumber, lineStart: this.lineStart, start, end: this.index }; }; Scanner2.prototype.testRegExp = function(pattern, flags) { var astralSubstitute = "\uFFFF"; var tmp = pattern; var self2 = this; if (flags.indexOf("u") >= 0) { tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function($0, $1, $2) { var codePoint = parseInt($1 || $2, 16); if (codePoint > 1114111) { self2.throwUnexpectedToken(messages_1.Messages.InvalidRegExp); } if (codePoint <= 65535) { return String.fromCharCode(codePoint); } return astralSubstitute; }).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, astralSubstitute); } try { RegExp(tmp); } catch (e2) { this.throwUnexpectedToken(messages_1.Messages.InvalidRegExp); } try { return new RegExp(pattern, flags); } catch (exception2) { return null; } }; Scanner2.prototype.scanRegExpBody = function() { var ch = this.source[this.index]; assert_1.assert(ch === "/", "Regular expression literal must start with a slash"); var str2 = this.source[this.index++]; var classMarker = false; var terminated = false; while (!this.eof()) { ch = this.source[this.index++]; str2 += ch; if (ch === "\\") { ch = this.source[this.index++]; if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp); } str2 += ch; } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp); } else if (classMarker) { if (ch === "]") { classMarker = false; } } else { if (ch === "/") { terminated = true; break; } else if (ch === "[") { classMarker = true; } } } if (!terminated) { this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp); } return str2.substr(1, str2.length - 2); }; Scanner2.prototype.scanRegExpFlags = function() { var str2 = ""; var flags = ""; while (!this.eof()) { var ch = this.source[this.index]; if (!character_1.Character.isIdentifierPart(ch.charCodeAt(0))) { break; } ++this.index; if (ch === "\\" && !this.eof()) { ch = this.source[this.index]; if (ch === "u") { ++this.index; var restore = this.index; var char = this.scanHexEscape("u"); if (char !== null) { flags += char; for (str2 += "\\u"; restore < this.index; ++restore) { str2 += this.source[restore]; } } else { this.index = restore; flags += "u"; str2 += "\\u"; } this.tolerateUnexpectedToken(); } else { str2 += "\\"; this.tolerateUnexpectedToken(); } } else { flags += ch; str2 += ch; } } return flags; }; Scanner2.prototype.scanRegExp = function() { var start = this.index; var pattern = this.scanRegExpBody(); var flags = this.scanRegExpFlags(); var value = this.testRegExp(pattern, flags); return { type: 9, value: "", pattern, flags, regex: value, lineNumber: this.lineNumber, lineStart: this.lineStart, start, end: this.index }; }; Scanner2.prototype.lex = function() { if (this.eof()) { return { type: 2, value: "", lineNumber: this.lineNumber, lineStart: this.lineStart, start: this.index, end: this.index }; } var cp = this.source.charCodeAt(this.index); if (character_1.Character.isIdentifierStart(cp)) { return this.scanIdentifier(); } if (cp === 40 || cp === 41 || cp === 59) { return this.scanPunctuator(); } if (cp === 39 || cp === 34) { return this.scanStringLiteral(); } if (cp === 46) { if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index + 1))) { return this.scanNumericLiteral(); } return this.scanPunctuator(); } if (character_1.Character.isDecimalDigit(cp)) { return this.scanNumericLiteral(); } if (cp === 96 || cp === 125 && this.curlyStack[this.curlyStack.length - 1] === "${") { return this.scanTemplate(); } if (cp >= 55296 && cp < 57343) { if (character_1.Character.isIdentifierStart(this.codePointAt(this.index))) { return this.scanIdentifier(); } } return this.scanPunctuator(); }; return Scanner2; }(); exports2.Scanner = Scanner; }, /* 13 */ /***/ function(module3, exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.TokenName = {}; exports2.TokenName[ 1 /* BooleanLiteral */ ] = "Boolean"; exports2.TokenName[ 2 /* EOF */ ] = ""; exports2.TokenName[ 3 /* Identifier */ ] = "Identifier"; exports2.TokenName[ 4 /* Keyword */ ] = "Keyword"; exports2.TokenName[ 5 /* NullLiteral */ ] = "Null"; exports2.TokenName[ 6 /* NumericLiteral */ ] = "Numeric"; exports2.TokenName[ 7 /* Punctuator */ ] = "Punctuator"; exports2.TokenName[ 8 /* StringLiteral */ ] = "String"; exports2.TokenName[ 9 /* RegularExpression */ ] = "RegularExpression"; exports2.TokenName[ 10 /* Template */ ] = "Template"; }, /* 14 */ /***/ function(module3, exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.XHTMLEntities = { quot: '"', amp: "&", apos: "'", gt: ">", nbsp: "\xA0", iexcl: "\xA1", cent: "\xA2", pound: "\xA3", curren: "\xA4", yen: "\xA5", brvbar: "\xA6", sect: "\xA7", uml: "\xA8", copy: "\xA9", ordf: "\xAA", laquo: "\xAB", not: "\xAC", shy: "\xAD", reg: "\xAE", macr: "\xAF", deg: "\xB0", plusmn: "\xB1", sup2: "\xB2", sup3: "\xB3", acute: "\xB4", micro: "\xB5", para: "\xB6", middot: "\xB7", cedil: "\xB8", sup1: "\xB9", ordm: "\xBA", raquo: "\xBB", frac14: "\xBC", frac12: "\xBD", frac34: "\xBE", iquest: "\xBF", Agrave: "\xC0", Aacute: "\xC1", Acirc: "\xC2", Atilde: "\xC3", Auml: "\xC4", Aring: "\xC5", AElig: "\xC6", Ccedil: "\xC7", Egrave: "\xC8", Eacute: "\xC9", Ecirc: "\xCA", Euml: "\xCB", Igrave: "\xCC", Iacute: "\xCD", Icirc: "\xCE", Iuml: "\xCF", ETH: "\xD0", Ntilde: "\xD1", Ograve: "\xD2", Oacute: "\xD3", Ocirc: "\xD4", Otilde: "\xD5", Ouml: "\xD6", times: "\xD7", Oslash: "\xD8", Ugrave: "\xD9", Uacute: "\xDA", Ucirc: "\xDB", Uuml: "\xDC", Yacute: "\xDD", THORN: "\xDE", szlig: "\xDF", agrave: "\xE0", aacute: "\xE1", acirc: "\xE2", atilde: "\xE3", auml: "\xE4", aring: "\xE5", aelig: "\xE6", ccedil: "\xE7", egrave: "\xE8", eacute: "\xE9", ecirc: "\xEA", euml: "\xEB", igrave: "\xEC", iacute: "\xED", icirc: "\xEE", iuml: "\xEF", eth: "\xF0", ntilde: "\xF1", ograve: "\xF2", oacute: "\xF3", ocirc: "\xF4", otilde: "\xF5", ouml: "\xF6", divide: "\xF7", oslash: "\xF8", ugrave: "\xF9", uacute: "\xFA", ucirc: "\xFB", uuml: "\xFC", yacute: "\xFD", thorn: "\xFE", yuml: "\xFF", OElig: "\u0152", oelig: "\u0153", Scaron: "\u0160", scaron: "\u0161", Yuml: "\u0178", fnof: "\u0192", circ: "\u02C6", tilde: "\u02DC", Alpha: "\u0391", Beta: "\u0392", Gamma: "\u0393", Delta: "\u0394", Epsilon: "\u0395", Zeta: "\u0396", Eta: "\u0397", Theta: "\u0398", Iota: "\u0399", Kappa: "\u039A", Lambda: "\u039B", Mu: "\u039C", Nu: "\u039D", Xi: "\u039E", Omicron: "\u039F", Pi: "\u03A0", Rho: "\u03A1", Sigma: "\u03A3", Tau: "\u03A4", Upsilon: "\u03A5", Phi: "\u03A6", Chi: "\u03A7", Psi: "\u03A8", Omega: "\u03A9", alpha: "\u03B1", beta: "\u03B2", gamma: "\u03B3", delta: "\u03B4", epsilon: "\u03B5", zeta: "\u03B6", eta: "\u03B7", theta: "\u03B8", iota: "\u03B9", kappa: "\u03BA", lambda: "\u03BB", mu: "\u03BC", nu: "\u03BD", xi: "\u03BE", omicron: "\u03BF", pi: "\u03C0", rho: "\u03C1", sigmaf: "\u03C2", sigma: "\u03C3", tau: "\u03C4", upsilon: "\u03C5", phi: "\u03C6", chi: "\u03C7", psi: "\u03C8", omega: "\u03C9", thetasym: "\u03D1", upsih: "\u03D2", piv: "\u03D6", ensp: "\u2002", emsp: "\u2003", thinsp: "\u2009", zwnj: "\u200C", zwj: "\u200D", lrm: "\u200E", rlm: "\u200F", ndash: "\u2013", mdash: "\u2014", lsquo: "\u2018", rsquo: "\u2019", sbquo: "\u201A", ldquo: "\u201C", rdquo: "\u201D", bdquo: "\u201E", dagger: "\u2020", Dagger: "\u2021", bull: "\u2022", hellip: "\u2026", permil: "\u2030", prime: "\u2032", Prime: "\u2033", lsaquo: "\u2039", rsaquo: "\u203A", oline: "\u203E", frasl: "\u2044", euro: "\u20AC", image: "\u2111", weierp: "\u2118", real: "\u211C", trade: "\u2122", alefsym: "\u2135", larr: "\u2190", uarr: "\u2191", rarr: "\u2192", darr: "\u2193", harr: "\u2194", crarr: "\u21B5", lArr: "\u21D0", uArr: "\u21D1", rArr: "\u21D2", dArr: "\u21D3", hArr: "\u21D4", forall: "\u2200", part: "\u2202", exist: "\u2203", empty: "\u2205", nabla: "\u2207", isin: "\u2208", notin: "\u2209", ni: "\u220B", prod: "\u220F", sum: "\u2211", minus: "\u2212", lowast: "\u2217", radic: "\u221A", prop: "\u221D", infin: "\u221E", ang: "\u2220", and: "\u2227", or: "\u2228", cap: "\u2229", cup: "\u222A", int: "\u222B", there4: "\u2234", sim: "\u223C", cong: "\u2245", asymp: "\u2248", ne: "\u2260", equiv: "\u2261", le: "\u2264", ge: "\u2265", sub: "\u2282", sup: "\u2283", nsub: "\u2284", sube: "\u2286", supe: "\u2287", oplus: "\u2295", otimes: "\u2297", perp: "\u22A5", sdot: "\u22C5", lceil: "\u2308", rceil: "\u2309", lfloor: "\u230A", rfloor: "\u230B", loz: "\u25CA", spades: "\u2660", clubs: "\u2663", hearts: "\u2665", diams: "\u2666", lang: "\u27E8", rang: "\u27E9" }; }, /* 15 */ /***/ function(module3, exports2, __webpack_require__) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var error_handler_1 = __webpack_require__(10); var scanner_1 = __webpack_require__(12); var token_1 = __webpack_require__(13); var Reader = function() { function Reader2() { this.values = []; this.curly = this.paren = -1; } Reader2.prototype.beforeFunctionExpression = function(t2) { return [ "(", "{", "[", "in", "typeof", "instanceof", "new", "return", "case", "delete", "throw", "void", // assignment operators "=", "+=", "-=", "*=", "**=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", ",", // binary/unary operators "+", "-", "*", "**", "/", "%", "++", "--", "<<", ">>", ">>>", "&", "|", "^", "!", "~", "&&", "||", "?", ":", "===", "==", ">=", "<=", "<", ">", "!=", "!==" ].indexOf(t2) >= 0; }; Reader2.prototype.isRegexStart = function() { var previous3 = this.values[this.values.length - 1]; var regex = previous3 !== null; switch (previous3) { case "this": case "]": regex = false; break; case ")": var keyword = this.values[this.paren - 1]; regex = keyword === "if" || keyword === "while" || keyword === "for" || keyword === "with"; break; case "}": regex = false; if (this.values[this.curly - 3] === "function") { var check = this.values[this.curly - 4]; regex = check ? !this.beforeFunctionExpression(check) : false; } else if (this.values[this.curly - 4] === "function") { var check = this.values[this.curly - 5]; regex = check ? !this.beforeFunctionExpression(check) : true; } break; default: break; } return regex; }; Reader2.prototype.push = function(token) { if (token.type === 7 || token.type === 4) { if (token.value === "{") { this.curly = this.values.length; } else if (token.value === "(") { this.paren = this.values.length; } this.values.push(token.value); } else { this.values.push(null); } }; return Reader2; }(); var Tokenizer = function() { function Tokenizer2(code, config) { this.errorHandler = new error_handler_1.ErrorHandler(); this.errorHandler.tolerant = config ? typeof config.tolerant === "boolean" && config.tolerant : false; this.scanner = new scanner_1.Scanner(code, this.errorHandler); this.scanner.trackComment = config ? typeof config.comment === "boolean" && config.comment : false; this.trackRange = config ? typeof config.range === "boolean" && config.range : false; this.trackLoc = config ? typeof config.loc === "boolean" && config.loc : false; this.buffer = []; this.reader = new Reader(); } Tokenizer2.prototype.errors = function() { return this.errorHandler.errors; }; Tokenizer2.prototype.getNextToken = function() { if (this.buffer.length === 0) { var comments = this.scanner.scanComments(); if (this.scanner.trackComment) { for (var i2 = 0; i2 < comments.length; ++i2) { var e2 = comments[i2]; var value = this.scanner.source.slice(e2.slice[0], e2.slice[1]); var comment = { type: e2.multiLine ? "BlockComment" : "LineComment", value }; if (this.trackRange) { comment.range = e2.range; } if (this.trackLoc) { comment.loc = e2.loc; } this.buffer.push(comment); } } if (!this.scanner.eof()) { var loc = void 0; if (this.trackLoc) { loc = { start: { line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart }, end: {} }; } var startRegex = this.scanner.source[this.scanner.index] === "/" && this.reader.isRegexStart(); var token = startRegex ? this.scanner.scanRegExp() : this.scanner.lex(); this.reader.push(token); var entry = { type: token_1.TokenName[token.type], value: this.scanner.source.slice(token.start, token.end) }; if (this.trackRange) { entry.range = [token.start, token.end]; } if (this.trackLoc) { loc.end = { line: this.scanner.lineNumber, column: this.scanner.index - this.scanner.lineStart }; entry.loc = loc; } if (token.type === 9) { var pattern = token.pattern; var flags = token.flags; entry.regex = { pattern, flags }; } this.buffer.push(entry); } } return this.buffer.shift(); }; return Tokenizer2; }(); exports2.Tokenizer = Tokenizer; } /******/ ]) ); }); } }); // node_modules/recast/parsers/esprima.js var require_esprima3 = __commonJS({ "node_modules/recast/parsers/esprima.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parse = void 0; var util_1 = require_util2(); function parse3(source, options) { var comments = []; var ast = require_esprima2().parse(source, { loc: true, locations: true, comment: true, onComment: comments, range: (0, util_1.getOption)(options, "range", false), tolerant: (0, util_1.getOption)(options, "tolerant", true), tokens: true, jsx: (0, util_1.getOption)(options, "jsx", false), sourceType: (0, util_1.getOption)(options, "sourceType", "module") }); if (!Array.isArray(ast.comments)) { ast.comments = comments; } return ast; } exports.parse = parse3; } }); // node_modules/recast/lib/options.js var require_options = __commonJS({ "node_modules/recast/lib/options.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.normalize = void 0; var util_1 = require_util2(); var defaults = { parser: require_esprima3(), tabWidth: 4, useTabs: false, reuseWhitespace: true, lineTerminator: (0, util_1.getLineTerminator)(), wrapColumn: 74, sourceFileName: null, sourceMapName: null, sourceRoot: null, inputSourceMap: null, range: false, tolerant: true, quote: null, trailingComma: false, arrayBracketSpacing: false, objectCurlySpacing: true, arrowParensAlways: false, flowObjectCommas: true, tokens: true }; var hasOwn = defaults.hasOwnProperty; function normalize(opts) { var options = opts || defaults; function get(key) { return hasOwn.call(options, key) ? options[key] : defaults[key]; } return { tabWidth: +get("tabWidth"), useTabs: !!get("useTabs"), reuseWhitespace: !!get("reuseWhitespace"), lineTerminator: get("lineTerminator"), wrapColumn: Math.max(get("wrapColumn"), 0), sourceFileName: get("sourceFileName"), sourceMapName: get("sourceMapName"), sourceRoot: get("sourceRoot"), inputSourceMap: get("inputSourceMap"), parser: get("esprima") || get("parser"), range: get("range"), tolerant: get("tolerant"), quote: get("quote"), trailingComma: get("trailingComma"), arrayBracketSpacing: get("arrayBracketSpacing"), objectCurlySpacing: get("objectCurlySpacing"), arrowParensAlways: get("arrowParensAlways"), flowObjectCommas: get("flowObjectCommas"), tokens: !!get("tokens") }; } exports.normalize = normalize; } }); // node_modules/recast/lib/mapping.js var require_mapping = __commonJS({ "node_modules/recast/lib/mapping.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); var assert_1 = tslib_1.__importDefault(require("assert")); var util_1 = require_util2(); var Mapping = ( /** @class */ function() { function Mapping2(sourceLines, sourceLoc, targetLoc) { if (targetLoc === void 0) { targetLoc = sourceLoc; } this.sourceLines = sourceLines; this.sourceLoc = sourceLoc; this.targetLoc = targetLoc; } Mapping2.prototype.slice = function(lines, start, end) { if (end === void 0) { end = lines.lastPos(); } var sourceLines = this.sourceLines; var sourceLoc = this.sourceLoc; var targetLoc = this.targetLoc; function skip(name) { var sourceFromPos = sourceLoc[name]; var targetFromPos = targetLoc[name]; var targetToPos = start; if (name === "end") { targetToPos = end; } else { assert_1.default.strictEqual(name, "start"); } return skipChars(sourceLines, sourceFromPos, lines, targetFromPos, targetToPos); } if ((0, util_1.comparePos)(start, targetLoc.start) <= 0) { if ((0, util_1.comparePos)(targetLoc.end, end) <= 0) { targetLoc = { start: subtractPos(targetLoc.start, start.line, start.column), end: subtractPos(targetLoc.end, start.line, start.column) }; } else if ((0, util_1.comparePos)(end, targetLoc.start) <= 0) { return null; } else { sourceLoc = { start: sourceLoc.start, end: skip("end") }; targetLoc = { start: subtractPos(targetLoc.start, start.line, start.column), end: subtractPos(end, start.line, start.column) }; } } else { if ((0, util_1.comparePos)(targetLoc.end, start) <= 0) { return null; } if ((0, util_1.comparePos)(targetLoc.end, end) <= 0) { sourceLoc = { start: skip("start"), end: sourceLoc.end }; targetLoc = { // Same as subtractPos(start, start.line, start.column): start: { line: 1, column: 0 }, end: subtractPos(targetLoc.end, start.line, start.column) }; } else { sourceLoc = { start: skip("start"), end: skip("end") }; targetLoc = { // Same as subtractPos(start, start.line, start.column): start: { line: 1, column: 0 }, end: subtractPos(end, start.line, start.column) }; } } return new Mapping2(this.sourceLines, sourceLoc, targetLoc); }; Mapping2.prototype.add = function(line, column) { return new Mapping2(this.sourceLines, this.sourceLoc, { start: addPos(this.targetLoc.start, line, column), end: addPos(this.targetLoc.end, line, column) }); }; Mapping2.prototype.subtract = function(line, column) { return new Mapping2(this.sourceLines, this.sourceLoc, { start: subtractPos(this.targetLoc.start, line, column), end: subtractPos(this.targetLoc.end, line, column) }); }; Mapping2.prototype.indent = function(by, skipFirstLine, noNegativeColumns) { if (skipFirstLine === void 0) { skipFirstLine = false; } if (noNegativeColumns === void 0) { noNegativeColumns = false; } if (by === 0) { return this; } var targetLoc = this.targetLoc; var startLine = targetLoc.start.line; var endLine = targetLoc.end.line; if (skipFirstLine && startLine === 1 && endLine === 1) { return this; } targetLoc = { start: targetLoc.start, end: targetLoc.end }; if (!skipFirstLine || startLine > 1) { var startColumn = targetLoc.start.column + by; targetLoc.start = { line: startLine, column: noNegativeColumns ? Math.max(0, startColumn) : startColumn }; } if (!skipFirstLine || endLine > 1) { var endColumn = targetLoc.end.column + by; targetLoc.end = { line: endLine, column: noNegativeColumns ? Math.max(0, endColumn) : endColumn }; } return new Mapping2(this.sourceLines, this.sourceLoc, targetLoc); }; return Mapping2; }() ); exports.default = Mapping; function addPos(toPos, line, column) { return { line: toPos.line + line - 1, column: toPos.line === 1 ? toPos.column + column : toPos.column }; } function subtractPos(fromPos, line, column) { return { line: fromPos.line - line + 1, column: fromPos.line === line ? fromPos.column - column : fromPos.column }; } function skipChars(sourceLines, sourceFromPos, targetLines, targetFromPos, targetToPos) { var targetComparison = (0, util_1.comparePos)(targetFromPos, targetToPos); if (targetComparison === 0) { return sourceFromPos; } var sourceCursor, targetCursor; if (targetComparison < 0) { sourceCursor = sourceLines.skipSpaces(sourceFromPos) || sourceLines.lastPos(); targetCursor = targetLines.skipSpaces(targetFromPos) || targetLines.lastPos(); var lineDiff = targetToPos.line - targetCursor.line; sourceCursor.line += lineDiff; targetCursor.line += lineDiff; if (lineDiff > 0) { sourceCursor.column = 0; targetCursor.column = 0; } else { assert_1.default.strictEqual(lineDiff, 0); } while ((0, util_1.comparePos)(targetCursor, targetToPos) < 0 && targetLines.nextPos(targetCursor, true)) { assert_1.default.ok(sourceLines.nextPos(sourceCursor, true)); assert_1.default.strictEqual(sourceLines.charAt(sourceCursor), targetLines.charAt(targetCursor)); } } else { sourceCursor = sourceLines.skipSpaces(sourceFromPos, true) || sourceLines.firstPos(); targetCursor = targetLines.skipSpaces(targetFromPos, true) || targetLines.firstPos(); var lineDiff = targetToPos.line - targetCursor.line; sourceCursor.line += lineDiff; targetCursor.line += lineDiff; if (lineDiff < 0) { sourceCursor.column = sourceLines.getLineLength(sourceCursor.line); targetCursor.column = targetLines.getLineLength(targetCursor.line); } else { assert_1.default.strictEqual(lineDiff, 0); } while ((0, util_1.comparePos)(targetToPos, targetCursor) < 0 && targetLines.prevPos(targetCursor, true)) { assert_1.default.ok(sourceLines.prevPos(sourceCursor, true)); assert_1.default.strictEqual(sourceLines.charAt(sourceCursor), targetLines.charAt(targetCursor)); } } return sourceCursor; } } }); // node_modules/recast/lib/lines.js var require_lines = __commonJS({ "node_modules/recast/lib/lines.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.concat = exports.fromString = exports.countSpaces = exports.Lines = void 0; var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); var assert_1 = tslib_1.__importDefault(require("assert")); var source_map_1 = tslib_1.__importDefault(require_source_map()); var options_1 = require_options(); var util_1 = require_util2(); var mapping_1 = tslib_1.__importDefault(require_mapping()); var Lines = ( /** @class */ function() { function Lines2(infos, sourceFileName) { if (sourceFileName === void 0) { sourceFileName = null; } this.infos = infos; this.mappings = []; this.cachedSourceMap = null; this.cachedTabWidth = void 0; assert_1.default.ok(infos.length > 0); this.length = infos.length; this.name = sourceFileName || null; if (this.name) { this.mappings.push(new mapping_1.default(this, { start: this.firstPos(), end: this.lastPos() })); } } Lines2.prototype.toString = function(options) { return this.sliceString(this.firstPos(), this.lastPos(), options); }; Lines2.prototype.getSourceMap = function(sourceMapName, sourceRoot) { if (!sourceMapName) { return null; } var targetLines = this; function updateJSON(json2) { json2 = json2 || {}; json2.file = sourceMapName; if (sourceRoot) { json2.sourceRoot = sourceRoot; } return json2; } if (targetLines.cachedSourceMap) { return updateJSON(targetLines.cachedSourceMap.toJSON()); } var smg = new source_map_1.default.SourceMapGenerator(updateJSON()); var sourcesToContents = {}; targetLines.mappings.forEach(function(mapping) { var sourceCursor = mapping.sourceLines.skipSpaces(mapping.sourceLoc.start) || mapping.sourceLines.lastPos(); var targetCursor = targetLines.skipSpaces(mapping.targetLoc.start) || targetLines.lastPos(); while ((0, util_1.comparePos)(sourceCursor, mapping.sourceLoc.end) < 0 && (0, util_1.comparePos)(targetCursor, mapping.targetLoc.end) < 0) { var sourceChar = mapping.sourceLines.charAt(sourceCursor); var targetChar = targetLines.charAt(targetCursor); assert_1.default.strictEqual(sourceChar, targetChar); var sourceName = mapping.sourceLines.name; smg.addMapping({ source: sourceName, original: { line: sourceCursor.line, column: sourceCursor.column }, generated: { line: targetCursor.line, column: targetCursor.column } }); if (!hasOwn.call(sourcesToContents, sourceName)) { var sourceContent = mapping.sourceLines.toString(); smg.setSourceContent(sourceName, sourceContent); sourcesToContents[sourceName] = sourceContent; } targetLines.nextPos(targetCursor, true); mapping.sourceLines.nextPos(sourceCursor, true); } }); targetLines.cachedSourceMap = smg; return smg.toJSON(); }; Lines2.prototype.bootstrapCharAt = function(pos) { assert_1.default.strictEqual(typeof pos, "object"); assert_1.default.strictEqual(typeof pos.line, "number"); assert_1.default.strictEqual(typeof pos.column, "number"); var line = pos.line, column = pos.column, strings = this.toString().split(lineTerminatorSeqExp), string3 = strings[line - 1]; if (typeof string3 === "undefined") return ""; if (column === string3.length && line < strings.length) return "\n"; if (column >= string3.length) return ""; return string3.charAt(column); }; Lines2.prototype.charAt = function(pos) { assert_1.default.strictEqual(typeof pos, "object"); assert_1.default.strictEqual(typeof pos.line, "number"); assert_1.default.strictEqual(typeof pos.column, "number"); var line = pos.line, column = pos.column, secret = this, infos = secret.infos, info = infos[line - 1], c2 = column; if (typeof info === "undefined" || c2 < 0) return ""; var indent2 = this.getIndentAt(line); if (c2 < indent2) return " "; c2 += info.sliceStart - indent2; if (c2 === info.sliceEnd && line < this.length) return "\n"; if (c2 >= info.sliceEnd) return ""; return info.line.charAt(c2); }; Lines2.prototype.stripMargin = function(width, skipFirstLine) { if (width === 0) return this; assert_1.default.ok(width > 0, "negative margin: " + width); if (skipFirstLine && this.length === 1) return this; var lines = new Lines2(this.infos.map(function(info, i2) { if (info.line && (i2 > 0 || !skipFirstLine)) { info = tslib_1.__assign(tslib_1.__assign({}, info), { indent: Math.max(0, info.indent - width) }); } return info; })); if (this.mappings.length > 0) { var newMappings_1 = lines.mappings; assert_1.default.strictEqual(newMappings_1.length, 0); this.mappings.forEach(function(mapping) { newMappings_1.push(mapping.indent(width, skipFirstLine, true)); }); } return lines; }; Lines2.prototype.indent = function(by) { if (by === 0) { return this; } var lines = new Lines2(this.infos.map(function(info) { if (info.line && !info.locked) { info = tslib_1.__assign(tslib_1.__assign({}, info), { indent: info.indent + by }); } return info; })); if (this.mappings.length > 0) { var newMappings_2 = lines.mappings; assert_1.default.strictEqual(newMappings_2.length, 0); this.mappings.forEach(function(mapping) { newMappings_2.push(mapping.indent(by)); }); } return lines; }; Lines2.prototype.indentTail = function(by) { if (by === 0) { return this; } if (this.length < 2) { return this; } var lines = new Lines2(this.infos.map(function(info, i2) { if (i2 > 0 && info.line && !info.locked) { info = tslib_1.__assign(tslib_1.__assign({}, info), { indent: info.indent + by }); } return info; })); if (this.mappings.length > 0) { var newMappings_3 = lines.mappings; assert_1.default.strictEqual(newMappings_3.length, 0); this.mappings.forEach(function(mapping) { newMappings_3.push(mapping.indent(by, true)); }); } return lines; }; Lines2.prototype.lockIndentTail = function() { if (this.length < 2) { return this; } return new Lines2(this.infos.map(function(info, i2) { return tslib_1.__assign(tslib_1.__assign({}, info), { locked: i2 > 0 }); })); }; Lines2.prototype.getIndentAt = function(line) { assert_1.default.ok(line >= 1, "no line " + line + " (line numbers start from 1)"); return Math.max(this.infos[line - 1].indent, 0); }; Lines2.prototype.guessTabWidth = function() { if (typeof this.cachedTabWidth === "number") { return this.cachedTabWidth; } var counts = []; var lastIndent = 0; for (var line = 1, last = this.length; line <= last; ++line) { var info = this.infos[line - 1]; var sliced = info.line.slice(info.sliceStart, info.sliceEnd); if (isOnlyWhitespace(sliced)) { continue; } var diff = Math.abs(info.indent - lastIndent); counts[diff] = ~~counts[diff] + 1; lastIndent = info.indent; } var maxCount = -1; var result = 2; for (var tabWidth = 1; tabWidth < counts.length; tabWidth += 1) { if (hasOwn.call(counts, tabWidth) && counts[tabWidth] > maxCount) { maxCount = counts[tabWidth]; result = tabWidth; } } return this.cachedTabWidth = result; }; Lines2.prototype.startsWithComment = function() { if (this.infos.length === 0) { return false; } var firstLineInfo = this.infos[0], sliceStart = firstLineInfo.sliceStart, sliceEnd = firstLineInfo.sliceEnd, firstLine = firstLineInfo.line.slice(sliceStart, sliceEnd).trim(); return firstLine.length === 0 || firstLine.slice(0, 2) === "//" || firstLine.slice(0, 2) === "/*"; }; Lines2.prototype.isOnlyWhitespace = function() { return isOnlyWhitespace(this.toString()); }; Lines2.prototype.isPrecededOnlyByWhitespace = function(pos) { var info = this.infos[pos.line - 1]; var indent2 = Math.max(info.indent, 0); var diff = pos.column - indent2; if (diff <= 0) { return true; } var start = info.sliceStart; var end = Math.min(start + diff, info.sliceEnd); var prefix = info.line.slice(start, end); return isOnlyWhitespace(prefix); }; Lines2.prototype.getLineLength = function(line) { var info = this.infos[line - 1]; return this.getIndentAt(line) + info.sliceEnd - info.sliceStart; }; Lines2.prototype.nextPos = function(pos, skipSpaces) { if (skipSpaces === void 0) { skipSpaces = false; } var l = Math.max(pos.line, 0), c2 = Math.max(pos.column, 0); if (c2 < this.getLineLength(l)) { pos.column += 1; return skipSpaces ? !!this.skipSpaces(pos, false, true) : true; } if (l < this.length) { pos.line += 1; pos.column = 0; return skipSpaces ? !!this.skipSpaces(pos, false, true) : true; } return false; }; Lines2.prototype.prevPos = function(pos, skipSpaces) { if (skipSpaces === void 0) { skipSpaces = false; } var l = pos.line, c2 = pos.column; if (c2 < 1) { l -= 1; if (l < 1) return false; c2 = this.getLineLength(l); } else { c2 = Math.min(c2 - 1, this.getLineLength(l)); } pos.line = l; pos.column = c2; return skipSpaces ? !!this.skipSpaces(pos, true, true) : true; }; Lines2.prototype.firstPos = function() { return { line: 1, column: 0 }; }; Lines2.prototype.lastPos = function() { return { line: this.length, column: this.getLineLength(this.length) }; }; Lines2.prototype.skipSpaces = function(pos, backward, modifyInPlace) { if (backward === void 0) { backward = false; } if (modifyInPlace === void 0) { modifyInPlace = false; } if (pos) { pos = modifyInPlace ? pos : { line: pos.line, column: pos.column }; } else if (backward) { pos = this.lastPos(); } else { pos = this.firstPos(); } if (backward) { while (this.prevPos(pos)) { if (!isOnlyWhitespace(this.charAt(pos)) && this.nextPos(pos)) { return pos; } } return null; } else { while (isOnlyWhitespace(this.charAt(pos))) { if (!this.nextPos(pos)) { return null; } } return pos; } }; Lines2.prototype.trimLeft = function() { var pos = this.skipSpaces(this.firstPos(), false, true); return pos ? this.slice(pos) : emptyLines; }; Lines2.prototype.trimRight = function() { var pos = this.skipSpaces(this.lastPos(), true, true); return pos ? this.slice(this.firstPos(), pos) : emptyLines; }; Lines2.prototype.trim = function() { var start = this.skipSpaces(this.firstPos(), false, true); if (start === null) { return emptyLines; } var end = this.skipSpaces(this.lastPos(), true, true); if (end === null) { return emptyLines; } return this.slice(start, end); }; Lines2.prototype.eachPos = function(callback, startPos, skipSpaces) { if (startPos === void 0) { startPos = this.firstPos(); } if (skipSpaces === void 0) { skipSpaces = false; } var pos = this.firstPos(); if (startPos) { pos.line = startPos.line, pos.column = startPos.column; } if (skipSpaces && !this.skipSpaces(pos, false, true)) { return; } do callback.call(this, pos); while (this.nextPos(pos, skipSpaces)); }; Lines2.prototype.bootstrapSlice = function(start, end) { var strings = this.toString().split(lineTerminatorSeqExp).slice(start.line - 1, end.line); if (strings.length > 0) { strings.push(strings.pop().slice(0, end.column)); strings[0] = strings[0].slice(start.column); } return fromString(strings.join("\n")); }; Lines2.prototype.slice = function(start, end) { if (!end) { if (!start) { return this; } end = this.lastPos(); } if (!start) { throw new Error("cannot slice with end but not start"); } var sliced = this.infos.slice(start.line - 1, end.line); if (start.line === end.line) { sliced[0] = sliceInfo(sliced[0], start.column, end.column); } else { assert_1.default.ok(start.line < end.line); sliced[0] = sliceInfo(sliced[0], start.column); sliced.push(sliceInfo(sliced.pop(), 0, end.column)); } var lines = new Lines2(sliced); if (this.mappings.length > 0) { var newMappings_4 = lines.mappings; assert_1.default.strictEqual(newMappings_4.length, 0); this.mappings.forEach(function(mapping) { var sliced2 = mapping.slice(this, start, end); if (sliced2) { newMappings_4.push(sliced2); } }, this); } return lines; }; Lines2.prototype.bootstrapSliceString = function(start, end, options) { return this.slice(start, end).toString(options); }; Lines2.prototype.sliceString = function(start, end, options) { if (start === void 0) { start = this.firstPos(); } if (end === void 0) { end = this.lastPos(); } var _a = (0, options_1.normalize)(options), tabWidth = _a.tabWidth, useTabs = _a.useTabs, reuseWhitespace = _a.reuseWhitespace, lineTerminator = _a.lineTerminator; var parts = []; for (var line = start.line; line <= end.line; ++line) { var info = this.infos[line - 1]; if (line === start.line) { if (line === end.line) { info = sliceInfo(info, start.column, end.column); } else { info = sliceInfo(info, start.column); } } else if (line === end.line) { info = sliceInfo(info, 0, end.column); } var indent2 = Math.max(info.indent, 0); var before_1 = info.line.slice(0, info.sliceStart); if (reuseWhitespace && isOnlyWhitespace(before_1) && countSpaces(before_1, tabWidth) === indent2) { parts.push(info.line.slice(0, info.sliceEnd)); continue; } var tabs = 0; var spaces = indent2; if (useTabs) { tabs = Math.floor(indent2 / tabWidth); spaces -= tabs * tabWidth; } var result = ""; if (tabs > 0) { result += new Array(tabs + 1).join(" "); } if (spaces > 0) { result += new Array(spaces + 1).join(" "); } result += info.line.slice(info.sliceStart, info.sliceEnd); parts.push(result); } return parts.join(lineTerminator); }; Lines2.prototype.isEmpty = function() { return this.length < 2 && this.getLineLength(1) < 1; }; Lines2.prototype.join = function(elements) { var separator = this; var infos = []; var mappings = []; var prevInfo; function appendLines(linesOrNull) { if (linesOrNull === null) { return; } if (prevInfo) { var info = linesOrNull.infos[0]; var indent2 = new Array(info.indent + 1).join(" "); var prevLine_1 = infos.length; var prevColumn_1 = Math.max(prevInfo.indent, 0) + prevInfo.sliceEnd - prevInfo.sliceStart; prevInfo.line = prevInfo.line.slice(0, prevInfo.sliceEnd) + indent2 + info.line.slice(info.sliceStart, info.sliceEnd); prevInfo.locked = prevInfo.locked || info.locked; prevInfo.sliceEnd = prevInfo.line.length; if (linesOrNull.mappings.length > 0) { linesOrNull.mappings.forEach(function(mapping) { mappings.push(mapping.add(prevLine_1, prevColumn_1)); }); } } else if (linesOrNull.mappings.length > 0) { mappings.push.apply(mappings, linesOrNull.mappings); } linesOrNull.infos.forEach(function(info2, i2) { if (!prevInfo || i2 > 0) { prevInfo = tslib_1.__assign({}, info2); infos.push(prevInfo); } }); } function appendWithSeparator(linesOrNull, i2) { if (i2 > 0) appendLines(separator); appendLines(linesOrNull); } elements.map(function(elem) { var lines2 = fromString(elem); if (lines2.isEmpty()) return null; return lines2; }).forEach(function(linesOrNull, i2) { if (separator.isEmpty()) { appendLines(linesOrNull); } else { appendWithSeparator(linesOrNull, i2); } }); if (infos.length < 1) return emptyLines; var lines = new Lines2(infos); lines.mappings = mappings; return lines; }; Lines2.prototype.concat = function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var list2 = [this]; list2.push.apply(list2, args); assert_1.default.strictEqual(list2.length, args.length + 1); return emptyLines.join(list2); }; return Lines2; }() ); exports.Lines = Lines; var fromStringCache = {}; var hasOwn = fromStringCache.hasOwnProperty; var maxCacheKeyLen = 10; function countSpaces(spaces, tabWidth) { var count = 0; var len = spaces.length; for (var i2 = 0; i2 < len; ++i2) { switch (spaces.charCodeAt(i2)) { case 9: { assert_1.default.strictEqual(typeof tabWidth, "number"); assert_1.default.ok(tabWidth > 0); var next = Math.ceil(count / tabWidth) * tabWidth; if (next === count) { count += tabWidth; } else { count = next; } break; } case 11: case 12: case 13: case 65279: break; case 32: default: count += 1; break; } } return count; } exports.countSpaces = countSpaces; var leadingSpaceExp = /^\s*/; var lineTerminatorSeqExp = /\u000D\u000A|\u000D(?!\u000A)|\u000A|\u2028|\u2029/; function fromString(string3, options) { if (string3 instanceof Lines) return string3; string3 += ""; var tabWidth = options && options.tabWidth; var tabless = string3.indexOf(" ") < 0; var cacheable = !options && tabless && string3.length <= maxCacheKeyLen; assert_1.default.ok(tabWidth || tabless, "No tab width specified but encountered tabs in string\n" + string3); if (cacheable && hasOwn.call(fromStringCache, string3)) return fromStringCache[string3]; var lines = new Lines(string3.split(lineTerminatorSeqExp).map(function(line) { var spaces = leadingSpaceExp.exec(line)[0]; return { line, indent: countSpaces(spaces, tabWidth), // Boolean indicating whether this line can be reindented. locked: false, sliceStart: spaces.length, sliceEnd: line.length }; }), (0, options_1.normalize)(options).sourceFileName); if (cacheable) fromStringCache[string3] = lines; return lines; } exports.fromString = fromString; function isOnlyWhitespace(string3) { return !/\S/.test(string3); } function sliceInfo(info, startCol, endCol) { var sliceStart = info.sliceStart; var sliceEnd = info.sliceEnd; var indent2 = Math.max(info.indent, 0); var lineLength = indent2 + sliceEnd - sliceStart; if (typeof endCol === "undefined") { endCol = lineLength; } startCol = Math.max(startCol, 0); endCol = Math.min(endCol, lineLength); endCol = Math.max(endCol, startCol); if (endCol < indent2) { indent2 = endCol; sliceEnd = sliceStart; } else { sliceEnd -= lineLength - endCol; } lineLength = endCol; lineLength -= startCol; if (startCol < indent2) { indent2 -= startCol; } else { startCol -= indent2; indent2 = 0; sliceStart += startCol; } assert_1.default.ok(indent2 >= 0); assert_1.default.ok(sliceStart <= sliceEnd); assert_1.default.strictEqual(lineLength, indent2 + sliceEnd - sliceStart); if (info.indent === indent2 && info.sliceStart === sliceStart && info.sliceEnd === sliceEnd) { return info; } return { line: info.line, indent: indent2, // A destructive slice always unlocks indentation. locked: false, sliceStart, sliceEnd }; } function concat(elements) { return emptyLines.join(elements); } exports.concat = concat; var emptyLines = fromString(""); } }); // node_modules/recast/lib/comments.js var require_comments = __commonJS({ "node_modules/recast/lib/comments.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.printComments = exports.attach = void 0; var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); var assert_1 = tslib_1.__importDefault(require("assert")); var types = tslib_1.__importStar(require_main()); var n = types.namedTypes; var isArray = types.builtInTypes.array; var isObject2 = types.builtInTypes.object; var lines_1 = require_lines(); var util_1 = require_util2(); var childNodesCache = /* @__PURE__ */ new WeakMap(); function getSortedChildNodes(node2, lines, resultArray) { if (!node2) { return resultArray; } (0, util_1.fixFaultyLocations)(node2, lines); if (resultArray) { if (n.Node.check(node2) && n.SourceLocation.check(node2.loc)) { var i2 = resultArray.length - 1; for (; i2 >= 0; --i2) { var child = resultArray[i2]; if (child && child.loc && (0, util_1.comparePos)(child.loc.end, node2.loc.start) <= 0) { break; } } resultArray.splice(i2 + 1, 0, node2); return resultArray; } } else { var childNodes = childNodesCache.get(node2); if (childNodes) { return childNodes; } } var names; if (isArray.check(node2)) { names = Object.keys(node2); } else if (isObject2.check(node2)) { names = types.getFieldNames(node2); } else { return resultArray; } if (!resultArray) { childNodesCache.set(node2, resultArray = []); } for (var i2 = 0, nameCount = names.length; i2 < nameCount; ++i2) { getSortedChildNodes(node2[names[i2]], lines, resultArray); } return resultArray; } function decorateComment(node2, comment, lines) { var childNodes = getSortedChildNodes(node2, lines); var left = 0; var right = childNodes && childNodes.length; var precedingNode; var followingNode; while (typeof right === "number" && left < right) { var middle = left + right >> 1; var child = childNodes[middle]; if ((0, util_1.comparePos)(child.loc.start, comment.loc.start) <= 0 && (0, util_1.comparePos)(comment.loc.end, child.loc.end) <= 0) { decorateComment(comment.enclosingNode = child, comment, lines); return; } if ((0, util_1.comparePos)(child.loc.end, comment.loc.start) <= 0) { precedingNode = child; left = middle + 1; continue; } if ((0, util_1.comparePos)(comment.loc.end, child.loc.start) <= 0) { followingNode = child; right = middle; continue; } throw new Error("Comment location overlaps with node location"); } if (precedingNode) { comment.precedingNode = precedingNode; } if (followingNode) { comment.followingNode = followingNode; } } function attach(comments, ast, lines) { if (!isArray.check(comments)) { return; } var tiesToBreak = []; comments.forEach(function(comment) { comment.loc.lines = lines; decorateComment(ast, comment, lines); var pn = comment.precedingNode; var en = comment.enclosingNode; var fn = comment.followingNode; if (pn && fn) { var tieCount = tiesToBreak.length; if (tieCount > 0) { var lastTie = tiesToBreak[tieCount - 1]; assert_1.default.strictEqual(lastTie.precedingNode === comment.precedingNode, lastTie.followingNode === comment.followingNode); if (lastTie.followingNode !== comment.followingNode) { breakTies(tiesToBreak, lines); } } tiesToBreak.push(comment); } else if (pn) { breakTies(tiesToBreak, lines); addTrailingComment(pn, comment); } else if (fn) { breakTies(tiesToBreak, lines); addLeadingComment(fn, comment); } else if (en) { breakTies(tiesToBreak, lines); addDanglingComment(en, comment); } else { throw new Error("AST contains no nodes at all?"); } }); breakTies(tiesToBreak, lines); comments.forEach(function(comment) { delete comment.precedingNode; delete comment.enclosingNode; delete comment.followingNode; }); } exports.attach = attach; function breakTies(tiesToBreak, lines) { var tieCount = tiesToBreak.length; if (tieCount === 0) { return; } var pn = tiesToBreak[0].precedingNode; var fn = tiesToBreak[0].followingNode; var gapEndPos = fn.loc.start; var indexOfFirstLeadingComment = tieCount; var comment; for (; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) { comment = tiesToBreak[indexOfFirstLeadingComment - 1]; assert_1.default.strictEqual(comment.precedingNode, pn); assert_1.default.strictEqual(comment.followingNode, fn); var gap = lines.sliceString(comment.loc.end, gapEndPos); if (/\S/.test(gap)) { break; } gapEndPos = comment.loc.start; } while (indexOfFirstLeadingComment <= tieCount && (comment = tiesToBreak[indexOfFirstLeadingComment]) && // If the comment is a //-style comment and indented more // deeply than the node itself, reconsider it as trailing. (comment.type === "Line" || comment.type === "CommentLine") && comment.loc.start.column > fn.loc.start.column) { ++indexOfFirstLeadingComment; } if (indexOfFirstLeadingComment) { var enclosingNode = tiesToBreak[indexOfFirstLeadingComment - 1].enclosingNode; if ((enclosingNode === null || enclosingNode === void 0 ? void 0 : enclosingNode.type) === "CallExpression") { --indexOfFirstLeadingComment; } } tiesToBreak.forEach(function(comment2, i2) { if (i2 < indexOfFirstLeadingComment) { addTrailingComment(pn, comment2); } else { addLeadingComment(fn, comment2); } }); tiesToBreak.length = 0; } function addCommentHelper(node2, comment) { var comments = node2.comments || (node2.comments = []); comments.push(comment); } function addLeadingComment(node2, comment) { comment.leading = true; comment.trailing = false; addCommentHelper(node2, comment); } function addDanglingComment(node2, comment) { comment.leading = false; comment.trailing = false; addCommentHelper(node2, comment); } function addTrailingComment(node2, comment) { comment.leading = false; comment.trailing = true; addCommentHelper(node2, comment); } function printLeadingComment(commentPath, print) { var comment = commentPath.getValue(); n.Comment.assert(comment); var loc = comment.loc; var lines = loc && loc.lines; var parts = [print(commentPath)]; if (comment.trailing) { parts.push("\n"); } else if (lines instanceof lines_1.Lines) { var trailingSpace = lines.slice(loc.end, lines.skipSpaces(loc.end) || lines.lastPos()); if (trailingSpace.length === 1) { parts.push(trailingSpace); } else { parts.push(new Array(trailingSpace.length).join("\n")); } } else { parts.push("\n"); } return (0, lines_1.concat)(parts); } function printTrailingComment(commentPath, print) { var comment = commentPath.getValue(commentPath); n.Comment.assert(comment); var loc = comment.loc; var lines = loc && loc.lines; var parts = []; if (lines instanceof lines_1.Lines) { var fromPos = lines.skipSpaces(loc.start, true) || lines.firstPos(); var leadingSpace = lines.slice(fromPos, loc.start); if (leadingSpace.length === 1) { parts.push(leadingSpace); } else { parts.push(new Array(leadingSpace.length).join("\n")); } } parts.push(print(commentPath)); return (0, lines_1.concat)(parts); } function printComments(path, print) { var value = path.getValue(); var innerLines = print(path); var comments = n.Node.check(value) && types.getFieldValue(value, "comments"); if (!comments || comments.length === 0) { return innerLines; } var leadingParts = []; var trailingParts = [innerLines]; path.each(function(commentPath) { var comment = commentPath.getValue(); var leading = types.getFieldValue(comment, "leading"); var trailing = types.getFieldValue(comment, "trailing"); if (leading || trailing && !(n.Statement.check(value) || comment.type === "Block" || comment.type === "CommentBlock")) { leadingParts.push(printLeadingComment(commentPath, print)); } else if (trailing) { trailingParts.push(printTrailingComment(commentPath, print)); } }, "comments"); leadingParts.push.apply(leadingParts, trailingParts); return (0, lines_1.concat)(leadingParts); } exports.printComments = printComments; } }); // node_modules/recast/lib/parser.js var require_parser = __commonJS({ "node_modules/recast/lib/parser.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parse = void 0; var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); var assert_1 = tslib_1.__importDefault(require("assert")); var types = tslib_1.__importStar(require_main()); var b2 = types.builders; var isObject2 = types.builtInTypes.object; var isArray = types.builtInTypes.array; var options_1 = require_options(); var lines_1 = require_lines(); var comments_1 = require_comments(); var util2 = tslib_1.__importStar(require_util2()); function parse3(source, options) { options = (0, options_1.normalize)(options); var lines = (0, lines_1.fromString)(source, options); var sourceWithoutTabs = lines.toString({ tabWidth: options.tabWidth, reuseWhitespace: false, useTabs: false }); var comments = []; var ast = options.parser.parse(sourceWithoutTabs, { jsx: true, loc: true, locations: true, range: options.range, comment: true, onComment: comments, tolerant: util2.getOption(options, "tolerant", true), ecmaVersion: 6, sourceType: util2.getOption(options, "sourceType", "module") }); var tokens = Array.isArray(ast.tokens) ? ast.tokens : require_esprima2().tokenize(sourceWithoutTabs, { loc: true }); delete ast.tokens; tokens.forEach(function(token) { if (typeof token.value !== "string") { token.value = lines.sliceString(token.loc.start, token.loc.end); } }); if (Array.isArray(ast.comments)) { comments = ast.comments; delete ast.comments; } if (ast.loc) { util2.fixFaultyLocations(ast, lines); } else { ast.loc = { start: lines.firstPos(), end: lines.lastPos() }; } ast.loc.lines = lines; ast.loc.indent = 0; var file; var program; if (ast.type === "Program") { program = ast; file = b2.file(ast, options.sourceFileName || null); file.loc = { start: lines.firstPos(), end: lines.lastPos(), lines, indent: 0 }; } else if (ast.type === "File") { file = ast; program = file.program; } if (options.tokens) { file.tokens = tokens; } var trueProgramLoc = util2.getTrueLoc({ type: program.type, loc: program.loc, body: [], comments }, lines); program.loc.start = trueProgramLoc.start; program.loc.end = trueProgramLoc.end; (0, comments_1.attach)(comments, program.body.length ? file.program : file, lines); return new TreeCopier(lines, tokens).copy(file); } exports.parse = parse3; var TreeCopier = function TreeCopier2(lines, tokens) { assert_1.default.ok(this instanceof TreeCopier2); this.lines = lines; this.tokens = tokens; this.startTokenIndex = 0; this.endTokenIndex = tokens.length; this.indent = 0; this.seen = /* @__PURE__ */ new Map(); }; var TCp = TreeCopier.prototype; TCp.copy = function(node2) { if (this.seen.has(node2)) { return this.seen.get(node2); } if (isArray.check(node2)) { var copy_1 = new Array(node2.length); this.seen.set(node2, copy_1); node2.forEach(function(item, i3) { copy_1[i3] = this.copy(item); }, this); return copy_1; } if (!isObject2.check(node2)) { return node2; } util2.fixFaultyLocations(node2, this.lines); var copy = Object.create(Object.getPrototypeOf(node2), { original: { // Provide a link from the copy to the original. value: node2, configurable: false, enumerable: false, writable: true } }); this.seen.set(node2, copy); var loc = node2.loc; var oldIndent = this.indent; var newIndent = oldIndent; var oldStartTokenIndex = this.startTokenIndex; var oldEndTokenIndex = this.endTokenIndex; if (loc) { if (node2.type === "Block" || node2.type === "Line" || node2.type === "CommentBlock" || node2.type === "CommentLine" || this.lines.isPrecededOnlyByWhitespace(loc.start)) { newIndent = this.indent = loc.start.column; } loc.lines = this.lines; loc.tokens = this.tokens; loc.indent = newIndent; this.findTokenRange(loc); } var keys = Object.keys(node2); var keyCount = keys.length; for (var i2 = 0; i2 < keyCount; ++i2) { var key = keys[i2]; if (key === "loc") { copy[key] = node2[key]; } else if (key === "tokens" && node2.type === "File") { copy[key] = node2[key]; } else { copy[key] = this.copy(node2[key]); } } this.indent = oldIndent; this.startTokenIndex = oldStartTokenIndex; this.endTokenIndex = oldEndTokenIndex; return copy; }; TCp.findTokenRange = function(loc) { while (this.startTokenIndex > 0) { var token = loc.tokens[this.startTokenIndex]; if (util2.comparePos(loc.start, token.loc.start) < 0) { --this.startTokenIndex; } else break; } while (this.endTokenIndex < loc.tokens.length) { var token = loc.tokens[this.endTokenIndex]; if (util2.comparePos(token.loc.end, loc.end) < 0) { ++this.endTokenIndex; } else break; } while (this.startTokenIndex < this.endTokenIndex) { var token = loc.tokens[this.startTokenIndex]; if (util2.comparePos(token.loc.start, loc.start) < 0) { ++this.startTokenIndex; } else break; } loc.start.token = this.startTokenIndex; while (this.endTokenIndex > this.startTokenIndex) { var token = loc.tokens[this.endTokenIndex - 1]; if (util2.comparePos(loc.end, token.loc.end) < 0) { --this.endTokenIndex; } else break; } loc.end.token = this.endTokenIndex; }; } }); // node_modules/recast/lib/fast-path.js var require_fast_path = __commonJS({ "node_modules/recast/lib/fast-path.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); var assert_1 = tslib_1.__importDefault(require("assert")); var types = tslib_1.__importStar(require_main()); var util2 = tslib_1.__importStar(require_util2()); var n = types.namedTypes; var isArray = types.builtInTypes.array; var isNumber = types.builtInTypes.number; var PRECEDENCE = {}; [ ["??"], ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"] ].forEach(function(tier, i2) { tier.forEach(function(op) { PRECEDENCE[op] = i2; }); }); var FastPath = function FastPath2(value) { assert_1.default.ok(this instanceof FastPath2); this.stack = [value]; }; var FPp = FastPath.prototype; FastPath.from = function(obj) { if (obj instanceof FastPath) { return obj.copy(); } if (obj instanceof types.NodePath) { var copy = Object.create(FastPath.prototype); var stack = [obj.value]; for (var pp = void 0; pp = obj.parentPath; obj = pp) stack.push(obj.name, pp.value); copy.stack = stack.reverse(); return copy; } return new FastPath(obj); }; FPp.copy = function copy() { var copy2 = Object.create(FastPath.prototype); copy2.stack = this.stack.slice(0); return copy2; }; FPp.getName = function getName() { var s3 = this.stack; var len = s3.length; if (len > 1) { return s3[len - 2]; } return null; }; FPp.getValue = function getValue() { var s3 = this.stack; return s3[s3.length - 1]; }; FPp.valueIsDuplicate = function() { var s3 = this.stack; var valueIndex = s3.length - 1; return s3.lastIndexOf(s3[valueIndex], valueIndex - 1) >= 0; }; function getNodeHelper(path, count) { var s3 = path.stack; for (var i2 = s3.length - 1; i2 >= 0; i2 -= 2) { var value = s3[i2]; if (n.Node.check(value) && --count < 0) { return value; } } return null; } FPp.getNode = function getNode(count) { if (count === void 0) { count = 0; } return getNodeHelper(this, ~~count); }; FPp.getParentNode = function getParentNode(count) { if (count === void 0) { count = 0; } return getNodeHelper(this, ~~count + 1); }; FPp.getRootValue = function getRootValue() { var s3 = this.stack; if (s3.length % 2 === 0) { return s3[1]; } return s3[0]; }; FPp.call = function call(callback) { var s3 = this.stack; var origLen = s3.length; var value = s3[origLen - 1]; var argc = arguments.length; for (var i2 = 1; i2 < argc; ++i2) { var name = arguments[i2]; value = value[name]; s3.push(name, value); } var result = callback(this); s3.length = origLen; return result; }; FPp.each = function each(callback) { var s3 = this.stack; var origLen = s3.length; var value = s3[origLen - 1]; var argc = arguments.length; for (var i2 = 1; i2 < argc; ++i2) { var name = arguments[i2]; value = value[name]; s3.push(name, value); } for (var i2 = 0; i2 < value.length; ++i2) { if (i2 in value) { s3.push(i2, value[i2]); callback(this); s3.length -= 2; } } s3.length = origLen; }; FPp.map = function map2(callback) { var s3 = this.stack; var origLen = s3.length; var value = s3[origLen - 1]; var argc = arguments.length; for (var i2 = 1; i2 < argc; ++i2) { var name = arguments[i2]; value = value[name]; s3.push(name, value); } var result = new Array(value.length); for (var i2 = 0; i2 < value.length; ++i2) { if (i2 in value) { s3.push(i2, value[i2]); result[i2] = callback(this, i2); s3.length -= 2; } } s3.length = origLen; return result; }; FPp.hasParens = function() { var node2 = this.getNode(); var prevToken = this.getPrevToken(node2); if (!prevToken) { return false; } var nextToken = this.getNextToken(node2); if (!nextToken) { return false; } if (prevToken.value === "(") { if (nextToken.value === ")") { return true; } var justNeedsOpeningParen = !this.canBeFirstInStatement() && this.firstInStatement() && !this.needsParens(true); if (justNeedsOpeningParen) { return true; } } return false; }; FPp.getPrevToken = function(node2) { node2 = node2 || this.getNode(); var loc = node2 && node2.loc; var tokens = loc && loc.tokens; if (tokens && loc.start.token > 0) { var token = tokens[loc.start.token - 1]; if (token) { var rootLoc = this.getRootValue().loc; if (util2.comparePos(rootLoc.start, token.loc.start) <= 0) { return token; } } } return null; }; FPp.getNextToken = function(node2) { node2 = node2 || this.getNode(); var loc = node2 && node2.loc; var tokens = loc && loc.tokens; if (tokens && loc.end.token < tokens.length) { var token = tokens[loc.end.token]; if (token) { var rootLoc = this.getRootValue().loc; if (util2.comparePos(token.loc.end, rootLoc.end) <= 0) { return token; } } } return null; }; FPp.needsParens = function(assumeExpressionContext) { var node2 = this.getNode(); if (node2.type === "AssignmentExpression" && node2.left.type === "ObjectPattern") { return true; } var parent = this.getParentNode(); var name = this.getName(); if (this.getValue() !== node2) { return false; } if (n.Statement.check(node2)) { return false; } if (node2.type === "Identifier") { return false; } if (parent && parent.type === "ParenthesizedExpression") { return false; } if (node2.extra && node2.extra.parenthesized) { return true; } if (!parent) return false; if (node2.type === "UnaryExpression" && parent.type === "BinaryExpression" && name === "left" && parent.left === node2 && parent.operator === "**") { return true; } switch (node2.type) { case "UnaryExpression": case "SpreadElement": case "SpreadProperty": return parent.type === "MemberExpression" && name === "object" && parent.object === node2; case "BinaryExpression": case "LogicalExpression": switch (parent.type) { case "CallExpression": return name === "callee" && parent.callee === node2; case "UnaryExpression": case "SpreadElement": case "SpreadProperty": return true; case "MemberExpression": return name === "object" && parent.object === node2; case "BinaryExpression": case "LogicalExpression": { var po = parent.operator; var pp = PRECEDENCE[po]; var no = node2.operator; var np = PRECEDENCE[no]; if (pp > np) { return true; } if (pp === np && name === "right") { assert_1.default.strictEqual(parent.right, node2); return true; } break; } default: return false; } break; case "SequenceExpression": switch (parent.type) { case "ReturnStatement": return false; case "ForStatement": return false; case "ExpressionStatement": return name !== "expression"; default: return true; } case "OptionalIndexedAccessType": return node2.optional && parent.type === "IndexedAccessType"; case "IntersectionTypeAnnotation": case "UnionTypeAnnotation": return parent.type === "NullableTypeAnnotation"; case "Literal": return parent.type === "MemberExpression" && isNumber.check(node2.value) && name === "object" && parent.object === node2; case "NumericLiteral": return parent.type === "MemberExpression" && name === "object" && parent.object === node2; case "YieldExpression": case "AwaitExpression": case "AssignmentExpression": case "ConditionalExpression": switch (parent.type) { case "UnaryExpression": case "SpreadElement": case "SpreadProperty": case "BinaryExpression": case "LogicalExpression": return true; case "CallExpression": case "NewExpression": return name === "callee" && parent.callee === node2; case "ConditionalExpression": return name === "test" && parent.test === node2; case "MemberExpression": return name === "object" && parent.object === node2; default: return false; } case "ArrowFunctionExpression": if (n.CallExpression.check(parent) && name === "callee" && parent.callee === node2) { return true; } if (n.MemberExpression.check(parent) && name === "object" && parent.object === node2) { return true; } if (n.TSAsExpression && n.TSAsExpression.check(parent) && name === "expression" && parent.expression === node2) { return true; } return isBinary2(parent); case "ObjectExpression": if (parent.type === "ArrowFunctionExpression" && name === "body" && parent.body === node2) { return true; } break; case "TSAsExpression": if (parent.type === "ArrowFunctionExpression" && name === "body" && parent.body === node2 && node2.expression.type === "ObjectExpression") { return true; } break; case "CallExpression": if (name === "declaration" && n.ExportDefaultDeclaration.check(parent) && n.FunctionExpression.check(node2.callee)) { return true; } } if (parent.type === "NewExpression" && name === "callee" && parent.callee === node2) { return containsCallExpression(node2); } if (assumeExpressionContext !== true && !this.canBeFirstInStatement() && this.firstInStatement()) { return true; } return false; }; function isBinary2(node2) { return n.BinaryExpression.check(node2) || n.LogicalExpression.check(node2); } function containsCallExpression(node2) { if (n.CallExpression.check(node2)) { return true; } if (isArray.check(node2)) { return node2.some(containsCallExpression); } if (n.Node.check(node2)) { return types.someField(node2, function(_name, child) { return containsCallExpression(child); }); } return false; } FPp.canBeFirstInStatement = function() { var node2 = this.getNode(); if (n.FunctionExpression.check(node2)) { return false; } if (n.ObjectExpression.check(node2)) { return false; } if (n.ClassExpression.check(node2)) { return false; } return true; }; FPp.firstInStatement = function() { var s3 = this.stack; var parentName, parent; var childName, child; for (var i2 = s3.length - 1; i2 >= 0; i2 -= 2) { if (n.Node.check(s3[i2])) { childName = parentName; child = parent; parentName = s3[i2 - 1]; parent = s3[i2]; } if (!parent || !child) { continue; } if (n.BlockStatement.check(parent) && parentName === "body" && childName === 0) { assert_1.default.strictEqual(parent.body[0], child); return true; } if (n.ExpressionStatement.check(parent) && childName === "expression") { assert_1.default.strictEqual(parent.expression, child); return true; } if (n.AssignmentExpression.check(parent) && childName === "left") { assert_1.default.strictEqual(parent.left, child); return true; } if (n.ArrowFunctionExpression.check(parent) && childName === "body") { assert_1.default.strictEqual(parent.body, child); return true; } if (n.SequenceExpression.check(parent) && s3[i2 + 1] === "expressions" && childName === 0) { assert_1.default.strictEqual(parent.expressions[0], child); continue; } if (n.CallExpression.check(parent) && childName === "callee") { assert_1.default.strictEqual(parent.callee, child); continue; } if (n.MemberExpression.check(parent) && childName === "object") { assert_1.default.strictEqual(parent.object, child); continue; } if (n.ConditionalExpression.check(parent) && childName === "test") { assert_1.default.strictEqual(parent.test, child); continue; } if (isBinary2(parent) && childName === "left") { assert_1.default.strictEqual(parent.left, child); continue; } if (n.UnaryExpression.check(parent) && !parent.prefix && childName === "argument") { assert_1.default.strictEqual(parent.argument, child); continue; } return false; } return true; }; exports.default = FastPath; } }); // node_modules/recast/lib/patcher.js var require_patcher = __commonJS({ "node_modules/recast/lib/patcher.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getReprinter = exports.Patcher = void 0; var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); var assert_1 = tslib_1.__importDefault(require("assert")); var linesModule = tslib_1.__importStar(require_lines()); var types = tslib_1.__importStar(require_main()); var Printable = types.namedTypes.Printable; var Expression = types.namedTypes.Expression; var ReturnStatement = types.namedTypes.ReturnStatement; var SourceLocation = types.namedTypes.SourceLocation; var util_1 = require_util2(); var fast_path_1 = tslib_1.__importDefault(require_fast_path()); var isObject2 = types.builtInTypes.object; var isArray = types.builtInTypes.array; var isString = types.builtInTypes.string; var riskyAdjoiningCharExp = /[0-9a-z_$]/i; var Patcher = function Patcher2(lines) { assert_1.default.ok(this instanceof Patcher2); assert_1.default.ok(lines instanceof linesModule.Lines); var self2 = this, replacements = []; self2.replace = function(loc, lines2) { if (isString.check(lines2)) lines2 = linesModule.fromString(lines2); replacements.push({ lines: lines2, start: loc.start, end: loc.end }); }; self2.get = function(loc) { loc = loc || { start: { line: 1, column: 0 }, end: { line: lines.length, column: lines.getLineLength(lines.length) } }; var sliceFrom = loc.start, toConcat = []; function pushSlice(from, to) { assert_1.default.ok((0, util_1.comparePos)(from, to) <= 0); toConcat.push(lines.slice(from, to)); } replacements.sort(function(a3, b2) { return (0, util_1.comparePos)(a3.start, b2.start); }).forEach(function(rep) { if ((0, util_1.comparePos)(sliceFrom, rep.start) > 0) { } else { pushSlice(sliceFrom, rep.start); toConcat.push(rep.lines); sliceFrom = rep.end; } }); pushSlice(sliceFrom, loc.end); return linesModule.concat(toConcat); }; }; exports.Patcher = Patcher; var Pp = Patcher.prototype; Pp.tryToReprintComments = function(newNode, oldNode, print) { var patcher = this; if (!newNode.comments && !oldNode.comments) { return true; } var newPath = fast_path_1.default.from(newNode); var oldPath = fast_path_1.default.from(oldNode); newPath.stack.push("comments", getSurroundingComments(newNode)); oldPath.stack.push("comments", getSurroundingComments(oldNode)); var reprints = []; var ableToReprintComments = findArrayReprints(newPath, oldPath, reprints); if (ableToReprintComments && reprints.length > 0) { reprints.forEach(function(reprint) { var oldComment = reprint.oldPath.getValue(); assert_1.default.ok(oldComment.leading || oldComment.trailing); patcher.replace( oldComment.loc, // Comments can't have .comments, so it doesn't matter whether we // print with comments or without. print(reprint.newPath).indentTail(oldComment.loc.indent) ); }); } return ableToReprintComments; }; function getSurroundingComments(node2) { var result = []; if (node2.comments && node2.comments.length > 0) { node2.comments.forEach(function(comment) { if (comment.leading || comment.trailing) { result.push(comment); } }); } return result; } Pp.deleteComments = function(node2) { if (!node2.comments) { return; } var patcher = this; node2.comments.forEach(function(comment) { if (comment.leading) { patcher.replace({ start: comment.loc.start, end: node2.loc.lines.skipSpaces(comment.loc.end, false, false) }, ""); } else if (comment.trailing) { patcher.replace({ start: node2.loc.lines.skipSpaces(comment.loc.start, true, false), end: comment.loc.end }, ""); } }); }; function getReprinter(path) { assert_1.default.ok(path instanceof fast_path_1.default); var node2 = path.getValue(); if (!Printable.check(node2)) return; var orig = node2.original; var origLoc = orig && orig.loc; var lines = origLoc && origLoc.lines; var reprints = []; if (!lines || !findReprints(path, reprints)) return; return function(print) { var patcher = new Patcher(lines); reprints.forEach(function(reprint) { var newNode = reprint.newPath.getValue(); var oldNode = reprint.oldPath.getValue(); SourceLocation.assert(oldNode.loc, true); var needToPrintNewPathWithComments = !patcher.tryToReprintComments(newNode, oldNode, print); if (needToPrintNewPathWithComments) { patcher.deleteComments(oldNode); } var newLines = print(reprint.newPath, { includeComments: needToPrintNewPathWithComments, // If the oldNode we're replacing already had parentheses, we may // not need to print the new node with any extra parentheses, // because the existing parentheses will suffice. However, if the // newNode has a different type than the oldNode, let the printer // decide if reprint.newPath needs parentheses, as usual. avoidRootParens: oldNode.type === newNode.type && reprint.oldPath.hasParens() }).indentTail(oldNode.loc.indent); var nls = needsLeadingSpace(lines, oldNode.loc, newLines); var nts = needsTrailingSpace(lines, oldNode.loc, newLines); if (nls || nts) { var newParts = []; nls && newParts.push(" "); newParts.push(newLines); nts && newParts.push(" "); newLines = linesModule.concat(newParts); } patcher.replace(oldNode.loc, newLines); }); var patchedLines = patcher.get(origLoc).indentTail(-orig.loc.indent); if (path.needsParens()) { return linesModule.concat(["(", patchedLines, ")"]); } return patchedLines; }; } exports.getReprinter = getReprinter; function needsLeadingSpace(oldLines, oldLoc, newLines) { var posBeforeOldLoc = (0, util_1.copyPos)(oldLoc.start); var charBeforeOldLoc = oldLines.prevPos(posBeforeOldLoc) && oldLines.charAt(posBeforeOldLoc); var newFirstChar = newLines.charAt(newLines.firstPos()); return charBeforeOldLoc && riskyAdjoiningCharExp.test(charBeforeOldLoc) && newFirstChar && riskyAdjoiningCharExp.test(newFirstChar); } function needsTrailingSpace(oldLines, oldLoc, newLines) { var charAfterOldLoc = oldLines.charAt(oldLoc.end); var newLastPos = newLines.lastPos(); var newLastChar = newLines.prevPos(newLastPos) && newLines.charAt(newLastPos); return newLastChar && riskyAdjoiningCharExp.test(newLastChar) && charAfterOldLoc && riskyAdjoiningCharExp.test(charAfterOldLoc); } function findReprints(newPath, reprints) { var newNode = newPath.getValue(); Printable.assert(newNode); var oldNode = newNode.original; Printable.assert(oldNode); assert_1.default.deepEqual(reprints, []); if (newNode.type !== oldNode.type) { return false; } var oldPath = new fast_path_1.default(oldNode); var canReprint = findChildReprints(newPath, oldPath, reprints); if (!canReprint) { reprints.length = 0; } return canReprint; } function findAnyReprints(newPath, oldPath, reprints) { var newNode = newPath.getValue(); var oldNode = oldPath.getValue(); if (newNode === oldNode) return true; if (isArray.check(newNode)) return findArrayReprints(newPath, oldPath, reprints); if (isObject2.check(newNode)) return findObjectReprints(newPath, oldPath, reprints); return false; } function findArrayReprints(newPath, oldPath, reprints) { var newNode = newPath.getValue(); var oldNode = oldPath.getValue(); if (newNode === oldNode || newPath.valueIsDuplicate() || oldPath.valueIsDuplicate()) { return true; } isArray.assert(newNode); var len = newNode.length; if (!(isArray.check(oldNode) && oldNode.length === len)) return false; for (var i2 = 0; i2 < len; ++i2) { newPath.stack.push(i2, newNode[i2]); oldPath.stack.push(i2, oldNode[i2]); var canReprint = findAnyReprints(newPath, oldPath, reprints); newPath.stack.length -= 2; oldPath.stack.length -= 2; if (!canReprint) { return false; } } return true; } function findObjectReprints(newPath, oldPath, reprints) { var newNode = newPath.getValue(); isObject2.assert(newNode); if (newNode.original === null) { return false; } var oldNode = oldPath.getValue(); if (!isObject2.check(oldNode)) return false; if (newNode === oldNode || newPath.valueIsDuplicate() || oldPath.valueIsDuplicate()) { return true; } if (Printable.check(newNode)) { if (!Printable.check(oldNode)) { return false; } var newParentNode = newPath.getParentNode(); var oldParentNode = oldPath.getParentNode(); if (oldParentNode !== null && oldParentNode.type === "FunctionTypeAnnotation" && newParentNode !== null && newParentNode.type === "FunctionTypeAnnotation") { var oldNeedsParens = oldParentNode.params.length !== 1 || !!oldParentNode.params[0].name; var newNeedParens = newParentNode.params.length !== 1 || !!newParentNode.params[0].name; if (!oldNeedsParens && newNeedParens) { return false; } } if (newNode.type === oldNode.type) { var childReprints = []; if (findChildReprints(newPath, oldPath, childReprints)) { reprints.push.apply(reprints, childReprints); } else if (oldNode.loc) { reprints.push({ oldPath: oldPath.copy(), newPath: newPath.copy() }); } else { return false; } return true; } if (Expression.check(newNode) && Expression.check(oldNode) && // If we have no .loc information for oldNode, then we won't be // able to reprint it. oldNode.loc) { reprints.push({ oldPath: oldPath.copy(), newPath: newPath.copy() }); return true; } return false; } return findChildReprints(newPath, oldPath, reprints); } function findChildReprints(newPath, oldPath, reprints) { var newNode = newPath.getValue(); var oldNode = oldPath.getValue(); isObject2.assert(newNode); isObject2.assert(oldNode); if (newNode.original === null) { return false; } if (newPath.needsParens() && !oldPath.hasParens()) { return false; } var keys = (0, util_1.getUnionOfKeys)(oldNode, newNode); if (oldNode.type === "File" || newNode.type === "File") { delete keys.tokens; } delete keys.loc; var originalReprintCount = reprints.length; for (var k2 in keys) { if (k2.charAt(0) === "_") { continue; } newPath.stack.push(k2, types.getFieldValue(newNode, k2)); oldPath.stack.push(k2, types.getFieldValue(oldNode, k2)); var canReprint = findAnyReprints(newPath, oldPath, reprints); newPath.stack.length -= 2; oldPath.stack.length -= 2; if (!canReprint) { return false; } } if (ReturnStatement.check(newPath.getNode()) && reprints.length > originalReprintCount) { return false; } return true; } } }); // node_modules/recast/lib/printer.js var require_printer = __commonJS({ "node_modules/recast/lib/printer.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Printer = void 0; var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); var assert_1 = tslib_1.__importDefault(require("assert")); var types = tslib_1.__importStar(require_main()); var comments_1 = require_comments(); var fast_path_1 = tslib_1.__importDefault(require_fast_path()); var lines_1 = require_lines(); var options_1 = require_options(); var patcher_1 = require_patcher(); var util2 = tslib_1.__importStar(require_util2()); var namedTypes = types.namedTypes; var isString = types.builtInTypes.string; var isObject2 = types.builtInTypes.object; var PrintResult = function PrintResult2(code, sourceMap) { assert_1.default.ok(this instanceof PrintResult2); isString.assert(code); this.code = code; if (sourceMap) { isObject2.assert(sourceMap); this.map = sourceMap; } }; var PRp = PrintResult.prototype; var warnedAboutToString = false; PRp.toString = function() { if (!warnedAboutToString) { console.warn("Deprecation warning: recast.print now returns an object with a .code property. You appear to be treating the object as a string, which might still work but is strongly discouraged."); warnedAboutToString = true; } return this.code; }; var emptyPrintResult = new PrintResult(""); var Printer = function Printer2(config) { assert_1.default.ok(this instanceof Printer2); var explicitTabWidth = config && config.tabWidth; config = (0, options_1.normalize)(config); config.sourceFileName = null; function makePrintFunctionWith(options, overrides) { options = Object.assign({}, options, overrides); return function(path) { return print(path, options); }; } function print(path, options) { assert_1.default.ok(path instanceof fast_path_1.default); options = options || {}; if (options.includeComments) { return (0, comments_1.printComments)(path, makePrintFunctionWith(options, { includeComments: false })); } var oldTabWidth = config.tabWidth; if (!explicitTabWidth) { var loc = path.getNode().loc; if (loc && loc.lines && loc.lines.guessTabWidth) { config.tabWidth = loc.lines.guessTabWidth(); } } var reprinter = (0, patcher_1.getReprinter)(path); var lines = reprinter ? ( // Since the print function that we pass to the reprinter will // be used to print "new" nodes, it's tempting to think we // should pass printRootGenerically instead of print, to avoid // calling maybeReprint again, but that would be a mistake // because the new nodes might not be entirely new, but merely // moved from elsewhere in the AST. The print function is the // right choice because it gives us the opportunity to reprint // such nodes using their original source. reprinter(print) ) : genericPrint(path, config, options, makePrintFunctionWith(options, { includeComments: true, avoidRootParens: false })); config.tabWidth = oldTabWidth; return lines; } this.print = function(ast) { if (!ast) { return emptyPrintResult; } var lines = print(fast_path_1.default.from(ast), { includeComments: true, avoidRootParens: false }); return new PrintResult(lines.toString(config), util2.composeSourceMaps(config.inputSourceMap, lines.getSourceMap(config.sourceMapName, config.sourceRoot))); }; this.printGenerically = function(ast) { if (!ast) { return emptyPrintResult; } function printGenerically(path2) { return (0, comments_1.printComments)(path2, function(path3) { return genericPrint(path3, config, { includeComments: true, avoidRootParens: false }, printGenerically); }); } var path = fast_path_1.default.from(ast); var oldReuseWhitespace = config.reuseWhitespace; config.reuseWhitespace = false; var pr = new PrintResult(printGenerically(path).toString(config)); config.reuseWhitespace = oldReuseWhitespace; return pr; }; }; exports.Printer = Printer; function genericPrint(path, config, options, printPath) { assert_1.default.ok(path instanceof fast_path_1.default); var node2 = path.getValue(); var parts = []; var linesWithoutParens = genericPrintNoParens(path, config, printPath); if (!node2 || linesWithoutParens.isEmpty()) { return linesWithoutParens; } var shouldAddParens = false; var decoratorsLines = printDecorators(path, printPath); if (decoratorsLines.isEmpty()) { if (!options.avoidRootParens) { shouldAddParens = path.needsParens(); } } else { parts.push(decoratorsLines); } if (shouldAddParens) { parts.unshift("("); } parts.push(linesWithoutParens); if (shouldAddParens) { parts.push(")"); } return (0, lines_1.concat)(parts); } function genericPrintNoParens(path, options, print) { var n = path.getValue(); if (!n) { return (0, lines_1.fromString)(""); } if (typeof n === "string") { return (0, lines_1.fromString)(n, options); } namedTypes.Printable.assert(n); var parts = []; switch (n.type) { case "File": return path.call(print, "program"); case "Program": if (n.directives) { path.each(function(childPath) { parts.push(print(childPath), ";\n"); }, "directives"); } if (n.interpreter) { parts.push(path.call(print, "interpreter")); } parts.push(path.call(function(bodyPath) { return printStatementSequence(bodyPath, options, print); }, "body")); return (0, lines_1.concat)(parts); case "Noop": case "EmptyStatement": return (0, lines_1.fromString)(""); case "ExpressionStatement": return (0, lines_1.concat)([path.call(print, "expression"), ";"]); case "ParenthesizedExpression": return (0, lines_1.concat)(["(", path.call(print, "expression"), ")"]); case "BinaryExpression": case "LogicalExpression": case "AssignmentExpression": return (0, lines_1.fromString)(" ").join([ path.call(print, "left"), n.operator, path.call(print, "right") ]); case "AssignmentPattern": return (0, lines_1.concat)([ path.call(print, "left"), " = ", path.call(print, "right") ]); case "MemberExpression": case "OptionalMemberExpression": { parts.push(path.call(print, "object")); var property = path.call(print, "property"); var optional = types.getFieldValue(n, "optional"); if (n.computed) { parts.push(optional ? "?.[" : "[", property, "]"); } else { parts.push(optional ? "?." : ".", property); } return (0, lines_1.concat)(parts); } case "ChainExpression": return path.call(print, "expression"); case "MetaProperty": return (0, lines_1.concat)([ path.call(print, "meta"), ".", path.call(print, "property") ]); case "BindExpression": if (n.object) { parts.push(path.call(print, "object")); } parts.push("::", path.call(print, "callee")); return (0, lines_1.concat)(parts); case "Path": return (0, lines_1.fromString)(".").join(n.body); case "Identifier": return (0, lines_1.concat)([ (0, lines_1.fromString)(n.name, options), n.optional ? "?" : "", path.call(print, "typeAnnotation") ]); case "SpreadElement": case "SpreadElementPattern": case "RestProperty": case "SpreadProperty": case "SpreadPropertyPattern": case "ObjectTypeSpreadProperty": case "RestElement": return (0, lines_1.concat)([ "...", path.call(print, "argument"), path.call(print, "typeAnnotation") ]); case "FunctionDeclaration": case "FunctionExpression": case "TSDeclareFunction": if (n.declare) { parts.push("declare "); } if (n.async) { parts.push("async "); } parts.push("function"); if (n.generator) parts.push("*"); if (n.id) { parts.push(" ", path.call(print, "id"), path.call(print, "typeParameters")); } else { if (n.typeParameters) { parts.push(path.call(print, "typeParameters")); } } parts.push("(", printFunctionParams(path, options, print), ")", path.call(print, "returnType")); if (n.body) { parts.push(" ", path.call(print, "body")); } return (0, lines_1.concat)(parts); case "ArrowFunctionExpression": if (n.async) { parts.push("async "); } if (n.typeParameters) { parts.push(path.call(print, "typeParameters")); } if (!options.arrowParensAlways && n.params.length === 1 && !n.rest && n.params[0].type === "Identifier" && !n.params[0].typeAnnotation && !n.returnType) { parts.push(path.call(print, "params", 0)); } else { parts.push("(", printFunctionParams(path, options, print), ")", path.call(print, "returnType")); } parts.push(" => ", path.call(print, "body")); return (0, lines_1.concat)(parts); case "MethodDefinition": return printMethod(path, options, print); case "YieldExpression": parts.push("yield"); if (n.delegate) parts.push("*"); if (n.argument) parts.push(" ", path.call(print, "argument")); return (0, lines_1.concat)(parts); case "AwaitExpression": parts.push("await"); if (n.all) parts.push("*"); if (n.argument) parts.push(" ", path.call(print, "argument")); return (0, lines_1.concat)(parts); case "ModuleExpression": return (0, lines_1.concat)([ "module {\n", path.call(print, "body").indent(options.tabWidth), "\n}" ]); case "ModuleDeclaration": parts.push("module", path.call(print, "id")); if (n.source) { assert_1.default.ok(!n.body); parts.push("from", path.call(print, "source")); } else { parts.push(path.call(print, "body")); } return (0, lines_1.fromString)(" ").join(parts); case "ImportSpecifier": if (n.importKind && n.importKind !== "value") { parts.push(n.importKind + " "); } if (n.imported) { parts.push(path.call(print, "imported")); if (n.local && n.local.name !== n.imported.name) { parts.push(" as ", path.call(print, "local")); } } else if (n.id) { parts.push(path.call(print, "id")); if (n.name) { parts.push(" as ", path.call(print, "name")); } } return (0, lines_1.concat)(parts); case "ExportSpecifier": if (n.exportKind && n.exportKind !== "value") { parts.push(n.exportKind + " "); } if (n.local) { parts.push(path.call(print, "local")); if (n.exported && n.exported.name !== n.local.name) { parts.push(" as ", path.call(print, "exported")); } } else if (n.id) { parts.push(path.call(print, "id")); if (n.name) { parts.push(" as ", path.call(print, "name")); } } return (0, lines_1.concat)(parts); case "ExportBatchSpecifier": return (0, lines_1.fromString)("*"); case "ImportNamespaceSpecifier": parts.push("* as "); if (n.local) { parts.push(path.call(print, "local")); } else if (n.id) { parts.push(path.call(print, "id")); } return (0, lines_1.concat)(parts); case "ImportDefaultSpecifier": if (n.local) { return path.call(print, "local"); } return path.call(print, "id"); case "TSExportAssignment": return (0, lines_1.concat)(["export = ", path.call(print, "expression")]); case "ExportDeclaration": case "ExportDefaultDeclaration": case "ExportNamedDeclaration": return printExportDeclaration(path, options, print); case "ExportAllDeclaration": parts.push("export *"); if (n.exported) { parts.push(" as ", path.call(print, "exported")); } parts.push(" from ", path.call(print, "source"), ";"); return (0, lines_1.concat)(parts); case "TSNamespaceExportDeclaration": parts.push("export as namespace ", path.call(print, "id")); return maybeAddSemicolon((0, lines_1.concat)(parts)); case "ExportNamespaceSpecifier": return (0, lines_1.concat)(["* as ", path.call(print, "exported")]); case "ExportDefaultSpecifier": return path.call(print, "exported"); case "Import": return (0, lines_1.fromString)("import", options); case "ImportExpression": return (0, lines_1.concat)(["import(", path.call(print, "source"), ")"]); case "ImportDeclaration": { parts.push("import "); if (n.importKind && n.importKind !== "value") { parts.push(n.importKind + " "); } if (n.specifiers && n.specifiers.length > 0) { var unbracedSpecifiers_1 = []; var bracedSpecifiers_1 = []; path.each(function(specifierPath) { var spec = specifierPath.getValue(); if (spec.type === "ImportSpecifier") { bracedSpecifiers_1.push(print(specifierPath)); } else if (spec.type === "ImportDefaultSpecifier" || spec.type === "ImportNamespaceSpecifier") { unbracedSpecifiers_1.push(print(specifierPath)); } }, "specifiers"); unbracedSpecifiers_1.forEach(function(lines2, i2) { if (i2 > 0) { parts.push(", "); } parts.push(lines2); }); if (bracedSpecifiers_1.length > 0) { var lines = (0, lines_1.fromString)(", ").join(bracedSpecifiers_1); if (lines.getLineLength(1) > options.wrapColumn) { lines = (0, lines_1.concat)([ (0, lines_1.fromString)(",\n").join(bracedSpecifiers_1).indent(options.tabWidth), "," ]); } if (unbracedSpecifiers_1.length > 0) { parts.push(", "); } if (lines.length > 1) { parts.push("{\n", lines, "\n}"); } else if (options.objectCurlySpacing) { parts.push("{ ", lines, " }"); } else { parts.push("{", lines, "}"); } } parts.push(" from "); } parts.push(path.call(print, "source"), maybePrintImportAssertions(path, options, print), ";"); return (0, lines_1.concat)(parts); } case "ImportAttribute": return (0, lines_1.concat)([path.call(print, "key"), ": ", path.call(print, "value")]); case "StaticBlock": parts.push("static "); case "BlockStatement": { var naked_1 = path.call(function(bodyPath) { return printStatementSequence(bodyPath, options, print); }, "body"); if (naked_1.isEmpty()) { if (!n.directives || n.directives.length === 0) { parts.push("{}"); return (0, lines_1.concat)(parts); } } parts.push("{\n"); if (n.directives) { path.each(function(childPath) { parts.push(maybeAddSemicolon(print(childPath).indent(options.tabWidth)), n.directives.length > 1 || !naked_1.isEmpty() ? "\n" : ""); }, "directives"); } parts.push(naked_1.indent(options.tabWidth)); parts.push("\n}"); return (0, lines_1.concat)(parts); } case "ReturnStatement": { parts.push("return"); if (n.argument) { var argLines = path.call(print, "argument"); if (argLines.startsWithComment() || argLines.length > 1 && namedTypes.JSXElement && namedTypes.JSXElement.check(n.argument)) { parts.push(" (\n", argLines.indent(options.tabWidth), "\n)"); } else { parts.push(" ", argLines); } } parts.push(";"); return (0, lines_1.concat)(parts); } case "CallExpression": case "OptionalCallExpression": parts.push(path.call(print, "callee")); if (n.typeParameters) { parts.push(path.call(print, "typeParameters")); } if (n.typeArguments) { parts.push(path.call(print, "typeArguments")); } if (types.getFieldValue(n, "optional")) { parts.push("?."); } parts.push(printArgumentsList(path, options, print)); return (0, lines_1.concat)(parts); case "RecordExpression": parts.push("#"); case "ObjectExpression": case "ObjectPattern": case "ObjectTypeAnnotation": { var isTypeAnnotation_1 = n.type === "ObjectTypeAnnotation"; var separator_1 = options.flowObjectCommas ? "," : isTypeAnnotation_1 ? ";" : ","; var fields = []; var allowBreak_1 = false; if (isTypeAnnotation_1) { fields.push("indexers", "callProperties"); if (n.internalSlots != null) { fields.push("internalSlots"); } } fields.push("properties"); var len_1 = 0; fields.forEach(function(field) { len_1 += n[field].length; }); var oneLine_1 = isTypeAnnotation_1 && len_1 === 1 || len_1 === 0; var leftBrace = n.exact ? "{|" : "{"; var rightBrace = n.exact ? "|}" : "}"; parts.push(oneLine_1 ? leftBrace : leftBrace + "\n"); var leftBraceIndex = parts.length - 1; var i_1 = 0; fields.forEach(function(field) { path.each(function(childPath) { var lines2 = print(childPath); if (!oneLine_1) { lines2 = lines2.indent(options.tabWidth); } var multiLine = !isTypeAnnotation_1 && lines2.length > 1; if (multiLine && allowBreak_1) { parts.push("\n"); } parts.push(lines2); if (i_1 < len_1 - 1) { parts.push(separator_1 + (multiLine ? "\n\n" : "\n")); allowBreak_1 = !multiLine; } else if (len_1 !== 1 && isTypeAnnotation_1) { parts.push(separator_1); } else if (!oneLine_1 && util2.isTrailingCommaEnabled(options, "objects") && childPath.getValue().type !== "RestElement") { parts.push(separator_1); } i_1++; }, field); }); if (n.inexact) { var line = (0, lines_1.fromString)("...", options); if (oneLine_1) { if (len_1 > 0) { parts.push(separator_1, " "); } parts.push(line); } else { parts.push("\n", line.indent(options.tabWidth)); } } parts.push(oneLine_1 ? rightBrace : "\n" + rightBrace); if (i_1 !== 0 && oneLine_1 && options.objectCurlySpacing) { parts[leftBraceIndex] = leftBrace + " "; parts[parts.length - 1] = " " + rightBrace; } if (n.typeAnnotation) { parts.push(path.call(print, "typeAnnotation")); } return (0, lines_1.concat)(parts); } case "PropertyPattern": return (0, lines_1.concat)([ path.call(print, "key"), ": ", path.call(print, "pattern") ]); case "ObjectProperty": case "Property": { if (n.method || n.kind === "get" || n.kind === "set") { return printMethod(path, options, print); } if (n.shorthand && n.value.type === "AssignmentPattern") { return path.call(print, "value"); } var key = path.call(print, "key"); if (n.computed) { parts.push("[", key, "]"); } else { parts.push(key); } if (!n.shorthand || n.key.name !== n.value.name) { parts.push(": ", path.call(print, "value")); } return (0, lines_1.concat)(parts); } case "ClassMethod": case "ObjectMethod": case "ClassPrivateMethod": case "TSDeclareMethod": return printMethod(path, options, print); case "PrivateName": return (0, lines_1.concat)(["#", path.call(print, "id")]); case "Decorator": return (0, lines_1.concat)(["@", path.call(print, "expression")]); case "TupleExpression": parts.push("#"); case "ArrayExpression": case "ArrayPattern": { var elems = n.elements; var len_2 = elems.length; var printed_1 = path.map(print, "elements"); var joined = (0, lines_1.fromString)(", ").join(printed_1); var oneLine_2 = joined.getLineLength(1) <= options.wrapColumn; if (oneLine_2) { if (options.arrayBracketSpacing) { parts.push("[ "); } else { parts.push("["); } } else { parts.push("[\n"); } path.each(function(elemPath) { var i2 = elemPath.getName(); var elem = elemPath.getValue(); if (!elem) { parts.push(","); } else { var lines2 = printed_1[i2]; if (oneLine_2) { if (i2 > 0) parts.push(" "); } else { lines2 = lines2.indent(options.tabWidth); } parts.push(lines2); if (i2 < len_2 - 1 || !oneLine_2 && util2.isTrailingCommaEnabled(options, "arrays")) parts.push(","); if (!oneLine_2) parts.push("\n"); } }, "elements"); if (oneLine_2 && options.arrayBracketSpacing) { parts.push(" ]"); } else { parts.push("]"); } if (n.typeAnnotation) { parts.push(path.call(print, "typeAnnotation")); } return (0, lines_1.concat)(parts); } case "SequenceExpression": return (0, lines_1.fromString)(", ").join(path.map(print, "expressions")); case "ThisExpression": return (0, lines_1.fromString)("this"); case "Super": return (0, lines_1.fromString)("super"); case "NullLiteral": return (0, lines_1.fromString)("null"); case "RegExpLiteral": return (0, lines_1.fromString)(getPossibleRaw(n) || "/".concat(n.pattern, "/").concat(n.flags || ""), options); case "BigIntLiteral": return (0, lines_1.fromString)(getPossibleRaw(n) || n.value + "n", options); case "NumericLiteral": return (0, lines_1.fromString)(getPossibleRaw(n) || n.value, options); case "DecimalLiteral": return (0, lines_1.fromString)(getPossibleRaw(n) || n.value + "m", options); case "StringLiteral": return (0, lines_1.fromString)(nodeStr(n.value, options)); case "BooleanLiteral": case "Literal": return (0, lines_1.fromString)(getPossibleRaw(n) || (typeof n.value === "string" ? nodeStr(n.value, options) : n.value), options); case "Directive": return path.call(print, "value"); case "DirectiveLiteral": return (0, lines_1.fromString)(getPossibleRaw(n) || nodeStr(n.value, options), options); case "InterpreterDirective": return (0, lines_1.fromString)("#!".concat(n.value, "\n"), options); case "ModuleSpecifier": if (n.local) { throw new Error("The ESTree ModuleSpecifier type should be abstract"); } return (0, lines_1.fromString)(nodeStr(n.value, options), options); case "UnaryExpression": parts.push(n.operator); if (/[a-z]$/.test(n.operator)) parts.push(" "); parts.push(path.call(print, "argument")); return (0, lines_1.concat)(parts); case "UpdateExpression": parts.push(path.call(print, "argument"), n.operator); if (n.prefix) parts.reverse(); return (0, lines_1.concat)(parts); case "ConditionalExpression": return (0, lines_1.concat)([ path.call(print, "test"), " ? ", path.call(print, "consequent"), " : ", path.call(print, "alternate") ]); case "NewExpression": { parts.push("new ", path.call(print, "callee")); if (n.typeParameters) { parts.push(path.call(print, "typeParameters")); } if (n.typeArguments) { parts.push(path.call(print, "typeArguments")); } var args = n.arguments; if (args) { parts.push(printArgumentsList(path, options, print)); } return (0, lines_1.concat)(parts); } case "VariableDeclaration": { if (n.declare) { parts.push("declare "); } parts.push(n.kind, " "); var maxLen_1 = 0; var printed = path.map(function(childPath) { var lines2 = print(childPath); maxLen_1 = Math.max(lines2.length, maxLen_1); return lines2; }, "declarations"); if (maxLen_1 === 1) { parts.push((0, lines_1.fromString)(", ").join(printed)); } else if (printed.length > 1) { parts.push((0, lines_1.fromString)(",\n").join(printed).indentTail(n.kind.length + 1)); } else { parts.push(printed[0]); } var parentNode = path.getParentNode(); if (!namedTypes.ForStatement.check(parentNode) && !namedTypes.ForInStatement.check(parentNode) && !(namedTypes.ForOfStatement && namedTypes.ForOfStatement.check(parentNode)) && !(namedTypes.ForAwaitStatement && namedTypes.ForAwaitStatement.check(parentNode))) { parts.push(";"); } return (0, lines_1.concat)(parts); } case "VariableDeclarator": return n.init ? (0, lines_1.fromString)(" = ").join([ path.call(print, "id"), path.call(print, "init") ]) : path.call(print, "id"); case "WithStatement": return (0, lines_1.concat)([ "with (", path.call(print, "object"), ") ", path.call(print, "body") ]); case "IfStatement": { var con = adjustClause(path.call(print, "consequent"), options); parts.push("if (", path.call(print, "test"), ")", con); if (n.alternate) parts.push(endsWithBrace(con) ? " else" : "\nelse", adjustClause(path.call(print, "alternate"), options)); return (0, lines_1.concat)(parts); } case "ForStatement": { var init = path.call(print, "init"); var sep = init.length > 1 ? ";\n" : "; "; var forParen = "for ("; var indented = (0, lines_1.fromString)(sep).join([init, path.call(print, "test"), path.call(print, "update")]).indentTail(forParen.length); var head = (0, lines_1.concat)([forParen, indented, ")"]); var clause = adjustClause(path.call(print, "body"), options); parts.push(head); if (head.length > 1) { parts.push("\n"); clause = clause.trimLeft(); } parts.push(clause); return (0, lines_1.concat)(parts); } case "WhileStatement": return (0, lines_1.concat)([ "while (", path.call(print, "test"), ")", adjustClause(path.call(print, "body"), options) ]); case "ForInStatement": return (0, lines_1.concat)([ n.each ? "for each (" : "for (", path.call(print, "left"), " in ", path.call(print, "right"), ")", adjustClause(path.call(print, "body"), options) ]); case "ForOfStatement": case "ForAwaitStatement": parts.push("for "); if (n.await || n.type === "ForAwaitStatement") { parts.push("await "); } parts.push("(", path.call(print, "left"), " of ", path.call(print, "right"), ")", adjustClause(path.call(print, "body"), options)); return (0, lines_1.concat)(parts); case "DoWhileStatement": { var doBody = (0, lines_1.concat)([ "do", adjustClause(path.call(print, "body"), options) ]); parts.push(doBody); if (endsWithBrace(doBody)) parts.push(" while"); else parts.push("\nwhile"); parts.push(" (", path.call(print, "test"), ");"); return (0, lines_1.concat)(parts); } case "DoExpression": { var statements = path.call(function(bodyPath) { return printStatementSequence(bodyPath, options, print); }, "body"); return (0, lines_1.concat)(["do {\n", statements.indent(options.tabWidth), "\n}"]); } case "BreakStatement": parts.push("break"); if (n.label) parts.push(" ", path.call(print, "label")); parts.push(";"); return (0, lines_1.concat)(parts); case "ContinueStatement": parts.push("continue"); if (n.label) parts.push(" ", path.call(print, "label")); parts.push(";"); return (0, lines_1.concat)(parts); case "LabeledStatement": return (0, lines_1.concat)([ path.call(print, "label"), ":\n", path.call(print, "body") ]); case "TryStatement": parts.push("try ", path.call(print, "block")); if (n.handler) { parts.push(" ", path.call(print, "handler")); } else if (n.handlers) { path.each(function(handlerPath) { parts.push(" ", print(handlerPath)); }, "handlers"); } if (n.finalizer) { parts.push(" finally ", path.call(print, "finalizer")); } return (0, lines_1.concat)(parts); case "CatchClause": parts.push("catch "); if (n.param) { parts.push("(", path.call(print, "param")); } if (n.guard) { parts.push(" if ", path.call(print, "guard")); } if (n.param) { parts.push(") "); } parts.push(path.call(print, "body")); return (0, lines_1.concat)(parts); case "ThrowStatement": return (0, lines_1.concat)(["throw ", path.call(print, "argument"), ";"]); case "SwitchStatement": return (0, lines_1.concat)([ "switch (", path.call(print, "discriminant"), ") {\n", (0, lines_1.fromString)("\n").join(path.map(print, "cases")), "\n}" ]); case "SwitchCase": if (n.test) parts.push("case ", path.call(print, "test"), ":"); else parts.push("default:"); if (n.consequent.length > 0) { parts.push("\n", path.call(function(consequentPath) { return printStatementSequence(consequentPath, options, print); }, "consequent").indent(options.tabWidth)); } return (0, lines_1.concat)(parts); case "DebuggerStatement": return (0, lines_1.fromString)("debugger;"); case "JSXAttribute": parts.push(path.call(print, "name")); if (n.value) parts.push("=", path.call(print, "value")); return (0, lines_1.concat)(parts); case "JSXIdentifier": return (0, lines_1.fromString)(n.name, options); case "JSXNamespacedName": return (0, lines_1.fromString)(":").join([ path.call(print, "namespace"), path.call(print, "name") ]); case "JSXMemberExpression": return (0, lines_1.fromString)(".").join([ path.call(print, "object"), path.call(print, "property") ]); case "JSXSpreadAttribute": return (0, lines_1.concat)(["{...", path.call(print, "argument"), "}"]); case "JSXSpreadChild": return (0, lines_1.concat)(["{...", path.call(print, "expression"), "}"]); case "JSXExpressionContainer": return (0, lines_1.concat)(["{", path.call(print, "expression"), "}"]); case "JSXElement": case "JSXFragment": { var openingPropName = "opening" + (n.type === "JSXElement" ? "Element" : "Fragment"); var closingPropName = "closing" + (n.type === "JSXElement" ? "Element" : "Fragment"); var openingLines = path.call(print, openingPropName); if (n[openingPropName].selfClosing) { assert_1.default.ok(!n[closingPropName], "unexpected " + closingPropName + " element in self-closing " + n.type); return openingLines; } var childLines = (0, lines_1.concat)(path.map(function(childPath) { var child = childPath.getValue(); if (namedTypes.Literal.check(child) && typeof child.value === "string") { if (/\S/.test(child.value)) { return child.value.replace(/^\s+|\s+$/g, ""); } else if (/\n/.test(child.value)) { return "\n"; } } return print(childPath); }, "children")).indentTail(options.tabWidth); var closingLines = path.call(print, closingPropName); return (0, lines_1.concat)([openingLines, childLines, closingLines]); } case "JSXOpeningElement": { parts.push("<", path.call(print, "name")); var attrParts_1 = []; path.each(function(attrPath) { attrParts_1.push(" ", print(attrPath)); }, "attributes"); var attrLines = (0, lines_1.concat)(attrParts_1); var needLineWrap = attrLines.length > 1 || attrLines.getLineLength(1) > options.wrapColumn; if (needLineWrap) { attrParts_1.forEach(function(part, i2) { if (part === " ") { assert_1.default.strictEqual(i2 % 2, 0); attrParts_1[i2] = "\n"; } }); attrLines = (0, lines_1.concat)(attrParts_1).indentTail(options.tabWidth); } parts.push(attrLines, n.selfClosing ? " />" : ">"); return (0, lines_1.concat)(parts); } case "JSXClosingElement": return (0, lines_1.concat)([""]); case "JSXOpeningFragment": return (0, lines_1.fromString)("<>"); case "JSXClosingFragment": return (0, lines_1.fromString)(""); case "JSXText": return (0, lines_1.fromString)(n.value, options); case "JSXEmptyExpression": return (0, lines_1.fromString)(""); case "TypeAnnotatedIdentifier": return (0, lines_1.concat)([ path.call(print, "annotation"), " ", path.call(print, "identifier") ]); case "ClassBody": if (n.body.length === 0) { return (0, lines_1.fromString)("{}"); } return (0, lines_1.concat)([ "{\n", path.call(function(bodyPath) { return printStatementSequence(bodyPath, options, print); }, "body").indent(options.tabWidth), "\n}" ]); case "ClassPropertyDefinition": parts.push("static ", path.call(print, "definition")); if (!namedTypes.MethodDefinition.check(n.definition)) parts.push(";"); return (0, lines_1.concat)(parts); case "ClassProperty": { if (n.declare) { parts.push("declare "); } var access = n.accessibility || n.access; if (typeof access === "string") { parts.push(access, " "); } if (n.static) { parts.push("static "); } if (n.abstract) { parts.push("abstract "); } if (n.readonly) { parts.push("readonly "); } var key = path.call(print, "key"); if (n.computed) { key = (0, lines_1.concat)(["[", key, "]"]); } if (n.variance) { key = (0, lines_1.concat)([printVariance(path, print), key]); } parts.push(key); if (n.optional) { parts.push("?"); } if (n.definite) { parts.push("!"); } if (n.typeAnnotation) { parts.push(path.call(print, "typeAnnotation")); } if (n.value) { parts.push(" = ", path.call(print, "value")); } parts.push(";"); return (0, lines_1.concat)(parts); } case "ClassPrivateProperty": if (n.static) { parts.push("static "); } parts.push(path.call(print, "key")); if (n.typeAnnotation) { parts.push(path.call(print, "typeAnnotation")); } if (n.value) { parts.push(" = ", path.call(print, "value")); } parts.push(";"); return (0, lines_1.concat)(parts); case "ClassAccessorProperty": { parts.push.apply(parts, tslib_1.__spreadArray(tslib_1.__spreadArray([], printClassMemberModifiers(n), false), ["accessor "], false)); if (n.computed) { parts.push("[", path.call(print, "key"), "]"); } else { parts.push(path.call(print, "key")); } if (n.optional) { parts.push("?"); } if (n.definite) { parts.push("!"); } if (n.typeAnnotation) { parts.push(path.call(print, "typeAnnotation")); } if (n.value) { parts.push(" = ", path.call(print, "value")); } parts.push(";"); return (0, lines_1.concat)(parts); } case "ClassDeclaration": case "ClassExpression": case "DeclareClass": if (n.declare) { parts.push("declare "); } if (n.abstract) { parts.push("abstract "); } parts.push("class"); if (n.id) { parts.push(" ", path.call(print, "id")); } if (n.typeParameters) { parts.push(path.call(print, "typeParameters")); } if (n.superClass) { parts.push(" extends ", path.call(print, "superClass"), path.call(print, "superTypeParameters")); } if (n.extends && n.extends.length > 0) { parts.push(" extends ", (0, lines_1.fromString)(", ").join(path.map(print, "extends"))); } if (n["implements"] && n["implements"].length > 0) { parts.push(" implements ", (0, lines_1.fromString)(", ").join(path.map(print, "implements"))); } parts.push(" ", path.call(print, "body")); if (n.type === "DeclareClass") { return printFlowDeclaration(path, parts); } else { return (0, lines_1.concat)(parts); } case "TemplateElement": return (0, lines_1.fromString)(n.value.raw, options).lockIndentTail(); case "TemplateLiteral": { var expressions_1 = path.map(print, "expressions"); parts.push("`"); path.each(function(childPath) { var i2 = childPath.getName(); parts.push(print(childPath)); if (i2 < expressions_1.length) { parts.push("${", expressions_1[i2], "}"); } }, "quasis"); parts.push("`"); return (0, lines_1.concat)(parts).lockIndentTail(); } case "TaggedTemplateExpression": return (0, lines_1.concat)([path.call(print, "tag"), path.call(print, "quasi")]); case "Node": case "Printable": case "SourceLocation": case "Position": case "Statement": case "Function": case "Pattern": case "Expression": case "Declaration": case "Specifier": case "NamedSpecifier": case "Comment": case "Flow": case "FlowType": case "FlowPredicate": case "MemberTypeAnnotation": case "Type": case "TSHasOptionalTypeParameterInstantiation": case "TSHasOptionalTypeParameters": case "TSHasOptionalTypeAnnotation": case "ChainElement": throw new Error("unprintable type: " + JSON.stringify(n.type)); case "CommentBlock": case "Block": return (0, lines_1.concat)(["/*", (0, lines_1.fromString)(n.value, options), "*/"]); case "CommentLine": case "Line": return (0, lines_1.concat)(["//", (0, lines_1.fromString)(n.value, options)]); case "TypeAnnotation": if (n.typeAnnotation) { if (n.typeAnnotation.type !== "FunctionTypeAnnotation") { parts.push(": "); } parts.push(path.call(print, "typeAnnotation")); return (0, lines_1.concat)(parts); } return (0, lines_1.fromString)(""); case "ExistentialTypeParam": case "ExistsTypeAnnotation": return (0, lines_1.fromString)("*", options); case "EmptyTypeAnnotation": return (0, lines_1.fromString)("empty", options); case "AnyTypeAnnotation": return (0, lines_1.fromString)("any", options); case "MixedTypeAnnotation": return (0, lines_1.fromString)("mixed", options); case "ArrayTypeAnnotation": return (0, lines_1.concat)([path.call(print, "elementType"), "[]"]); case "TupleTypeAnnotation": { var printed_2 = path.map(print, "types"); var joined = (0, lines_1.fromString)(", ").join(printed_2); var oneLine_3 = joined.getLineLength(1) <= options.wrapColumn; if (oneLine_3) { if (options.arrayBracketSpacing) { parts.push("[ "); } else { parts.push("["); } } else { parts.push("[\n"); } path.each(function(elemPath) { var i2 = elemPath.getName(); var elem = elemPath.getValue(); if (!elem) { parts.push(","); } else { var lines2 = printed_2[i2]; if (oneLine_3) { if (i2 > 0) parts.push(" "); } else { lines2 = lines2.indent(options.tabWidth); } parts.push(lines2); if (i2 < n.types.length - 1 || !oneLine_3 && util2.isTrailingCommaEnabled(options, "arrays")) parts.push(","); if (!oneLine_3) parts.push("\n"); } }, "types"); if (oneLine_3 && options.arrayBracketSpacing) { parts.push(" ]"); } else { parts.push("]"); } return (0, lines_1.concat)(parts); } case "BooleanTypeAnnotation": return (0, lines_1.fromString)("boolean", options); case "BooleanLiteralTypeAnnotation": assert_1.default.strictEqual(typeof n.value, "boolean"); return (0, lines_1.fromString)("" + n.value, options); case "InterfaceTypeAnnotation": parts.push("interface"); if (n.extends && n.extends.length > 0) { parts.push(" extends ", (0, lines_1.fromString)(", ").join(path.map(print, "extends"))); } parts.push(" ", path.call(print, "body")); return (0, lines_1.concat)(parts); case "DeclareFunction": return printFlowDeclaration(path, [ "function ", path.call(print, "id"), ";" ]); case "DeclareModule": return printFlowDeclaration(path, [ "module ", path.call(print, "id"), " ", path.call(print, "body") ]); case "DeclareModuleExports": return printFlowDeclaration(path, [ "module.exports", path.call(print, "typeAnnotation") ]); case "DeclareVariable": return printFlowDeclaration(path, ["var ", path.call(print, "id"), ";"]); case "DeclareExportDeclaration": case "DeclareExportAllDeclaration": return (0, lines_1.concat)(["declare ", printExportDeclaration(path, options, print)]); case "EnumDeclaration": return (0, lines_1.concat)([ "enum ", path.call(print, "id"), path.call(print, "body") ]); case "EnumBooleanBody": case "EnumNumberBody": case "EnumStringBody": case "EnumSymbolBody": { if (n.type === "EnumSymbolBody" || n.explicitType) { parts.push( " of ", // EnumBooleanBody => boolean, etc. n.type.slice(4, -4).toLowerCase() ); } parts.push(" {\n", (0, lines_1.fromString)("\n").join(path.map(print, "members")).indent(options.tabWidth), "\n}"); return (0, lines_1.concat)(parts); } case "EnumDefaultedMember": return (0, lines_1.concat)([path.call(print, "id"), ","]); case "EnumBooleanMember": case "EnumNumberMember": case "EnumStringMember": return (0, lines_1.concat)([ path.call(print, "id"), " = ", path.call(print, "init"), "," ]); case "InferredPredicate": return (0, lines_1.fromString)("%checks", options); case "DeclaredPredicate": return (0, lines_1.concat)(["%checks(", path.call(print, "value"), ")"]); case "FunctionTypeAnnotation": { var parent = path.getParentNode(0); var isArrowFunctionTypeAnnotation = !(namedTypes.ObjectTypeCallProperty.check(parent) || namedTypes.ObjectTypeInternalSlot.check(parent) && parent.method || namedTypes.DeclareFunction.check(path.getParentNode(2))); var needsColon = isArrowFunctionTypeAnnotation && !namedTypes.FunctionTypeParam.check(parent) && !namedTypes.TypeAlias.check(parent); if (needsColon) { parts.push(": "); } var hasTypeParameters = !!n.typeParameters; var needsParens = hasTypeParameters || n.params.length !== 1 || n.params[0].name; parts.push(hasTypeParameters ? path.call(print, "typeParameters") : "", needsParens ? "(" : "", printFunctionParams(path, options, print), needsParens ? ")" : ""); if (n.returnType) { parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType")); } return (0, lines_1.concat)(parts); } case "FunctionTypeParam": { var name = path.call(print, "name"); parts.push(name); if (n.optional) { parts.push("?"); } if (name.infos[0].line) { parts.push(": "); } parts.push(path.call(print, "typeAnnotation")); return (0, lines_1.concat)(parts); } case "GenericTypeAnnotation": return (0, lines_1.concat)([ path.call(print, "id"), path.call(print, "typeParameters") ]); case "DeclareInterface": parts.push("declare "); case "InterfaceDeclaration": case "TSInterfaceDeclaration": if (n.declare) { parts.push("declare "); } parts.push("interface ", path.call(print, "id"), path.call(print, "typeParameters"), " "); if (n["extends"] && n["extends"].length > 0) { parts.push("extends ", (0, lines_1.fromString)(", ").join(path.map(print, "extends")), " "); } if (n.body) { parts.push(path.call(print, "body")); } return (0, lines_1.concat)(parts); case "ClassImplements": case "InterfaceExtends": return (0, lines_1.concat)([ path.call(print, "id"), path.call(print, "typeParameters") ]); case "IntersectionTypeAnnotation": return (0, lines_1.fromString)(" & ").join(path.map(print, "types")); case "NullableTypeAnnotation": return (0, lines_1.concat)(["?", path.call(print, "typeAnnotation")]); case "NullLiteralTypeAnnotation": return (0, lines_1.fromString)("null", options); case "ThisTypeAnnotation": return (0, lines_1.fromString)("this", options); case "NumberTypeAnnotation": return (0, lines_1.fromString)("number", options); case "ObjectTypeCallProperty": return path.call(print, "value"); case "ObjectTypeIndexer": if (n.static) { parts.push("static "); } parts.push(printVariance(path, print), "["); if (n.id) { parts.push(path.call(print, "id"), ": "); } parts.push(path.call(print, "key"), "]: ", path.call(print, "value")); return (0, lines_1.concat)(parts); case "ObjectTypeProperty": return (0, lines_1.concat)([ printVariance(path, print), path.call(print, "key"), n.optional ? "?" : "", ": ", path.call(print, "value") ]); case "ObjectTypeInternalSlot": return (0, lines_1.concat)([ n.static ? "static " : "", "[[", path.call(print, "id"), "]]", n.optional ? "?" : "", n.value.type !== "FunctionTypeAnnotation" ? ": " : "", path.call(print, "value") ]); case "QualifiedTypeIdentifier": return (0, lines_1.concat)([ path.call(print, "qualification"), ".", path.call(print, "id") ]); case "StringLiteralTypeAnnotation": return (0, lines_1.fromString)(nodeStr(n.value, options), options); case "NumberLiteralTypeAnnotation": case "NumericLiteralTypeAnnotation": assert_1.default.strictEqual(typeof n.value, "number"); return (0, lines_1.fromString)(JSON.stringify(n.value), options); case "BigIntLiteralTypeAnnotation": return (0, lines_1.fromString)(n.raw, options); case "StringTypeAnnotation": return (0, lines_1.fromString)("string", options); case "DeclareTypeAlias": parts.push("declare "); case "TypeAlias": return (0, lines_1.concat)([ "type ", path.call(print, "id"), path.call(print, "typeParameters"), " = ", path.call(print, "right"), ";" ]); case "DeclareOpaqueType": parts.push("declare "); case "OpaqueType": parts.push("opaque type ", path.call(print, "id"), path.call(print, "typeParameters")); if (n["supertype"]) { parts.push(": ", path.call(print, "supertype")); } if (n["impltype"]) { parts.push(" = ", path.call(print, "impltype")); } parts.push(";"); return (0, lines_1.concat)(parts); case "TypeCastExpression": return (0, lines_1.concat)([ "(", path.call(print, "expression"), path.call(print, "typeAnnotation"), ")" ]); case "TypeParameterDeclaration": case "TypeParameterInstantiation": return (0, lines_1.concat)([ "<", (0, lines_1.fromString)(", ").join(path.map(print, "params")), ">" ]); case "Variance": if (n.kind === "plus") { return (0, lines_1.fromString)("+"); } if (n.kind === "minus") { return (0, lines_1.fromString)("-"); } return (0, lines_1.fromString)(""); case "TypeParameter": if (n.variance) { parts.push(printVariance(path, print)); } parts.push(path.call(print, "name")); if (n.bound) { parts.push(path.call(print, "bound")); } if (n["default"]) { parts.push("=", path.call(print, "default")); } return (0, lines_1.concat)(parts); case "TypeofTypeAnnotation": return (0, lines_1.concat)([ (0, lines_1.fromString)("typeof ", options), path.call(print, "argument") ]); case "IndexedAccessType": case "OptionalIndexedAccessType": return (0, lines_1.concat)([ path.call(print, "objectType"), n.optional ? "?." : "", "[", path.call(print, "indexType"), "]" ]); case "UnionTypeAnnotation": return (0, lines_1.fromString)(" | ").join(path.map(print, "types")); case "VoidTypeAnnotation": return (0, lines_1.fromString)("void", options); case "NullTypeAnnotation": return (0, lines_1.fromString)("null", options); case "SymbolTypeAnnotation": return (0, lines_1.fromString)("symbol", options); case "BigIntTypeAnnotation": return (0, lines_1.fromString)("bigint", options); case "TSType": throw new Error("unprintable type: " + JSON.stringify(n.type)); case "TSNumberKeyword": return (0, lines_1.fromString)("number", options); case "TSBigIntKeyword": return (0, lines_1.fromString)("bigint", options); case "TSObjectKeyword": return (0, lines_1.fromString)("object", options); case "TSBooleanKeyword": return (0, lines_1.fromString)("boolean", options); case "TSStringKeyword": return (0, lines_1.fromString)("string", options); case "TSSymbolKeyword": return (0, lines_1.fromString)("symbol", options); case "TSAnyKeyword": return (0, lines_1.fromString)("any", options); case "TSVoidKeyword": return (0, lines_1.fromString)("void", options); case "TSIntrinsicKeyword": return (0, lines_1.fromString)("intrinsic", options); case "TSThisType": return (0, lines_1.fromString)("this", options); case "TSNullKeyword": return (0, lines_1.fromString)("null", options); case "TSUndefinedKeyword": return (0, lines_1.fromString)("undefined", options); case "TSUnknownKeyword": return (0, lines_1.fromString)("unknown", options); case "TSNeverKeyword": return (0, lines_1.fromString)("never", options); case "TSArrayType": return (0, lines_1.concat)([path.call(print, "elementType"), "[]"]); case "TSLiteralType": return path.call(print, "literal"); case "TSUnionType": return (0, lines_1.fromString)(" | ").join(path.map(print, "types")); case "TSIntersectionType": return (0, lines_1.fromString)(" & ").join(path.map(print, "types")); case "TSConditionalType": parts.push(path.call(print, "checkType"), " extends ", path.call(print, "extendsType"), " ? ", path.call(print, "trueType"), " : ", path.call(print, "falseType")); return (0, lines_1.concat)(parts); case "TSInferType": parts.push("infer ", path.call(print, "typeParameter")); return (0, lines_1.concat)(parts); case "TSParenthesizedType": return (0, lines_1.concat)(["(", path.call(print, "typeAnnotation"), ")"]); case "TSFunctionType": return (0, lines_1.concat)([ path.call(print, "typeParameters"), "(", printFunctionParams(path, options, print), ") => ", path.call(print, "typeAnnotation", "typeAnnotation") ]); case "TSConstructorType": return (0, lines_1.concat)([ "new ", path.call(print, "typeParameters"), "(", printFunctionParams(path, options, print), ") => ", path.call(print, "typeAnnotation", "typeAnnotation") ]); case "TSMappedType": { parts.push(n.readonly ? "readonly " : "", "[", path.call(print, "typeParameter"), "]", n.optional ? "?" : ""); if (n.typeAnnotation) { parts.push(": ", path.call(print, "typeAnnotation"), ";"); } return (0, lines_1.concat)(["{\n", (0, lines_1.concat)(parts).indent(options.tabWidth), "\n}"]); } case "TSTupleType": return (0, lines_1.concat)([ "[", (0, lines_1.fromString)(", ").join(path.map(print, "elementTypes")), "]" ]); case "TSNamedTupleMember": parts.push(path.call(print, "label")); if (n.optional) { parts.push("?"); } parts.push(": ", path.call(print, "elementType")); return (0, lines_1.concat)(parts); case "TSRestType": return (0, lines_1.concat)(["...", path.call(print, "typeAnnotation")]); case "TSOptionalType": return (0, lines_1.concat)([path.call(print, "typeAnnotation"), "?"]); case "TSIndexedAccessType": return (0, lines_1.concat)([ path.call(print, "objectType"), "[", path.call(print, "indexType"), "]" ]); case "TSTypeOperator": return (0, lines_1.concat)([ path.call(print, "operator"), " ", path.call(print, "typeAnnotation") ]); case "TSTypeLiteral": { var members = (0, lines_1.fromString)("\n").join(path.map(print, "members").map(function(member) { if (lastNonSpaceCharacter(member) !== ";") { return member.concat(";"); } return member; })); if (members.isEmpty()) { return (0, lines_1.fromString)("{}", options); } parts.push("{\n", members.indent(options.tabWidth), "\n}"); return (0, lines_1.concat)(parts); } case "TSEnumMember": parts.push(path.call(print, "id")); if (n.initializer) { parts.push(" = ", path.call(print, "initializer")); } return (0, lines_1.concat)(parts); case "TSTypeQuery": return (0, lines_1.concat)(["typeof ", path.call(print, "exprName")]); case "TSParameterProperty": if (n.accessibility) { parts.push(n.accessibility, " "); } if (n.export) { parts.push("export "); } if (n.static) { parts.push("static "); } if (n.readonly) { parts.push("readonly "); } parts.push(path.call(print, "parameter")); return (0, lines_1.concat)(parts); case "TSTypeReference": return (0, lines_1.concat)([ path.call(print, "typeName"), path.call(print, "typeParameters") ]); case "TSQualifiedName": return (0, lines_1.concat)([path.call(print, "left"), ".", path.call(print, "right")]); case "TSAsExpression": case "TSSatisfiesExpression": { var expression = path.call(print, "expression"); parts.push(expression, n.type === "TSSatisfiesExpression" ? " satisfies " : " as ", path.call(print, "typeAnnotation")); return (0, lines_1.concat)(parts); } case "TSTypeCastExpression": return (0, lines_1.concat)([ path.call(print, "expression"), path.call(print, "typeAnnotation") ]); case "TSNonNullExpression": return (0, lines_1.concat)([path.call(print, "expression"), "!"]); case "TSTypeAnnotation": return (0, lines_1.concat)([": ", path.call(print, "typeAnnotation")]); case "TSIndexSignature": return (0, lines_1.concat)([ n.readonly ? "readonly " : "", "[", path.map(print, "parameters"), "]", path.call(print, "typeAnnotation") ]); case "TSPropertySignature": parts.push(printVariance(path, print), n.readonly ? "readonly " : ""); if (n.computed) { parts.push("[", path.call(print, "key"), "]"); } else { parts.push(path.call(print, "key")); } parts.push(n.optional ? "?" : "", path.call(print, "typeAnnotation")); return (0, lines_1.concat)(parts); case "TSMethodSignature": if (n.computed) { parts.push("[", path.call(print, "key"), "]"); } else { parts.push(path.call(print, "key")); } if (n.optional) { parts.push("?"); } parts.push(path.call(print, "typeParameters"), "(", printFunctionParams(path, options, print), ")", path.call(print, "typeAnnotation")); return (0, lines_1.concat)(parts); case "TSTypePredicate": if (n.asserts) { parts.push("asserts "); } parts.push(path.call(print, "parameterName")); if (n.typeAnnotation) { parts.push(" is ", path.call(print, "typeAnnotation", "typeAnnotation")); } return (0, lines_1.concat)(parts); case "TSCallSignatureDeclaration": return (0, lines_1.concat)([ path.call(print, "typeParameters"), "(", printFunctionParams(path, options, print), ")", path.call(print, "typeAnnotation") ]); case "TSConstructSignatureDeclaration": if (n.typeParameters) { parts.push("new", path.call(print, "typeParameters")); } else { parts.push("new "); } parts.push("(", printFunctionParams(path, options, print), ")", path.call(print, "typeAnnotation")); return (0, lines_1.concat)(parts); case "TSTypeAliasDeclaration": return (0, lines_1.concat)([ n.declare ? "declare " : "", "type ", path.call(print, "id"), path.call(print, "typeParameters"), " = ", path.call(print, "typeAnnotation"), ";" ]); case "TSTypeParameter": { parts.push(path.call(print, "name")); var parent = path.getParentNode(0); var isInMappedType = namedTypes.TSMappedType.check(parent); if (n.constraint) { parts.push(isInMappedType ? " in " : " extends ", path.call(print, "constraint")); } if (n["default"]) { parts.push(" = ", path.call(print, "default")); } return (0, lines_1.concat)(parts); } case "TSTypeAssertion": { parts.push("<", path.call(print, "typeAnnotation"), "> ", path.call(print, "expression")); return (0, lines_1.concat)(parts); } case "TSTypeParameterDeclaration": case "TSTypeParameterInstantiation": return (0, lines_1.concat)([ "<", (0, lines_1.fromString)(", ").join(path.map(print, "params")), ">" ]); case "TSEnumDeclaration": { parts.push(n.declare ? "declare " : "", n.const ? "const " : "", "enum ", path.call(print, "id")); var memberLines = (0, lines_1.fromString)(",\n").join(path.map(print, "members")); if (memberLines.isEmpty()) { parts.push(" {}"); } else { parts.push(" {\n", memberLines.indent(options.tabWidth), "\n}"); } return (0, lines_1.concat)(parts); } case "TSExpressionWithTypeArguments": return (0, lines_1.concat)([ path.call(print, "expression"), path.call(print, "typeParameters") ]); case "TSInterfaceBody": { var lines = (0, lines_1.fromString)("\n").join(path.map(print, "body").map(function(element2) { if (lastNonSpaceCharacter(element2) !== ";") { return element2.concat(";"); } return element2; })); if (lines.isEmpty()) { return (0, lines_1.fromString)("{}", options); } return (0, lines_1.concat)(["{\n", lines.indent(options.tabWidth), "\n}"]); } case "TSImportType": parts.push("import(", path.call(print, "argument"), ")"); if (n.qualifier) { parts.push(".", path.call(print, "qualifier")); } if (n.typeParameters) { parts.push(path.call(print, "typeParameters")); } return (0, lines_1.concat)(parts); case "TSImportEqualsDeclaration": if (n.isExport) { parts.push("export "); } parts.push("import ", path.call(print, "id"), " = ", path.call(print, "moduleReference")); return maybeAddSemicolon((0, lines_1.concat)(parts)); case "TSExternalModuleReference": return (0, lines_1.concat)(["require(", path.call(print, "expression"), ")"]); case "TSModuleDeclaration": { var parent = path.getParentNode(); if (parent.type === "TSModuleDeclaration") { parts.push("."); } else { if (n.declare) { parts.push("declare "); } if (!n.global) { var isExternal = n.id.type === "StringLiteral" || n.id.type === "Literal" && typeof n.id.value === "string"; if (isExternal) { parts.push("module "); } else if (n.loc && n.loc.lines && n.id.loc) { var prefix = n.loc.lines.sliceString(n.loc.start, n.id.loc.start); if (prefix.indexOf("module") >= 0) { parts.push("module "); } else { parts.push("namespace "); } } else { parts.push("namespace "); } } } parts.push(path.call(print, "id")); if (n.body) { parts.push(" "); parts.push(path.call(print, "body")); } return (0, lines_1.concat)(parts); } case "TSModuleBlock": { var naked = path.call(function(bodyPath) { return printStatementSequence(bodyPath, options, print); }, "body"); if (naked.isEmpty()) { parts.push("{}"); } else { parts.push("{\n", naked.indent(options.tabWidth), "\n}"); } return (0, lines_1.concat)(parts); } case "TSInstantiationExpression": { parts.push(path.call(print, "expression"), path.call(print, "typeParameters")); return (0, lines_1.concat)(parts); } case "V8IntrinsicIdentifier": return (0, lines_1.concat)(["%", path.call(print, "name")]); case "TopicReference": return (0, lines_1.fromString)("#"); case "ClassHeritage": case "ComprehensionBlock": case "ComprehensionExpression": case "Glob": case "GeneratorExpression": case "LetStatement": case "LetExpression": case "GraphExpression": case "GraphIndexExpression": case "XMLDefaultDeclaration": case "XMLAnyName": case "XMLQualifiedIdentifier": case "XMLFunctionQualifiedIdentifier": case "XMLAttributeSelector": case "XMLFilterExpression": case "XML": case "XMLElement": case "XMLList": case "XMLEscape": case "XMLText": case "XMLStartTag": case "XMLEndTag": case "XMLPointTag": case "XMLName": case "XMLAttribute": case "XMLCdata": case "XMLComment": case "XMLProcessingInstruction": default: debugger; throw new Error("unknown type: " + JSON.stringify(n.type)); } } function printDecorators(path, printPath) { var parts = []; var node2 = path.getValue(); if (node2.decorators && node2.decorators.length > 0 && // If the parent node is an export declaration, it will be // responsible for printing node.decorators. !util2.getParentExportDeclaration(path)) { path.each(function(decoratorPath) { parts.push(printPath(decoratorPath), "\n"); }, "decorators"); } else if (util2.isExportDeclaration(node2) && node2.declaration && node2.declaration.decorators) { path.each(function(decoratorPath) { parts.push(printPath(decoratorPath), "\n"); }, "declaration", "decorators"); } return (0, lines_1.concat)(parts); } function printStatementSequence(path, options, print) { var filtered = []; var sawComment = false; var sawStatement = false; path.each(function(stmtPath) { var stmt = stmtPath.getValue(); if (!stmt) { return; } if (stmt.type === "EmptyStatement" && !(stmt.comments && stmt.comments.length > 0)) { return; } if (namedTypes.Comment.check(stmt)) { sawComment = true; } else if (namedTypes.Statement.check(stmt)) { sawStatement = true; } else { isString.assert(stmt); } filtered.push({ node: stmt, printed: print(stmtPath) }); }); if (sawComment) { assert_1.default.strictEqual(sawStatement, false, "Comments may appear as statements in otherwise empty statement lists, but may not coexist with non-Comment nodes."); } var prevTrailingSpace = null; var len = filtered.length; var parts = []; filtered.forEach(function(info, i2) { var printed = info.printed; var stmt = info.node; var multiLine = printed.length > 1; var notFirst = i2 > 0; var notLast = i2 < len - 1; var leadingSpace; var trailingSpace; var lines = stmt && stmt.loc && stmt.loc.lines; var trueLoc = lines && options.reuseWhitespace && util2.getTrueLoc(stmt, lines); if (notFirst) { if (trueLoc) { var beforeStart = lines.skipSpaces(trueLoc.start, true); var beforeStartLine = beforeStart ? beforeStart.line : 1; var leadingGap = trueLoc.start.line - beforeStartLine; leadingSpace = Array(leadingGap + 1).join("\n"); } else { leadingSpace = multiLine ? "\n\n" : "\n"; } } else { leadingSpace = ""; } if (notLast) { if (trueLoc) { var afterEnd = lines.skipSpaces(trueLoc.end); var afterEndLine = afterEnd ? afterEnd.line : lines.length; var trailingGap = afterEndLine - trueLoc.end.line; trailingSpace = Array(trailingGap + 1).join("\n"); } else { trailingSpace = multiLine ? "\n\n" : "\n"; } } else { trailingSpace = ""; } parts.push(maxSpace(prevTrailingSpace, leadingSpace), printed); if (notLast) { prevTrailingSpace = trailingSpace; } else if (trailingSpace) { parts.push(trailingSpace); } }); return (0, lines_1.concat)(parts); } function maxSpace(s1, s22) { if (!s1 && !s22) { return (0, lines_1.fromString)(""); } if (!s1) { return (0, lines_1.fromString)(s22); } if (!s22) { return (0, lines_1.fromString)(s1); } var spaceLines1 = (0, lines_1.fromString)(s1); var spaceLines2 = (0, lines_1.fromString)(s22); if (spaceLines2.length > spaceLines1.length) { return spaceLines2; } return spaceLines1; } function printClassMemberModifiers(node2) { var parts = []; if (node2.declare) { parts.push("declare "); } var access = node2.accessibility || node2.access; if (typeof access === "string") { parts.push(access, " "); } if (node2.static) { parts.push("static "); } if (node2.override) { parts.push("override "); } if (node2.abstract) { parts.push("abstract "); } if (node2.readonly) { parts.push("readonly "); } return parts; } function printMethod(path, options, print) { var node2 = path.getNode(); var kind = node2.kind; var parts = []; var nodeValue = node2.value; if (!namedTypes.FunctionExpression.check(nodeValue)) { nodeValue = node2; } parts.push.apply(parts, printClassMemberModifiers(node2)); if (nodeValue.async) { parts.push("async "); } if (nodeValue.generator) { parts.push("*"); } if (kind === "get" || kind === "set") { parts.push(kind, " "); } var key = path.call(print, "key"); if (node2.computed) { key = (0, lines_1.concat)(["[", key, "]"]); } parts.push(key); if (node2.optional) { parts.push("?"); } if (node2 === nodeValue) { parts.push(path.call(print, "typeParameters"), "(", printFunctionParams(path, options, print), ")", path.call(print, "returnType")); if (node2.body) { parts.push(" ", path.call(print, "body")); } else { parts.push(";"); } } else { parts.push(path.call(print, "value", "typeParameters"), "(", path.call(function(valuePath) { return printFunctionParams(valuePath, options, print); }, "value"), ")", path.call(print, "value", "returnType")); if (nodeValue.body) { parts.push(" ", path.call(print, "value", "body")); } else { parts.push(";"); } } return (0, lines_1.concat)(parts); } function printArgumentsList(path, options, print) { var printed = path.map(print, "arguments"); var trailingComma = util2.isTrailingCommaEnabled(options, "parameters"); var joined = (0, lines_1.fromString)(", ").join(printed); if (joined.getLineLength(1) > options.wrapColumn) { joined = (0, lines_1.fromString)(",\n").join(printed); return (0, lines_1.concat)([ "(\n", joined.indent(options.tabWidth), trailingComma ? ",\n)" : "\n)" ]); } return (0, lines_1.concat)(["(", joined, ")"]); } function printFunctionParams(path, options, print) { var fun = path.getValue(); var params; var printed = []; if (fun.params) { params = fun.params; printed = path.map(print, "params"); } else if (fun.parameters) { params = fun.parameters; printed = path.map(print, "parameters"); } if (fun.defaults) { path.each(function(defExprPath) { var i2 = defExprPath.getName(); var p = printed[i2]; if (p && defExprPath.getValue()) { printed[i2] = (0, lines_1.concat)([p, " = ", print(defExprPath)]); } }, "defaults"); } if (fun.rest) { printed.push((0, lines_1.concat)(["...", path.call(print, "rest")])); } var joined = (0, lines_1.fromString)(", ").join(printed); if (joined.length > 1 || joined.getLineLength(1) > options.wrapColumn) { joined = (0, lines_1.fromString)(",\n").join(printed); if (util2.isTrailingCommaEnabled(options, "parameters") && !fun.rest && params[params.length - 1].type !== "RestElement") { joined = (0, lines_1.concat)([joined, ",\n"]); } else { joined = (0, lines_1.concat)([joined, "\n"]); } return (0, lines_1.concat)(["\n", joined.indent(options.tabWidth)]); } return joined; } function maybePrintImportAssertions(path, options, print) { var n = path.getValue(); if (n.assertions && n.assertions.length > 0) { var parts = [" assert {"]; var printed = path.map(print, "assertions"); var flat = (0, lines_1.fromString)(", ").join(printed); if (flat.length > 1 || flat.getLineLength(1) > options.wrapColumn) { parts.push("\n", (0, lines_1.fromString)(",\n").join(printed).indent(options.tabWidth), "\n}"); } else { parts.push(" ", flat, " }"); } return (0, lines_1.concat)(parts); } return (0, lines_1.fromString)(""); } function printExportDeclaration(path, options, print) { var decl = path.getValue(); var parts = ["export "]; if (decl.exportKind && decl.exportKind === "type") { if (!decl.declaration) { parts.push("type "); } } var shouldPrintSpaces = options.objectCurlySpacing; namedTypes.Declaration.assert(decl); if (decl["default"] || decl.type === "ExportDefaultDeclaration") { parts.push("default "); } if (decl.declaration) { parts.push(path.call(print, "declaration")); } else if (decl.specifiers) { if (decl.specifiers.length === 1 && decl.specifiers[0].type === "ExportBatchSpecifier") { parts.push("*"); } else if (decl.specifiers.length === 0) { parts.push("{}"); } else if (decl.specifiers[0].type === "ExportDefaultSpecifier") { var unbracedSpecifiers_2 = []; var bracedSpecifiers_2 = []; path.each(function(specifierPath) { var spec = specifierPath.getValue(); if (spec.type === "ExportDefaultSpecifier") { unbracedSpecifiers_2.push(print(specifierPath)); } else { bracedSpecifiers_2.push(print(specifierPath)); } }, "specifiers"); unbracedSpecifiers_2.forEach(function(lines2, i2) { if (i2 > 0) { parts.push(", "); } parts.push(lines2); }); if (bracedSpecifiers_2.length > 0) { var lines_2 = (0, lines_1.fromString)(", ").join(bracedSpecifiers_2); if (lines_2.getLineLength(1) > options.wrapColumn) { lines_2 = (0, lines_1.concat)([ (0, lines_1.fromString)(",\n").join(bracedSpecifiers_2).indent(options.tabWidth), "," ]); } if (unbracedSpecifiers_2.length > 0) { parts.push(", "); } if (lines_2.length > 1) { parts.push("{\n", lines_2, "\n}"); } else if (options.objectCurlySpacing) { parts.push("{ ", lines_2, " }"); } else { parts.push("{", lines_2, "}"); } } } else { parts.push(shouldPrintSpaces ? "{ " : "{", (0, lines_1.fromString)(", ").join(path.map(print, "specifiers")), shouldPrintSpaces ? " }" : "}"); } if (decl.source) { parts.push(" from ", path.call(print, "source"), maybePrintImportAssertions(path, options, print)); } } var lines = (0, lines_1.concat)(parts); if (lastNonSpaceCharacter(lines) !== ";" && !(decl.declaration && (decl.declaration.type === "FunctionDeclaration" || decl.declaration.type === "ClassDeclaration" || decl.declaration.type === "TSModuleDeclaration" || decl.declaration.type === "TSInterfaceDeclaration" || decl.declaration.type === "TSEnumDeclaration"))) { lines = (0, lines_1.concat)([lines, ";"]); } return lines; } function printFlowDeclaration(path, parts) { var parentExportDecl = util2.getParentExportDeclaration(path); if (parentExportDecl) { assert_1.default.strictEqual(parentExportDecl.type, "DeclareExportDeclaration"); } else { parts.unshift("declare "); } return (0, lines_1.concat)(parts); } function printVariance(path, print) { return path.call(function(variancePath) { var value = variancePath.getValue(); if (value) { if (value === "plus") { return (0, lines_1.fromString)("+"); } if (value === "minus") { return (0, lines_1.fromString)("-"); } return print(variancePath); } return (0, lines_1.fromString)(""); }, "variance"); } function adjustClause(clause, options) { if (clause.length > 1) return (0, lines_1.concat)([" ", clause]); return (0, lines_1.concat)(["\n", maybeAddSemicolon(clause).indent(options.tabWidth)]); } function lastNonSpaceCharacter(lines) { var pos = lines.lastPos(); do { var ch = lines.charAt(pos); if (/\S/.test(ch)) return ch; } while (lines.prevPos(pos)); } function endsWithBrace(lines) { return lastNonSpaceCharacter(lines) === "}"; } function swapQuotes(str2) { return str2.replace(/['"]/g, function(m3) { return m3 === '"' ? "'" : '"'; }); } function getPossibleRaw(node2) { var value = types.getFieldValue(node2, "value"); var extra = types.getFieldValue(node2, "extra"); if (extra && typeof extra.raw === "string" && value == extra.rawValue) { return extra.raw; } if (node2.type === "Literal") { var raw = node2.raw; if (typeof raw === "string" && value == raw) { return raw; } } } function jsSafeStringify(str2) { return JSON.stringify(str2).replace(/[\u2028\u2029]/g, function(m3) { return "\\u" + m3.charCodeAt(0).toString(16); }); } function nodeStr(str2, options) { isString.assert(str2); switch (options.quote) { case "auto": { var double = jsSafeStringify(str2); var single = swapQuotes(jsSafeStringify(swapQuotes(str2))); return double.length > single.length ? single : double; } case "single": return swapQuotes(jsSafeStringify(swapQuotes(str2))); case "double": default: return jsSafeStringify(str2); } } function maybeAddSemicolon(lines) { var eoc = lastNonSpaceCharacter(lines); if (!eoc || "\n};".indexOf(eoc) < 0) return (0, lines_1.concat)([lines, ";"]); return lines; } } }); // node_modules/recast/main.js var require_main2 = __commonJS({ "node_modules/recast/main.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.run = exports.prettyPrint = exports.print = exports.visit = exports.types = exports.parse = void 0; var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); var fs_1 = tslib_1.__importDefault(require("fs")); var types = tslib_1.__importStar(require_main()); exports.types = types; var parser_1 = require_parser(); Object.defineProperty(exports, "parse", { enumerable: true, get: function() { return parser_1.parse; } }); var printer_1 = require_printer(); var ast_types_1 = require_main(); Object.defineProperty(exports, "visit", { enumerable: true, get: function() { return ast_types_1.visit; } }); function print(node2, options) { return new printer_1.Printer(options).print(node2); } exports.print = print; function prettyPrint(node2, options) { return new printer_1.Printer(options).printGenerically(node2); } exports.prettyPrint = prettyPrint; function run(transformer, options) { return runFile(process.argv[2], transformer, options); } exports.run = run; function runFile(path, transformer, options) { fs_1.default.readFile(path, "utf-8", function(err, code) { if (err) { console.error(err); return; } runString(code, transformer, options); }); } function defaultWriteback(output) { process.stdout.write(output); } function runString(code, transformer, options) { var writeback = options && options.writeback || defaultWriteback; transformer((0, parser_1.parse)(code, options), function(node2) { writeback(print(node2, options).code); }); } } }); // node_modules/recast/parsers/_babel_options.js var require_babel_options = __commonJS({ "node_modules/recast/parsers/_babel_options.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util2(); function getBabelOptions(options) { return { sourceType: (0, util_1.getOption)(options, "sourceType", "module"), strictMode: (0, util_1.getOption)(options, "strictMode", false), allowImportExportEverywhere: true, allowReturnOutsideFunction: true, startLine: 1, tokens: true, plugins: [ "asyncGenerators", "bigInt", "classPrivateMethods", "classPrivateProperties", "classProperties", "classStaticBlock", "decimal", "decorators-legacy", "doExpressions", "dynamicImport", "exportDefaultFrom", "exportExtensions", "exportNamespaceFrom", "functionBind", "functionSent", "importAssertions", "importMeta", "nullishCoalescingOperator", "numericSeparator", "objectRestSpread", "optionalCatchBinding", "optionalChaining", [ "pipelineOperator", { proposal: "minimal" } ], [ "recordAndTuple", { syntaxType: "hash" } ], "throwExpressions", "topLevelAwait", "v8intrinsic" ] }; } exports.default = getBabelOptions; } }); // node_modules/@babel/parser/lib/index.js var require_lib2 = __commonJS({ "node_modules/@babel/parser/lib/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i2; for (i2 = 0; i2 < sourceKeys.length; i2++) { key = sourceKeys[i2]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } var Position = class { constructor(line, col, index2) { this.line = void 0; this.column = void 0; this.index = void 0; this.line = line; this.column = col; this.index = index2; } }; var SourceLocation = class { constructor(start, end) { this.start = void 0; this.end = void 0; this.filename = void 0; this.identifierName = void 0; this.start = start; this.end = end; } }; function createPositionWithColumnOffset(position2, columnOffset) { const { line, column, index: index2 } = position2; return new Position(line, column + columnOffset, index2 + columnOffset); } var code = "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"; var ModuleErrors = { ImportMetaOutsideModule: { message: `import.meta may appear only with 'sourceType: "module"'`, code }, ImportOutsideModule: { message: `'import' and 'export' may appear only with 'sourceType: "module"'`, code } }; var NodeDescriptions = { ArrayPattern: "array destructuring pattern", AssignmentExpression: "assignment expression", AssignmentPattern: "assignment expression", ArrowFunctionExpression: "arrow function expression", ConditionalExpression: "conditional expression", CatchClause: "catch clause", ForOfStatement: "for-of statement", ForInStatement: "for-in statement", ForStatement: "for-loop", FormalParameters: "function parameter list", Identifier: "identifier", ImportSpecifier: "import specifier", ImportDefaultSpecifier: "import default specifier", ImportNamespaceSpecifier: "import namespace specifier", ObjectPattern: "object destructuring pattern", ParenthesizedExpression: "parenthesized expression", RestElement: "rest element", UpdateExpression: { true: "prefix operation", false: "postfix operation" }, VariableDeclarator: "variable declaration", YieldExpression: "yield expression" }; var toNodeDescription = ({ type: type2, prefix: prefix2 }) => type2 === "UpdateExpression" ? NodeDescriptions.UpdateExpression[String(prefix2)] : NodeDescriptions[type2]; var StandardErrors = { AccessorIsGenerator: ({ kind }) => `A ${kind}ter cannot be a generator.`, ArgumentsInClass: "'arguments' is only allowed in functions and class methods.", AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.", AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.", AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.", AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.", AwaitUsingNotInAsyncContext: "'await using' is only allowed within async functions and at the top levels of modules.", AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.", AwaitNotInAsyncFunction: "'await' is only allowed within async functions.", BadGetterArity: "A 'get' accessor must not have any formal parameters.", BadSetterArity: "A 'set' accessor must have exactly one formal parameter.", BadSetterRestParameter: "A 'set' accessor function argument must not be a rest parameter.", ConstructorClassField: "Classes may not have a field named 'constructor'.", ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.", ConstructorIsAccessor: "Class constructor may not be an accessor.", ConstructorIsAsync: "Constructor can't be an async function.", ConstructorIsGenerator: "Constructor can't be a generator.", DeclarationMissingInitializer: ({ kind }) => `Missing initializer in ${kind} declaration.`, DecoratorArgumentsOutsideParentheses: "Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.", DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.", DecoratorsBeforeAfterExport: "Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.", DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?", DecoratorExportClass: "Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.", DecoratorSemicolon: "Decorators must not be followed by a semicolon.", DecoratorStaticBlock: "Decorators can't be used with a static block.", DeferImportRequiresNamespace: 'Only `import defer * as x from "./module"` is valid.', DeletePrivateField: "Deleting a private field is not allowed.", DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.", DuplicateConstructor: "Duplicate constructor in the same class.", DuplicateDefaultExport: "Only one default export allowed per module.", DuplicateExport: ({ exportName }) => `\`${exportName}\` has already been exported. Exported identifiers must be unique.`, DuplicateProto: "Redefinition of __proto__ property.", DuplicateRegExpFlags: "Duplicate regular expression flag.", DynamicImportPhaseRequiresImportExpressions: ({ phase }) => `'import.${phase}(...)' can only be parsed when using the 'createImportExpressions' option.`, ElementAfterRest: "Rest element must be last element.", EscapedCharNotAnIdentifier: "Invalid Unicode escape.", ExportBindingIsString: ({ localName, exportName }) => `A string literal cannot be used as an exported binding without \`from\`. - Did you mean \`export { '${localName}' as '${exportName}' } from 'some-module'\`?`, ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.", ForInOfLoopInitializer: ({ type: type2 }) => `'${type2 === "ForInStatement" ? "for-in" : "for-of"}' loop variable declaration may not have an initializer.`, ForInUsing: "For-in loop may not start with 'using' declaration.", ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.", ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.", GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.", IllegalBreakContinue: ({ type: type2 }) => `Unsyntactic ${type2 === "BreakStatement" ? "break" : "continue"}.`, IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.", IllegalReturn: "'return' outside of function.", ImportAttributesUseAssert: "The `assert` keyword in import attributes is deprecated and it has been replaced by the `with` keyword. You can enable the `deprecatedAssertSyntax: true` option in the import attributes plugin to suppress this error.", ImportBindingIsString: ({ importName }) => `A string literal cannot be used as an imported binding. - Did you mean \`import { "${importName}" as foo }\`?`, ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments.", ImportCallArity: ({ maxArgumentCount }) => `\`import()\` requires exactly ${maxArgumentCount === 1 ? "one argument" : "one or two arguments"}.`, ImportCallNotNewExpression: "Cannot use new with import(...).", ImportCallSpreadArgument: "`...` is not allowed in `import()`.", ImportJSONBindingNotDefault: "A JSON module can only be imported with `default`.", ImportReflectionHasAssertion: "`import module x` cannot have assertions.", ImportReflectionNotBinding: 'Only `import module x from "./module"` is valid.', IncompatibleRegExpUVFlags: "The 'u' and 'v' regular expression flags cannot be enabled at the same time.", InvalidBigIntLiteral: "Invalid BigIntLiteral.", InvalidCodePoint: "Code point out of bounds.", InvalidCoverInitializedName: "Invalid shorthand property initializer.", InvalidDecimal: "Invalid decimal.", InvalidDigit: ({ radix }) => `Expected number in radix ${radix}.`, InvalidEscapeSequence: "Bad character escape sequence.", InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.", InvalidEscapedReservedWord: ({ reservedWord }) => `Escape sequence in keyword ${reservedWord}.`, InvalidIdentifier: ({ identifierName }) => `Invalid identifier ${identifierName}.`, InvalidLhs: ({ ancestor }) => `Invalid left-hand side in ${toNodeDescription(ancestor)}.`, InvalidLhsBinding: ({ ancestor }) => `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`, InvalidLhsOptionalChaining: ({ ancestor }) => `Invalid optional chaining in the left-hand side of ${toNodeDescription(ancestor)}.`, InvalidNumber: "Invalid number.", InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.", InvalidOrUnexpectedToken: ({ unexpected }) => `Unexpected character '${unexpected}'.`, InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.", InvalidPrivateFieldResolution: ({ identifierName }) => `Private name #${identifierName} is not defined.`, InvalidPropertyBindingPattern: "Binding member expression.", InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.", InvalidRestAssignmentPattern: "Invalid rest operator's argument.", LabelRedeclaration: ({ labelName }) => `Label '${labelName}' is already declared.`, LetInLexicalBinding: "'let' is disallowed as a lexically bound name.", LineTerminatorBeforeArrow: "No line break is allowed before '=>'.", MalformedRegExpFlags: "Invalid regular expression flag.", MissingClassName: "A class name is required.", MissingEqInAssignment: "Only '=' operator can be used for specifying default value.", MissingSemicolon: "Missing semicolon.", MissingPlugin: ({ missingPlugin }) => `This experimental syntax requires enabling the parser plugin: ${missingPlugin.map((name) => JSON.stringify(name)).join(", ")}.`, MissingOneOfPlugins: ({ missingPlugin }) => `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin.map((name) => JSON.stringify(name)).join(", ")}.`, MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.", MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.", ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.", ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.", ModuleAttributesWithDuplicateKeys: ({ key }) => `Duplicate key "${key}" is not allowed in module attributes.`, ModuleExportNameHasLoneSurrogate: ({ surrogateCharCode }) => `An export name cannot include a lone surrogate, found '\\u${surrogateCharCode.toString(16)}'.`, ModuleExportUndefined: ({ localName }) => `Export '${localName}' is not defined.`, MultipleDefaultsInSwitch: "Multiple default clauses.", NewlineAfterThrow: "Illegal newline after throw.", NoCatchOrFinally: "Missing catch or finally clause.", NumberIdentifier: "Identifier directly after number.", NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.", ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.", OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.", OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.", OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.", ParamDupe: "Argument name clash.", PatternHasAccessor: "Object pattern can't contain getter or setter.", PatternHasMethod: "Object pattern can't contain methods.", PrivateInExpectedIn: ({ identifierName }) => `Private names are only allowed in property accesses (\`obj.#${identifierName}\`) or in \`in\` expressions (\`#${identifierName} in obj\`).`, PrivateNameRedeclaration: ({ identifierName }) => `Duplicate private name #${identifierName}.`, RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.", RecordNoProto: "'__proto__' is not allowed in Record expressions.", RestTrailingComma: "Unexpected trailing comma after rest element.", SloppyFunction: "In non-strict mode code, functions can only be declared at top level or inside a block.", SloppyFunctionAnnexB: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.", SourcePhaseImportRequiresDefault: 'Only `import source x from "./module"` is valid.', StaticPrototype: "Classes may not have static property named prototype.", SuperNotAllowed: "`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?", SuperPrivateField: "Private fields can't be accessed on super.", TrailingDecorator: "Decorators must be attached to a class element.", TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.", TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.", UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.", UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.', UnexpectedDigitAfterHash: "Unexpected digit after hash token.", UnexpectedImportExport: "'import' and 'export' may only appear at the top level.", UnexpectedKeyword: ({ keyword }) => `Unexpected keyword '${keyword}'.`, UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.", UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.", UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.", UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.", UnexpectedPrivateField: "Unexpected private name.", UnexpectedReservedWord: ({ reservedWord }) => `Unexpected reserved word '${reservedWord}'.`, UnexpectedSuper: "'super' is only allowed in object methods and classes.", UnexpectedToken: ({ expected, unexpected }) => `Unexpected token${unexpected ? ` '${unexpected}'.` : ""}${expected ? `, expected "${expected}"` : ""}`, UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.", UnexpectedUsingDeclaration: "Using declaration cannot appear in the top level when source type is `script`.", UnsupportedBind: "Binding should be performed on object property.", UnsupportedDecoratorExport: "A decorated export must export a class declaration.", UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.", UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.", UnsupportedMetaProperty: ({ target, onlyValidPropertyName }) => `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`, UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.", UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.", UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).", UnterminatedComment: "Unterminated comment.", UnterminatedRegExp: "Unterminated regular expression.", UnterminatedString: "Unterminated string constant.", UnterminatedTemplate: "Unterminated template.", UsingDeclarationHasBindingPattern: "Using declaration cannot have destructuring patterns.", VarRedeclaration: ({ identifierName }) => `Identifier '${identifierName}' has already been declared.`, YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.", YieldInParameter: "Yield expression is not allowed in formal parameters.", ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0." }; var StrictModeErrors = { StrictDelete: "Deleting local variable in strict mode.", StrictEvalArguments: ({ referenceName }) => `Assigning to '${referenceName}' in strict mode.`, StrictEvalArgumentsBinding: ({ bindingName }) => `Binding '${bindingName}' in strict mode.`, StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.", StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.", StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.", StrictWith: "'with' in strict mode." }; var UnparenthesizedPipeBodyDescriptions = /* @__PURE__ */ new Set(["ArrowFunctionExpression", "AssignmentExpression", "ConditionalExpression", "YieldExpression"]); var PipelineOperatorErrors = { PipeBodyIsTighter: "Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.", PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.', PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.", PipeTopicUnconfiguredToken: ({ token }) => `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${token}" }.`, PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.", PipeUnparenthesizedBody: ({ type: type2 }) => `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({ type: type2 })}; please wrap it in parentheses.`, PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.', PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.", PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.", PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.", PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.", PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.' }; var _excluded$1 = ["toMessage"]; var _excluded2$1 = ["message"]; function defineHidden(obj, key, value) { Object.defineProperty(obj, key, { enumerable: false, configurable: true, value }); } function toParseErrorConstructor(_ref) { let { toMessage } = _ref, properties = _objectWithoutPropertiesLoose(_ref, _excluded$1); return function constructor({ loc, details }) { const error = new SyntaxError(); Object.assign(error, properties, { loc, pos: loc.index }); if ("missingPlugin" in details) { Object.assign(error, { missingPlugin: details.missingPlugin }); } defineHidden(error, "clone", function clone(overrides = {}) { var _overrides$loc; const { line, column, index: index2 } = (_overrides$loc = overrides.loc) != null ? _overrides$loc : loc; return constructor({ loc: new Position(line, column, index2), details: Object.assign({}, details, overrides.details) }); }); defineHidden(error, "details", details); Object.defineProperty(error, "message", { configurable: true, get() { const message = `${toMessage(details)} (${loc.line}:${loc.column})`; this.message = message; return message; }, set(value) { Object.defineProperty(this, "message", { value, writable: true }); } }); return error; }; } function ParseErrorEnum(argument, syntaxPlugin) { if (Array.isArray(argument)) { return (parseErrorTemplates) => ParseErrorEnum(parseErrorTemplates, argument[0]); } const ParseErrorConstructors = {}; for (const reasonCode of Object.keys(argument)) { const template = argument[reasonCode]; const _ref2 = typeof template === "string" ? { message: () => template } : typeof template === "function" ? { message: template } : template, { message } = _ref2, rest = _objectWithoutPropertiesLoose(_ref2, _excluded2$1); const toMessage = typeof message === "string" ? () => message : message; ParseErrorConstructors[reasonCode] = toParseErrorConstructor(Object.assign({ code: "BABEL_PARSER_SYNTAX_ERROR", reasonCode, toMessage }, syntaxPlugin ? { syntaxPlugin } : {}, rest)); } return ParseErrorConstructors; } var Errors = Object.assign({}, ParseErrorEnum(ModuleErrors), ParseErrorEnum(StandardErrors), ParseErrorEnum(StrictModeErrors), ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors)); var { defineProperty } = Object; var toUnenumerable = (object, key) => defineProperty(object, key, { enumerable: false, value: object[key] }); function toESTreeLocation(node2) { node2.loc.start && toUnenumerable(node2.loc.start, "index"); node2.loc.end && toUnenumerable(node2.loc.end, "index"); return node2; } var estree = (superClass) => class ESTreeParserMixin extends superClass { parse() { const file = toESTreeLocation(super.parse()); if (this.options.tokens) { file.tokens = file.tokens.map(toESTreeLocation); } return file; } parseRegExpLiteral({ pattern, flags }) { let regex = null; try { regex = new RegExp(pattern, flags); } catch (e2) { } const node2 = this.estreeParseLiteral(regex); node2.regex = { pattern, flags }; return node2; } parseBigIntLiteral(value) { let bigInt; try { bigInt = BigInt(value); } catch (_unused) { bigInt = null; } const node2 = this.estreeParseLiteral(bigInt); node2.bigint = String(node2.value || value); return node2; } parseDecimalLiteral(value) { const decimal = null; const node2 = this.estreeParseLiteral(decimal); node2.decimal = String(node2.value || value); return node2; } estreeParseLiteral(value) { return this.parseLiteral(value, "Literal"); } parseStringLiteral(value) { return this.estreeParseLiteral(value); } parseNumericLiteral(value) { return this.estreeParseLiteral(value); } parseNullLiteral() { return this.estreeParseLiteral(null); } parseBooleanLiteral(value) { return this.estreeParseLiteral(value); } directiveToStmt(directive) { const expression = directive.value; delete directive.value; expression.type = "Literal"; expression.raw = expression.extra.raw; expression.value = expression.extra.expressionValue; const stmt = directive; stmt.type = "ExpressionStatement"; stmt.expression = expression; stmt.directive = expression.extra.rawValue; delete expression.extra; return stmt; } initFunction(node2, isAsync2) { super.initFunction(node2, isAsync2); node2.expression = false; } checkDeclaration(node2) { if (node2 != null && this.isObjectProperty(node2)) { this.checkDeclaration(node2.value); } else { super.checkDeclaration(node2); } } getObjectOrClassMethodParams(method) { return method.value.params; } isValidDirective(stmt) { var _stmt$expression$extr; return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized); } parseBlockBody(node2, allowDirectives, topLevel, end, afterBlockParse) { super.parseBlockBody(node2, allowDirectives, topLevel, end, afterBlockParse); const directiveStatements = node2.directives.map((d3) => this.directiveToStmt(d3)); node2.body = directiveStatements.concat(node2.body); delete node2.directives; } pushClassMethod(classBody, method, isGenerator, isAsync2, isConstructor, allowsDirectSuper) { this.parseMethod(method, isGenerator, isAsync2, isConstructor, allowsDirectSuper, "ClassMethod", true); if (method.typeParameters) { method.value.typeParameters = method.typeParameters; delete method.typeParameters; } classBody.body.push(method); } parsePrivateName() { const node2 = super.parsePrivateName(); { if (!this.getPluginOption("estree", "classFeatures")) { return node2; } } return this.convertPrivateNameToPrivateIdentifier(node2); } convertPrivateNameToPrivateIdentifier(node2) { const name = super.getPrivateNameSV(node2); node2 = node2; delete node2.id; node2.name = name; node2.type = "PrivateIdentifier"; return node2; } isPrivateName(node2) { { if (!this.getPluginOption("estree", "classFeatures")) { return super.isPrivateName(node2); } } return node2.type === "PrivateIdentifier"; } getPrivateNameSV(node2) { { if (!this.getPluginOption("estree", "classFeatures")) { return super.getPrivateNameSV(node2); } } return node2.name; } parseLiteral(value, type2) { const node2 = super.parseLiteral(value, type2); node2.raw = node2.extra.raw; delete node2.extra; return node2; } parseFunctionBody(node2, allowExpression, isMethod = false) { super.parseFunctionBody(node2, allowExpression, isMethod); node2.expression = node2.body.type !== "BlockStatement"; } parseMethod(node2, isGenerator, isAsync2, isConstructor, allowDirectSuper, type2, inClassScope = false) { let funcNode = this.startNode(); funcNode.kind = node2.kind; funcNode = super.parseMethod(funcNode, isGenerator, isAsync2, isConstructor, allowDirectSuper, type2, inClassScope); funcNode.type = "FunctionExpression"; delete funcNode.kind; node2.value = funcNode; if (type2 === "ClassPrivateMethod") { node2.computed = false; } return this.finishNode(node2, "MethodDefinition"); } parseClassProperty(...args) { const propertyNode = super.parseClassProperty(...args); { if (!this.getPluginOption("estree", "classFeatures")) { return propertyNode; } } propertyNode.type = "PropertyDefinition"; return propertyNode; } parseClassPrivateProperty(...args) { const propertyNode = super.parseClassPrivateProperty(...args); { if (!this.getPluginOption("estree", "classFeatures")) { return propertyNode; } } propertyNode.type = "PropertyDefinition"; propertyNode.computed = false; return propertyNode; } parseObjectMethod(prop, isGenerator, isAsync2, isPattern, isAccessor) { const node2 = super.parseObjectMethod(prop, isGenerator, isAsync2, isPattern, isAccessor); if (node2) { node2.type = "Property"; if (node2.kind === "method") { node2.kind = "init"; } node2.shorthand = false; } return node2; } parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) { const node2 = super.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors); if (node2) { node2.kind = "init"; node2.type = "Property"; } return node2; } isValidLVal(type2, isUnparenthesizedInAssign, binding) { return type2 === "Property" ? "value" : super.isValidLVal(type2, isUnparenthesizedInAssign, binding); } isAssignable(node2, isBinding) { if (node2 != null && this.isObjectProperty(node2)) { return this.isAssignable(node2.value, isBinding); } return super.isAssignable(node2, isBinding); } toAssignable(node2, isLHS = false) { if (node2 != null && this.isObjectProperty(node2)) { const { key, value } = node2; if (this.isPrivateName(key)) { this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start); } this.toAssignable(value, isLHS); } else { super.toAssignable(node2, isLHS); } } toAssignableObjectExpressionProp(prop, isLast, isLHS) { if (prop.kind === "get" || prop.kind === "set") { this.raise(Errors.PatternHasAccessor, { at: prop.key }); } else if (prop.method) { this.raise(Errors.PatternHasMethod, { at: prop.key }); } else { super.toAssignableObjectExpressionProp(prop, isLast, isLHS); } } finishCallExpression(unfinished, optional) { const node2 = super.finishCallExpression(unfinished, optional); if (node2.callee.type === "Import") { node2.type = "ImportExpression"; node2.source = node2.arguments[0]; if (this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions")) { var _node$arguments$, _node$arguments$2; node2.options = (_node$arguments$ = node2.arguments[1]) != null ? _node$arguments$ : null; node2.attributes = (_node$arguments$2 = node2.arguments[1]) != null ? _node$arguments$2 : null; } delete node2.arguments; delete node2.callee; } return node2; } toReferencedArguments(node2) { if (node2.type === "ImportExpression") { return; } super.toReferencedArguments(node2); } parseExport(unfinished, decorators) { const exportStartLoc = this.state.lastTokStartLoc; const node2 = super.parseExport(unfinished, decorators); switch (node2.type) { case "ExportAllDeclaration": node2.exported = null; break; case "ExportNamedDeclaration": if (node2.specifiers.length === 1 && node2.specifiers[0].type === "ExportNamespaceSpecifier") { node2.type = "ExportAllDeclaration"; node2.exported = node2.specifiers[0].exported; delete node2.specifiers; } case "ExportDefaultDeclaration": { var _declaration$decorato; const { declaration } = node2; if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && ((_declaration$decorato = declaration.decorators) == null ? void 0 : _declaration$decorato.length) > 0 && declaration.start === node2.start) { this.resetStartLocation(node2, exportStartLoc); } } break; } return node2; } parseSubscript(base, startLoc, noCalls, state) { const node2 = super.parseSubscript(base, startLoc, noCalls, state); if (state.optionalChainMember) { if (node2.type === "OptionalMemberExpression" || node2.type === "OptionalCallExpression") { node2.type = node2.type.substring(8); } if (state.stop) { const chain = this.startNodeAtNode(node2); chain.expression = node2; return this.finishNode(chain, "ChainExpression"); } } else if (node2.type === "MemberExpression" || node2.type === "CallExpression") { node2.optional = false; } return node2; } isOptionalMemberExpression(node2) { if (node2.type === "ChainExpression") { return node2.expression.type === "MemberExpression"; } return super.isOptionalMemberExpression(node2); } hasPropertyAsPrivateName(node2) { if (node2.type === "ChainExpression") { node2 = node2.expression; } return super.hasPropertyAsPrivateName(node2); } isObjectProperty(node2) { return node2.type === "Property" && node2.kind === "init" && !node2.method; } isObjectMethod(node2) { return node2.method || node2.kind === "get" || node2.kind === "set"; } finishNodeAt(node2, type2, endLoc) { return toESTreeLocation(super.finishNodeAt(node2, type2, endLoc)); } resetStartLocation(node2, startLoc) { super.resetStartLocation(node2, startLoc); toESTreeLocation(node2); } resetEndLocation(node2, endLoc = this.state.lastTokEndLoc) { super.resetEndLocation(node2, endLoc); toESTreeLocation(node2); } }; var TokContext = class { constructor(token, preserveSpace) { this.token = void 0; this.preserveSpace = void 0; this.token = token; this.preserveSpace = !!preserveSpace; } }; var types = { brace: new TokContext("{"), j_oTag: new TokContext("...", true) }; { types.template = new TokContext("`", true); } var beforeExpr = true; var startsExpr = true; var isLoop = true; var isAssign = true; var prefix = true; var postfix = true; var ExportedTokenType = class { constructor(label, conf = {}) { this.label = void 0; this.keyword = void 0; this.beforeExpr = void 0; this.startsExpr = void 0; this.rightAssociative = void 0; this.isLoop = void 0; this.isAssign = void 0; this.prefix = void 0; this.postfix = void 0; this.binop = void 0; this.label = label; this.keyword = conf.keyword; this.beforeExpr = !!conf.beforeExpr; this.startsExpr = !!conf.startsExpr; this.rightAssociative = !!conf.rightAssociative; this.isLoop = !!conf.isLoop; this.isAssign = !!conf.isAssign; this.prefix = !!conf.prefix; this.postfix = !!conf.postfix; this.binop = conf.binop != null ? conf.binop : null; { this.updateContext = null; } } }; var keywords$1 = /* @__PURE__ */ new Map(); function createKeyword(name, options = {}) { options.keyword = name; const token = createToken(name, options); keywords$1.set(name, token); return token; } function createBinop(name, binop) { return createToken(name, { beforeExpr, binop }); } var tokenTypeCounter = -1; var tokenTypes = []; var tokenLabels = []; var tokenBinops = []; var tokenBeforeExprs = []; var tokenStartsExprs = []; var tokenPrefixes = []; function createToken(name, options = {}) { var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix; ++tokenTypeCounter; tokenLabels.push(name); tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1); tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false); tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false); tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false); tokenTypes.push(new ExportedTokenType(name, options)); return tokenTypeCounter; } function createKeywordLike(name, options = {}) { var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2; ++tokenTypeCounter; keywords$1.set(name, tokenTypeCounter); tokenLabels.push(name); tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1); tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false); tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false); tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false); tokenTypes.push(new ExportedTokenType("name", options)); return tokenTypeCounter; } var tt = { bracketL: createToken("[", { beforeExpr, startsExpr }), bracketHashL: createToken("#[", { beforeExpr, startsExpr }), bracketBarL: createToken("[|", { beforeExpr, startsExpr }), bracketR: createToken("]"), bracketBarR: createToken("|]"), braceL: createToken("{", { beforeExpr, startsExpr }), braceBarL: createToken("{|", { beforeExpr, startsExpr }), braceHashL: createToken("#{", { beforeExpr, startsExpr }), braceR: createToken("}"), braceBarR: createToken("|}"), parenL: createToken("(", { beforeExpr, startsExpr }), parenR: createToken(")"), comma: createToken(",", { beforeExpr }), semi: createToken(";", { beforeExpr }), colon: createToken(":", { beforeExpr }), doubleColon: createToken("::", { beforeExpr }), dot: createToken("."), question: createToken("?", { beforeExpr }), questionDot: createToken("?."), arrow: createToken("=>", { beforeExpr }), template: createToken("template"), ellipsis: createToken("...", { beforeExpr }), backQuote: createToken("`", { startsExpr }), dollarBraceL: createToken("${", { beforeExpr, startsExpr }), templateTail: createToken("...`", { startsExpr }), templateNonTail: createToken("...${", { beforeExpr, startsExpr }), at: createToken("@"), hash: createToken("#", { startsExpr }), interpreterDirective: createToken("#!..."), eq: createToken("=", { beforeExpr, isAssign }), assign: createToken("_=", { beforeExpr, isAssign }), slashAssign: createToken("_=", { beforeExpr, isAssign }), xorAssign: createToken("_=", { beforeExpr, isAssign }), moduloAssign: createToken("_=", { beforeExpr, isAssign }), incDec: createToken("++/--", { prefix, postfix, startsExpr }), bang: createToken("!", { beforeExpr, prefix, startsExpr }), tilde: createToken("~", { beforeExpr, prefix, startsExpr }), doubleCaret: createToken("^^", { startsExpr }), doubleAt: createToken("@@", { startsExpr }), pipeline: createBinop("|>", 0), nullishCoalescing: createBinop("??", 1), logicalOR: createBinop("||", 1), logicalAND: createBinop("&&", 2), bitwiseOR: createBinop("|", 3), bitwiseXOR: createBinop("^", 4), bitwiseAND: createBinop("&", 5), equality: createBinop("==/!=/===/!==", 6), lt: createBinop("/<=/>=", 7), gt: createBinop("/<=/>=", 7), relational: createBinop("/<=/>=", 7), bitShift: createBinop("<>/>>>", 8), bitShiftL: createBinop("<>/>>>", 8), bitShiftR: createBinop("<>/>>>", 8), plusMin: createToken("+/-", { beforeExpr, binop: 9, prefix, startsExpr }), modulo: createToken("%", { binop: 10, startsExpr }), star: createToken("*", { binop: 10 }), slash: createBinop("/", 10), exponent: createToken("**", { beforeExpr, binop: 11, rightAssociative: true }), _in: createKeyword("in", { beforeExpr, binop: 7 }), _instanceof: createKeyword("instanceof", { beforeExpr, binop: 7 }), _break: createKeyword("break"), _case: createKeyword("case", { beforeExpr }), _catch: createKeyword("catch"), _continue: createKeyword("continue"), _debugger: createKeyword("debugger"), _default: createKeyword("default", { beforeExpr }), _else: createKeyword("else", { beforeExpr }), _finally: createKeyword("finally"), _function: createKeyword("function", { startsExpr }), _if: createKeyword("if"), _return: createKeyword("return", { beforeExpr }), _switch: createKeyword("switch"), _throw: createKeyword("throw", { beforeExpr, prefix, startsExpr }), _try: createKeyword("try"), _var: createKeyword("var"), _const: createKeyword("const"), _with: createKeyword("with"), _new: createKeyword("new", { beforeExpr, startsExpr }), _this: createKeyword("this", { startsExpr }), _super: createKeyword("super", { startsExpr }), _class: createKeyword("class", { startsExpr }), _extends: createKeyword("extends", { beforeExpr }), _export: createKeyword("export"), _import: createKeyword("import", { startsExpr }), _null: createKeyword("null", { startsExpr }), _true: createKeyword("true", { startsExpr }), _false: createKeyword("false", { startsExpr }), _typeof: createKeyword("typeof", { beforeExpr, prefix, startsExpr }), _void: createKeyword("void", { beforeExpr, prefix, startsExpr }), _delete: createKeyword("delete", { beforeExpr, prefix, startsExpr }), _do: createKeyword("do", { isLoop, beforeExpr }), _for: createKeyword("for", { isLoop }), _while: createKeyword("while", { isLoop }), _as: createKeywordLike("as", { startsExpr }), _assert: createKeywordLike("assert", { startsExpr }), _async: createKeywordLike("async", { startsExpr }), _await: createKeywordLike("await", { startsExpr }), _defer: createKeywordLike("defer", { startsExpr }), _from: createKeywordLike("from", { startsExpr }), _get: createKeywordLike("get", { startsExpr }), _let: createKeywordLike("let", { startsExpr }), _meta: createKeywordLike("meta", { startsExpr }), _of: createKeywordLike("of", { startsExpr }), _sent: createKeywordLike("sent", { startsExpr }), _set: createKeywordLike("set", { startsExpr }), _source: createKeywordLike("source", { startsExpr }), _static: createKeywordLike("static", { startsExpr }), _using: createKeywordLike("using", { startsExpr }), _yield: createKeywordLike("yield", { startsExpr }), _asserts: createKeywordLike("asserts", { startsExpr }), _checks: createKeywordLike("checks", { startsExpr }), _exports: createKeywordLike("exports", { startsExpr }), _global: createKeywordLike("global", { startsExpr }), _implements: createKeywordLike("implements", { startsExpr }), _intrinsic: createKeywordLike("intrinsic", { startsExpr }), _infer: createKeywordLike("infer", { startsExpr }), _is: createKeywordLike("is", { startsExpr }), _mixins: createKeywordLike("mixins", { startsExpr }), _proto: createKeywordLike("proto", { startsExpr }), _require: createKeywordLike("require", { startsExpr }), _satisfies: createKeywordLike("satisfies", { startsExpr }), _keyof: createKeywordLike("keyof", { startsExpr }), _readonly: createKeywordLike("readonly", { startsExpr }), _unique: createKeywordLike("unique", { startsExpr }), _abstract: createKeywordLike("abstract", { startsExpr }), _declare: createKeywordLike("declare", { startsExpr }), _enum: createKeywordLike("enum", { startsExpr }), _module: createKeywordLike("module", { startsExpr }), _namespace: createKeywordLike("namespace", { startsExpr }), _interface: createKeywordLike("interface", { startsExpr }), _type: createKeywordLike("type", { startsExpr }), _opaque: createKeywordLike("opaque", { startsExpr }), name: createToken("name", { startsExpr }), string: createToken("string", { startsExpr }), num: createToken("num", { startsExpr }), bigint: createToken("bigint", { startsExpr }), decimal: createToken("decimal", { startsExpr }), regexp: createToken("regexp", { startsExpr }), privateName: createToken("#name", { startsExpr }), eof: createToken("eof"), jsxName: createToken("jsxName"), jsxText: createToken("jsxText", { beforeExpr: true }), jsxTagStart: createToken("jsxTagStart", { startsExpr: true }), jsxTagEnd: createToken("jsxTagEnd"), placeholder: createToken("%%", { startsExpr: true }) }; function tokenIsIdentifier(token) { return token >= 93 && token <= 132; } function tokenKeywordOrIdentifierIsKeyword(token) { return token <= 92; } function tokenIsKeywordOrIdentifier(token) { return token >= 58 && token <= 132; } function tokenIsLiteralPropertyName(token) { return token >= 58 && token <= 136; } function tokenComesBeforeExpression(token) { return tokenBeforeExprs[token]; } function tokenCanStartExpression(token) { return tokenStartsExprs[token]; } function tokenIsAssignment(token) { return token >= 29 && token <= 33; } function tokenIsFlowInterfaceOrTypeOrOpaque(token) { return token >= 129 && token <= 131; } function tokenIsLoop(token) { return token >= 90 && token <= 92; } function tokenIsKeyword(token) { return token >= 58 && token <= 92; } function tokenIsOperator(token) { return token >= 39 && token <= 59; } function tokenIsPostfix(token) { return token === 34; } function tokenIsPrefix(token) { return tokenPrefixes[token]; } function tokenIsTSTypeOperator(token) { return token >= 121 && token <= 123; } function tokenIsTSDeclarationStart(token) { return token >= 124 && token <= 130; } function tokenLabelName(token) { return tokenLabels[token]; } function tokenOperatorPrecedence(token) { return tokenBinops[token]; } function tokenIsRightAssociative(token) { return token === 57; } function tokenIsTemplate(token) { return token >= 24 && token <= 25; } function getExportedToken(token) { return tokenTypes[token]; } { tokenTypes[8].updateContext = (context) => { context.pop(); }; tokenTypes[5].updateContext = tokenTypes[7].updateContext = tokenTypes[23].updateContext = (context) => { context.push(types.brace); }; tokenTypes[22].updateContext = (context) => { if (context[context.length - 1] === types.template) { context.pop(); } else { context.push(types.template); } }; tokenTypes[142].updateContext = (context) => { context.push(types.j_expr, types.j_oTag); }; } var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC"; var nonASCIIidentifierChars = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0898-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ACE\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65"; var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191]; var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; function isInAstralSet(code2, set2) { let pos = 65536; for (let i2 = 0, length = set2.length; i2 < length; i2 += 2) { pos += set2[i2]; if (pos > code2) return false; pos += set2[i2 + 1]; if (pos >= code2) return true; } return false; } function isIdentifierStart(code2) { if (code2 < 65) return code2 === 36; if (code2 <= 90) return true; if (code2 < 97) return code2 === 95; if (code2 <= 122) return true; if (code2 <= 65535) { return code2 >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code2)); } return isInAstralSet(code2, astralIdentifierStartCodes); } function isIdentifierChar(code2) { if (code2 < 48) return code2 === 36; if (code2 < 58) return true; if (code2 < 65) return false; if (code2 <= 90) return true; if (code2 < 97) return code2 === 95; if (code2 <= 122) return true; if (code2 <= 65535) { return code2 >= 170 && nonASCIIidentifier.test(String.fromCharCode(code2)); } return isInAstralSet(code2, astralIdentifierStartCodes) || isInAstralSet(code2, astralIdentifierCodes); } var reservedWords = { keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], strictBind: ["eval", "arguments"] }; var keywords = new Set(reservedWords.keyword); var reservedWordsStrictSet = new Set(reservedWords.strict); var reservedWordsStrictBindSet = new Set(reservedWords.strictBind); function isReservedWord(word, inModule) { return inModule && word === "await" || word === "enum"; } function isStrictReservedWord(word, inModule) { return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); } function isStrictBindOnlyReservedWord(word) { return reservedWordsStrictBindSet.has(word); } function isStrictBindReservedWord(word, inModule) { return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); } function isKeyword(word) { return keywords.has(word); } function isIteratorStart(current, next, next2) { return current === 64 && next === 64 && isIdentifierStart(next2); } var reservedWordLikeSet = /* @__PURE__ */ new Set(["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete", "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield", "eval", "arguments", "enum", "await"]); function canBeReservedWord(word) { return reservedWordLikeSet.has(word); } var Scope = class { constructor(flags) { this.var = /* @__PURE__ */ new Set(); this.lexical = /* @__PURE__ */ new Set(); this.functions = /* @__PURE__ */ new Set(); this.flags = flags; } }; var ScopeHandler = class { constructor(parser, inModule) { this.parser = void 0; this.scopeStack = []; this.inModule = void 0; this.undefinedExports = /* @__PURE__ */ new Map(); this.parser = parser; this.inModule = inModule; } get inTopLevel() { return (this.currentScope().flags & 1) > 0; } get inFunction() { return (this.currentVarScopeFlags() & 2) > 0; } get allowSuper() { return (this.currentThisScopeFlags() & 16) > 0; } get allowDirectSuper() { return (this.currentThisScopeFlags() & 32) > 0; } get inClass() { return (this.currentThisScopeFlags() & 64) > 0; } get inClassAndNotInNonArrowFunction() { const flags = this.currentThisScopeFlags(); return (flags & 64) > 0 && (flags & 2) === 0; } get inStaticBlock() { for (let i2 = this.scopeStack.length - 1; ; i2--) { const { flags } = this.scopeStack[i2]; if (flags & 128) { return true; } if (flags & (387 | 64)) { return false; } } } get inNonArrowFunction() { return (this.currentThisScopeFlags() & 2) > 0; } get treatFunctionsAsVar() { return this.treatFunctionsAsVarInScope(this.currentScope()); } createScope(flags) { return new Scope(flags); } enter(flags) { this.scopeStack.push(this.createScope(flags)); } exit() { const scope = this.scopeStack.pop(); return scope.flags; } treatFunctionsAsVarInScope(scope) { return !!(scope.flags & (2 | 128) || !this.parser.inModule && scope.flags & 1); } declareName(name, bindingType, loc) { let scope = this.currentScope(); if (bindingType & 8 || bindingType & 16) { this.checkRedeclarationInScope(scope, name, bindingType, loc); if (bindingType & 16) { scope.functions.add(name); } else { scope.lexical.add(name); } if (bindingType & 8) { this.maybeExportDefined(scope, name); } } else if (bindingType & 4) { for (let i2 = this.scopeStack.length - 1; i2 >= 0; --i2) { scope = this.scopeStack[i2]; this.checkRedeclarationInScope(scope, name, bindingType, loc); scope.var.add(name); this.maybeExportDefined(scope, name); if (scope.flags & 387) break; } } if (this.parser.inModule && scope.flags & 1) { this.undefinedExports.delete(name); } } maybeExportDefined(scope, name) { if (this.parser.inModule && scope.flags & 1) { this.undefinedExports.delete(name); } } checkRedeclarationInScope(scope, name, bindingType, loc) { if (this.isRedeclaredInScope(scope, name, bindingType)) { this.parser.raise(Errors.VarRedeclaration, { at: loc, identifierName: name }); } } isRedeclaredInScope(scope, name, bindingType) { if (!(bindingType & 1)) return false; if (bindingType & 8) { return scope.lexical.has(name) || scope.functions.has(name) || scope.var.has(name); } if (bindingType & 16) { return scope.lexical.has(name) || !this.treatFunctionsAsVarInScope(scope) && scope.var.has(name); } return scope.lexical.has(name) && !(scope.flags & 8 && scope.lexical.values().next().value === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.has(name); } checkLocalExport(id) { const { name } = id; const topLevelScope = this.scopeStack[0]; if (!topLevelScope.lexical.has(name) && !topLevelScope.var.has(name) && !topLevelScope.functions.has(name)) { this.undefinedExports.set(name, id.loc.start); } } currentScope() { return this.scopeStack[this.scopeStack.length - 1]; } currentVarScopeFlags() { for (let i2 = this.scopeStack.length - 1; ; i2--) { const { flags } = this.scopeStack[i2]; if (flags & 387) { return flags; } } } currentThisScopeFlags() { for (let i2 = this.scopeStack.length - 1; ; i2--) { const { flags } = this.scopeStack[i2]; if (flags & (387 | 64) && !(flags & 4)) { return flags; } } } }; var FlowScope = class extends Scope { constructor(...args) { super(...args); this.declareFunctions = /* @__PURE__ */ new Set(); } }; var FlowScopeHandler = class extends ScopeHandler { createScope(flags) { return new FlowScope(flags); } declareName(name, bindingType, loc) { const scope = this.currentScope(); if (bindingType & 2048) { this.checkRedeclarationInScope(scope, name, bindingType, loc); this.maybeExportDefined(scope, name); scope.declareFunctions.add(name); return; } super.declareName(name, bindingType, loc); } isRedeclaredInScope(scope, name, bindingType) { if (super.isRedeclaredInScope(scope, name, bindingType)) return true; if (bindingType & 2048) { return !scope.declareFunctions.has(name) && (scope.lexical.has(name) || scope.functions.has(name)); } return false; } checkLocalExport(id) { if (!this.scopeStack[0].declareFunctions.has(id.name)) { super.checkLocalExport(id); } } }; var BaseParser = class { constructor() { this.sawUnambiguousESM = false; this.ambiguousScriptDifferentAst = false; } hasPlugin(pluginConfig) { if (typeof pluginConfig === "string") { return this.plugins.has(pluginConfig); } else { const [pluginName, pluginOptions] = pluginConfig; if (!this.hasPlugin(pluginName)) { return false; } const actualOptions = this.plugins.get(pluginName); for (const key of Object.keys(pluginOptions)) { if ((actualOptions == null ? void 0 : actualOptions[key]) !== pluginOptions[key]) { return false; } } return true; } } getPluginOption(plugin, name) { var _this$plugins$get; return (_this$plugins$get = this.plugins.get(plugin)) == null ? void 0 : _this$plugins$get[name]; } }; function setTrailingComments(node2, comments) { if (node2.trailingComments === void 0) { node2.trailingComments = comments; } else { node2.trailingComments.unshift(...comments); } } function setLeadingComments(node2, comments) { if (node2.leadingComments === void 0) { node2.leadingComments = comments; } else { node2.leadingComments.unshift(...comments); } } function setInnerComments(node2, comments) { if (node2.innerComments === void 0) { node2.innerComments = comments; } else { node2.innerComments.unshift(...comments); } } function adjustInnerComments(node2, elements, commentWS) { let lastElement = null; let i2 = elements.length; while (lastElement === null && i2 > 0) { lastElement = elements[--i2]; } if (lastElement === null || lastElement.start > commentWS.start) { setInnerComments(node2, commentWS.comments); } else { setTrailingComments(lastElement, commentWS.comments); } } var CommentsParser = class extends BaseParser { addComment(comment) { if (this.filename) comment.loc.filename = this.filename; this.state.comments.push(comment); } processComment(node2) { const { commentStack } = this.state; const commentStackLength = commentStack.length; if (commentStackLength === 0) return; let i2 = commentStackLength - 1; const lastCommentWS = commentStack[i2]; if (lastCommentWS.start === node2.end) { lastCommentWS.leadingNode = node2; i2--; } const { start: nodeStart } = node2; for (; i2 >= 0; i2--) { const commentWS = commentStack[i2]; const commentEnd = commentWS.end; if (commentEnd > nodeStart) { commentWS.containingNode = node2; this.finalizeComment(commentWS); commentStack.splice(i2, 1); } else { if (commentEnd === nodeStart) { commentWS.trailingNode = node2; } break; } } } finalizeComment(commentWS) { const { comments } = commentWS; if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) { if (commentWS.leadingNode !== null) { setTrailingComments(commentWS.leadingNode, comments); } if (commentWS.trailingNode !== null) { setLeadingComments(commentWS.trailingNode, comments); } } else { const { containingNode: node2, start: commentStart } = commentWS; if (this.input.charCodeAt(commentStart - 1) === 44) { switch (node2.type) { case "ObjectExpression": case "ObjectPattern": case "RecordExpression": adjustInnerComments(node2, node2.properties, commentWS); break; case "CallExpression": case "OptionalCallExpression": adjustInnerComments(node2, node2.arguments, commentWS); break; case "FunctionDeclaration": case "FunctionExpression": case "ArrowFunctionExpression": case "ObjectMethod": case "ClassMethod": case "ClassPrivateMethod": adjustInnerComments(node2, node2.params, commentWS); break; case "ArrayExpression": case "ArrayPattern": case "TupleExpression": adjustInnerComments(node2, node2.elements, commentWS); break; case "ExportNamedDeclaration": case "ImportDeclaration": adjustInnerComments(node2, node2.specifiers, commentWS); break; default: { setInnerComments(node2, comments); } } } else { setInnerComments(node2, comments); } } } finalizeRemainingComments() { const { commentStack } = this.state; for (let i2 = commentStack.length - 1; i2 >= 0; i2--) { this.finalizeComment(commentStack[i2]); } this.state.commentStack = []; } resetPreviousNodeTrailingComments(node2) { const { commentStack } = this.state; const { length } = commentStack; if (length === 0) return; const commentWS = commentStack[length - 1]; if (commentWS.leadingNode === node2) { commentWS.leadingNode = null; } } resetPreviousIdentifierLeadingComments(node2) { const { commentStack } = this.state; const { length } = commentStack; if (length === 0) return; if (commentStack[length - 1].trailingNode === node2) { commentStack[length - 1].trailingNode = null; } else if (length >= 2 && commentStack[length - 2].trailingNode === node2) { commentStack[length - 2].trailingNode = null; } } takeSurroundingComments(node2, start, end) { const { commentStack } = this.state; const commentStackLength = commentStack.length; if (commentStackLength === 0) return; let i2 = commentStackLength - 1; for (; i2 >= 0; i2--) { const commentWS = commentStack[i2]; const commentEnd = commentWS.end; const commentStart = commentWS.start; if (commentStart === end) { commentWS.leadingNode = node2; } else if (commentEnd === start) { commentWS.trailingNode = node2; } else if (commentEnd < start) { break; } } } }; var lineBreak = /\r\n?|[\n\u2028\u2029]/; var lineBreakG = new RegExp(lineBreak.source, "g"); function isNewLine(code2) { switch (code2) { case 10: case 13: case 8232: case 8233: return true; default: return false; } } var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; var skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/g; var skipWhiteSpaceToLineBreak = new RegExp("(?=(" + skipWhiteSpaceInLine.source + "))\\1" + /(?=[\n\r\u2028\u2029]|\/\*(?!.*?\*\/)|$)/.source, "y"); function isWhitespace2(code2) { switch (code2) { case 9: case 11: case 12: case 32: case 160: case 5760: case 8192: case 8193: case 8194: case 8195: case 8196: case 8197: case 8198: case 8199: case 8200: case 8201: case 8202: case 8239: case 8287: case 12288: case 65279: return true; default: return false; } } var State2 = class { constructor() { this.strict = void 0; this.curLine = void 0; this.lineStart = void 0; this.startLoc = void 0; this.endLoc = void 0; this.errors = []; this.potentialArrowAt = -1; this.noArrowAt = []; this.noArrowParamsConversionAt = []; this.maybeInArrowParameters = false; this.inType = false; this.noAnonFunctionType = false; this.hasFlowComment = false; this.isAmbientContext = false; this.inAbstractClass = false; this.inDisallowConditionalTypesContext = false; this.topicContext = { maxNumOfResolvableTopics: 0, maxTopicIndex: null }; this.soloAwait = false; this.inFSharpPipelineDirectBody = false; this.labels = []; this.comments = []; this.commentStack = []; this.pos = 0; this.type = 139; this.value = null; this.start = 0; this.end = 0; this.lastTokEndLoc = null; this.lastTokStartLoc = null; this.lastTokStart = 0; this.context = [types.brace]; this.canStartJSXElement = true; this.containsEsc = false; this.firstInvalidTemplateEscapePos = null; this.strictErrors = /* @__PURE__ */ new Map(); this.tokensLength = 0; } init({ strictMode, sourceType, startLine, startColumn }) { this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module"; this.curLine = startLine; this.lineStart = -startColumn; this.startLoc = this.endLoc = new Position(startLine, startColumn, 0); } curPosition() { return new Position(this.curLine, this.pos - this.lineStart, this.pos); } clone(skipArrays) { const state = new State2(); const keys = Object.keys(this); for (let i2 = 0, length = keys.length; i2 < length; i2++) { const key = keys[i2]; let val = this[key]; if (!skipArrays && Array.isArray(val)) { val = val.slice(); } state[key] = val; } return state; } }; var _isDigit = function isDigit(code2) { return code2 >= 48 && code2 <= 57; }; var forbiddenNumericSeparatorSiblings = { decBinOct: /* @__PURE__ */ new Set([46, 66, 69, 79, 95, 98, 101, 111]), hex: /* @__PURE__ */ new Set([46, 88, 95, 120]) }; var isAllowedNumericSeparatorSibling = { bin: (ch) => ch === 48 || ch === 49, oct: (ch) => ch >= 48 && ch <= 55, dec: (ch) => ch >= 48 && ch <= 57, hex: (ch) => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102 }; function readStringContents(type2, input, pos, lineStart, curLine, errors) { const initialPos = pos; const initialLineStart = lineStart; const initialCurLine = curLine; let out = ""; let firstInvalidLoc = null; let chunkStart = pos; const { length } = input; for (; ; ) { if (pos >= length) { errors.unterminated(initialPos, initialLineStart, initialCurLine); out += input.slice(chunkStart, pos); break; } const ch = input.charCodeAt(pos); if (isStringEnd(type2, ch, input, pos)) { out += input.slice(chunkStart, pos); break; } if (ch === 92) { out += input.slice(chunkStart, pos); const res = readEscapedChar(input, pos, lineStart, curLine, type2 === "template", errors); if (res.ch === null && !firstInvalidLoc) { firstInvalidLoc = { pos, lineStart, curLine }; } else { out += res.ch; } ({ pos, lineStart, curLine } = res); chunkStart = pos; } else if (ch === 8232 || ch === 8233) { ++pos; ++curLine; lineStart = pos; } else if (ch === 10 || ch === 13) { if (type2 === "template") { out += input.slice(chunkStart, pos) + "\n"; ++pos; if (ch === 13 && input.charCodeAt(pos) === 10) { ++pos; } ++curLine; chunkStart = lineStart = pos; } else { errors.unterminated(initialPos, initialLineStart, initialCurLine); } } else { ++pos; } } return { pos, str: out, firstInvalidLoc, lineStart, curLine, containsInvalid: !!firstInvalidLoc }; } function isStringEnd(type2, ch, input, pos) { if (type2 === "template") { return ch === 96 || ch === 36 && input.charCodeAt(pos + 1) === 123; } return ch === (type2 === "double" ? 34 : 39); } function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) { const throwOnInvalid = !inTemplate; pos++; const res = (ch2) => ({ pos, ch: ch2, lineStart, curLine }); const ch = input.charCodeAt(pos++); switch (ch) { case 110: return res("\n"); case 114: return res("\r"); case 120: { let code2; ({ code: code2, pos } = readHexChar(input, pos, lineStart, curLine, 2, false, throwOnInvalid, errors)); return res(code2 === null ? null : String.fromCharCode(code2)); } case 117: { let code2; ({ code: code2, pos } = readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors)); return res(code2 === null ? null : String.fromCodePoint(code2)); } case 116: return res(" "); case 98: return res("\b"); case 118: return res("\v"); case 102: return res("\f"); case 13: if (input.charCodeAt(pos) === 10) { ++pos; } case 10: lineStart = pos; ++curLine; case 8232: case 8233: return res(""); case 56: case 57: if (inTemplate) { return res(null); } else { errors.strictNumericEscape(pos - 1, lineStart, curLine); } default: if (ch >= 48 && ch <= 55) { const startPos = pos - 1; const match2 = input.slice(startPos, pos + 2).match(/^[0-7]+/); let octalStr = match2[0]; let octal = parseInt(octalStr, 8); if (octal > 255) { octalStr = octalStr.slice(0, -1); octal = parseInt(octalStr, 8); } pos += octalStr.length - 1; const next = input.charCodeAt(pos); if (octalStr !== "0" || next === 56 || next === 57) { if (inTemplate) { return res(null); } else { errors.strictNumericEscape(startPos, lineStart, curLine); } } return res(String.fromCharCode(octal)); } return res(String.fromCharCode(ch)); } } function readHexChar(input, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors) { const initialPos = pos; let n; ({ n, pos } = readInt(input, pos, lineStart, curLine, 16, len, forceLen, false, errors, !throwOnInvalid)); if (n === null) { if (throwOnInvalid) { errors.invalidEscapeSequence(initialPos, lineStart, curLine); } else { pos = initialPos - 1; } } return { code: n, pos }; } function readInt(input, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors, bailOnError) { const start = pos; const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct; const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin; let invalid = false; let total = 0; for (let i2 = 0, e2 = len == null ? Infinity : len; i2 < e2; ++i2) { const code2 = input.charCodeAt(pos); let val; if (code2 === 95 && allowNumSeparator !== "bail") { const prev = input.charCodeAt(pos - 1); const next = input.charCodeAt(pos + 1); if (!allowNumSeparator) { if (bailOnError) return { n: null, pos }; errors.numericSeparatorInEscapeSequence(pos, lineStart, curLine); } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) { if (bailOnError) return { n: null, pos }; errors.unexpectedNumericSeparator(pos, lineStart, curLine); } ++pos; continue; } if (code2 >= 97) { val = code2 - 97 + 10; } else if (code2 >= 65) { val = code2 - 65 + 10; } else if (_isDigit(code2)) { val = code2 - 48; } else { val = Infinity; } if (val >= radix) { if (val <= 9 && bailOnError) { return { n: null, pos }; } else if (val <= 9 && errors.invalidDigit(pos, lineStart, curLine, radix)) { val = 0; } else if (forceLen) { val = 0; invalid = true; } else { break; } } ++pos; total = total * radix + val; } if (pos === start || len != null && pos - start !== len || invalid) { return { n: null, pos }; } return { n: total, pos }; } function readCodePoint(input, pos, lineStart, curLine, throwOnInvalid, errors) { const ch = input.charCodeAt(pos); let code2; if (ch === 123) { ++pos; ({ code: code2, pos } = readHexChar(input, pos, lineStart, curLine, input.indexOf("}", pos) - pos, true, throwOnInvalid, errors)); ++pos; if (code2 !== null && code2 > 1114111) { if (throwOnInvalid) { errors.invalidCodePoint(pos, lineStart, curLine); } else { return { code: null, pos }; } } } else { ({ code: code2, pos } = readHexChar(input, pos, lineStart, curLine, 4, false, throwOnInvalid, errors)); } return { code: code2, pos }; } var _excluded = ["at"]; var _excluded2 = ["at"]; function buildPosition(pos, lineStart, curLine) { return new Position(curLine, pos - lineStart, pos); } var VALID_REGEX_FLAGS = /* @__PURE__ */ new Set([103, 109, 115, 105, 121, 117, 100, 118]); var Token = class { constructor(state) { this.type = state.type; this.value = state.value; this.start = state.start; this.end = state.end; this.loc = new SourceLocation(state.startLoc, state.endLoc); } }; var Tokenizer = class extends CommentsParser { constructor(options, input) { super(); this.isLookahead = void 0; this.tokens = []; this.errorHandlers_readInt = { invalidDigit: (pos, lineStart, curLine, radix) => { if (!this.options.errorRecovery) return false; this.raise(Errors.InvalidDigit, { at: buildPosition(pos, lineStart, curLine), radix }); return true; }, numericSeparatorInEscapeSequence: this.errorBuilder(Errors.NumericSeparatorInEscapeSequence), unexpectedNumericSeparator: this.errorBuilder(Errors.UnexpectedNumericSeparator) }; this.errorHandlers_readCodePoint = Object.assign({}, this.errorHandlers_readInt, { invalidEscapeSequence: this.errorBuilder(Errors.InvalidEscapeSequence), invalidCodePoint: this.errorBuilder(Errors.InvalidCodePoint) }); this.errorHandlers_readStringContents_string = Object.assign({}, this.errorHandlers_readCodePoint, { strictNumericEscape: (pos, lineStart, curLine) => { this.recordStrictModeErrors(Errors.StrictNumericEscape, { at: buildPosition(pos, lineStart, curLine) }); }, unterminated: (pos, lineStart, curLine) => { throw this.raise(Errors.UnterminatedString, { at: buildPosition(pos - 1, lineStart, curLine) }); } }); this.errorHandlers_readStringContents_template = Object.assign({}, this.errorHandlers_readCodePoint, { strictNumericEscape: this.errorBuilder(Errors.StrictNumericEscape), unterminated: (pos, lineStart, curLine) => { throw this.raise(Errors.UnterminatedTemplate, { at: buildPosition(pos, lineStart, curLine) }); } }); this.state = new State2(); this.state.init(options); this.input = input; this.length = input.length; this.isLookahead = false; } pushToken(token) { this.tokens.length = this.state.tokensLength; this.tokens.push(token); ++this.state.tokensLength; } next() { this.checkKeywordEscapes(); if (this.options.tokens) { this.pushToken(new Token(this.state)); } this.state.lastTokStart = this.state.start; this.state.lastTokEndLoc = this.state.endLoc; this.state.lastTokStartLoc = this.state.startLoc; this.nextToken(); } eat(type2) { if (this.match(type2)) { this.next(); return true; } else { return false; } } match(type2) { return this.state.type === type2; } createLookaheadState(state) { return { pos: state.pos, value: null, type: state.type, start: state.start, end: state.end, context: [this.curContext()], inType: state.inType, startLoc: state.startLoc, lastTokEndLoc: state.lastTokEndLoc, curLine: state.curLine, lineStart: state.lineStart, curPosition: state.curPosition }; } lookahead() { const old = this.state; this.state = this.createLookaheadState(old); this.isLookahead = true; this.nextToken(); this.isLookahead = false; const curr = this.state; this.state = old; return curr; } nextTokenStart() { return this.nextTokenStartSince(this.state.pos); } nextTokenStartSince(pos) { skipWhiteSpace.lastIndex = pos; return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos; } lookaheadCharCode() { return this.input.charCodeAt(this.nextTokenStart()); } nextTokenInLineStart() { return this.nextTokenInLineStartSince(this.state.pos); } nextTokenInLineStartSince(pos) { skipWhiteSpaceInLine.lastIndex = pos; return skipWhiteSpaceInLine.test(this.input) ? skipWhiteSpaceInLine.lastIndex : pos; } lookaheadInLineCharCode() { return this.input.charCodeAt(this.nextTokenInLineStart()); } codePointAtPos(pos) { let cp = this.input.charCodeAt(pos); if ((cp & 64512) === 55296 && ++pos < this.input.length) { const trail = this.input.charCodeAt(pos); if ((trail & 64512) === 56320) { cp = 65536 + ((cp & 1023) << 10) + (trail & 1023); } } return cp; } setStrict(strict) { this.state.strict = strict; if (strict) { this.state.strictErrors.forEach(([toParseError, at]) => this.raise(toParseError, { at })); this.state.strictErrors.clear(); } } curContext() { return this.state.context[this.state.context.length - 1]; } nextToken() { this.skipSpace(); this.state.start = this.state.pos; if (!this.isLookahead) this.state.startLoc = this.state.curPosition(); if (this.state.pos >= this.length) { this.finishToken(139); return; } this.getTokenFromCode(this.codePointAtPos(this.state.pos)); } skipBlockComment(commentEnd) { let startLoc; if (!this.isLookahead) startLoc = this.state.curPosition(); const start = this.state.pos; const end = this.input.indexOf(commentEnd, start + 2); if (end === -1) { throw this.raise(Errors.UnterminatedComment, { at: this.state.curPosition() }); } this.state.pos = end + commentEnd.length; lineBreakG.lastIndex = start + 2; while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) { ++this.state.curLine; this.state.lineStart = lineBreakG.lastIndex; } if (this.isLookahead) return; const comment = { type: "CommentBlock", value: this.input.slice(start + 2, end), start, end: end + commentEnd.length, loc: new SourceLocation(startLoc, this.state.curPosition()) }; if (this.options.tokens) this.pushToken(comment); return comment; } skipLineComment(startSkip) { const start = this.state.pos; let startLoc; if (!this.isLookahead) startLoc = this.state.curPosition(); let ch = this.input.charCodeAt(this.state.pos += startSkip); if (this.state.pos < this.length) { while (!isNewLine(ch) && ++this.state.pos < this.length) { ch = this.input.charCodeAt(this.state.pos); } } if (this.isLookahead) return; const end = this.state.pos; const value = this.input.slice(start + startSkip, end); const comment = { type: "CommentLine", value, start, end, loc: new SourceLocation(startLoc, this.state.curPosition()) }; if (this.options.tokens) this.pushToken(comment); return comment; } skipSpace() { const spaceStart = this.state.pos; const comments = []; loop: while (this.state.pos < this.length) { const ch = this.input.charCodeAt(this.state.pos); switch (ch) { case 32: case 160: case 9: ++this.state.pos; break; case 13: if (this.input.charCodeAt(this.state.pos + 1) === 10) { ++this.state.pos; } case 10: case 8232: case 8233: ++this.state.pos; ++this.state.curLine; this.state.lineStart = this.state.pos; break; case 47: switch (this.input.charCodeAt(this.state.pos + 1)) { case 42: { const comment = this.skipBlockComment("*/"); if (comment !== void 0) { this.addComment(comment); if (this.options.attachComment) comments.push(comment); } break; } case 47: { const comment = this.skipLineComment(2); if (comment !== void 0) { this.addComment(comment); if (this.options.attachComment) comments.push(comment); } break; } default: break loop; } break; default: if (isWhitespace2(ch)) { ++this.state.pos; } else if (ch === 45 && !this.inModule && this.options.annexB) { const pos = this.state.pos; if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) { const comment = this.skipLineComment(3); if (comment !== void 0) { this.addComment(comment); if (this.options.attachComment) comments.push(comment); } } else { break loop; } } else if (ch === 60 && !this.inModule && this.options.annexB) { const pos = this.state.pos; if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) { const comment = this.skipLineComment(4); if (comment !== void 0) { this.addComment(comment); if (this.options.attachComment) comments.push(comment); } } else { break loop; } } else { break loop; } } } if (comments.length > 0) { const end = this.state.pos; const commentWhitespace = { start: spaceStart, end, comments, leadingNode: null, trailingNode: null, containingNode: null }; this.state.commentStack.push(commentWhitespace); } } finishToken(type2, val) { this.state.end = this.state.pos; this.state.endLoc = this.state.curPosition(); const prevType = this.state.type; this.state.type = type2; this.state.value = val; if (!this.isLookahead) { this.updateContext(prevType); } } replaceToken(type2) { this.state.type = type2; this.updateContext(); } readToken_numberSign() { if (this.state.pos === 0 && this.readToken_interpreter()) { return; } const nextPos = this.state.pos + 1; const next = this.codePointAtPos(nextPos); if (next >= 48 && next <= 57) { throw this.raise(Errors.UnexpectedDigitAfterHash, { at: this.state.curPosition() }); } if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) { this.expectPlugin("recordAndTuple"); if (this.getPluginOption("recordAndTuple", "syntaxType") === "bar") { throw this.raise(next === 123 ? Errors.RecordExpressionHashIncorrectStartSyntaxType : Errors.TupleExpressionHashIncorrectStartSyntaxType, { at: this.state.curPosition() }); } this.state.pos += 2; if (next === 123) { this.finishToken(7); } else { this.finishToken(1); } } else if (isIdentifierStart(next)) { ++this.state.pos; this.finishToken(138, this.readWord1(next)); } else if (next === 92) { ++this.state.pos; this.finishToken(138, this.readWord1()); } else { this.finishOp(27, 1); } } readToken_dot() { const next = this.input.charCodeAt(this.state.pos + 1); if (next >= 48 && next <= 57) { this.readNumber(true); return; } if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) { this.state.pos += 3; this.finishToken(21); } else { ++this.state.pos; this.finishToken(16); } } readToken_slash() { const next = this.input.charCodeAt(this.state.pos + 1); if (next === 61) { this.finishOp(31, 2); } else { this.finishOp(56, 1); } } readToken_interpreter() { if (this.state.pos !== 0 || this.length < 2) return false; let ch = this.input.charCodeAt(this.state.pos + 1); if (ch !== 33) return false; const start = this.state.pos; this.state.pos += 1; while (!isNewLine(ch) && ++this.state.pos < this.length) { ch = this.input.charCodeAt(this.state.pos); } const value = this.input.slice(start + 2, this.state.pos); this.finishToken(28, value); return true; } readToken_mult_modulo(code2) { let type2 = code2 === 42 ? 55 : 54; let width = 1; let next = this.input.charCodeAt(this.state.pos + 1); if (code2 === 42 && next === 42) { width++; next = this.input.charCodeAt(this.state.pos + 2); type2 = 57; } if (next === 61 && !this.state.inType) { width++; type2 = code2 === 37 ? 33 : 30; } this.finishOp(type2, width); } readToken_pipe_amp(code2) { const next = this.input.charCodeAt(this.state.pos + 1); if (next === code2) { if (this.input.charCodeAt(this.state.pos + 2) === 61) { this.finishOp(30, 3); } else { this.finishOp(code2 === 124 ? 41 : 42, 2); } return; } if (code2 === 124) { if (next === 62) { this.finishOp(39, 2); return; } if (this.hasPlugin("recordAndTuple") && next === 125) { if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { throw this.raise(Errors.RecordExpressionBarIncorrectEndSyntaxType, { at: this.state.curPosition() }); } this.state.pos += 2; this.finishToken(9); return; } if (this.hasPlugin("recordAndTuple") && next === 93) { if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { throw this.raise(Errors.TupleExpressionBarIncorrectEndSyntaxType, { at: this.state.curPosition() }); } this.state.pos += 2; this.finishToken(4); return; } } if (next === 61) { this.finishOp(30, 2); return; } this.finishOp(code2 === 124 ? 43 : 45, 1); } readToken_caret() { const next = this.input.charCodeAt(this.state.pos + 1); if (next === 61 && !this.state.inType) { this.finishOp(32, 2); } else if (next === 94 && this.hasPlugin(["pipelineOperator", { proposal: "hack", topicToken: "^^" }])) { this.finishOp(37, 2); const lookaheadCh = this.input.codePointAt(this.state.pos); if (lookaheadCh === 94) { this.unexpected(); } } else { this.finishOp(44, 1); } } readToken_atSign() { const next = this.input.charCodeAt(this.state.pos + 1); if (next === 64 && this.hasPlugin(["pipelineOperator", { proposal: "hack", topicToken: "@@" }])) { this.finishOp(38, 2); } else { this.finishOp(26, 1); } } readToken_plus_min(code2) { const next = this.input.charCodeAt(this.state.pos + 1); if (next === code2) { this.finishOp(34, 2); return; } if (next === 61) { this.finishOp(30, 2); } else { this.finishOp(53, 1); } } readToken_lt() { const { pos } = this.state; const next = this.input.charCodeAt(pos + 1); if (next === 60) { if (this.input.charCodeAt(pos + 2) === 61) { this.finishOp(30, 3); return; } this.finishOp(51, 2); return; } if (next === 61) { this.finishOp(49, 2); return; } this.finishOp(47, 1); } readToken_gt() { const { pos } = this.state; const next = this.input.charCodeAt(pos + 1); if (next === 62) { const size = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2; if (this.input.charCodeAt(pos + size) === 61) { this.finishOp(30, size + 1); return; } this.finishOp(52, size); return; } if (next === 61) { this.finishOp(49, 2); return; } this.finishOp(48, 1); } readToken_eq_excl(code2) { const next = this.input.charCodeAt(this.state.pos + 1); if (next === 61) { this.finishOp(46, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2); return; } if (code2 === 61 && next === 62) { this.state.pos += 2; this.finishToken(19); return; } this.finishOp(code2 === 61 ? 29 : 35, 1); } readToken_question() { const next = this.input.charCodeAt(this.state.pos + 1); const next2 = this.input.charCodeAt(this.state.pos + 2); if (next === 63) { if (next2 === 61) { this.finishOp(30, 3); } else { this.finishOp(40, 2); } } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) { this.state.pos += 2; this.finishToken(18); } else { ++this.state.pos; this.finishToken(17); } } getTokenFromCode(code2) { switch (code2) { case 46: this.readToken_dot(); return; case 40: ++this.state.pos; this.finishToken(10); return; case 41: ++this.state.pos; this.finishToken(11); return; case 59: ++this.state.pos; this.finishToken(13); return; case 44: ++this.state.pos; this.finishToken(12); return; case 91: if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { throw this.raise(Errors.TupleExpressionBarIncorrectStartSyntaxType, { at: this.state.curPosition() }); } this.state.pos += 2; this.finishToken(2); } else { ++this.state.pos; this.finishToken(0); } return; case 93: ++this.state.pos; this.finishToken(3); return; case 123: if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) { if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") { throw this.raise(Errors.RecordExpressionBarIncorrectStartSyntaxType, { at: this.state.curPosition() }); } this.state.pos += 2; this.finishToken(6); } else { ++this.state.pos; this.finishToken(5); } return; case 125: ++this.state.pos; this.finishToken(8); return; case 58: if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) { this.finishOp(15, 2); } else { ++this.state.pos; this.finishToken(14); } return; case 63: this.readToken_question(); return; case 96: this.readTemplateToken(); return; case 48: { const next = this.input.charCodeAt(this.state.pos + 1); if (next === 120 || next === 88) { this.readRadixNumber(16); return; } if (next === 111 || next === 79) { this.readRadixNumber(8); return; } if (next === 98 || next === 66) { this.readRadixNumber(2); return; } } case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: this.readNumber(false); return; case 34: case 39: this.readString(code2); return; case 47: this.readToken_slash(); return; case 37: case 42: this.readToken_mult_modulo(code2); return; case 124: case 38: this.readToken_pipe_amp(code2); return; case 94: this.readToken_caret(); return; case 43: case 45: this.readToken_plus_min(code2); return; case 60: this.readToken_lt(); return; case 62: this.readToken_gt(); return; case 61: case 33: this.readToken_eq_excl(code2); return; case 126: this.finishOp(36, 1); return; case 64: this.readToken_atSign(); return; case 35: this.readToken_numberSign(); return; case 92: this.readWord(); return; default: if (isIdentifierStart(code2)) { this.readWord(code2); return; } } throw this.raise(Errors.InvalidOrUnexpectedToken, { at: this.state.curPosition(), unexpected: String.fromCodePoint(code2) }); } finishOp(type2, size) { const str2 = this.input.slice(this.state.pos, this.state.pos + size); this.state.pos += size; this.finishToken(type2, str2); } readRegexp() { const startLoc = this.state.startLoc; const start = this.state.start + 1; let escaped, inClass; let { pos } = this.state; for (; ; ++pos) { if (pos >= this.length) { throw this.raise(Errors.UnterminatedRegExp, { at: createPositionWithColumnOffset(startLoc, 1) }); } const ch = this.input.charCodeAt(pos); if (isNewLine(ch)) { throw this.raise(Errors.UnterminatedRegExp, { at: createPositionWithColumnOffset(startLoc, 1) }); } if (escaped) { escaped = false; } else { if (ch === 91) { inClass = true; } else if (ch === 93 && inClass) { inClass = false; } else if (ch === 47 && !inClass) { break; } escaped = ch === 92; } } const content3 = this.input.slice(start, pos); ++pos; let mods = ""; const nextPos = () => createPositionWithColumnOffset(startLoc, pos + 2 - start); while (pos < this.length) { const cp = this.codePointAtPos(pos); const char = String.fromCharCode(cp); if (VALID_REGEX_FLAGS.has(cp)) { if (cp === 118) { if (mods.includes("u")) { this.raise(Errors.IncompatibleRegExpUVFlags, { at: nextPos() }); } } else if (cp === 117) { if (mods.includes("v")) { this.raise(Errors.IncompatibleRegExpUVFlags, { at: nextPos() }); } } if (mods.includes(char)) { this.raise(Errors.DuplicateRegExpFlags, { at: nextPos() }); } } else if (isIdentifierChar(cp) || cp === 92) { this.raise(Errors.MalformedRegExpFlags, { at: nextPos() }); } else { break; } ++pos; mods += char; } this.state.pos = pos; this.finishToken(137, { pattern: content3, flags: mods }); } readInt(radix, len, forceLen = false, allowNumSeparator = true) { const { n, pos } = readInt(this.input, this.state.pos, this.state.lineStart, this.state.curLine, radix, len, forceLen, allowNumSeparator, this.errorHandlers_readInt, false); this.state.pos = pos; return n; } readRadixNumber(radix) { const startLoc = this.state.curPosition(); let isBigInt = false; this.state.pos += 2; const val = this.readInt(radix); if (val == null) { this.raise(Errors.InvalidDigit, { at: createPositionWithColumnOffset(startLoc, 2), radix }); } const next = this.input.charCodeAt(this.state.pos); if (next === 110) { ++this.state.pos; isBigInt = true; } else if (next === 109) { throw this.raise(Errors.InvalidDecimal, { at: startLoc }); } if (isIdentifierStart(this.codePointAtPos(this.state.pos))) { throw this.raise(Errors.NumberIdentifier, { at: this.state.curPosition() }); } if (isBigInt) { const str2 = this.input.slice(startLoc.index, this.state.pos).replace(/[_n]/g, ""); this.finishToken(135, str2); return; } this.finishToken(134, val); } readNumber(startsWithDot) { const start = this.state.pos; const startLoc = this.state.curPosition(); let isFloat2 = false; let isBigInt = false; let isDecimal = false; let hasExponent = false; let isOctal = false; if (!startsWithDot && this.readInt(10) === null) { this.raise(Errors.InvalidNumber, { at: this.state.curPosition() }); } const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48; if (hasLeadingZero) { const integer = this.input.slice(start, this.state.pos); this.recordStrictModeErrors(Errors.StrictOctalLiteral, { at: startLoc }); if (!this.state.strict) { const underscorePos = integer.indexOf("_"); if (underscorePos > 0) { this.raise(Errors.ZeroDigitNumericSeparator, { at: createPositionWithColumnOffset(startLoc, underscorePos) }); } } isOctal = hasLeadingZero && !/[89]/.test(integer); } let next = this.input.charCodeAt(this.state.pos); if (next === 46 && !isOctal) { ++this.state.pos; this.readInt(10); isFloat2 = true; next = this.input.charCodeAt(this.state.pos); } if ((next === 69 || next === 101) && !isOctal) { next = this.input.charCodeAt(++this.state.pos); if (next === 43 || next === 45) { ++this.state.pos; } if (this.readInt(10) === null) { this.raise(Errors.InvalidOrMissingExponent, { at: startLoc }); } isFloat2 = true; hasExponent = true; next = this.input.charCodeAt(this.state.pos); } if (next === 110) { if (isFloat2 || hasLeadingZero) { this.raise(Errors.InvalidBigIntLiteral, { at: startLoc }); } ++this.state.pos; isBigInt = true; } if (next === 109) { this.expectPlugin("decimal", this.state.curPosition()); if (hasExponent || hasLeadingZero) { this.raise(Errors.InvalidDecimal, { at: startLoc }); } ++this.state.pos; isDecimal = true; } if (isIdentifierStart(this.codePointAtPos(this.state.pos))) { throw this.raise(Errors.NumberIdentifier, { at: this.state.curPosition() }); } const str2 = this.input.slice(start, this.state.pos).replace(/[_mn]/g, ""); if (isBigInt) { this.finishToken(135, str2); return; } if (isDecimal) { this.finishToken(136, str2); return; } const val = isOctal ? parseInt(str2, 8) : parseFloat(str2); this.finishToken(134, val); } readCodePoint(throwOnInvalid) { const { code: code2, pos } = readCodePoint(this.input, this.state.pos, this.state.lineStart, this.state.curLine, throwOnInvalid, this.errorHandlers_readCodePoint); this.state.pos = pos; return code2; } readString(quote) { const { str: str2, pos, curLine, lineStart } = readStringContents(quote === 34 ? "double" : "single", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_string); this.state.pos = pos + 1; this.state.lineStart = lineStart; this.state.curLine = curLine; this.finishToken(133, str2); } readTemplateContinuation() { if (!this.match(8)) { this.unexpected(null, 8); } this.state.pos--; this.readTemplateToken(); } readTemplateToken() { const opening = this.input[this.state.pos]; const { str: str2, firstInvalidLoc, pos, curLine, lineStart } = readStringContents("template", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_template); this.state.pos = pos + 1; this.state.lineStart = lineStart; this.state.curLine = curLine; if (firstInvalidLoc) { this.state.firstInvalidTemplateEscapePos = new Position(firstInvalidLoc.curLine, firstInvalidLoc.pos - firstInvalidLoc.lineStart, firstInvalidLoc.pos); } if (this.input.codePointAt(pos) === 96) { this.finishToken(24, firstInvalidLoc ? null : opening + str2 + "`"); } else { this.state.pos++; this.finishToken(25, firstInvalidLoc ? null : opening + str2 + "${"); } } recordStrictModeErrors(toParseError, { at }) { const index2 = at.index; if (this.state.strict && !this.state.strictErrors.has(index2)) { this.raise(toParseError, { at }); } else { this.state.strictErrors.set(index2, [toParseError, at]); } } readWord1(firstCode) { this.state.containsEsc = false; let word = ""; const start = this.state.pos; let chunkStart = this.state.pos; if (firstCode !== void 0) { this.state.pos += firstCode <= 65535 ? 1 : 2; } while (this.state.pos < this.length) { const ch = this.codePointAtPos(this.state.pos); if (isIdentifierChar(ch)) { this.state.pos += ch <= 65535 ? 1 : 2; } else if (ch === 92) { this.state.containsEsc = true; word += this.input.slice(chunkStart, this.state.pos); const escStart = this.state.curPosition(); const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar; if (this.input.charCodeAt(++this.state.pos) !== 117) { this.raise(Errors.MissingUnicodeEscape, { at: this.state.curPosition() }); chunkStart = this.state.pos - 1; continue; } ++this.state.pos; const esc = this.readCodePoint(true); if (esc !== null) { if (!identifierCheck(esc)) { this.raise(Errors.EscapedCharNotAnIdentifier, { at: escStart }); } word += String.fromCodePoint(esc); } chunkStart = this.state.pos; } else { break; } } return word + this.input.slice(chunkStart, this.state.pos); } readWord(firstCode) { const word = this.readWord1(firstCode); const type2 = keywords$1.get(word); if (type2 !== void 0) { this.finishToken(type2, tokenLabelName(type2)); } else { this.finishToken(132, word); } } checkKeywordEscapes() { const { type: type2 } = this.state; if (tokenIsKeyword(type2) && this.state.containsEsc) { this.raise(Errors.InvalidEscapedReservedWord, { at: this.state.startLoc, reservedWord: tokenLabelName(type2) }); } } raise(toParseError, raiseProperties) { const { at } = raiseProperties, details = _objectWithoutPropertiesLoose(raiseProperties, _excluded); const loc = at instanceof Position ? at : at.loc.start; const error = toParseError({ loc, details }); if (!this.options.errorRecovery) throw error; if (!this.isLookahead) this.state.errors.push(error); return error; } raiseOverwrite(toParseError, raiseProperties) { const { at } = raiseProperties, details = _objectWithoutPropertiesLoose(raiseProperties, _excluded2); const loc = at instanceof Position ? at : at.loc.start; const pos = loc.index; const errors = this.state.errors; for (let i2 = errors.length - 1; i2 >= 0; i2--) { const error = errors[i2]; if (error.loc.index === pos) { return errors[i2] = toParseError({ loc, details }); } if (error.loc.index < pos) break; } return this.raise(toParseError, raiseProperties); } updateContext(prevType) { } unexpected(loc, type2) { throw this.raise(Errors.UnexpectedToken, { expected: type2 ? tokenLabelName(type2) : null, at: loc != null ? loc : this.state.startLoc }); } expectPlugin(pluginName, loc) { if (this.hasPlugin(pluginName)) { return true; } throw this.raise(Errors.MissingPlugin, { at: loc != null ? loc : this.state.startLoc, missingPlugin: [pluginName] }); } expectOnePlugin(pluginNames) { if (!pluginNames.some((name) => this.hasPlugin(name))) { throw this.raise(Errors.MissingOneOfPlugins, { at: this.state.startLoc, missingPlugin: pluginNames }); } } errorBuilder(error) { return (pos, lineStart, curLine) => { this.raise(error, { at: buildPosition(pos, lineStart, curLine) }); }; } }; var ClassScope = class { constructor() { this.privateNames = /* @__PURE__ */ new Set(); this.loneAccessors = /* @__PURE__ */ new Map(); this.undefinedPrivateNames = /* @__PURE__ */ new Map(); } }; var ClassScopeHandler = class { constructor(parser) { this.parser = void 0; this.stack = []; this.undefinedPrivateNames = /* @__PURE__ */ new Map(); this.parser = parser; } current() { return this.stack[this.stack.length - 1]; } enter() { this.stack.push(new ClassScope()); } exit() { const oldClassScope = this.stack.pop(); const current = this.current(); for (const [name, loc] of Array.from(oldClassScope.undefinedPrivateNames)) { if (current) { if (!current.undefinedPrivateNames.has(name)) { current.undefinedPrivateNames.set(name, loc); } } else { this.parser.raise(Errors.InvalidPrivateFieldResolution, { at: loc, identifierName: name }); } } } declarePrivateName(name, elementType, loc) { const { privateNames, loneAccessors, undefinedPrivateNames } = this.current(); let redefined = privateNames.has(name); if (elementType & 3) { const accessor = redefined && loneAccessors.get(name); if (accessor) { const oldStatic = accessor & 4; const newStatic = elementType & 4; const oldKind = accessor & 3; const newKind = elementType & 3; redefined = oldKind === newKind || oldStatic !== newStatic; if (!redefined) loneAccessors.delete(name); } else if (!redefined) { loneAccessors.set(name, elementType); } } if (redefined) { this.parser.raise(Errors.PrivateNameRedeclaration, { at: loc, identifierName: name }); } privateNames.add(name); undefinedPrivateNames.delete(name); } usePrivateName(name, loc) { let classScope; for (classScope of this.stack) { if (classScope.privateNames.has(name)) return; } if (classScope) { classScope.undefinedPrivateNames.set(name, loc); } else { this.parser.raise(Errors.InvalidPrivateFieldResolution, { at: loc, identifierName: name }); } } }; var ExpressionScope = class { constructor(type2 = 0) { this.type = type2; } canBeArrowParameterDeclaration() { return this.type === 2 || this.type === 1; } isCertainlyParameterDeclaration() { return this.type === 3; } }; var ArrowHeadParsingScope = class extends ExpressionScope { constructor(type2) { super(type2); this.declarationErrors = /* @__PURE__ */ new Map(); } recordDeclarationError(ParsingErrorClass, { at }) { const index2 = at.index; this.declarationErrors.set(index2, [ParsingErrorClass, at]); } clearDeclarationError(index2) { this.declarationErrors.delete(index2); } iterateErrors(iterator) { this.declarationErrors.forEach(iterator); } }; var ExpressionScopeHandler = class { constructor(parser) { this.parser = void 0; this.stack = [new ExpressionScope()]; this.parser = parser; } enter(scope) { this.stack.push(scope); } exit() { this.stack.pop(); } recordParameterInitializerError(toParseError, { at: node2 }) { const origin = { at: node2.loc.start }; const { stack } = this; let i2 = stack.length - 1; let scope = stack[i2]; while (!scope.isCertainlyParameterDeclaration()) { if (scope.canBeArrowParameterDeclaration()) { scope.recordDeclarationError(toParseError, origin); } else { return; } scope = stack[--i2]; } this.parser.raise(toParseError, origin); } recordArrowParameterBindingError(error, { at: node2 }) { const { stack } = this; const scope = stack[stack.length - 1]; const origin = { at: node2.loc.start }; if (scope.isCertainlyParameterDeclaration()) { this.parser.raise(error, origin); } else if (scope.canBeArrowParameterDeclaration()) { scope.recordDeclarationError(error, origin); } else { return; } } recordAsyncArrowParametersError({ at }) { const { stack } = this; let i2 = stack.length - 1; let scope = stack[i2]; while (scope.canBeArrowParameterDeclaration()) { if (scope.type === 2) { scope.recordDeclarationError(Errors.AwaitBindingIdentifier, { at }); } scope = stack[--i2]; } } validateAsPattern() { const { stack } = this; const currentScope = stack[stack.length - 1]; if (!currentScope.canBeArrowParameterDeclaration()) return; currentScope.iterateErrors(([toParseError, loc]) => { this.parser.raise(toParseError, { at: loc }); let i2 = stack.length - 2; let scope = stack[i2]; while (scope.canBeArrowParameterDeclaration()) { scope.clearDeclarationError(loc.index); scope = stack[--i2]; } }); } }; function newParameterDeclarationScope() { return new ExpressionScope(3); } function newArrowHeadScope() { return new ArrowHeadParsingScope(1); } function newAsyncArrowScope() { return new ArrowHeadParsingScope(2); } function newExpressionScope() { return new ExpressionScope(); } var PARAM = 0; var PARAM_YIELD = 1; var PARAM_AWAIT = 2; var PARAM_RETURN = 4; var PARAM_IN = 8; var ProductionParameterHandler = class { constructor() { this.stacks = []; } enter(flags) { this.stacks.push(flags); } exit() { this.stacks.pop(); } currentFlags() { return this.stacks[this.stacks.length - 1]; } get hasAwait() { return (this.currentFlags() & PARAM_AWAIT) > 0; } get hasYield() { return (this.currentFlags() & PARAM_YIELD) > 0; } get hasReturn() { return (this.currentFlags() & PARAM_RETURN) > 0; } get hasIn() { return (this.currentFlags() & PARAM_IN) > 0; } }; function functionFlags(isAsync2, isGenerator) { return (isAsync2 ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0); } var UtilParser = class extends Tokenizer { addExtra(node2, key, value, enumerable = true) { if (!node2) return; const extra = node2.extra = node2.extra || {}; if (enumerable) { extra[key] = value; } else { Object.defineProperty(extra, key, { enumerable, value }); } } isContextual(token) { return this.state.type === token && !this.state.containsEsc; } isUnparsedContextual(nameStart, name) { const nameEnd = nameStart + name.length; if (this.input.slice(nameStart, nameEnd) === name) { const nextCh = this.input.charCodeAt(nameEnd); return !(isIdentifierChar(nextCh) || (nextCh & 64512) === 55296); } return false; } isLookaheadContextual(name) { const next = this.nextTokenStart(); return this.isUnparsedContextual(next, name); } eatContextual(token) { if (this.isContextual(token)) { this.next(); return true; } return false; } expectContextual(token, toParseError) { if (!this.eatContextual(token)) { if (toParseError != null) { throw this.raise(toParseError, { at: this.state.startLoc }); } this.unexpected(null, token); } } canInsertSemicolon() { return this.match(139) || this.match(8) || this.hasPrecedingLineBreak(); } hasPrecedingLineBreak() { return lineBreak.test(this.input.slice(this.state.lastTokEndLoc.index, this.state.start)); } hasFollowingLineBreak() { skipWhiteSpaceToLineBreak.lastIndex = this.state.end; return skipWhiteSpaceToLineBreak.test(this.input); } isLineTerminator() { return this.eat(13) || this.canInsertSemicolon(); } semicolon(allowAsi = true) { if (allowAsi ? this.isLineTerminator() : this.eat(13)) return; this.raise(Errors.MissingSemicolon, { at: this.state.lastTokEndLoc }); } expect(type2, loc) { this.eat(type2) || this.unexpected(loc, type2); } tryParse(fn, oldState = this.state.clone()) { const abortSignal = { node: null }; try { const node2 = fn((node3 = null) => { abortSignal.node = node3; throw abortSignal; }); if (this.state.errors.length > oldState.errors.length) { const failState = this.state; this.state = oldState; this.state.tokensLength = failState.tokensLength; return { node: node2, error: failState.errors[oldState.errors.length], thrown: false, aborted: false, failState }; } return { node: node2, error: null, thrown: false, aborted: false, failState: null }; } catch (error) { const failState = this.state; this.state = oldState; if (error instanceof SyntaxError) { return { node: null, error, thrown: true, aborted: false, failState }; } if (error === abortSignal) { return { node: abortSignal.node, error: null, thrown: false, aborted: true, failState }; } throw error; } } checkExpressionErrors(refExpressionErrors, andThrow) { if (!refExpressionErrors) return false; const { shorthandAssignLoc, doubleProtoLoc, privateKeyLoc, optionalParametersLoc } = refExpressionErrors; const hasErrors = !!shorthandAssignLoc || !!doubleProtoLoc || !!optionalParametersLoc || !!privateKeyLoc; if (!andThrow) { return hasErrors; } if (shorthandAssignLoc != null) { this.raise(Errors.InvalidCoverInitializedName, { at: shorthandAssignLoc }); } if (doubleProtoLoc != null) { this.raise(Errors.DuplicateProto, { at: doubleProtoLoc }); } if (privateKeyLoc != null) { this.raise(Errors.UnexpectedPrivateField, { at: privateKeyLoc }); } if (optionalParametersLoc != null) { this.unexpected(optionalParametersLoc); } } isLiteralPropertyName() { return tokenIsLiteralPropertyName(this.state.type); } isPrivateName(node2) { return node2.type === "PrivateName"; } getPrivateNameSV(node2) { return node2.id.name; } hasPropertyAsPrivateName(node2) { return (node2.type === "MemberExpression" || node2.type === "OptionalMemberExpression") && this.isPrivateName(node2.property); } isObjectProperty(node2) { return node2.type === "ObjectProperty"; } isObjectMethod(node2) { return node2.type === "ObjectMethod"; } initializeScopes(inModule = this.options.sourceType === "module") { const oldLabels = this.state.labels; this.state.labels = []; const oldExportedIdentifiers = this.exportedIdentifiers; this.exportedIdentifiers = /* @__PURE__ */ new Set(); const oldInModule = this.inModule; this.inModule = inModule; const oldScope = this.scope; const ScopeHandler2 = this.getScopeHandler(); this.scope = new ScopeHandler2(this, inModule); const oldProdParam = this.prodParam; this.prodParam = new ProductionParameterHandler(); const oldClassScope = this.classScope; this.classScope = new ClassScopeHandler(this); const oldExpressionScope = this.expressionScope; this.expressionScope = new ExpressionScopeHandler(this); return () => { this.state.labels = oldLabels; this.exportedIdentifiers = oldExportedIdentifiers; this.inModule = oldInModule; this.scope = oldScope; this.prodParam = oldProdParam; this.classScope = oldClassScope; this.expressionScope = oldExpressionScope; }; } enterInitialScopes() { let paramFlags = PARAM; if (this.inModule) { paramFlags |= PARAM_AWAIT; } this.scope.enter(1); this.prodParam.enter(paramFlags); } checkDestructuringPrivate(refExpressionErrors) { const { privateKeyLoc } = refExpressionErrors; if (privateKeyLoc !== null) { this.expectPlugin("destructuringPrivate", privateKeyLoc); } } }; var ExpressionErrors = class { constructor() { this.shorthandAssignLoc = null; this.doubleProtoLoc = null; this.privateKeyLoc = null; this.optionalParametersLoc = null; } }; var Node = class { constructor(parser, pos, loc) { this.type = ""; this.start = pos; this.end = 0; this.loc = new SourceLocation(loc); if (parser != null && parser.options.ranges) this.range = [pos, 0]; if (parser != null && parser.filename) this.loc.filename = parser.filename; } }; var NodePrototype = Node.prototype; { NodePrototype.__clone = function() { const newNode = new Node(void 0, this.start, this.loc.start); const keys = Object.keys(this); for (let i2 = 0, length = keys.length; i2 < length; i2++) { const key = keys[i2]; if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") { newNode[key] = this[key]; } } return newNode; }; } function clonePlaceholder(node2) { return cloneIdentifier(node2); } function cloneIdentifier(node2) { const { type: type2, start, end, loc, range, extra, name } = node2; const cloned = Object.create(NodePrototype); cloned.type = type2; cloned.start = start; cloned.end = end; cloned.loc = loc; cloned.range = range; cloned.extra = extra; cloned.name = name; if (type2 === "Placeholder") { cloned.expectedNode = node2.expectedNode; } return cloned; } function cloneStringLiteral(node2) { const { type: type2, start, end, loc, range, extra } = node2; if (type2 === "Placeholder") { return clonePlaceholder(node2); } const cloned = Object.create(NodePrototype); cloned.type = type2; cloned.start = start; cloned.end = end; cloned.loc = loc; cloned.range = range; if (node2.raw !== void 0) { cloned.raw = node2.raw; } else { cloned.extra = extra; } cloned.value = node2.value; return cloned; } var NodeUtils = class extends UtilParser { startNode() { return new Node(this, this.state.start, this.state.startLoc); } startNodeAt(loc) { return new Node(this, loc.index, loc); } startNodeAtNode(type2) { return this.startNodeAt(type2.loc.start); } finishNode(node2, type2) { return this.finishNodeAt(node2, type2, this.state.lastTokEndLoc); } finishNodeAt(node2, type2, endLoc) { node2.type = type2; node2.end = endLoc.index; node2.loc.end = endLoc; if (this.options.ranges) node2.range[1] = endLoc.index; if (this.options.attachComment) this.processComment(node2); return node2; } resetStartLocation(node2, startLoc) { node2.start = startLoc.index; node2.loc.start = startLoc; if (this.options.ranges) node2.range[0] = startLoc.index; } resetEndLocation(node2, endLoc = this.state.lastTokEndLoc) { node2.end = endLoc.index; node2.loc.end = endLoc; if (this.options.ranges) node2.range[1] = endLoc.index; } resetStartLocationFromNode(node2, locationNode) { this.resetStartLocation(node2, locationNode.loc.start); } }; var reservedTypes = /* @__PURE__ */ new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]); var FlowErrors = ParseErrorEnum`flow`({ AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.", AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.", AssignReservedType: ({ reservedType }) => `Cannot overwrite reserved type ${reservedType}.`, DeclareClassElement: "The `declare` modifier can only appear on class fields.", DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.", DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.", EnumBooleanMemberNotInitialized: ({ memberName, enumName }) => `Boolean enum members need to be initialized. Use either \`${memberName} = true,\` or \`${memberName} = false,\` in enum \`${enumName}\`.`, EnumDuplicateMemberName: ({ memberName, enumName }) => `Enum member names need to be unique, but the name \`${memberName}\` has already been used before in enum \`${enumName}\`.`, EnumInconsistentMemberValues: ({ enumName }) => `Enum \`${enumName}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`, EnumInvalidExplicitType: ({ invalidEnumType, enumName }) => `Enum type \`${invalidEnumType}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`, EnumInvalidExplicitTypeUnknownSupplied: ({ enumName }) => `Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`, EnumInvalidMemberInitializerPrimaryType: ({ enumName, memberName, explicitType }) => `Enum \`${enumName}\` has type \`${explicitType}\`, so the initializer of \`${memberName}\` needs to be a ${explicitType} literal.`, EnumInvalidMemberInitializerSymbolType: ({ enumName, memberName }) => `Symbol enum members cannot be initialized. Use \`${memberName},\` in enum \`${enumName}\`.`, EnumInvalidMemberInitializerUnknownType: ({ enumName, memberName }) => `The enum member initializer for \`${memberName}\` needs to be a literal (either a boolean, number, or string) in enum \`${enumName}\`.`, EnumInvalidMemberName: ({ enumName, memberName, suggestion }) => `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${memberName}\`, consider using \`${suggestion}\`, in enum \`${enumName}\`.`, EnumNumberMemberNotInitialized: ({ enumName, memberName }) => `Number enum members need to be initialized, e.g. \`${memberName} = 1\` in enum \`${enumName}\`.`, EnumStringMemberInconsistentlyInitialized: ({ enumName }) => `String enum members need to consistently either all use initializers, or use no initializers, in enum \`${enumName}\`.`, GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.", ImportReflectionHasImportType: "An `import module` declaration can not use `type` or `typeof` keyword.", ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.", InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.", InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.", InexactVariance: "Explicit inexact syntax cannot have variance.", InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.", MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.", NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.", NestedFlowComment: "Cannot have a flow comment inside another flow comment.", PatternIsOptional: Object.assign({ message: "A binding pattern parameter cannot be optional in an implementation signature." }, { reasonCode: "OptionalBindingPattern" }), SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.", SpreadVariance: "Spread properties cannot have variance.", ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.", ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.", ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.", ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.", ThisParamNoDefault: "The `this` parameter may not have a default value.", TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.", TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.", UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.", UnexpectedReservedType: ({ reservedType }) => `Unexpected reserved type ${reservedType}.`, UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.", UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.", UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.", UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".', UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.", UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of ` async () => {}`, use `async () => {}`.", UnsupportedDeclareExportKind: ({ unsupportedExportKind, suggestion }) => `\`declare export ${unsupportedExportKind}\` is not supported. Use \`${suggestion}\` instead.`, UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.", UnterminatedFlowComment: "Unterminated flow-comment." }); function isEsModuleType(bodyElement) { return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration"); } function hasTypeImportKind(node2) { return node2.importKind === "type" || node2.importKind === "typeof"; } var exportSuggestions = { const: "declare export var", let: "declare export var", type: "export type", interface: "export interface" }; function partition(list2, test) { const list1 = []; const list22 = []; for (let i2 = 0; i2 < list2.length; i2++) { (test(list2[i2], i2, list2) ? list1 : list22).push(list2[i2]); } return [list1, list22]; } var FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/; var flow3 = (superClass) => class FlowParserMixin extends superClass { constructor(...args) { super(...args); this.flowPragma = void 0; } getScopeHandler() { return FlowScopeHandler; } shouldParseTypes() { return this.getPluginOption("flow", "all") || this.flowPragma === "flow"; } shouldParseEnums() { return !!this.getPluginOption("flow", "enums"); } finishToken(type2, val) { if (type2 !== 133 && type2 !== 13 && type2 !== 28) { if (this.flowPragma === void 0) { this.flowPragma = null; } } super.finishToken(type2, val); } addComment(comment) { if (this.flowPragma === void 0) { const matches = FLOW_PRAGMA_REGEX.exec(comment.value); if (!matches) ; else if (matches[1] === "flow") { this.flowPragma = "flow"; } else if (matches[1] === "noflow") { this.flowPragma = "noflow"; } else { throw new Error("Unexpected flow pragma"); } } super.addComment(comment); } flowParseTypeInitialiser(tok) { const oldInType = this.state.inType; this.state.inType = true; this.expect(tok || 14); const type2 = this.flowParseType(); this.state.inType = oldInType; return type2; } flowParsePredicate() { const node2 = this.startNode(); const moduloLoc = this.state.startLoc; this.next(); this.expectContextual(110); if (this.state.lastTokStart > moduloLoc.index + 1) { this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, { at: moduloLoc }); } if (this.eat(10)) { node2.value = super.parseExpression(); this.expect(11); return this.finishNode(node2, "DeclaredPredicate"); } else { return this.finishNode(node2, "InferredPredicate"); } } flowParseTypeAndPredicateInitialiser() { const oldInType = this.state.inType; this.state.inType = true; this.expect(14); let type2 = null; let predicate = null; if (this.match(54)) { this.state.inType = oldInType; predicate = this.flowParsePredicate(); } else { type2 = this.flowParseType(); this.state.inType = oldInType; if (this.match(54)) { predicate = this.flowParsePredicate(); } } return [type2, predicate]; } flowParseDeclareClass(node2) { this.next(); this.flowParseInterfaceish(node2, true); return this.finishNode(node2, "DeclareClass"); } flowParseDeclareFunction(node2) { this.next(); const id = node2.id = this.parseIdentifier(); const typeNode = this.startNode(); const typeContainer = this.startNode(); if (this.match(47)) { typeNode.typeParameters = this.flowParseTypeParameterDeclaration(); } else { typeNode.typeParameters = null; } this.expect(10); const tmp = this.flowParseFunctionTypeParams(); typeNode.params = tmp.params; typeNode.rest = tmp.rest; typeNode.this = tmp._this; this.expect(11); [typeNode.returnType, node2.predicate] = this.flowParseTypeAndPredicateInitialiser(); typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation"); id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation"); this.resetEndLocation(id); this.semicolon(); this.scope.declareName(node2.id.name, 2048, node2.id.loc.start); return this.finishNode(node2, "DeclareFunction"); } flowParseDeclare(node2, insideModule) { if (this.match(80)) { return this.flowParseDeclareClass(node2); } else if (this.match(68)) { return this.flowParseDeclareFunction(node2); } else if (this.match(74)) { return this.flowParseDeclareVariable(node2); } else if (this.eatContextual(127)) { if (this.match(16)) { return this.flowParseDeclareModuleExports(node2); } else { if (insideModule) { this.raise(FlowErrors.NestedDeclareModule, { at: this.state.lastTokStartLoc }); } return this.flowParseDeclareModule(node2); } } else if (this.isContextual(130)) { return this.flowParseDeclareTypeAlias(node2); } else if (this.isContextual(131)) { return this.flowParseDeclareOpaqueType(node2); } else if (this.isContextual(129)) { return this.flowParseDeclareInterface(node2); } else if (this.match(82)) { return this.flowParseDeclareExportDeclaration(node2, insideModule); } else { this.unexpected(); } } flowParseDeclareVariable(node2) { this.next(); node2.id = this.flowParseTypeAnnotatableIdentifier(true); this.scope.declareName(node2.id.name, 5, node2.id.loc.start); this.semicolon(); return this.finishNode(node2, "DeclareVariable"); } flowParseDeclareModule(node2) { this.scope.enter(0); if (this.match(133)) { node2.id = super.parseExprAtom(); } else { node2.id = this.parseIdentifier(); } const bodyNode = node2.body = this.startNode(); const body = bodyNode.body = []; this.expect(5); while (!this.match(8)) { let bodyNode2 = this.startNode(); if (this.match(83)) { this.next(); if (!this.isContextual(130) && !this.match(87)) { this.raise(FlowErrors.InvalidNonTypeImportInDeclareModule, { at: this.state.lastTokStartLoc }); } super.parseImport(bodyNode2); } else { this.expectContextual(125, FlowErrors.UnsupportedStatementInDeclareModule); bodyNode2 = this.flowParseDeclare(bodyNode2, true); } body.push(bodyNode2); } this.scope.exit(); this.expect(8); this.finishNode(bodyNode, "BlockStatement"); let kind = null; let hasModuleExport = false; body.forEach((bodyElement) => { if (isEsModuleType(bodyElement)) { if (kind === "CommonJS") { this.raise(FlowErrors.AmbiguousDeclareModuleKind, { at: bodyElement }); } kind = "ES"; } else if (bodyElement.type === "DeclareModuleExports") { if (hasModuleExport) { this.raise(FlowErrors.DuplicateDeclareModuleExports, { at: bodyElement }); } if (kind === "ES") { this.raise(FlowErrors.AmbiguousDeclareModuleKind, { at: bodyElement }); } kind = "CommonJS"; hasModuleExport = true; } }); node2.kind = kind || "CommonJS"; return this.finishNode(node2, "DeclareModule"); } flowParseDeclareExportDeclaration(node2, insideModule) { this.expect(82); if (this.eat(65)) { if (this.match(68) || this.match(80)) { node2.declaration = this.flowParseDeclare(this.startNode()); } else { node2.declaration = this.flowParseType(); this.semicolon(); } node2.default = true; return this.finishNode(node2, "DeclareExportDeclaration"); } else { if (this.match(75) || this.isLet() || (this.isContextual(130) || this.isContextual(129)) && !insideModule) { const label = this.state.value; throw this.raise(FlowErrors.UnsupportedDeclareExportKind, { at: this.state.startLoc, unsupportedExportKind: label, suggestion: exportSuggestions[label] }); } if (this.match(74) || this.match(68) || this.match(80) || this.isContextual(131)) { node2.declaration = this.flowParseDeclare(this.startNode()); node2.default = false; return this.finishNode(node2, "DeclareExportDeclaration"); } else if (this.match(55) || this.match(5) || this.isContextual(129) || this.isContextual(130) || this.isContextual(131)) { node2 = this.parseExport(node2, null); if (node2.type === "ExportNamedDeclaration") { node2.type = "ExportDeclaration"; node2.default = false; delete node2.exportKind; } node2.type = "Declare" + node2.type; return node2; } } this.unexpected(); } flowParseDeclareModuleExports(node2) { this.next(); this.expectContextual(111); node2.typeAnnotation = this.flowParseTypeAnnotation(); this.semicolon(); return this.finishNode(node2, "DeclareModuleExports"); } flowParseDeclareTypeAlias(node2) { this.next(); const finished = this.flowParseTypeAlias(node2); finished.type = "DeclareTypeAlias"; return finished; } flowParseDeclareOpaqueType(node2) { this.next(); const finished = this.flowParseOpaqueType(node2, true); finished.type = "DeclareOpaqueType"; return finished; } flowParseDeclareInterface(node2) { this.next(); this.flowParseInterfaceish(node2, false); return this.finishNode(node2, "DeclareInterface"); } flowParseInterfaceish(node2, isClass) { node2.id = this.flowParseRestrictedIdentifier(!isClass, true); this.scope.declareName(node2.id.name, isClass ? 17 : 8201, node2.id.loc.start); if (this.match(47)) { node2.typeParameters = this.flowParseTypeParameterDeclaration(); } else { node2.typeParameters = null; } node2.extends = []; if (this.eat(81)) { do { node2.extends.push(this.flowParseInterfaceExtends()); } while (!isClass && this.eat(12)); } if (isClass) { node2.implements = []; node2.mixins = []; if (this.eatContextual(117)) { do { node2.mixins.push(this.flowParseInterfaceExtends()); } while (this.eat(12)); } if (this.eatContextual(113)) { do { node2.implements.push(this.flowParseInterfaceExtends()); } while (this.eat(12)); } } node2.body = this.flowParseObjectType({ allowStatic: isClass, allowExact: false, allowSpread: false, allowProto: isClass, allowInexact: false }); } flowParseInterfaceExtends() { const node2 = this.startNode(); node2.id = this.flowParseQualifiedTypeIdentifier(); if (this.match(47)) { node2.typeParameters = this.flowParseTypeParameterInstantiation(); } else { node2.typeParameters = null; } return this.finishNode(node2, "InterfaceExtends"); } flowParseInterface(node2) { this.flowParseInterfaceish(node2, false); return this.finishNode(node2, "InterfaceDeclaration"); } checkNotUnderscore(word) { if (word === "_") { this.raise(FlowErrors.UnexpectedReservedUnderscore, { at: this.state.startLoc }); } } checkReservedType(word, startLoc, declaration) { if (!reservedTypes.has(word)) return; this.raise(declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, { at: startLoc, reservedType: word }); } flowParseRestrictedIdentifier(liberal, declaration) { this.checkReservedType(this.state.value, this.state.startLoc, declaration); return this.parseIdentifier(liberal); } flowParseTypeAlias(node2) { node2.id = this.flowParseRestrictedIdentifier(false, true); this.scope.declareName(node2.id.name, 8201, node2.id.loc.start); if (this.match(47)) { node2.typeParameters = this.flowParseTypeParameterDeclaration(); } else { node2.typeParameters = null; } node2.right = this.flowParseTypeInitialiser(29); this.semicolon(); return this.finishNode(node2, "TypeAlias"); } flowParseOpaqueType(node2, declare) { this.expectContextual(130); node2.id = this.flowParseRestrictedIdentifier(true, true); this.scope.declareName(node2.id.name, 8201, node2.id.loc.start); if (this.match(47)) { node2.typeParameters = this.flowParseTypeParameterDeclaration(); } else { node2.typeParameters = null; } node2.supertype = null; if (this.match(14)) { node2.supertype = this.flowParseTypeInitialiser(14); } node2.impltype = null; if (!declare) { node2.impltype = this.flowParseTypeInitialiser(29); } this.semicolon(); return this.finishNode(node2, "OpaqueType"); } flowParseTypeParameter(requireDefault = false) { const nodeStartLoc = this.state.startLoc; const node2 = this.startNode(); const variance = this.flowParseVariance(); const ident = this.flowParseTypeAnnotatableIdentifier(); node2.name = ident.name; node2.variance = variance; node2.bound = ident.typeAnnotation; if (this.match(29)) { this.eat(29); node2.default = this.flowParseType(); } else { if (requireDefault) { this.raise(FlowErrors.MissingTypeParamDefault, { at: nodeStartLoc }); } } return this.finishNode(node2, "TypeParameter"); } flowParseTypeParameterDeclaration() { const oldInType = this.state.inType; const node2 = this.startNode(); node2.params = []; this.state.inType = true; if (this.match(47) || this.match(142)) { this.next(); } else { this.unexpected(); } let defaultRequired = false; do { const typeParameter = this.flowParseTypeParameter(defaultRequired); node2.params.push(typeParameter); if (typeParameter.default) { defaultRequired = true; } if (!this.match(48)) { this.expect(12); } } while (!this.match(48)); this.expect(48); this.state.inType = oldInType; return this.finishNode(node2, "TypeParameterDeclaration"); } flowParseTypeParameterInstantiation() { const node2 = this.startNode(); const oldInType = this.state.inType; node2.params = []; this.state.inType = true; this.expect(47); const oldNoAnonFunctionType = this.state.noAnonFunctionType; this.state.noAnonFunctionType = false; while (!this.match(48)) { node2.params.push(this.flowParseType()); if (!this.match(48)) { this.expect(12); } } this.state.noAnonFunctionType = oldNoAnonFunctionType; this.expect(48); this.state.inType = oldInType; return this.finishNode(node2, "TypeParameterInstantiation"); } flowParseTypeParameterInstantiationCallOrNew() { const node2 = this.startNode(); const oldInType = this.state.inType; node2.params = []; this.state.inType = true; this.expect(47); while (!this.match(48)) { node2.params.push(this.flowParseTypeOrImplicitInstantiation()); if (!this.match(48)) { this.expect(12); } } this.expect(48); this.state.inType = oldInType; return this.finishNode(node2, "TypeParameterInstantiation"); } flowParseInterfaceType() { const node2 = this.startNode(); this.expectContextual(129); node2.extends = []; if (this.eat(81)) { do { node2.extends.push(this.flowParseInterfaceExtends()); } while (this.eat(12)); } node2.body = this.flowParseObjectType({ allowStatic: false, allowExact: false, allowSpread: false, allowProto: false, allowInexact: false }); return this.finishNode(node2, "InterfaceTypeAnnotation"); } flowParseObjectPropertyKey() { return this.match(134) || this.match(133) ? super.parseExprAtom() : this.parseIdentifier(true); } flowParseObjectTypeIndexer(node2, isStatic, variance) { node2.static = isStatic; if (this.lookahead().type === 14) { node2.id = this.flowParseObjectPropertyKey(); node2.key = this.flowParseTypeInitialiser(); } else { node2.id = null; node2.key = this.flowParseType(); } this.expect(3); node2.value = this.flowParseTypeInitialiser(); node2.variance = variance; return this.finishNode(node2, "ObjectTypeIndexer"); } flowParseObjectTypeInternalSlot(node2, isStatic) { node2.static = isStatic; node2.id = this.flowParseObjectPropertyKey(); this.expect(3); this.expect(3); if (this.match(47) || this.match(10)) { node2.method = true; node2.optional = false; node2.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node2.loc.start)); } else { node2.method = false; if (this.eat(17)) { node2.optional = true; } node2.value = this.flowParseTypeInitialiser(); } return this.finishNode(node2, "ObjectTypeInternalSlot"); } flowParseObjectTypeMethodish(node2) { node2.params = []; node2.rest = null; node2.typeParameters = null; node2.this = null; if (this.match(47)) { node2.typeParameters = this.flowParseTypeParameterDeclaration(); } this.expect(10); if (this.match(78)) { node2.this = this.flowParseFunctionTypeParam(true); node2.this.name = null; if (!this.match(11)) { this.expect(12); } } while (!this.match(11) && !this.match(21)) { node2.params.push(this.flowParseFunctionTypeParam(false)); if (!this.match(11)) { this.expect(12); } } if (this.eat(21)) { node2.rest = this.flowParseFunctionTypeParam(false); } this.expect(11); node2.returnType = this.flowParseTypeInitialiser(); return this.finishNode(node2, "FunctionTypeAnnotation"); } flowParseObjectTypeCallProperty(node2, isStatic) { const valueNode = this.startNode(); node2.static = isStatic; node2.value = this.flowParseObjectTypeMethodish(valueNode); return this.finishNode(node2, "ObjectTypeCallProperty"); } flowParseObjectType({ allowStatic, allowExact, allowSpread, allowProto, allowInexact }) { const oldInType = this.state.inType; this.state.inType = true; const nodeStart = this.startNode(); nodeStart.callProperties = []; nodeStart.properties = []; nodeStart.indexers = []; nodeStart.internalSlots = []; let endDelim; let exact; let inexact = false; if (allowExact && this.match(6)) { this.expect(6); endDelim = 9; exact = true; } else { this.expect(5); endDelim = 8; exact = false; } nodeStart.exact = exact; while (!this.match(endDelim)) { let isStatic = false; let protoStartLoc = null; let inexactStartLoc = null; const node2 = this.startNode(); if (allowProto && this.isContextual(118)) { const lookahead = this.lookahead(); if (lookahead.type !== 14 && lookahead.type !== 17) { this.next(); protoStartLoc = this.state.startLoc; allowStatic = false; } } if (allowStatic && this.isContextual(106)) { const lookahead = this.lookahead(); if (lookahead.type !== 14 && lookahead.type !== 17) { this.next(); isStatic = true; } } const variance = this.flowParseVariance(); if (this.eat(0)) { if (protoStartLoc != null) { this.unexpected(protoStartLoc); } if (this.eat(0)) { if (variance) { this.unexpected(variance.loc.start); } nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node2, isStatic)); } else { nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node2, isStatic, variance)); } } else if (this.match(10) || this.match(47)) { if (protoStartLoc != null) { this.unexpected(protoStartLoc); } if (variance) { this.unexpected(variance.loc.start); } nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node2, isStatic)); } else { let kind = "init"; if (this.isContextual(99) || this.isContextual(104)) { const lookahead = this.lookahead(); if (tokenIsLiteralPropertyName(lookahead.type)) { kind = this.state.value; this.next(); } } const propOrInexact = this.flowParseObjectTypeProperty(node2, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact); if (propOrInexact === null) { inexact = true; inexactStartLoc = this.state.lastTokStartLoc; } else { nodeStart.properties.push(propOrInexact); } } this.flowObjectTypeSemicolon(); if (inexactStartLoc && !this.match(8) && !this.match(9)) { this.raise(FlowErrors.UnexpectedExplicitInexactInObject, { at: inexactStartLoc }); } } this.expect(endDelim); if (allowSpread) { nodeStart.inexact = inexact; } const out = this.finishNode(nodeStart, "ObjectTypeAnnotation"); this.state.inType = oldInType; return out; } flowParseObjectTypeProperty(node2, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact) { if (this.eat(21)) { const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9); if (isInexactToken) { if (!allowSpread) { this.raise(FlowErrors.InexactInsideNonObject, { at: this.state.lastTokStartLoc }); } else if (!allowInexact) { this.raise(FlowErrors.InexactInsideExact, { at: this.state.lastTokStartLoc }); } if (variance) { this.raise(FlowErrors.InexactVariance, { at: variance }); } return null; } if (!allowSpread) { this.raise(FlowErrors.UnexpectedSpreadType, { at: this.state.lastTokStartLoc }); } if (protoStartLoc != null) { this.unexpected(protoStartLoc); } if (variance) { this.raise(FlowErrors.SpreadVariance, { at: variance }); } node2.argument = this.flowParseType(); return this.finishNode(node2, "ObjectTypeSpreadProperty"); } else { node2.key = this.flowParseObjectPropertyKey(); node2.static = isStatic; node2.proto = protoStartLoc != null; node2.kind = kind; let optional = false; if (this.match(47) || this.match(10)) { node2.method = true; if (protoStartLoc != null) { this.unexpected(protoStartLoc); } if (variance) { this.unexpected(variance.loc.start); } node2.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node2.loc.start)); if (kind === "get" || kind === "set") { this.flowCheckGetterSetterParams(node2); } if (!allowSpread && node2.key.name === "constructor" && node2.value.this) { this.raise(FlowErrors.ThisParamBannedInConstructor, { at: node2.value.this }); } } else { if (kind !== "init") this.unexpected(); node2.method = false; if (this.eat(17)) { optional = true; } node2.value = this.flowParseTypeInitialiser(); node2.variance = variance; } node2.optional = optional; return this.finishNode(node2, "ObjectTypeProperty"); } } flowCheckGetterSetterParams(property) { const paramCount = property.kind === "get" ? 0 : 1; const length = property.value.params.length + (property.value.rest ? 1 : 0); if (property.value.this) { this.raise(property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam, { at: property.value.this }); } if (length !== paramCount) { this.raise(property.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, { at: property }); } if (property.kind === "set" && property.value.rest) { this.raise(Errors.BadSetterRestParameter, { at: property }); } } flowObjectTypeSemicolon() { if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) { this.unexpected(); } } flowParseQualifiedTypeIdentifier(startLoc, id) { var _startLoc; (_startLoc = startLoc) != null ? _startLoc : startLoc = this.state.startLoc; let node2 = id || this.flowParseRestrictedIdentifier(true); while (this.eat(16)) { const node22 = this.startNodeAt(startLoc); node22.qualification = node2; node22.id = this.flowParseRestrictedIdentifier(true); node2 = this.finishNode(node22, "QualifiedTypeIdentifier"); } return node2; } flowParseGenericType(startLoc, id) { const node2 = this.startNodeAt(startLoc); node2.typeParameters = null; node2.id = this.flowParseQualifiedTypeIdentifier(startLoc, id); if (this.match(47)) { node2.typeParameters = this.flowParseTypeParameterInstantiation(); } return this.finishNode(node2, "GenericTypeAnnotation"); } flowParseTypeofType() { const node2 = this.startNode(); this.expect(87); node2.argument = this.flowParsePrimaryType(); return this.finishNode(node2, "TypeofTypeAnnotation"); } flowParseTupleType() { const node2 = this.startNode(); node2.types = []; this.expect(0); while (this.state.pos < this.length && !this.match(3)) { node2.types.push(this.flowParseType()); if (this.match(3)) break; this.expect(12); } this.expect(3); return this.finishNode(node2, "TupleTypeAnnotation"); } flowParseFunctionTypeParam(first) { let name = null; let optional = false; let typeAnnotation = null; const node2 = this.startNode(); const lh = this.lookahead(); const isThis = this.state.type === 78; if (lh.type === 14 || lh.type === 17) { if (isThis && !first) { this.raise(FlowErrors.ThisParamMustBeFirst, { at: node2 }); } name = this.parseIdentifier(isThis); if (this.eat(17)) { optional = true; if (isThis) { this.raise(FlowErrors.ThisParamMayNotBeOptional, { at: node2 }); } } typeAnnotation = this.flowParseTypeInitialiser(); } else { typeAnnotation = this.flowParseType(); } node2.name = name; node2.optional = optional; node2.typeAnnotation = typeAnnotation; return this.finishNode(node2, "FunctionTypeParam"); } reinterpretTypeAsFunctionTypeParam(type2) { const node2 = this.startNodeAt(type2.loc.start); node2.name = null; node2.optional = false; node2.typeAnnotation = type2; return this.finishNode(node2, "FunctionTypeParam"); } flowParseFunctionTypeParams(params = []) { let rest = null; let _this = null; if (this.match(78)) { _this = this.flowParseFunctionTypeParam(true); _this.name = null; if (!this.match(11)) { this.expect(12); } } while (!this.match(11) && !this.match(21)) { params.push(this.flowParseFunctionTypeParam(false)); if (!this.match(11)) { this.expect(12); } } if (this.eat(21)) { rest = this.flowParseFunctionTypeParam(false); } return { params, rest, _this }; } flowIdentToTypeAnnotation(startLoc, node2, id) { switch (id.name) { case "any": return this.finishNode(node2, "AnyTypeAnnotation"); case "bool": case "boolean": return this.finishNode(node2, "BooleanTypeAnnotation"); case "mixed": return this.finishNode(node2, "MixedTypeAnnotation"); case "empty": return this.finishNode(node2, "EmptyTypeAnnotation"); case "number": return this.finishNode(node2, "NumberTypeAnnotation"); case "string": return this.finishNode(node2, "StringTypeAnnotation"); case "symbol": return this.finishNode(node2, "SymbolTypeAnnotation"); default: this.checkNotUnderscore(id.name); return this.flowParseGenericType(startLoc, id); } } flowParsePrimaryType() { const startLoc = this.state.startLoc; const node2 = this.startNode(); let tmp; let type2; let isGroupedType = false; const oldNoAnonFunctionType = this.state.noAnonFunctionType; switch (this.state.type) { case 5: return this.flowParseObjectType({ allowStatic: false, allowExact: false, allowSpread: true, allowProto: false, allowInexact: true }); case 6: return this.flowParseObjectType({ allowStatic: false, allowExact: true, allowSpread: true, allowProto: false, allowInexact: false }); case 0: this.state.noAnonFunctionType = false; type2 = this.flowParseTupleType(); this.state.noAnonFunctionType = oldNoAnonFunctionType; return type2; case 47: node2.typeParameters = this.flowParseTypeParameterDeclaration(); this.expect(10); tmp = this.flowParseFunctionTypeParams(); node2.params = tmp.params; node2.rest = tmp.rest; node2.this = tmp._this; this.expect(11); this.expect(19); node2.returnType = this.flowParseType(); return this.finishNode(node2, "FunctionTypeAnnotation"); case 10: this.next(); if (!this.match(11) && !this.match(21)) { if (tokenIsIdentifier(this.state.type) || this.match(78)) { const token = this.lookahead().type; isGroupedType = token !== 17 && token !== 14; } else { isGroupedType = true; } } if (isGroupedType) { this.state.noAnonFunctionType = false; type2 = this.flowParseType(); this.state.noAnonFunctionType = oldNoAnonFunctionType; if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) { this.expect(11); return type2; } else { this.eat(12); } } if (type2) { tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type2)]); } else { tmp = this.flowParseFunctionTypeParams(); } node2.params = tmp.params; node2.rest = tmp.rest; node2.this = tmp._this; this.expect(11); this.expect(19); node2.returnType = this.flowParseType(); node2.typeParameters = null; return this.finishNode(node2, "FunctionTypeAnnotation"); case 133: return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation"); case 85: case 86: node2.value = this.match(85); this.next(); return this.finishNode(node2, "BooleanLiteralTypeAnnotation"); case 53: if (this.state.value === "-") { this.next(); if (this.match(134)) { return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node2); } if (this.match(135)) { return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node2); } throw this.raise(FlowErrors.UnexpectedSubtractionOperand, { at: this.state.startLoc }); } this.unexpected(); return; case 134: return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation"); case 135: return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation"); case 88: this.next(); return this.finishNode(node2, "VoidTypeAnnotation"); case 84: this.next(); return this.finishNode(node2, "NullLiteralTypeAnnotation"); case 78: this.next(); return this.finishNode(node2, "ThisTypeAnnotation"); case 55: this.next(); return this.finishNode(node2, "ExistsTypeAnnotation"); case 87: return this.flowParseTypeofType(); default: if (tokenIsKeyword(this.state.type)) { const label = tokenLabelName(this.state.type); this.next(); return super.createIdentifier(node2, label); } else if (tokenIsIdentifier(this.state.type)) { if (this.isContextual(129)) { return this.flowParseInterfaceType(); } return this.flowIdentToTypeAnnotation(startLoc, node2, this.parseIdentifier()); } } this.unexpected(); } flowParsePostfixType() { const startLoc = this.state.startLoc; let type2 = this.flowParsePrimaryType(); let seenOptionalIndexedAccess = false; while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) { const node2 = this.startNodeAt(startLoc); const optional = this.eat(18); seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional; this.expect(0); if (!optional && this.match(3)) { node2.elementType = type2; this.next(); type2 = this.finishNode(node2, "ArrayTypeAnnotation"); } else { node2.objectType = type2; node2.indexType = this.flowParseType(); this.expect(3); if (seenOptionalIndexedAccess) { node2.optional = optional; type2 = this.finishNode(node2, "OptionalIndexedAccessType"); } else { type2 = this.finishNode(node2, "IndexedAccessType"); } } } return type2; } flowParsePrefixType() { const node2 = this.startNode(); if (this.eat(17)) { node2.typeAnnotation = this.flowParsePrefixType(); return this.finishNode(node2, "NullableTypeAnnotation"); } else { return this.flowParsePostfixType(); } } flowParseAnonFunctionWithoutParens() { const param = this.flowParsePrefixType(); if (!this.state.noAnonFunctionType && this.eat(19)) { const node2 = this.startNodeAt(param.loc.start); node2.params = [this.reinterpretTypeAsFunctionTypeParam(param)]; node2.rest = null; node2.this = null; node2.returnType = this.flowParseType(); node2.typeParameters = null; return this.finishNode(node2, "FunctionTypeAnnotation"); } return param; } flowParseIntersectionType() { const node2 = this.startNode(); this.eat(45); const type2 = this.flowParseAnonFunctionWithoutParens(); node2.types = [type2]; while (this.eat(45)) { node2.types.push(this.flowParseAnonFunctionWithoutParens()); } return node2.types.length === 1 ? type2 : this.finishNode(node2, "IntersectionTypeAnnotation"); } flowParseUnionType() { const node2 = this.startNode(); this.eat(43); const type2 = this.flowParseIntersectionType(); node2.types = [type2]; while (this.eat(43)) { node2.types.push(this.flowParseIntersectionType()); } return node2.types.length === 1 ? type2 : this.finishNode(node2, "UnionTypeAnnotation"); } flowParseType() { const oldInType = this.state.inType; this.state.inType = true; const type2 = this.flowParseUnionType(); this.state.inType = oldInType; return type2; } flowParseTypeOrImplicitInstantiation() { if (this.state.type === 132 && this.state.value === "_") { const startLoc = this.state.startLoc; const node2 = this.parseIdentifier(); return this.flowParseGenericType(startLoc, node2); } else { return this.flowParseType(); } } flowParseTypeAnnotation() { const node2 = this.startNode(); node2.typeAnnotation = this.flowParseTypeInitialiser(); return this.finishNode(node2, "TypeAnnotation"); } flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) { const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier(); if (this.match(14)) { ident.typeAnnotation = this.flowParseTypeAnnotation(); this.resetEndLocation(ident); } return ident; } typeCastToParameter(node2) { node2.expression.typeAnnotation = node2.typeAnnotation; this.resetEndLocation(node2.expression, node2.typeAnnotation.loc.end); return node2.expression; } flowParseVariance() { let variance = null; if (this.match(53)) { variance = this.startNode(); if (this.state.value === "+") { variance.kind = "plus"; } else { variance.kind = "minus"; } this.next(); return this.finishNode(variance, "Variance"); } return variance; } parseFunctionBody(node2, allowExpressionBody, isMethod = false) { if (allowExpressionBody) { this.forwardNoArrowParamsConversionAt(node2, () => super.parseFunctionBody(node2, true, isMethod)); return; } super.parseFunctionBody(node2, false, isMethod); } parseFunctionBodyAndFinish(node2, type2, isMethod = false) { if (this.match(14)) { const typeNode = this.startNode(); [typeNode.typeAnnotation, node2.predicate] = this.flowParseTypeAndPredicateInitialiser(); node2.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null; } return super.parseFunctionBodyAndFinish(node2, type2, isMethod); } parseStatementLike(flags) { if (this.state.strict && this.isContextual(129)) { const lookahead = this.lookahead(); if (tokenIsKeywordOrIdentifier(lookahead.type)) { const node2 = this.startNode(); this.next(); return this.flowParseInterface(node2); } } else if (this.shouldParseEnums() && this.isContextual(126)) { const node2 = this.startNode(); this.next(); return this.flowParseEnumDeclaration(node2); } const stmt = super.parseStatementLike(flags); if (this.flowPragma === void 0 && !this.isValidDirective(stmt)) { this.flowPragma = null; } return stmt; } parseExpressionStatement(node2, expr, decorators) { if (expr.type === "Identifier") { if (expr.name === "declare") { if (this.match(80) || tokenIsIdentifier(this.state.type) || this.match(68) || this.match(74) || this.match(82)) { return this.flowParseDeclare(node2); } } else if (tokenIsIdentifier(this.state.type)) { if (expr.name === "interface") { return this.flowParseInterface(node2); } else if (expr.name === "type") { return this.flowParseTypeAlias(node2); } else if (expr.name === "opaque") { return this.flowParseOpaqueType(node2, false); } } } return super.parseExpressionStatement(node2, expr, decorators); } shouldParseExportDeclaration() { const { type: type2 } = this.state; if (tokenIsFlowInterfaceOrTypeOrOpaque(type2) || this.shouldParseEnums() && type2 === 126) { return !this.state.containsEsc; } return super.shouldParseExportDeclaration(); } isExportDefaultSpecifier() { const { type: type2 } = this.state; if (tokenIsFlowInterfaceOrTypeOrOpaque(type2) || this.shouldParseEnums() && type2 === 126) { return this.state.containsEsc; } return super.isExportDefaultSpecifier(); } parseExportDefaultExpression() { if (this.shouldParseEnums() && this.isContextual(126)) { const node2 = this.startNode(); this.next(); return this.flowParseEnumDeclaration(node2); } return super.parseExportDefaultExpression(); } parseConditional(expr, startLoc, refExpressionErrors) { if (!this.match(17)) return expr; if (this.state.maybeInArrowParameters) { const nextCh = this.lookaheadCharCode(); if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) { this.setOptionalParametersError(refExpressionErrors); return expr; } } this.expect(17); const state = this.state.clone(); const originalNoArrowAt = this.state.noArrowAt; const node2 = this.startNodeAt(startLoc); let { consequent, failed } = this.tryParseConditionalConsequent(); let [valid, invalid] = this.getArrowLikeExpressions(consequent); if (failed || invalid.length > 0) { const noArrowAt = [...originalNoArrowAt]; if (invalid.length > 0) { this.state = state; this.state.noArrowAt = noArrowAt; for (let i2 = 0; i2 < invalid.length; i2++) { noArrowAt.push(invalid[i2].start); } ({ consequent, failed } = this.tryParseConditionalConsequent()); [valid, invalid] = this.getArrowLikeExpressions(consequent); } if (failed && valid.length > 1) { this.raise(FlowErrors.AmbiguousConditionalArrow, { at: state.startLoc }); } if (failed && valid.length === 1) { this.state = state; noArrowAt.push(valid[0].start); this.state.noArrowAt = noArrowAt; ({ consequent, failed } = this.tryParseConditionalConsequent()); } } this.getArrowLikeExpressions(consequent, true); this.state.noArrowAt = originalNoArrowAt; this.expect(14); node2.test = expr; node2.consequent = consequent; node2.alternate = this.forwardNoArrowParamsConversionAt(node2, () => this.parseMaybeAssign(void 0, void 0)); return this.finishNode(node2, "ConditionalExpression"); } tryParseConditionalConsequent() { this.state.noArrowParamsConversionAt.push(this.state.start); const consequent = this.parseMaybeAssignAllowIn(); const failed = !this.match(14); this.state.noArrowParamsConversionAt.pop(); return { consequent, failed }; } getArrowLikeExpressions(node2, disallowInvalid) { const stack = [node2]; const arrows = []; while (stack.length !== 0) { const node3 = stack.pop(); if (node3.type === "ArrowFunctionExpression") { if (node3.typeParameters || !node3.returnType) { this.finishArrowValidation(node3); } else { arrows.push(node3); } stack.push(node3.body); } else if (node3.type === "ConditionalExpression") { stack.push(node3.consequent); stack.push(node3.alternate); } } if (disallowInvalid) { arrows.forEach((node3) => this.finishArrowValidation(node3)); return [arrows, []]; } return partition(arrows, (node3) => node3.params.every((param) => this.isAssignable(param, true))); } finishArrowValidation(node2) { var _node$extra; this.toAssignableList(node2.params, (_node$extra = node2.extra) == null ? void 0 : _node$extra.trailingCommaLoc, false); this.scope.enter(2 | 4); super.checkParams(node2, false, true); this.scope.exit(); } forwardNoArrowParamsConversionAt(node2, parse4) { let result; if (this.state.noArrowParamsConversionAt.indexOf(node2.start) !== -1) { this.state.noArrowParamsConversionAt.push(this.state.start); result = parse4(); this.state.noArrowParamsConversionAt.pop(); } else { result = parse4(); } return result; } parseParenItem(node2, startLoc) { node2 = super.parseParenItem(node2, startLoc); if (this.eat(17)) { node2.optional = true; this.resetEndLocation(node2); } if (this.match(14)) { const typeCastNode = this.startNodeAt(startLoc); typeCastNode.expression = node2; typeCastNode.typeAnnotation = this.flowParseTypeAnnotation(); return this.finishNode(typeCastNode, "TypeCastExpression"); } return node2; } assertModuleNodeAllowed(node2) { if (node2.type === "ImportDeclaration" && (node2.importKind === "type" || node2.importKind === "typeof") || node2.type === "ExportNamedDeclaration" && node2.exportKind === "type" || node2.type === "ExportAllDeclaration" && node2.exportKind === "type") { return; } super.assertModuleNodeAllowed(node2); } parseExportDeclaration(node2) { if (this.isContextual(130)) { node2.exportKind = "type"; const declarationNode = this.startNode(); this.next(); if (this.match(5)) { node2.specifiers = this.parseExportSpecifiers(true); super.parseExportFrom(node2); return null; } else { return this.flowParseTypeAlias(declarationNode); } } else if (this.isContextual(131)) { node2.exportKind = "type"; const declarationNode = this.startNode(); this.next(); return this.flowParseOpaqueType(declarationNode, false); } else if (this.isContextual(129)) { node2.exportKind = "type"; const declarationNode = this.startNode(); this.next(); return this.flowParseInterface(declarationNode); } else if (this.shouldParseEnums() && this.isContextual(126)) { node2.exportKind = "value"; const declarationNode = this.startNode(); this.next(); return this.flowParseEnumDeclaration(declarationNode); } else { return super.parseExportDeclaration(node2); } } eatExportStar(node2) { if (super.eatExportStar(node2)) return true; if (this.isContextual(130) && this.lookahead().type === 55) { node2.exportKind = "type"; this.next(); this.next(); return true; } return false; } maybeParseExportNamespaceSpecifier(node2) { const { startLoc } = this.state; const hasNamespace = super.maybeParseExportNamespaceSpecifier(node2); if (hasNamespace && node2.exportKind === "type") { this.unexpected(startLoc); } return hasNamespace; } parseClassId(node2, isStatement, optionalId) { super.parseClassId(node2, isStatement, optionalId); if (this.match(47)) { node2.typeParameters = this.flowParseTypeParameterDeclaration(); } } parseClassMember(classBody, member, state) { const { startLoc } = this.state; if (this.isContextual(125)) { if (super.parseClassMemberFromModifier(classBody, member)) { return; } member.declare = true; } super.parseClassMember(classBody, member, state); if (member.declare) { if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") { this.raise(FlowErrors.DeclareClassElement, { at: startLoc }); } else if (member.value) { this.raise(FlowErrors.DeclareClassFieldInitializer, { at: member.value }); } } } isIterator(word) { return word === "iterator" || word === "asyncIterator"; } readIterator() { const word = super.readWord1(); const fullWord = "@@" + word; if (!this.isIterator(word) || !this.state.inType) { this.raise(Errors.InvalidIdentifier, { at: this.state.curPosition(), identifierName: fullWord }); } this.finishToken(132, fullWord); } getTokenFromCode(code2) { const next = this.input.charCodeAt(this.state.pos + 1); if (code2 === 123 && next === 124) { this.finishOp(6, 2); } else if (this.state.inType && (code2 === 62 || code2 === 60)) { this.finishOp(code2 === 62 ? 48 : 47, 1); } else if (this.state.inType && code2 === 63) { if (next === 46) { this.finishOp(18, 2); } else { this.finishOp(17, 1); } } else if (isIteratorStart(code2, next, this.input.charCodeAt(this.state.pos + 2))) { this.state.pos += 2; this.readIterator(); } else { super.getTokenFromCode(code2); } } isAssignable(node2, isBinding) { if (node2.type === "TypeCastExpression") { return this.isAssignable(node2.expression, isBinding); } else { return super.isAssignable(node2, isBinding); } } toAssignable(node2, isLHS = false) { if (!isLHS && node2.type === "AssignmentExpression" && node2.left.type === "TypeCastExpression") { node2.left = this.typeCastToParameter(node2.left); } super.toAssignable(node2, isLHS); } toAssignableList(exprList, trailingCommaLoc, isLHS) { for (let i2 = 0; i2 < exprList.length; i2++) { const expr = exprList[i2]; if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") { exprList[i2] = this.typeCastToParameter(expr); } } super.toAssignableList(exprList, trailingCommaLoc, isLHS); } toReferencedList(exprList, isParenthesizedExpr) { for (let i2 = 0; i2 < exprList.length; i2++) { var _expr$extra; const expr = exprList[i2]; if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) { this.raise(FlowErrors.TypeCastInPattern, { at: expr.typeAnnotation }); } } return exprList; } parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) { const node2 = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors); if (canBePattern && !this.state.maybeInArrowParameters) { this.toReferencedList(node2.elements); } return node2; } isValidLVal(type2, isParenthesized, binding) { return type2 === "TypeCastExpression" || super.isValidLVal(type2, isParenthesized, binding); } parseClassProperty(node2) { if (this.match(14)) { node2.typeAnnotation = this.flowParseTypeAnnotation(); } return super.parseClassProperty(node2); } parseClassPrivateProperty(node2) { if (this.match(14)) { node2.typeAnnotation = this.flowParseTypeAnnotation(); } return super.parseClassPrivateProperty(node2); } isClassMethod() { return this.match(47) || super.isClassMethod(); } isClassProperty() { return this.match(14) || super.isClassProperty(); } isNonstaticConstructor(method) { return !this.match(14) && super.isNonstaticConstructor(method); } pushClassMethod(classBody, method, isGenerator, isAsync2, isConstructor, allowsDirectSuper) { if (method.variance) { this.unexpected(method.variance.loc.start); } delete method.variance; if (this.match(47)) { method.typeParameters = this.flowParseTypeParameterDeclaration(); } super.pushClassMethod(classBody, method, isGenerator, isAsync2, isConstructor, allowsDirectSuper); if (method.params && isConstructor) { const params = method.params; if (params.length > 0 && this.isThisParam(params[0])) { this.raise(FlowErrors.ThisParamBannedInConstructor, { at: method }); } } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) { const params = method.value.params; if (params.length > 0 && this.isThisParam(params[0])) { this.raise(FlowErrors.ThisParamBannedInConstructor, { at: method }); } } } pushClassPrivateMethod(classBody, method, isGenerator, isAsync2) { if (method.variance) { this.unexpected(method.variance.loc.start); } delete method.variance; if (this.match(47)) { method.typeParameters = this.flowParseTypeParameterDeclaration(); } super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync2); } parseClassSuper(node2) { super.parseClassSuper(node2); if (node2.superClass && this.match(47)) { node2.superTypeParameters = this.flowParseTypeParameterInstantiation(); } if (this.isContextual(113)) { this.next(); const implemented = node2.implements = []; do { const node3 = this.startNode(); node3.id = this.flowParseRestrictedIdentifier(true); if (this.match(47)) { node3.typeParameters = this.flowParseTypeParameterInstantiation(); } else { node3.typeParameters = null; } implemented.push(this.finishNode(node3, "ClassImplements")); } while (this.eat(12)); } } checkGetterSetterParams(method) { super.checkGetterSetterParams(method); const params = this.getObjectOrClassMethodParams(method); if (params.length > 0) { const param = params[0]; if (this.isThisParam(param) && method.kind === "get") { this.raise(FlowErrors.GetterMayNotHaveThisParam, { at: param }); } else if (this.isThisParam(param)) { this.raise(FlowErrors.SetterMayNotHaveThisParam, { at: param }); } } } parsePropertyNamePrefixOperator(node2) { node2.variance = this.flowParseVariance(); } parseObjPropValue(prop, startLoc, isGenerator, isAsync2, isPattern, isAccessor, refExpressionErrors) { if (prop.variance) { this.unexpected(prop.variance.loc.start); } delete prop.variance; let typeParameters; if (this.match(47) && !isAccessor) { typeParameters = this.flowParseTypeParameterDeclaration(); if (!this.match(10)) this.unexpected(); } const result = super.parseObjPropValue(prop, startLoc, isGenerator, isAsync2, isPattern, isAccessor, refExpressionErrors); if (typeParameters) { (result.value || result).typeParameters = typeParameters; } return result; } parseAssignableListItemTypes(param) { if (this.eat(17)) { if (param.type !== "Identifier") { this.raise(FlowErrors.PatternIsOptional, { at: param }); } if (this.isThisParam(param)) { this.raise(FlowErrors.ThisParamMayNotBeOptional, { at: param }); } param.optional = true; } if (this.match(14)) { param.typeAnnotation = this.flowParseTypeAnnotation(); } else if (this.isThisParam(param)) { this.raise(FlowErrors.ThisParamAnnotationRequired, { at: param }); } if (this.match(29) && this.isThisParam(param)) { this.raise(FlowErrors.ThisParamNoDefault, { at: param }); } this.resetEndLocation(param); return param; } parseMaybeDefault(startLoc, left) { const node2 = super.parseMaybeDefault(startLoc, left); if (node2.type === "AssignmentPattern" && node2.typeAnnotation && node2.right.start < node2.typeAnnotation.start) { this.raise(FlowErrors.TypeBeforeInitializer, { at: node2.typeAnnotation }); } return node2; } checkImportReflection(node2) { super.checkImportReflection(node2); if (node2.module && node2.importKind !== "value") { this.raise(FlowErrors.ImportReflectionHasImportType, { at: node2.specifiers[0].loc.start }); } } parseImportSpecifierLocal(node2, specifier, type2) { specifier.local = hasTypeImportKind(node2) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier(); node2.specifiers.push(this.finishImportSpecifier(specifier, type2)); } isPotentialImportPhase(isExport) { if (super.isPotentialImportPhase(isExport)) return true; if (this.isContextual(130)) { if (!isExport) return true; const ch = this.lookaheadCharCode(); return ch === 123 || ch === 42; } return !isExport && this.isContextual(87); } applyImportPhase(node2, isExport, phase, loc) { super.applyImportPhase(node2, isExport, phase, loc); if (isExport) { if (!phase && this.match(65)) { return; } node2.exportKind = phase === "type" ? phase : "value"; } else { if (phase === "type" && this.match(55)) this.unexpected(); node2.importKind = phase === "type" || phase === "typeof" ? phase : "value"; } } parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { const firstIdent = specifier.imported; let specifierTypeKind = null; if (firstIdent.type === "Identifier") { if (firstIdent.name === "type") { specifierTypeKind = "type"; } else if (firstIdent.name === "typeof") { specifierTypeKind = "typeof"; } } let isBinding = false; if (this.isContextual(93) && !this.isLookaheadContextual("as")) { const as_ident = this.parseIdentifier(true); if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) { specifier.imported = as_ident; specifier.importKind = specifierTypeKind; specifier.local = cloneIdentifier(as_ident); } else { specifier.imported = firstIdent; specifier.importKind = null; specifier.local = this.parseIdentifier(); } } else { if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) { specifier.imported = this.parseIdentifier(true); specifier.importKind = specifierTypeKind; } else { if (importedIsString) { throw this.raise(Errors.ImportBindingIsString, { at: specifier, importName: firstIdent.value }); } specifier.imported = firstIdent; specifier.importKind = null; } if (this.eatContextual(93)) { specifier.local = this.parseIdentifier(); } else { isBinding = true; specifier.local = cloneIdentifier(specifier.imported); } } const specifierIsTypeImport = hasTypeImportKind(specifier); if (isInTypeOnlyImport && specifierIsTypeImport) { this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, { at: specifier }); } if (isInTypeOnlyImport || specifierIsTypeImport) { this.checkReservedType(specifier.local.name, specifier.local.loc.start, true); } if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) { this.checkReservedWord(specifier.local.name, specifier.loc.start, true, true); } return this.finishImportSpecifier(specifier, "ImportSpecifier"); } parseBindingAtom() { switch (this.state.type) { case 78: return this.parseIdentifier(true); default: return super.parseBindingAtom(); } } parseFunctionParams(node2, isConstructor) { const kind = node2.kind; if (kind !== "get" && kind !== "set" && this.match(47)) { node2.typeParameters = this.flowParseTypeParameterDeclaration(); } super.parseFunctionParams(node2, isConstructor); } parseVarId(decl, kind) { super.parseVarId(decl, kind); if (this.match(14)) { decl.id.typeAnnotation = this.flowParseTypeAnnotation(); this.resetEndLocation(decl.id); } } parseAsyncArrowFromCallExpression(node2, call) { if (this.match(14)) { const oldNoAnonFunctionType = this.state.noAnonFunctionType; this.state.noAnonFunctionType = true; node2.returnType = this.flowParseTypeAnnotation(); this.state.noAnonFunctionType = oldNoAnonFunctionType; } return super.parseAsyncArrowFromCallExpression(node2, call); } shouldParseAsyncArrow() { return this.match(14) || super.shouldParseAsyncArrow(); } parseMaybeAssign(refExpressionErrors, afterLeftParse) { var _jsx; let state = null; let jsx2; if (this.hasPlugin("jsx") && (this.match(142) || this.match(47))) { state = this.state.clone(); jsx2 = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); if (!jsx2.error) return jsx2.node; const { context } = this.state; const currentContext = context[context.length - 1]; if (currentContext === types.j_oTag || currentContext === types.j_expr) { context.pop(); } } if ((_jsx = jsx2) != null && _jsx.error || this.match(47)) { var _jsx2, _jsx3; state = state || this.state.clone(); let typeParameters; const arrow = this.tryParse((abort) => { var _arrowExpression$extr; typeParameters = this.flowParseTypeParameterDeclaration(); const arrowExpression2 = this.forwardNoArrowParamsConversionAt(typeParameters, () => { const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse); this.resetStartLocationFromNode(result, typeParameters); return result; }); if ((_arrowExpression$extr = arrowExpression2.extra) != null && _arrowExpression$extr.parenthesized) abort(); const expr = this.maybeUnwrapTypeCastExpression(arrowExpression2); if (expr.type !== "ArrowFunctionExpression") abort(); expr.typeParameters = typeParameters; this.resetStartLocationFromNode(expr, typeParameters); return arrowExpression2; }, state); let arrowExpression = null; if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") { if (!arrow.error && !arrow.aborted) { if (arrow.node.async) { this.raise(FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction, { at: typeParameters }); } return arrow.node; } arrowExpression = arrow.node; } if ((_jsx2 = jsx2) != null && _jsx2.node) { this.state = jsx2.failState; return jsx2.node; } if (arrowExpression) { this.state = arrow.failState; return arrowExpression; } if ((_jsx3 = jsx2) != null && _jsx3.thrown) throw jsx2.error; if (arrow.thrown) throw arrow.error; throw this.raise(FlowErrors.UnexpectedTokenAfterTypeParameter, { at: typeParameters }); } return super.parseMaybeAssign(refExpressionErrors, afterLeftParse); } parseArrow(node2) { if (this.match(14)) { const result = this.tryParse(() => { const oldNoAnonFunctionType = this.state.noAnonFunctionType; this.state.noAnonFunctionType = true; const typeNode = this.startNode(); [typeNode.typeAnnotation, node2.predicate] = this.flowParseTypeAndPredicateInitialiser(); this.state.noAnonFunctionType = oldNoAnonFunctionType; if (this.canInsertSemicolon()) this.unexpected(); if (!this.match(19)) this.unexpected(); return typeNode; }); if (result.thrown) return null; if (result.error) this.state = result.failState; node2.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null; } return super.parseArrow(node2); } shouldParseArrow(params) { return this.match(14) || super.shouldParseArrow(params); } setArrowFunctionParameters(node2, params) { if (this.state.noArrowParamsConversionAt.indexOf(node2.start) !== -1) { node2.params = params; } else { super.setArrowFunctionParameters(node2, params); } } checkParams(node2, allowDuplicates, isArrowFunction, strictModeChanged = true) { if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node2.start) !== -1) { return; } for (let i2 = 0; i2 < node2.params.length; i2++) { if (this.isThisParam(node2.params[i2]) && i2 > 0) { this.raise(FlowErrors.ThisParamMustBeFirst, { at: node2.params[i2] }); } } super.checkParams(node2, allowDuplicates, isArrowFunction, strictModeChanged); } parseParenAndDistinguishExpression(canBeArrow) { return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1); } parseSubscripts(base, startLoc, noCalls) { if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startLoc.index) !== -1) { this.next(); const node2 = this.startNodeAt(startLoc); node2.callee = base; node2.arguments = super.parseCallExpressionArguments(11, false); base = this.finishNode(node2, "CallExpression"); } else if (base.type === "Identifier" && base.name === "async" && this.match(47)) { const state = this.state.clone(); const arrow = this.tryParse((abort) => this.parseAsyncArrowWithTypeParameters(startLoc) || abort(), state); if (!arrow.error && !arrow.aborted) return arrow.node; const result = this.tryParse(() => super.parseSubscripts(base, startLoc, noCalls), state); if (result.node && !result.error) return result.node; if (arrow.node) { this.state = arrow.failState; return arrow.node; } if (result.node) { this.state = result.failState; return result.node; } throw arrow.error || result.error; } return super.parseSubscripts(base, startLoc, noCalls); } parseSubscript(base, startLoc, noCalls, subscriptState) { if (this.match(18) && this.isLookaheadToken_lt()) { subscriptState.optionalChainMember = true; if (noCalls) { subscriptState.stop = true; return base; } this.next(); const node2 = this.startNodeAt(startLoc); node2.callee = base; node2.typeArguments = this.flowParseTypeParameterInstantiation(); this.expect(10); node2.arguments = this.parseCallExpressionArguments(11, false); node2.optional = true; return this.finishCallExpression(node2, true); } else if (!noCalls && this.shouldParseTypes() && this.match(47)) { const node2 = this.startNodeAt(startLoc); node2.callee = base; const result = this.tryParse(() => { node2.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew(); this.expect(10); node2.arguments = super.parseCallExpressionArguments(11, false); if (subscriptState.optionalChainMember) { node2.optional = false; } return this.finishCallExpression(node2, subscriptState.optionalChainMember); }); if (result.node) { if (result.error) this.state = result.failState; return result.node; } } return super.parseSubscript(base, startLoc, noCalls, subscriptState); } parseNewCallee(node2) { super.parseNewCallee(node2); let targs = null; if (this.shouldParseTypes() && this.match(47)) { targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node; } node2.typeArguments = targs; } parseAsyncArrowWithTypeParameters(startLoc) { const node2 = this.startNodeAt(startLoc); this.parseFunctionParams(node2, false); if (!this.parseArrow(node2)) return; return super.parseArrowExpression(node2, void 0, true); } readToken_mult_modulo(code2) { const next = this.input.charCodeAt(this.state.pos + 1); if (code2 === 42 && next === 47 && this.state.hasFlowComment) { this.state.hasFlowComment = false; this.state.pos += 2; this.nextToken(); return; } super.readToken_mult_modulo(code2); } readToken_pipe_amp(code2) { const next = this.input.charCodeAt(this.state.pos + 1); if (code2 === 124 && next === 125) { this.finishOp(9, 2); return; } super.readToken_pipe_amp(code2); } parseTopLevel(file, program) { const fileNode = super.parseTopLevel(file, program); if (this.state.hasFlowComment) { this.raise(FlowErrors.UnterminatedFlowComment, { at: this.state.curPosition() }); } return fileNode; } skipBlockComment() { if (this.hasPlugin("flowComments") && this.skipFlowComment()) { if (this.state.hasFlowComment) { throw this.raise(FlowErrors.NestedFlowComment, { at: this.state.startLoc }); } this.hasFlowCommentCompletion(); const commentSkip = this.skipFlowComment(); if (commentSkip) { this.state.pos += commentSkip; this.state.hasFlowComment = true; } return; } return super.skipBlockComment(this.state.hasFlowComment ? "*-/" : "*/"); } skipFlowComment() { const { pos } = this.state; let shiftToFirstNonWhiteSpace = 2; while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) { shiftToFirstNonWhiteSpace++; } const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos); const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1); if (ch2 === 58 && ch3 === 58) { return shiftToFirstNonWhiteSpace + 2; } if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") { return shiftToFirstNonWhiteSpace + 12; } if (ch2 === 58 && ch3 !== 58) { return shiftToFirstNonWhiteSpace; } return false; } hasFlowCommentCompletion() { const end = this.input.indexOf("*/", this.state.pos); if (end === -1) { throw this.raise(Errors.UnterminatedComment, { at: this.state.curPosition() }); } } flowEnumErrorBooleanMemberNotInitialized(loc, { enumName, memberName }) { this.raise(FlowErrors.EnumBooleanMemberNotInitialized, { at: loc, memberName, enumName }); } flowEnumErrorInvalidMemberInitializer(loc, enumContext) { return this.raise(!enumContext.explicitType ? FlowErrors.EnumInvalidMemberInitializerUnknownType : enumContext.explicitType === "symbol" ? FlowErrors.EnumInvalidMemberInitializerSymbolType : FlowErrors.EnumInvalidMemberInitializerPrimaryType, Object.assign({ at: loc }, enumContext)); } flowEnumErrorNumberMemberNotInitialized(loc, { enumName, memberName }) { this.raise(FlowErrors.EnumNumberMemberNotInitialized, { at: loc, enumName, memberName }); } flowEnumErrorStringMemberInconsistentlyInitialized(node2, { enumName }) { this.raise(FlowErrors.EnumStringMemberInconsistentlyInitialized, { at: node2, enumName }); } flowEnumMemberInit() { const startLoc = this.state.startLoc; const endOfInit = () => this.match(12) || this.match(8); switch (this.state.type) { case 134: { const literal = this.parseNumericLiteral(this.state.value); if (endOfInit()) { return { type: "number", loc: literal.loc.start, value: literal }; } return { type: "invalid", loc: startLoc }; } case 133: { const literal = this.parseStringLiteral(this.state.value); if (endOfInit()) { return { type: "string", loc: literal.loc.start, value: literal }; } return { type: "invalid", loc: startLoc }; } case 85: case 86: { const literal = this.parseBooleanLiteral(this.match(85)); if (endOfInit()) { return { type: "boolean", loc: literal.loc.start, value: literal }; } return { type: "invalid", loc: startLoc }; } default: return { type: "invalid", loc: startLoc }; } } flowEnumMemberRaw() { const loc = this.state.startLoc; const id = this.parseIdentifier(true); const init = this.eat(29) ? this.flowEnumMemberInit() : { type: "none", loc }; return { id, init }; } flowEnumCheckExplicitTypeMismatch(loc, context, expectedType) { const { explicitType } = context; if (explicitType === null) { return; } if (explicitType !== expectedType) { this.flowEnumErrorInvalidMemberInitializer(loc, context); } } flowEnumMembers({ enumName, explicitType }) { const seenNames = /* @__PURE__ */ new Set(); const members = { booleanMembers: [], numberMembers: [], stringMembers: [], defaultedMembers: [] }; let hasUnknownMembers = false; while (!this.match(8)) { if (this.eat(21)) { hasUnknownMembers = true; break; } const memberNode = this.startNode(); const { id, init } = this.flowEnumMemberRaw(); const memberName = id.name; if (memberName === "") { continue; } if (/^[a-z]/.test(memberName)) { this.raise(FlowErrors.EnumInvalidMemberName, { at: id, memberName, suggestion: memberName[0].toUpperCase() + memberName.slice(1), enumName }); } if (seenNames.has(memberName)) { this.raise(FlowErrors.EnumDuplicateMemberName, { at: id, memberName, enumName }); } seenNames.add(memberName); const context = { enumName, explicitType, memberName }; memberNode.id = id; switch (init.type) { case "boolean": { this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "boolean"); memberNode.init = init.value; members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember")); break; } case "number": { this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "number"); memberNode.init = init.value; members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember")); break; } case "string": { this.flowEnumCheckExplicitTypeMismatch(init.loc, context, "string"); memberNode.init = init.value; members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember")); break; } case "invalid": { throw this.flowEnumErrorInvalidMemberInitializer(init.loc, context); } case "none": { switch (explicitType) { case "boolean": this.flowEnumErrorBooleanMemberNotInitialized(init.loc, context); break; case "number": this.flowEnumErrorNumberMemberNotInitialized(init.loc, context); break; default: members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember")); } } } if (!this.match(8)) { this.expect(12); } } return { members, hasUnknownMembers }; } flowEnumStringMembers(initializedMembers, defaultedMembers, { enumName }) { if (initializedMembers.length === 0) { return defaultedMembers; } else if (defaultedMembers.length === 0) { return initializedMembers; } else if (defaultedMembers.length > initializedMembers.length) { for (const member of initializedMembers) { this.flowEnumErrorStringMemberInconsistentlyInitialized(member, { enumName }); } return defaultedMembers; } else { for (const member of defaultedMembers) { this.flowEnumErrorStringMemberInconsistentlyInitialized(member, { enumName }); } return initializedMembers; } } flowEnumParseExplicitType({ enumName }) { if (!this.eatContextual(102)) return null; if (!tokenIsIdentifier(this.state.type)) { throw this.raise(FlowErrors.EnumInvalidExplicitTypeUnknownSupplied, { at: this.state.startLoc, enumName }); } const { value } = this.state; this.next(); if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") { this.raise(FlowErrors.EnumInvalidExplicitType, { at: this.state.startLoc, enumName, invalidEnumType: value }); } return value; } flowEnumBody(node2, id) { const enumName = id.name; const nameLoc = id.loc.start; const explicitType = this.flowEnumParseExplicitType({ enumName }); this.expect(5); const { members, hasUnknownMembers } = this.flowEnumMembers({ enumName, explicitType }); node2.hasUnknownMembers = hasUnknownMembers; switch (explicitType) { case "boolean": node2.explicitType = true; node2.members = members.booleanMembers; this.expect(8); return this.finishNode(node2, "EnumBooleanBody"); case "number": node2.explicitType = true; node2.members = members.numberMembers; this.expect(8); return this.finishNode(node2, "EnumNumberBody"); case "string": node2.explicitType = true; node2.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, { enumName }); this.expect(8); return this.finishNode(node2, "EnumStringBody"); case "symbol": node2.members = members.defaultedMembers; this.expect(8); return this.finishNode(node2, "EnumSymbolBody"); default: { const empty = () => { node2.members = []; this.expect(8); return this.finishNode(node2, "EnumStringBody"); }; node2.explicitType = false; const boolsLen = members.booleanMembers.length; const numsLen = members.numberMembers.length; const strsLen = members.stringMembers.length; const defaultedLen = members.defaultedMembers.length; if (!boolsLen && !numsLen && !strsLen && !defaultedLen) { return empty(); } else if (!boolsLen && !numsLen) { node2.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, { enumName }); this.expect(8); return this.finishNode(node2, "EnumStringBody"); } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) { for (const member of members.defaultedMembers) { this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, { enumName, memberName: member.id.name }); } node2.members = members.booleanMembers; this.expect(8); return this.finishNode(node2, "EnumBooleanBody"); } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) { for (const member of members.defaultedMembers) { this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, { enumName, memberName: member.id.name }); } node2.members = members.numberMembers; this.expect(8); return this.finishNode(node2, "EnumNumberBody"); } else { this.raise(FlowErrors.EnumInconsistentMemberValues, { at: nameLoc, enumName }); return empty(); } } } } flowParseEnumDeclaration(node2) { const id = this.parseIdentifier(); node2.id = id; node2.body = this.flowEnumBody(this.startNode(), id); return this.finishNode(node2, "EnumDeclaration"); } isLookaheadToken_lt() { const next = this.nextTokenStart(); if (this.input.charCodeAt(next) === 60) { const afterNext = this.input.charCodeAt(next + 1); return afterNext !== 60 && afterNext !== 61; } return false; } maybeUnwrapTypeCastExpression(node2) { return node2.type === "TypeCastExpression" ? node2.expression : node2; } }; var entities = { __proto__: null, quot: '"', amp: "&", apos: "'", lt: "<", gt: ">", nbsp: "\xA0", iexcl: "\xA1", cent: "\xA2", pound: "\xA3", curren: "\xA4", yen: "\xA5", brvbar: "\xA6", sect: "\xA7", uml: "\xA8", copy: "\xA9", ordf: "\xAA", laquo: "\xAB", not: "\xAC", shy: "\xAD", reg: "\xAE", macr: "\xAF", deg: "\xB0", plusmn: "\xB1", sup2: "\xB2", sup3: "\xB3", acute: "\xB4", micro: "\xB5", para: "\xB6", middot: "\xB7", cedil: "\xB8", sup1: "\xB9", ordm: "\xBA", raquo: "\xBB", frac14: "\xBC", frac12: "\xBD", frac34: "\xBE", iquest: "\xBF", Agrave: "\xC0", Aacute: "\xC1", Acirc: "\xC2", Atilde: "\xC3", Auml: "\xC4", Aring: "\xC5", AElig: "\xC6", Ccedil: "\xC7", Egrave: "\xC8", Eacute: "\xC9", Ecirc: "\xCA", Euml: "\xCB", Igrave: "\xCC", Iacute: "\xCD", Icirc: "\xCE", Iuml: "\xCF", ETH: "\xD0", Ntilde: "\xD1", Ograve: "\xD2", Oacute: "\xD3", Ocirc: "\xD4", Otilde: "\xD5", Ouml: "\xD6", times: "\xD7", Oslash: "\xD8", Ugrave: "\xD9", Uacute: "\xDA", Ucirc: "\xDB", Uuml: "\xDC", Yacute: "\xDD", THORN: "\xDE", szlig: "\xDF", agrave: "\xE0", aacute: "\xE1", acirc: "\xE2", atilde: "\xE3", auml: "\xE4", aring: "\xE5", aelig: "\xE6", ccedil: "\xE7", egrave: "\xE8", eacute: "\xE9", ecirc: "\xEA", euml: "\xEB", igrave: "\xEC", iacute: "\xED", icirc: "\xEE", iuml: "\xEF", eth: "\xF0", ntilde: "\xF1", ograve: "\xF2", oacute: "\xF3", ocirc: "\xF4", otilde: "\xF5", ouml: "\xF6", divide: "\xF7", oslash: "\xF8", ugrave: "\xF9", uacute: "\xFA", ucirc: "\xFB", uuml: "\xFC", yacute: "\xFD", thorn: "\xFE", yuml: "\xFF", OElig: "\u0152", oelig: "\u0153", Scaron: "\u0160", scaron: "\u0161", Yuml: "\u0178", fnof: "\u0192", circ: "\u02C6", tilde: "\u02DC", Alpha: "\u0391", Beta: "\u0392", Gamma: "\u0393", Delta: "\u0394", Epsilon: "\u0395", Zeta: "\u0396", Eta: "\u0397", Theta: "\u0398", Iota: "\u0399", Kappa: "\u039A", Lambda: "\u039B", Mu: "\u039C", Nu: "\u039D", Xi: "\u039E", Omicron: "\u039F", Pi: "\u03A0", Rho: "\u03A1", Sigma: "\u03A3", Tau: "\u03A4", Upsilon: "\u03A5", Phi: "\u03A6", Chi: "\u03A7", Psi: "\u03A8", Omega: "\u03A9", alpha: "\u03B1", beta: "\u03B2", gamma: "\u03B3", delta: "\u03B4", epsilon: "\u03B5", zeta: "\u03B6", eta: "\u03B7", theta: "\u03B8", iota: "\u03B9", kappa: "\u03BA", lambda: "\u03BB", mu: "\u03BC", nu: "\u03BD", xi: "\u03BE", omicron: "\u03BF", pi: "\u03C0", rho: "\u03C1", sigmaf: "\u03C2", sigma: "\u03C3", tau: "\u03C4", upsilon: "\u03C5", phi: "\u03C6", chi: "\u03C7", psi: "\u03C8", omega: "\u03C9", thetasym: "\u03D1", upsih: "\u03D2", piv: "\u03D6", ensp: "\u2002", emsp: "\u2003", thinsp: "\u2009", zwnj: "\u200C", zwj: "\u200D", lrm: "\u200E", rlm: "\u200F", ndash: "\u2013", mdash: "\u2014", lsquo: "\u2018", rsquo: "\u2019", sbquo: "\u201A", ldquo: "\u201C", rdquo: "\u201D", bdquo: "\u201E", dagger: "\u2020", Dagger: "\u2021", bull: "\u2022", hellip: "\u2026", permil: "\u2030", prime: "\u2032", Prime: "\u2033", lsaquo: "\u2039", rsaquo: "\u203A", oline: "\u203E", frasl: "\u2044", euro: "\u20AC", image: "\u2111", weierp: "\u2118", real: "\u211C", trade: "\u2122", alefsym: "\u2135", larr: "\u2190", uarr: "\u2191", rarr: "\u2192", darr: "\u2193", harr: "\u2194", crarr: "\u21B5", lArr: "\u21D0", uArr: "\u21D1", rArr: "\u21D2", dArr: "\u21D3", hArr: "\u21D4", forall: "\u2200", part: "\u2202", exist: "\u2203", empty: "\u2205", nabla: "\u2207", isin: "\u2208", notin: "\u2209", ni: "\u220B", prod: "\u220F", sum: "\u2211", minus: "\u2212", lowast: "\u2217", radic: "\u221A", prop: "\u221D", infin: "\u221E", ang: "\u2220", and: "\u2227", or: "\u2228", cap: "\u2229", cup: "\u222A", int: "\u222B", there4: "\u2234", sim: "\u223C", cong: "\u2245", asymp: "\u2248", ne: "\u2260", equiv: "\u2261", le: "\u2264", ge: "\u2265", sub: "\u2282", sup: "\u2283", nsub: "\u2284", sube: "\u2286", supe: "\u2287", oplus: "\u2295", otimes: "\u2297", perp: "\u22A5", sdot: "\u22C5", lceil: "\u2308", rceil: "\u2309", lfloor: "\u230A", rfloor: "\u230B", lang: "\u2329", rang: "\u232A", loz: "\u25CA", spades: "\u2660", clubs: "\u2663", hearts: "\u2665", diams: "\u2666" }; var JsxErrors = ParseErrorEnum`jsx`({ AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.", MissingClosingTagElement: ({ openingTagName }) => `Expected corresponding JSX closing tag for <${openingTagName}>.`, MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.", UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?", UnexpectedToken: ({ unexpected, HTMLEntity }) => `Unexpected token \`${unexpected}\`. Did you mean \`${HTMLEntity}\` or \`{'${unexpected}'}\`?`, UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.", UnterminatedJsxContent: "Unterminated JSX contents.", UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...?" }); function isFragment(object) { return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false; } function getQualifiedJSXName(object) { if (object.type === "JSXIdentifier") { return object.name; } if (object.type === "JSXNamespacedName") { return object.namespace.name + ":" + object.name.name; } if (object.type === "JSXMemberExpression") { return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property); } throw new Error("Node had unexpected type: " + object.type); } var jsx = (superClass) => class JSXParserMixin extends superClass { jsxReadToken() { let out = ""; let chunkStart = this.state.pos; for (; ; ) { if (this.state.pos >= this.length) { throw this.raise(JsxErrors.UnterminatedJsxContent, { at: this.state.startLoc }); } const ch = this.input.charCodeAt(this.state.pos); switch (ch) { case 60: case 123: if (this.state.pos === this.state.start) { if (ch === 60 && this.state.canStartJSXElement) { ++this.state.pos; this.finishToken(142); } else { super.getTokenFromCode(ch); } return; } out += this.input.slice(chunkStart, this.state.pos); this.finishToken(141, out); return; case 38: out += this.input.slice(chunkStart, this.state.pos); out += this.jsxReadEntity(); chunkStart = this.state.pos; break; case 62: case 125: default: if (isNewLine(ch)) { out += this.input.slice(chunkStart, this.state.pos); out += this.jsxReadNewLine(true); chunkStart = this.state.pos; } else { ++this.state.pos; } } } } jsxReadNewLine(normalizeCRLF) { const ch = this.input.charCodeAt(this.state.pos); let out; ++this.state.pos; if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) { ++this.state.pos; out = normalizeCRLF ? "\n" : "\r\n"; } else { out = String.fromCharCode(ch); } ++this.state.curLine; this.state.lineStart = this.state.pos; return out; } jsxReadString(quote) { let out = ""; let chunkStart = ++this.state.pos; for (; ; ) { if (this.state.pos >= this.length) { throw this.raise(Errors.UnterminatedString, { at: this.state.startLoc }); } const ch = this.input.charCodeAt(this.state.pos); if (ch === quote) break; if (ch === 38) { out += this.input.slice(chunkStart, this.state.pos); out += this.jsxReadEntity(); chunkStart = this.state.pos; } else if (isNewLine(ch)) { out += this.input.slice(chunkStart, this.state.pos); out += this.jsxReadNewLine(false); chunkStart = this.state.pos; } else { ++this.state.pos; } } out += this.input.slice(chunkStart, this.state.pos++); this.finishToken(133, out); } jsxReadEntity() { const startPos = ++this.state.pos; if (this.codePointAtPos(this.state.pos) === 35) { ++this.state.pos; let radix = 10; if (this.codePointAtPos(this.state.pos) === 120) { radix = 16; ++this.state.pos; } const codePoint = this.readInt(radix, void 0, false, "bail"); if (codePoint !== null && this.codePointAtPos(this.state.pos) === 59) { ++this.state.pos; return String.fromCodePoint(codePoint); } } else { let count = 0; let semi = false; while (count++ < 10 && this.state.pos < this.length && !(semi = this.codePointAtPos(this.state.pos) == 59)) { ++this.state.pos; } if (semi) { const desc = this.input.slice(startPos, this.state.pos); const entity = entities[desc]; ++this.state.pos; if (entity) { return entity; } } } this.state.pos = startPos; return "&"; } jsxReadWord() { let ch; const start = this.state.pos; do { ch = this.input.charCodeAt(++this.state.pos); } while (isIdentifierChar(ch) || ch === 45); this.finishToken(140, this.input.slice(start, this.state.pos)); } jsxParseIdentifier() { const node2 = this.startNode(); if (this.match(140)) { node2.name = this.state.value; } else if (tokenIsKeyword(this.state.type)) { node2.name = tokenLabelName(this.state.type); } else { this.unexpected(); } this.next(); return this.finishNode(node2, "JSXIdentifier"); } jsxParseNamespacedName() { const startLoc = this.state.startLoc; const name = this.jsxParseIdentifier(); if (!this.eat(14)) return name; const node2 = this.startNodeAt(startLoc); node2.namespace = name; node2.name = this.jsxParseIdentifier(); return this.finishNode(node2, "JSXNamespacedName"); } jsxParseElementName() { const startLoc = this.state.startLoc; let node2 = this.jsxParseNamespacedName(); if (node2.type === "JSXNamespacedName") { return node2; } while (this.eat(16)) { const newNode = this.startNodeAt(startLoc); newNode.object = node2; newNode.property = this.jsxParseIdentifier(); node2 = this.finishNode(newNode, "JSXMemberExpression"); } return node2; } jsxParseAttributeValue() { let node2; switch (this.state.type) { case 5: node2 = this.startNode(); this.setContext(types.brace); this.next(); node2 = this.jsxParseExpressionContainer(node2, types.j_oTag); if (node2.expression.type === "JSXEmptyExpression") { this.raise(JsxErrors.AttributeIsEmpty, { at: node2 }); } return node2; case 142: case 133: return this.parseExprAtom(); default: throw this.raise(JsxErrors.UnsupportedJsxValue, { at: this.state.startLoc }); } } jsxParseEmptyExpression() { const node2 = this.startNodeAt(this.state.lastTokEndLoc); return this.finishNodeAt(node2, "JSXEmptyExpression", this.state.startLoc); } jsxParseSpreadChild(node2) { this.next(); node2.expression = this.parseExpression(); this.setContext(types.j_expr); this.state.canStartJSXElement = true; this.expect(8); return this.finishNode(node2, "JSXSpreadChild"); } jsxParseExpressionContainer(node2, previousContext) { if (this.match(8)) { node2.expression = this.jsxParseEmptyExpression(); } else { const expression = this.parseExpression(); node2.expression = expression; } this.setContext(previousContext); this.state.canStartJSXElement = true; this.expect(8); return this.finishNode(node2, "JSXExpressionContainer"); } jsxParseAttribute() { const node2 = this.startNode(); if (this.match(5)) { this.setContext(types.brace); this.next(); this.expect(21); node2.argument = this.parseMaybeAssignAllowIn(); this.setContext(types.j_oTag); this.state.canStartJSXElement = true; this.expect(8); return this.finishNode(node2, "JSXSpreadAttribute"); } node2.name = this.jsxParseNamespacedName(); node2.value = this.eat(29) ? this.jsxParseAttributeValue() : null; return this.finishNode(node2, "JSXAttribute"); } jsxParseOpeningElementAt(startLoc) { const node2 = this.startNodeAt(startLoc); if (this.eat(143)) { return this.finishNode(node2, "JSXOpeningFragment"); } node2.name = this.jsxParseElementName(); return this.jsxParseOpeningElementAfterName(node2); } jsxParseOpeningElementAfterName(node2) { const attributes = []; while (!this.match(56) && !this.match(143)) { attributes.push(this.jsxParseAttribute()); } node2.attributes = attributes; node2.selfClosing = this.eat(56); this.expect(143); return this.finishNode(node2, "JSXOpeningElement"); } jsxParseClosingElementAt(startLoc) { const node2 = this.startNodeAt(startLoc); if (this.eat(143)) { return this.finishNode(node2, "JSXClosingFragment"); } node2.name = this.jsxParseElementName(); this.expect(143); return this.finishNode(node2, "JSXClosingElement"); } jsxParseElementAt(startLoc) { const node2 = this.startNodeAt(startLoc); const children = []; const openingElement = this.jsxParseOpeningElementAt(startLoc); let closingElement = null; if (!openingElement.selfClosing) { contents: for (; ; ) { switch (this.state.type) { case 142: startLoc = this.state.startLoc; this.next(); if (this.eat(56)) { closingElement = this.jsxParseClosingElementAt(startLoc); break contents; } children.push(this.jsxParseElementAt(startLoc)); break; case 141: children.push(this.parseExprAtom()); break; case 5: { const node3 = this.startNode(); this.setContext(types.brace); this.next(); if (this.match(21)) { children.push(this.jsxParseSpreadChild(node3)); } else { children.push(this.jsxParseExpressionContainer(node3, types.j_expr)); } break; } default: this.unexpected(); } } if (isFragment(openingElement) && !isFragment(closingElement) && closingElement !== null) { this.raise(JsxErrors.MissingClosingTagFragment, { at: closingElement }); } else if (!isFragment(openingElement) && isFragment(closingElement)) { this.raise(JsxErrors.MissingClosingTagElement, { at: closingElement, openingTagName: getQualifiedJSXName(openingElement.name) }); } else if (!isFragment(openingElement) && !isFragment(closingElement)) { if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) { this.raise(JsxErrors.MissingClosingTagElement, { at: closingElement, openingTagName: getQualifiedJSXName(openingElement.name) }); } } } if (isFragment(openingElement)) { node2.openingFragment = openingElement; node2.closingFragment = closingElement; } else { node2.openingElement = openingElement; node2.closingElement = closingElement; } node2.children = children; if (this.match(47)) { throw this.raise(JsxErrors.UnwrappedAdjacentJSXElements, { at: this.state.startLoc }); } return isFragment(openingElement) ? this.finishNode(node2, "JSXFragment") : this.finishNode(node2, "JSXElement"); } jsxParseElement() { const startLoc = this.state.startLoc; this.next(); return this.jsxParseElementAt(startLoc); } setContext(newContext) { const { context } = this.state; context[context.length - 1] = newContext; } parseExprAtom(refExpressionErrors) { if (this.match(141)) { return this.parseLiteral(this.state.value, "JSXText"); } else if (this.match(142)) { return this.jsxParseElement(); } else if (this.match(47) && this.input.charCodeAt(this.state.pos) !== 33) { this.replaceToken(142); return this.jsxParseElement(); } else { return super.parseExprAtom(refExpressionErrors); } } skipSpace() { const curContext = this.curContext(); if (!curContext.preserveSpace) super.skipSpace(); } getTokenFromCode(code2) { const context = this.curContext(); if (context === types.j_expr) { this.jsxReadToken(); return; } if (context === types.j_oTag || context === types.j_cTag) { if (isIdentifierStart(code2)) { this.jsxReadWord(); return; } if (code2 === 62) { ++this.state.pos; this.finishToken(143); return; } if ((code2 === 34 || code2 === 39) && context === types.j_oTag) { this.jsxReadString(code2); return; } } if (code2 === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) { ++this.state.pos; this.finishToken(142); return; } super.getTokenFromCode(code2); } updateContext(prevType) { const { context, type: type2 } = this.state; if (type2 === 56 && prevType === 142) { context.splice(-2, 2, types.j_cTag); this.state.canStartJSXElement = false; } else if (type2 === 142) { context.push(types.j_oTag); } else if (type2 === 143) { const out = context[context.length - 1]; if (out === types.j_oTag && prevType === 56 || out === types.j_cTag) { context.pop(); this.state.canStartJSXElement = context[context.length - 1] === types.j_expr; } else { this.setContext(types.j_expr); this.state.canStartJSXElement = true; } } else { this.state.canStartJSXElement = tokenComesBeforeExpression(type2); } } }; var TypeScriptScope = class extends Scope { constructor(...args) { super(...args); this.types = /* @__PURE__ */ new Set(); this.enums = /* @__PURE__ */ new Set(); this.constEnums = /* @__PURE__ */ new Set(); this.classes = /* @__PURE__ */ new Set(); this.exportOnlyBindings = /* @__PURE__ */ new Set(); } }; var TypeScriptScopeHandler = class extends ScopeHandler { constructor(...args) { super(...args); this.importsStack = []; } createScope(flags) { this.importsStack.push(/* @__PURE__ */ new Set()); return new TypeScriptScope(flags); } enter(flags) { if (flags == 256) { this.importsStack.push(/* @__PURE__ */ new Set()); } super.enter(flags); } exit() { const flags = super.exit(); if (flags == 256) { this.importsStack.pop(); } return flags; } hasImport(name, allowShadow) { const len = this.importsStack.length; if (this.importsStack[len - 1].has(name)) { return true; } if (!allowShadow && len > 1) { for (let i2 = 0; i2 < len - 1; i2++) { if (this.importsStack[i2].has(name)) return true; } } return false; } declareName(name, bindingType, loc) { if (bindingType & 4096) { if (this.hasImport(name, true)) { this.parser.raise(Errors.VarRedeclaration, { at: loc, identifierName: name }); } this.importsStack[this.importsStack.length - 1].add(name); return; } const scope = this.currentScope(); if (bindingType & 1024) { this.maybeExportDefined(scope, name); scope.exportOnlyBindings.add(name); return; } super.declareName(name, bindingType, loc); if (bindingType & 2) { if (!(bindingType & 1)) { this.checkRedeclarationInScope(scope, name, bindingType, loc); this.maybeExportDefined(scope, name); } scope.types.add(name); } if (bindingType & 256) scope.enums.add(name); if (bindingType & 512) { scope.constEnums.add(name); } if (bindingType & 128) scope.classes.add(name); } isRedeclaredInScope(scope, name, bindingType) { if (scope.enums.has(name)) { if (bindingType & 256) { const isConst = !!(bindingType & 512); const wasConst = scope.constEnums.has(name); return isConst !== wasConst; } return true; } if (bindingType & 128 && scope.classes.has(name)) { if (scope.lexical.has(name)) { return !!(bindingType & 1); } else { return false; } } if (bindingType & 2 && scope.types.has(name)) { return true; } return super.isRedeclaredInScope(scope, name, bindingType); } checkLocalExport(id) { const { name } = id; if (this.hasImport(name)) return; const len = this.scopeStack.length; for (let i2 = len - 1; i2 >= 0; i2--) { const scope = this.scopeStack[i2]; if (scope.types.has(name) || scope.exportOnlyBindings.has(name)) return; } super.checkLocalExport(id); } }; var getOwn$1 = (object, key) => Object.hasOwnProperty.call(object, key) && object[key]; var unwrapParenthesizedExpression = (node2) => { return node2.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node2.expression) : node2; }; var LValParser = class extends NodeUtils { toAssignable(node2, isLHS = false) { var _node$extra, _node$extra3; let parenthesized = void 0; if (node2.type === "ParenthesizedExpression" || (_node$extra = node2.extra) != null && _node$extra.parenthesized) { parenthesized = unwrapParenthesizedExpression(node2); if (isLHS) { if (parenthesized.type === "Identifier") { this.expressionScope.recordArrowParameterBindingError(Errors.InvalidParenthesizedAssignment, { at: node2 }); } else if (parenthesized.type !== "MemberExpression" && !this.isOptionalMemberExpression(parenthesized)) { this.raise(Errors.InvalidParenthesizedAssignment, { at: node2 }); } } else { this.raise(Errors.InvalidParenthesizedAssignment, { at: node2 }); } } switch (node2.type) { case "Identifier": case "ObjectPattern": case "ArrayPattern": case "AssignmentPattern": case "RestElement": break; case "ObjectExpression": node2.type = "ObjectPattern"; for (let i2 = 0, length = node2.properties.length, last = length - 1; i2 < length; i2++) { var _node$extra2; const prop = node2.properties[i2]; const isLast = i2 === last; this.toAssignableObjectExpressionProp(prop, isLast, isLHS); if (isLast && prop.type === "RestElement" && (_node$extra2 = node2.extra) != null && _node$extra2.trailingCommaLoc) { this.raise(Errors.RestTrailingComma, { at: node2.extra.trailingCommaLoc }); } } break; case "ObjectProperty": { const { key, value } = node2; if (this.isPrivateName(key)) { this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start); } this.toAssignable(value, isLHS); break; } case "SpreadElement": { throw new Error("Internal @babel/parser error (this is a bug, please report it). SpreadElement should be converted by .toAssignable's caller."); } case "ArrayExpression": node2.type = "ArrayPattern"; this.toAssignableList(node2.elements, (_node$extra3 = node2.extra) == null ? void 0 : _node$extra3.trailingCommaLoc, isLHS); break; case "AssignmentExpression": if (node2.operator !== "=") { this.raise(Errors.MissingEqInAssignment, { at: node2.left.loc.end }); } node2.type = "AssignmentPattern"; delete node2.operator; this.toAssignable(node2.left, isLHS); break; case "ParenthesizedExpression": this.toAssignable(parenthesized, isLHS); break; } } toAssignableObjectExpressionProp(prop, isLast, isLHS) { if (prop.type === "ObjectMethod") { this.raise(prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor : Errors.PatternHasMethod, { at: prop.key }); } else if (prop.type === "SpreadElement") { prop.type = "RestElement"; const arg = prop.argument; this.checkToRestConversion(arg, false); this.toAssignable(arg, isLHS); if (!isLast) { this.raise(Errors.RestTrailingComma, { at: prop }); } } else { this.toAssignable(prop, isLHS); } } toAssignableList(exprList, trailingCommaLoc, isLHS) { const end = exprList.length - 1; for (let i2 = 0; i2 <= end; i2++) { const elt = exprList[i2]; if (!elt) continue; if (elt.type === "SpreadElement") { elt.type = "RestElement"; const arg = elt.argument; this.checkToRestConversion(arg, true); this.toAssignable(arg, isLHS); } else { this.toAssignable(elt, isLHS); } if (elt.type === "RestElement") { if (i2 < end) { this.raise(Errors.RestTrailingComma, { at: elt }); } else if (trailingCommaLoc) { this.raise(Errors.RestTrailingComma, { at: trailingCommaLoc }); } } } } isAssignable(node2, isBinding) { switch (node2.type) { case "Identifier": case "ObjectPattern": case "ArrayPattern": case "AssignmentPattern": case "RestElement": return true; case "ObjectExpression": { const last = node2.properties.length - 1; return node2.properties.every((prop, i2) => { return prop.type !== "ObjectMethod" && (i2 === last || prop.type !== "SpreadElement") && this.isAssignable(prop); }); } case "ObjectProperty": return this.isAssignable(node2.value); case "SpreadElement": return this.isAssignable(node2.argument); case "ArrayExpression": return node2.elements.every((element2) => element2 === null || this.isAssignable(element2)); case "AssignmentExpression": return node2.operator === "="; case "ParenthesizedExpression": return this.isAssignable(node2.expression); case "MemberExpression": case "OptionalMemberExpression": return !isBinding; default: return false; } } toReferencedList(exprList, isParenthesizedExpr) { return exprList; } toReferencedListDeep(exprList, isParenthesizedExpr) { this.toReferencedList(exprList, isParenthesizedExpr); for (const expr of exprList) { if ((expr == null ? void 0 : expr.type) === "ArrayExpression") { this.toReferencedListDeep(expr.elements); } } } parseSpread(refExpressionErrors) { const node2 = this.startNode(); this.next(); node2.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, void 0); return this.finishNode(node2, "SpreadElement"); } parseRestBinding() { const node2 = this.startNode(); this.next(); node2.argument = this.parseBindingAtom(); return this.finishNode(node2, "RestElement"); } parseBindingAtom() { switch (this.state.type) { case 0: { const node2 = this.startNode(); this.next(); node2.elements = this.parseBindingList(3, 93, 1); return this.finishNode(node2, "ArrayPattern"); } case 5: return this.parseObjectLike(8, true); } return this.parseIdentifier(); } parseBindingList(close, closeCharCode, flags) { const allowEmpty = flags & 1; const elts = []; let first = true; while (!this.eat(close)) { if (first) { first = false; } else { this.expect(12); } if (allowEmpty && this.match(12)) { elts.push(null); } else if (this.eat(close)) { break; } else if (this.match(21)) { elts.push(this.parseAssignableListItemTypes(this.parseRestBinding(), flags)); if (!this.checkCommaAfterRest(closeCharCode)) { this.expect(close); break; } } else { const decorators = []; if (this.match(26) && this.hasPlugin("decorators")) { this.raise(Errors.UnsupportedParameterDecorator, { at: this.state.startLoc }); } while (this.match(26)) { decorators.push(this.parseDecorator()); } elts.push(this.parseAssignableListItem(flags, decorators)); } } return elts; } parseBindingRestProperty(prop) { this.next(); prop.argument = this.parseIdentifier(); this.checkCommaAfterRest(125); return this.finishNode(prop, "RestElement"); } parseBindingProperty() { const prop = this.startNode(); const { type: type2, startLoc } = this.state; if (type2 === 21) { return this.parseBindingRestProperty(prop); } else if (type2 === 138) { this.expectPlugin("destructuringPrivate", startLoc); this.classScope.usePrivateName(this.state.value, startLoc); prop.key = this.parsePrivateName(); } else { this.parsePropertyName(prop); } prop.method = false; return this.parseObjPropValue(prop, startLoc, false, false, true, false); } parseAssignableListItem(flags, decorators) { const left = this.parseMaybeDefault(); this.parseAssignableListItemTypes(left, flags); const elt = this.parseMaybeDefault(left.loc.start, left); if (decorators.length) { left.decorators = decorators; } return elt; } parseAssignableListItemTypes(param, flags) { return param; } parseMaybeDefault(startLoc, left) { var _startLoc, _left; (_startLoc = startLoc) != null ? _startLoc : startLoc = this.state.startLoc; left = (_left = left) != null ? _left : this.parseBindingAtom(); if (!this.eat(29)) return left; const node2 = this.startNodeAt(startLoc); node2.left = left; node2.right = this.parseMaybeAssignAllowIn(); return this.finishNode(node2, "AssignmentPattern"); } isValidLVal(type2, isUnparenthesizedInAssign, binding) { return getOwn$1({ AssignmentPattern: "left", RestElement: "argument", ObjectProperty: "value", ParenthesizedExpression: "expression", ArrayPattern: "elements", ObjectPattern: "properties" }, type2); } isOptionalMemberExpression(expression) { return expression.type === "OptionalMemberExpression"; } checkLVal(expression, { in: ancestor, binding = 64, checkClashes = false, strictModeChanged = false, hasParenthesizedAncestor = false }) { var _expression$extra; const type2 = expression.type; if (this.isObjectMethod(expression)) return; const isOptionalMemberExpression = this.isOptionalMemberExpression(expression); if (isOptionalMemberExpression || type2 === "MemberExpression") { if (isOptionalMemberExpression) { this.expectPlugin("optionalChainingAssign", expression.loc.start); if (ancestor.type !== "AssignmentExpression") { this.raise(Errors.InvalidLhsOptionalChaining, { at: expression, ancestor }); } } if (binding !== 64) { this.raise(Errors.InvalidPropertyBindingPattern, { at: expression }); } return; } if (type2 === "Identifier") { this.checkIdentifier(expression, binding, strictModeChanged); const { name } = expression; if (checkClashes) { if (checkClashes.has(name)) { this.raise(Errors.ParamDupe, { at: expression }); } else { checkClashes.add(name); } } return; } const validity = this.isValidLVal(type2, !(hasParenthesizedAncestor || (_expression$extra = expression.extra) != null && _expression$extra.parenthesized) && ancestor.type === "AssignmentExpression", binding); if (validity === true) return; if (validity === false) { const ParseErrorClass = binding === 64 ? Errors.InvalidLhs : Errors.InvalidLhsBinding; this.raise(ParseErrorClass, { at: expression, ancestor }); return; } const [key, isParenthesizedExpression] = Array.isArray(validity) ? validity : [validity, type2 === "ParenthesizedExpression"]; const nextAncestor = type2 === "ArrayPattern" || type2 === "ObjectPattern" ? { type: type2 } : ancestor; for (const child of [].concat(expression[key])) { if (child) { this.checkLVal(child, { in: nextAncestor, binding, checkClashes, strictModeChanged, hasParenthesizedAncestor: isParenthesizedExpression }); } } } checkIdentifier(at, bindingType, strictModeChanged = false) { if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(at.name, this.inModule) : isStrictBindOnlyReservedWord(at.name))) { if (bindingType === 64) { this.raise(Errors.StrictEvalArguments, { at, referenceName: at.name }); } else { this.raise(Errors.StrictEvalArgumentsBinding, { at, bindingName: at.name }); } } if (bindingType & 8192 && at.name === "let") { this.raise(Errors.LetInLexicalBinding, { at }); } if (!(bindingType & 64)) { this.declareNameFromIdentifier(at, bindingType); } } declareNameFromIdentifier(identifier, binding) { this.scope.declareName(identifier.name, binding, identifier.loc.start); } checkToRestConversion(node2, allowPattern) { switch (node2.type) { case "ParenthesizedExpression": this.checkToRestConversion(node2.expression, allowPattern); break; case "Identifier": case "MemberExpression": break; case "ArrayExpression": case "ObjectExpression": if (allowPattern) break; default: this.raise(Errors.InvalidRestAssignmentPattern, { at: node2 }); } } checkCommaAfterRest(close) { if (!this.match(12)) { return false; } this.raise(this.lookaheadCharCode() === close ? Errors.RestTrailingComma : Errors.ElementAfterRest, { at: this.state.startLoc }); return true; } }; var getOwn = (object, key) => Object.hasOwnProperty.call(object, key) && object[key]; function nonNull(x2) { if (x2 == null) { throw new Error(`Unexpected ${x2} value.`); } return x2; } function assert(x2) { if (!x2) { throw new Error("Assert fail"); } } var TSErrors = ParseErrorEnum`typescript`({ AbstractMethodHasImplementation: ({ methodName }) => `Method '${methodName}' cannot have an implementation because it is marked abstract.`, AbstractPropertyHasInitializer: ({ propertyName }) => `Property '${propertyName}' cannot have an initializer because it is marked abstract.`, AccesorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.", AccesorCannotHaveTypeParameters: "An accessor cannot have type parameters.", AccessorCannotBeOptional: "An 'accessor' property cannot be declared optional.", ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.", ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.", ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference: "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.", ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.", DeclareAccessor: ({ kind }) => `'declare' is not allowed in ${kind}ters.`, DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.", DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.", DuplicateAccessibilityModifier: ({ modifier }) => `Accessibility modifier already seen.`, DuplicateModifier: ({ modifier }) => `Duplicate modifier: '${modifier}'.`, EmptyHeritageClauseType: ({ token }) => `'${token}' list cannot be empty.`, EmptyTypeArguments: "Type argument list cannot be empty.", EmptyTypeParameters: "Type parameter list cannot be empty.", ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.", ImportAliasHasImportType: "An import alias can not use 'import type'.", ImportReflectionHasImportType: "An `import module` declaration can not use `type` modifier", IncompatibleModifiers: ({ modifiers }) => `'${modifiers[0]}' modifier cannot be used with '${modifiers[1]}' modifier.`, IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.", IndexSignatureHasAccessibility: ({ modifier }) => `Index signatures cannot have an accessibility modifier ('${modifier}').`, IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.", IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.", IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.", InitializerNotAllowedInAmbientContext: "Initializers are not allowed in ambient contexts.", InvalidModifierOnTypeMember: ({ modifier }) => `'${modifier}' modifier cannot appear on a type member.`, InvalidModifierOnTypeParameter: ({ modifier }) => `'${modifier}' modifier cannot appear on a type parameter.`, InvalidModifierOnTypeParameterPositions: ({ modifier }) => `'${modifier}' modifier can only appear on a type parameter of a class, interface or type alias.`, InvalidModifiersOrder: ({ orderedModifiers }) => `'${orderedModifiers[0]}' modifier must precede '${orderedModifiers[1]}' modifier.`, InvalidPropertyAccessAfterInstantiationExpression: "Invalid property access after an instantiation expression. You can either wrap the instantiation expression in parentheses, or delete the type arguments.", InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.", MissingInterfaceName: "'interface' declarations must be followed by an identifier.", NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.", NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.", OptionalTypeBeforeRequired: "A required element cannot follow an optional element.", OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.", PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.", PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.", PrivateElementHasAccessibility: ({ modifier }) => `Private elements cannot have an accessibility modifier ('${modifier}').`, ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.", ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `() => ...`.", ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.", SetAccesorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.", SetAccesorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.", SetAccesorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.", SingleTypeParameterWithoutTrailingComma: ({ typeParameterName }) => `Single type parameter ${typeParameterName} should have a trailing comma. Example usage: <${typeParameterName},>.`, StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.", TupleOptionalAfterType: "A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).", TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.", TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.", TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.", TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.", UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.", UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.", UnexpectedTypeAnnotation: "Did not expect a type annotation here.", UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.", UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.", UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.", UnsupportedSignatureParameterKind: ({ type: type2 }) => `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${type2}.` }); function keywordTypeFromName(value) { switch (value) { case "any": return "TSAnyKeyword"; case "boolean": return "TSBooleanKeyword"; case "bigint": return "TSBigIntKeyword"; case "never": return "TSNeverKeyword"; case "number": return "TSNumberKeyword"; case "object": return "TSObjectKeyword"; case "string": return "TSStringKeyword"; case "symbol": return "TSSymbolKeyword"; case "undefined": return "TSUndefinedKeyword"; case "unknown": return "TSUnknownKeyword"; default: return void 0; } } function tsIsAccessModifier(modifier) { return modifier === "private" || modifier === "public" || modifier === "protected"; } function tsIsVarianceAnnotations(modifier) { return modifier === "in" || modifier === "out"; } var typescript = (superClass) => class TypeScriptParserMixin extends superClass { constructor(...args) { super(...args); this.tsParseInOutModifiers = this.tsParseModifiers.bind(this, { allowedModifiers: ["in", "out"], disallowedModifiers: ["const", "public", "private", "protected", "readonly", "declare", "abstract", "override"], errorTemplate: TSErrors.InvalidModifierOnTypeParameter }); this.tsParseConstModifier = this.tsParseModifiers.bind(this, { allowedModifiers: ["const"], disallowedModifiers: ["in", "out"], errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions }); this.tsParseInOutConstModifiers = this.tsParseModifiers.bind(this, { allowedModifiers: ["in", "out", "const"], disallowedModifiers: ["public", "private", "protected", "readonly", "declare", "abstract", "override"], errorTemplate: TSErrors.InvalidModifierOnTypeParameter }); } getScopeHandler() { return TypeScriptScopeHandler; } tsIsIdentifier() { return tokenIsIdentifier(this.state.type); } tsTokenCanFollowModifier() { return (this.match(0) || this.match(5) || this.match(55) || this.match(21) || this.match(138) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak(); } tsNextTokenCanFollowModifier() { this.next(); return this.tsTokenCanFollowModifier(); } tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock) { if (!tokenIsIdentifier(this.state.type) && this.state.type !== 58 && this.state.type !== 75) { return void 0; } const modifier = this.state.value; if (allowedModifiers.indexOf(modifier) !== -1) { if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) { return void 0; } if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) { return modifier; } } return void 0; } tsParseModifiers({ allowedModifiers, disallowedModifiers, stopOnStartOfClassStaticBlock, errorTemplate = TSErrors.InvalidModifierOnTypeMember }, modified) { const enforceOrder = (loc, modifier, before, after) => { if (modifier === before && modified[after]) { this.raise(TSErrors.InvalidModifiersOrder, { at: loc, orderedModifiers: [before, after] }); } }; const incompatible = (loc, modifier, mod1, mod2) => { if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) { this.raise(TSErrors.IncompatibleModifiers, { at: loc, modifiers: [mod1, mod2] }); } }; for (; ; ) { const { startLoc } = this.state; const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock); if (!modifier) break; if (tsIsAccessModifier(modifier)) { if (modified.accessibility) { this.raise(TSErrors.DuplicateAccessibilityModifier, { at: startLoc, modifier }); } else { enforceOrder(startLoc, modifier, modifier, "override"); enforceOrder(startLoc, modifier, modifier, "static"); enforceOrder(startLoc, modifier, modifier, "readonly"); modified.accessibility = modifier; } } else if (tsIsVarianceAnnotations(modifier)) { if (modified[modifier]) { this.raise(TSErrors.DuplicateModifier, { at: startLoc, modifier }); } modified[modifier] = true; enforceOrder(startLoc, modifier, "in", "out"); } else { if (Object.hasOwnProperty.call(modified, modifier)) { this.raise(TSErrors.DuplicateModifier, { at: startLoc, modifier }); } else { enforceOrder(startLoc, modifier, "static", "readonly"); enforceOrder(startLoc, modifier, "static", "override"); enforceOrder(startLoc, modifier, "override", "readonly"); enforceOrder(startLoc, modifier, "abstract", "override"); incompatible(startLoc, modifier, "declare", "override"); incompatible(startLoc, modifier, "static", "abstract"); } modified[modifier] = true; } if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) { this.raise(errorTemplate, { at: startLoc, modifier }); } } } tsIsListTerminator(kind) { switch (kind) { case "EnumMembers": case "TypeMembers": return this.match(8); case "HeritageClauseElement": return this.match(5); case "TupleElementTypes": return this.match(3); case "TypeParametersOrArguments": return this.match(48); } } tsParseList(kind, parseElement) { const result = []; while (!this.tsIsListTerminator(kind)) { result.push(parseElement()); } return result; } tsParseDelimitedList(kind, parseElement, refTrailingCommaPos) { return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true, refTrailingCommaPos)); } tsParseDelimitedListWorker(kind, parseElement, expectSuccess, refTrailingCommaPos) { const result = []; let trailingCommaPos = -1; for (; ; ) { if (this.tsIsListTerminator(kind)) { break; } trailingCommaPos = -1; const element2 = parseElement(); if (element2 == null) { return void 0; } result.push(element2); if (this.eat(12)) { trailingCommaPos = this.state.lastTokStart; continue; } if (this.tsIsListTerminator(kind)) { break; } if (expectSuccess) { this.expect(12); } return void 0; } if (refTrailingCommaPos) { refTrailingCommaPos.value = trailingCommaPos; } return result; } tsParseBracketedList(kind, parseElement, bracket, skipFirstToken, refTrailingCommaPos) { if (!skipFirstToken) { if (bracket) { this.expect(0); } else { this.expect(47); } } const result = this.tsParseDelimitedList(kind, parseElement, refTrailingCommaPos); if (bracket) { this.expect(3); } else { this.expect(48); } return result; } tsParseImportType() { const node2 = this.startNode(); this.expect(83); this.expect(10); if (!this.match(133)) { this.raise(TSErrors.UnsupportedImportTypeArgument, { at: this.state.startLoc }); } node2.argument = super.parseExprAtom(); this.expect(11); if (this.eat(16)) { node2.qualifier = this.tsParseEntityName(); } if (this.match(47)) { node2.typeParameters = this.tsParseTypeArguments(); } return this.finishNode(node2, "TSImportType"); } tsParseEntityName(allowReservedWords = true) { let entity = this.parseIdentifier(allowReservedWords); while (this.eat(16)) { const node2 = this.startNodeAtNode(entity); node2.left = entity; node2.right = this.parseIdentifier(allowReservedWords); entity = this.finishNode(node2, "TSQualifiedName"); } return entity; } tsParseTypeReference() { const node2 = this.startNode(); node2.typeName = this.tsParseEntityName(); if (!this.hasPrecedingLineBreak() && this.match(47)) { node2.typeParameters = this.tsParseTypeArguments(); } return this.finishNode(node2, "TSTypeReference"); } tsParseThisTypePredicate(lhs) { this.next(); const node2 = this.startNodeAtNode(lhs); node2.parameterName = lhs; node2.typeAnnotation = this.tsParseTypeAnnotation(false); node2.asserts = false; return this.finishNode(node2, "TSTypePredicate"); } tsParseThisTypeNode() { const node2 = this.startNode(); this.next(); return this.finishNode(node2, "TSThisType"); } tsParseTypeQuery() { const node2 = this.startNode(); this.expect(87); if (this.match(83)) { node2.exprName = this.tsParseImportType(); } else { node2.exprName = this.tsParseEntityName(); } if (!this.hasPrecedingLineBreak() && this.match(47)) { node2.typeParameters = this.tsParseTypeArguments(); } return this.finishNode(node2, "TSTypeQuery"); } tsParseTypeParameter(parseModifiers) { const node2 = this.startNode(); parseModifiers(node2); node2.name = this.tsParseTypeParameterName(); node2.constraint = this.tsEatThenParseType(81); node2.default = this.tsEatThenParseType(29); return this.finishNode(node2, "TSTypeParameter"); } tsTryParseTypeParameters(parseModifiers) { if (this.match(47)) { return this.tsParseTypeParameters(parseModifiers); } } tsParseTypeParameters(parseModifiers) { const node2 = this.startNode(); if (this.match(47) || this.match(142)) { this.next(); } else { this.unexpected(); } const refTrailingCommaPos = { value: -1 }; node2.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this, parseModifiers), false, true, refTrailingCommaPos); if (node2.params.length === 0) { this.raise(TSErrors.EmptyTypeParameters, { at: node2 }); } if (refTrailingCommaPos.value !== -1) { this.addExtra(node2, "trailingComma", refTrailingCommaPos.value); } return this.finishNode(node2, "TSTypeParameterDeclaration"); } tsFillSignature(returnToken, signature) { const returnTokenRequired = returnToken === 19; const paramsKey = "parameters"; const returnTypeKey = "typeAnnotation"; signature.typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); this.expect(10); signature[paramsKey] = this.tsParseBindingListForSignature(); if (returnTokenRequired) { signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken); } else if (this.match(returnToken)) { signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken); } } tsParseBindingListForSignature() { const list2 = super.parseBindingList(11, 41, 2); for (const pattern of list2) { const { type: type2 } = pattern; if (type2 === "AssignmentPattern" || type2 === "TSParameterProperty") { this.raise(TSErrors.UnsupportedSignatureParameterKind, { at: pattern, type: type2 }); } } return list2; } tsParseTypeMemberSemicolon() { if (!this.eat(12) && !this.isLineTerminator()) { this.expect(13); } } tsParseSignatureMember(kind, node2) { this.tsFillSignature(14, node2); this.tsParseTypeMemberSemicolon(); return this.finishNode(node2, kind); } tsIsUnambiguouslyIndexSignature() { this.next(); if (tokenIsIdentifier(this.state.type)) { this.next(); return this.match(14); } return false; } tsTryParseIndexSignature(node2) { if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) { return; } this.expect(0); const id = this.parseIdentifier(); id.typeAnnotation = this.tsParseTypeAnnotation(); this.resetEndLocation(id); this.expect(3); node2.parameters = [id]; const type2 = this.tsTryParseTypeAnnotation(); if (type2) node2.typeAnnotation = type2; this.tsParseTypeMemberSemicolon(); return this.finishNode(node2, "TSIndexSignature"); } tsParsePropertyOrMethodSignature(node2, readonly) { if (this.eat(17)) node2.optional = true; const nodeAny = node2; if (this.match(10) || this.match(47)) { if (readonly) { this.raise(TSErrors.ReadonlyForMethodSignature, { at: node2 }); } const method = nodeAny; if (method.kind && this.match(47)) { this.raise(TSErrors.AccesorCannotHaveTypeParameters, { at: this.state.curPosition() }); } this.tsFillSignature(14, method); this.tsParseTypeMemberSemicolon(); const paramsKey = "parameters"; const returnTypeKey = "typeAnnotation"; if (method.kind === "get") { if (method[paramsKey].length > 0) { this.raise(Errors.BadGetterArity, { at: this.state.curPosition() }); if (this.isThisParam(method[paramsKey][0])) { this.raise(TSErrors.AccesorCannotDeclareThisParameter, { at: this.state.curPosition() }); } } } else if (method.kind === "set") { if (method[paramsKey].length !== 1) { this.raise(Errors.BadSetterArity, { at: this.state.curPosition() }); } else { const firstParameter = method[paramsKey][0]; if (this.isThisParam(firstParameter)) { this.raise(TSErrors.AccesorCannotDeclareThisParameter, { at: this.state.curPosition() }); } if (firstParameter.type === "Identifier" && firstParameter.optional) { this.raise(TSErrors.SetAccesorCannotHaveOptionalParameter, { at: this.state.curPosition() }); } if (firstParameter.type === "RestElement") { this.raise(TSErrors.SetAccesorCannotHaveRestParameter, { at: this.state.curPosition() }); } } if (method[returnTypeKey]) { this.raise(TSErrors.SetAccesorCannotHaveReturnType, { at: method[returnTypeKey] }); } } else { method.kind = "method"; } return this.finishNode(method, "TSMethodSignature"); } else { const property = nodeAny; if (readonly) property.readonly = true; const type2 = this.tsTryParseTypeAnnotation(); if (type2) property.typeAnnotation = type2; this.tsParseTypeMemberSemicolon(); return this.finishNode(property, "TSPropertySignature"); } } tsParseTypeMember() { const node2 = this.startNode(); if (this.match(10) || this.match(47)) { return this.tsParseSignatureMember("TSCallSignatureDeclaration", node2); } if (this.match(77)) { const id = this.startNode(); this.next(); if (this.match(10) || this.match(47)) { return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node2); } else { node2.key = this.createIdentifier(id, "new"); return this.tsParsePropertyOrMethodSignature(node2, false); } } this.tsParseModifiers({ allowedModifiers: ["readonly"], disallowedModifiers: ["declare", "abstract", "private", "protected", "public", "static", "override"] }, node2); const idx = this.tsTryParseIndexSignature(node2); if (idx) { return idx; } super.parsePropertyName(node2); if (!node2.computed && node2.key.type === "Identifier" && (node2.key.name === "get" || node2.key.name === "set") && this.tsTokenCanFollowModifier()) { node2.kind = node2.key.name; super.parsePropertyName(node2); } return this.tsParsePropertyOrMethodSignature(node2, !!node2.readonly); } tsParseTypeLiteral() { const node2 = this.startNode(); node2.members = this.tsParseObjectTypeMembers(); return this.finishNode(node2, "TSTypeLiteral"); } tsParseObjectTypeMembers() { this.expect(5); const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this)); this.expect(8); return members; } tsIsStartOfMappedType() { this.next(); if (this.eat(53)) { return this.isContextual(122); } if (this.isContextual(122)) { this.next(); } if (!this.match(0)) { return false; } this.next(); if (!this.tsIsIdentifier()) { return false; } this.next(); return this.match(58); } tsParseMappedTypeParameter() { const node2 = this.startNode(); node2.name = this.tsParseTypeParameterName(); node2.constraint = this.tsExpectThenParseType(58); return this.finishNode(node2, "TSTypeParameter"); } tsParseMappedType() { const node2 = this.startNode(); this.expect(5); if (this.match(53)) { node2.readonly = this.state.value; this.next(); this.expectContextual(122); } else if (this.eatContextual(122)) { node2.readonly = true; } this.expect(0); node2.typeParameter = this.tsParseMappedTypeParameter(); node2.nameType = this.eatContextual(93) ? this.tsParseType() : null; this.expect(3); if (this.match(53)) { node2.optional = this.state.value; this.next(); this.expect(17); } else if (this.eat(17)) { node2.optional = true; } node2.typeAnnotation = this.tsTryParseType(); this.semicolon(); this.expect(8); return this.finishNode(node2, "TSMappedType"); } tsParseTupleType() { const node2 = this.startNode(); node2.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false); let seenOptionalElement = false; node2.elementTypes.forEach((elementNode) => { const { type: type2 } = elementNode; if (seenOptionalElement && type2 !== "TSRestType" && type2 !== "TSOptionalType" && !(type2 === "TSNamedTupleMember" && elementNode.optional)) { this.raise(TSErrors.OptionalTypeBeforeRequired, { at: elementNode }); } seenOptionalElement || (seenOptionalElement = type2 === "TSNamedTupleMember" && elementNode.optional || type2 === "TSOptionalType"); }); return this.finishNode(node2, "TSTupleType"); } tsParseTupleElementType() { const { startLoc } = this.state; const rest = this.eat(21); let labeled; let label; let optional; let type2; const isWord = tokenIsKeywordOrIdentifier(this.state.type); const chAfterWord = isWord ? this.lookaheadCharCode() : null; if (chAfterWord === 58) { labeled = true; optional = false; label = this.parseIdentifier(true); this.expect(14); type2 = this.tsParseType(); } else if (chAfterWord === 63) { optional = true; const startLoc2 = this.state.startLoc; const wordName = this.state.value; const typeOrLabel = this.tsParseNonArrayType(); if (this.lookaheadCharCode() === 58) { labeled = true; label = this.createIdentifier(this.startNodeAt(startLoc2), wordName); this.expect(17); this.expect(14); type2 = this.tsParseType(); } else { labeled = false; type2 = typeOrLabel; this.expect(17); } } else { type2 = this.tsParseType(); optional = this.eat(17); labeled = this.eat(14); } if (labeled) { let labeledNode; if (label) { labeledNode = this.startNodeAtNode(label); labeledNode.optional = optional; labeledNode.label = label; labeledNode.elementType = type2; if (this.eat(17)) { labeledNode.optional = true; this.raise(TSErrors.TupleOptionalAfterType, { at: this.state.lastTokStartLoc }); } } else { labeledNode = this.startNodeAtNode(type2); labeledNode.optional = optional; this.raise(TSErrors.InvalidTupleMemberLabel, { at: type2 }); labeledNode.label = type2; labeledNode.elementType = this.tsParseType(); } type2 = this.finishNode(labeledNode, "TSNamedTupleMember"); } else if (optional) { const optionalTypeNode = this.startNodeAtNode(type2); optionalTypeNode.typeAnnotation = type2; type2 = this.finishNode(optionalTypeNode, "TSOptionalType"); } if (rest) { const restNode = this.startNodeAt(startLoc); restNode.typeAnnotation = type2; type2 = this.finishNode(restNode, "TSRestType"); } return type2; } tsParseParenthesizedType() { const node2 = this.startNode(); this.expect(10); node2.typeAnnotation = this.tsParseType(); this.expect(11); return this.finishNode(node2, "TSParenthesizedType"); } tsParseFunctionOrConstructorType(type2, abstract) { const node2 = this.startNode(); if (type2 === "TSConstructorType") { node2.abstract = !!abstract; if (abstract) this.next(); this.next(); } this.tsInAllowConditionalTypesContext(() => this.tsFillSignature(19, node2)); return this.finishNode(node2, type2); } tsParseLiteralTypeNode() { const node2 = this.startNode(); switch (this.state.type) { case 134: case 135: case 133: case 85: case 86: node2.literal = super.parseExprAtom(); break; default: this.unexpected(); } return this.finishNode(node2, "TSLiteralType"); } tsParseTemplateLiteralType() { const node2 = this.startNode(); node2.literal = super.parseTemplate(false); return this.finishNode(node2, "TSLiteralType"); } parseTemplateSubstitution() { if (this.state.inType) return this.tsParseType(); return super.parseTemplateSubstitution(); } tsParseThisTypeOrThisTypePredicate() { const thisKeyword = this.tsParseThisTypeNode(); if (this.isContextual(116) && !this.hasPrecedingLineBreak()) { return this.tsParseThisTypePredicate(thisKeyword); } else { return thisKeyword; } } tsParseNonArrayType() { switch (this.state.type) { case 133: case 134: case 135: case 85: case 86: return this.tsParseLiteralTypeNode(); case 53: if (this.state.value === "-") { const node2 = this.startNode(); const nextToken = this.lookahead(); if (nextToken.type !== 134 && nextToken.type !== 135) { this.unexpected(); } node2.literal = this.parseMaybeUnary(); return this.finishNode(node2, "TSLiteralType"); } break; case 78: return this.tsParseThisTypeOrThisTypePredicate(); case 87: return this.tsParseTypeQuery(); case 83: return this.tsParseImportType(); case 5: return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral(); case 0: return this.tsParseTupleType(); case 10: return this.tsParseParenthesizedType(); case 25: case 24: return this.tsParseTemplateLiteralType(); default: { const { type: type2 } = this.state; if (tokenIsIdentifier(type2) || type2 === 88 || type2 === 84) { const nodeType = type2 === 88 ? "TSVoidKeyword" : type2 === 84 ? "TSNullKeyword" : keywordTypeFromName(this.state.value); if (nodeType !== void 0 && this.lookaheadCharCode() !== 46) { const node2 = this.startNode(); this.next(); return this.finishNode(node2, nodeType); } return this.tsParseTypeReference(); } } } this.unexpected(); } tsParseArrayTypeOrHigher() { let type2 = this.tsParseNonArrayType(); while (!this.hasPrecedingLineBreak() && this.eat(0)) { if (this.match(3)) { const node2 = this.startNodeAtNode(type2); node2.elementType = type2; this.expect(3); type2 = this.finishNode(node2, "TSArrayType"); } else { const node2 = this.startNodeAtNode(type2); node2.objectType = type2; node2.indexType = this.tsParseType(); this.expect(3); type2 = this.finishNode(node2, "TSIndexedAccessType"); } } return type2; } tsParseTypeOperator() { const node2 = this.startNode(); const operator = this.state.value; this.next(); node2.operator = operator; node2.typeAnnotation = this.tsParseTypeOperatorOrHigher(); if (operator === "readonly") { this.tsCheckTypeAnnotationForReadOnly(node2); } return this.finishNode(node2, "TSTypeOperator"); } tsCheckTypeAnnotationForReadOnly(node2) { switch (node2.typeAnnotation.type) { case "TSTupleType": case "TSArrayType": return; default: this.raise(TSErrors.UnexpectedReadonly, { at: node2 }); } } tsParseInferType() { const node2 = this.startNode(); this.expectContextual(115); const typeParameter = this.startNode(); typeParameter.name = this.tsParseTypeParameterName(); typeParameter.constraint = this.tsTryParse(() => this.tsParseConstraintForInferType()); node2.typeParameter = this.finishNode(typeParameter, "TSTypeParameter"); return this.finishNode(node2, "TSInferType"); } tsParseConstraintForInferType() { if (this.eat(81)) { const constraint = this.tsInDisallowConditionalTypesContext(() => this.tsParseType()); if (this.state.inDisallowConditionalTypesContext || !this.match(17)) { return constraint; } } } tsParseTypeOperatorOrHigher() { const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc; return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(115) ? this.tsParseInferType() : this.tsInAllowConditionalTypesContext(() => this.tsParseArrayTypeOrHigher()); } tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) { const node2 = this.startNode(); const hasLeadingOperator = this.eat(operator); const types2 = []; do { types2.push(parseConstituentType()); } while (this.eat(operator)); if (types2.length === 1 && !hasLeadingOperator) { return types2[0]; } node2.types = types2; return this.finishNode(node2, kind); } tsParseIntersectionTypeOrHigher() { return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 45); } tsParseUnionTypeOrHigher() { return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 43); } tsIsStartOfFunctionType() { if (this.match(47)) { return true; } return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this)); } tsSkipParameterStart() { if (tokenIsIdentifier(this.state.type) || this.match(78)) { this.next(); return true; } if (this.match(5)) { const { errors } = this.state; const previousErrorCount = errors.length; try { this.parseObjectLike(8, true); return errors.length === previousErrorCount; } catch (_unused) { return false; } } if (this.match(0)) { this.next(); const { errors } = this.state; const previousErrorCount = errors.length; try { super.parseBindingList(3, 93, 1); return errors.length === previousErrorCount; } catch (_unused2) { return false; } } return false; } tsIsUnambiguouslyStartOfFunctionType() { this.next(); if (this.match(11) || this.match(21)) { return true; } if (this.tsSkipParameterStart()) { if (this.match(14) || this.match(12) || this.match(17) || this.match(29)) { return true; } if (this.match(11)) { this.next(); if (this.match(19)) { return true; } } } return false; } tsParseTypeOrTypePredicateAnnotation(returnToken) { return this.tsInType(() => { const t2 = this.startNode(); this.expect(returnToken); const node2 = this.startNode(); const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this)); if (asserts && this.match(78)) { let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate(); if (thisTypePredicate.type === "TSThisType") { node2.parameterName = thisTypePredicate; node2.asserts = true; node2.typeAnnotation = null; thisTypePredicate = this.finishNode(node2, "TSTypePredicate"); } else { this.resetStartLocationFromNode(thisTypePredicate, node2); thisTypePredicate.asserts = true; } t2.typeAnnotation = thisTypePredicate; return this.finishNode(t2, "TSTypeAnnotation"); } const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this)); if (!typePredicateVariable) { if (!asserts) { return this.tsParseTypeAnnotation(false, t2); } node2.parameterName = this.parseIdentifier(); node2.asserts = asserts; node2.typeAnnotation = null; t2.typeAnnotation = this.finishNode(node2, "TSTypePredicate"); return this.finishNode(t2, "TSTypeAnnotation"); } const type2 = this.tsParseTypeAnnotation(false); node2.parameterName = typePredicateVariable; node2.typeAnnotation = type2; node2.asserts = asserts; t2.typeAnnotation = this.finishNode(node2, "TSTypePredicate"); return this.finishNode(t2, "TSTypeAnnotation"); }); } tsTryParseTypeOrTypePredicateAnnotation() { if (this.match(14)) { return this.tsParseTypeOrTypePredicateAnnotation(14); } } tsTryParseTypeAnnotation() { if (this.match(14)) { return this.tsParseTypeAnnotation(); } } tsTryParseType() { return this.tsEatThenParseType(14); } tsParseTypePredicatePrefix() { const id = this.parseIdentifier(); if (this.isContextual(116) && !this.hasPrecedingLineBreak()) { this.next(); return id; } } tsParseTypePredicateAsserts() { if (this.state.type !== 109) { return false; } const containsEsc = this.state.containsEsc; this.next(); if (!tokenIsIdentifier(this.state.type) && !this.match(78)) { return false; } if (containsEsc) { this.raise(Errors.InvalidEscapedReservedWord, { at: this.state.lastTokStartLoc, reservedWord: "asserts" }); } return true; } tsParseTypeAnnotation(eatColon = true, t2 = this.startNode()) { this.tsInType(() => { if (eatColon) this.expect(14); t2.typeAnnotation = this.tsParseType(); }); return this.finishNode(t2, "TSTypeAnnotation"); } tsParseType() { assert(this.state.inType); const type2 = this.tsParseNonConditionalType(); if (this.state.inDisallowConditionalTypesContext || this.hasPrecedingLineBreak() || !this.eat(81)) { return type2; } const node2 = this.startNodeAtNode(type2); node2.checkType = type2; node2.extendsType = this.tsInDisallowConditionalTypesContext(() => this.tsParseNonConditionalType()); this.expect(17); node2.trueType = this.tsInAllowConditionalTypesContext(() => this.tsParseType()); this.expect(14); node2.falseType = this.tsInAllowConditionalTypesContext(() => this.tsParseType()); return this.finishNode(node2, "TSConditionalType"); } isAbstractConstructorSignature() { return this.isContextual(124) && this.lookahead().type === 77; } tsParseNonConditionalType() { if (this.tsIsStartOfFunctionType()) { return this.tsParseFunctionOrConstructorType("TSFunctionType"); } if (this.match(77)) { return this.tsParseFunctionOrConstructorType("TSConstructorType"); } else if (this.isAbstractConstructorSignature()) { return this.tsParseFunctionOrConstructorType("TSConstructorType", true); } return this.tsParseUnionTypeOrHigher(); } tsParseTypeAssertion() { if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) { this.raise(TSErrors.ReservedTypeAssertion, { at: this.state.startLoc }); } const node2 = this.startNode(); node2.typeAnnotation = this.tsInType(() => { this.next(); return this.match(75) ? this.tsParseTypeReference() : this.tsParseType(); }); this.expect(48); node2.expression = this.parseMaybeUnary(); return this.finishNode(node2, "TSTypeAssertion"); } tsParseHeritageClause(token) { const originalStartLoc = this.state.startLoc; const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", () => { const node2 = this.startNode(); node2.expression = this.tsParseEntityName(); if (this.match(47)) { node2.typeParameters = this.tsParseTypeArguments(); } return this.finishNode(node2, "TSExpressionWithTypeArguments"); }); if (!delimitedList.length) { this.raise(TSErrors.EmptyHeritageClauseType, { at: originalStartLoc, token }); } return delimitedList; } tsParseInterfaceDeclaration(node2, properties = {}) { if (this.hasFollowingLineBreak()) return null; this.expectContextual(129); if (properties.declare) node2.declare = true; if (tokenIsIdentifier(this.state.type)) { node2.id = this.parseIdentifier(); this.checkIdentifier(node2.id, 130); } else { node2.id = null; this.raise(TSErrors.MissingInterfaceName, { at: this.state.startLoc }); } node2.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers); if (this.eat(81)) { node2.extends = this.tsParseHeritageClause("extends"); } const body = this.startNode(); body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this)); node2.body = this.finishNode(body, "TSInterfaceBody"); return this.finishNode(node2, "TSInterfaceDeclaration"); } tsParseTypeAliasDeclaration(node2) { node2.id = this.parseIdentifier(); this.checkIdentifier(node2.id, 2); node2.typeAnnotation = this.tsInType(() => { node2.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers); this.expect(29); if (this.isContextual(114) && this.lookahead().type !== 16) { const node3 = this.startNode(); this.next(); return this.finishNode(node3, "TSIntrinsicKeyword"); } return this.tsParseType(); }); this.semicolon(); return this.finishNode(node2, "TSTypeAliasDeclaration"); } tsInNoContext(cb) { const oldContext = this.state.context; this.state.context = [oldContext[0]]; try { return cb(); } finally { this.state.context = oldContext; } } tsInType(cb) { const oldInType = this.state.inType; this.state.inType = true; try { return cb(); } finally { this.state.inType = oldInType; } } tsInDisallowConditionalTypesContext(cb) { const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext; this.state.inDisallowConditionalTypesContext = true; try { return cb(); } finally { this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext; } } tsInAllowConditionalTypesContext(cb) { const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext; this.state.inDisallowConditionalTypesContext = false; try { return cb(); } finally { this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext; } } tsEatThenParseType(token) { if (this.match(token)) { return this.tsNextThenParseType(); } } tsExpectThenParseType(token) { return this.tsInType(() => { this.expect(token); return this.tsParseType(); }); } tsNextThenParseType() { return this.tsInType(() => { this.next(); return this.tsParseType(); }); } tsParseEnumMember() { const node2 = this.startNode(); node2.id = this.match(133) ? super.parseStringLiteral(this.state.value) : this.parseIdentifier(true); if (this.eat(29)) { node2.initializer = super.parseMaybeAssignAllowIn(); } return this.finishNode(node2, "TSEnumMember"); } tsParseEnumDeclaration(node2, properties = {}) { if (properties.const) node2.const = true; if (properties.declare) node2.declare = true; this.expectContextual(126); node2.id = this.parseIdentifier(); this.checkIdentifier(node2.id, node2.const ? 8971 : 8459); this.expect(5); node2.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this)); this.expect(8); return this.finishNode(node2, "TSEnumDeclaration"); } tsParseModuleBlock() { const node2 = this.startNode(); this.scope.enter(0); this.expect(5); super.parseBlockOrModuleBlockBody(node2.body = [], void 0, true, 8); this.scope.exit(); return this.finishNode(node2, "TSModuleBlock"); } tsParseModuleOrNamespaceDeclaration(node2, nested = false) { node2.id = this.parseIdentifier(); if (!nested) { this.checkIdentifier(node2.id, 1024); } if (this.eat(16)) { const inner = this.startNode(); this.tsParseModuleOrNamespaceDeclaration(inner, true); node2.body = inner; } else { this.scope.enter(256); this.prodParam.enter(PARAM); node2.body = this.tsParseModuleBlock(); this.prodParam.exit(); this.scope.exit(); } return this.finishNode(node2, "TSModuleDeclaration"); } tsParseAmbientExternalModuleDeclaration(node2) { if (this.isContextual(112)) { node2.global = true; node2.id = this.parseIdentifier(); } else if (this.match(133)) { node2.id = super.parseStringLiteral(this.state.value); } else { this.unexpected(); } if (this.match(5)) { this.scope.enter(256); this.prodParam.enter(PARAM); node2.body = this.tsParseModuleBlock(); this.prodParam.exit(); this.scope.exit(); } else { this.semicolon(); } return this.finishNode(node2, "TSModuleDeclaration"); } tsParseImportEqualsDeclaration(node2, maybeDefaultIdentifier, isExport) { node2.isExport = isExport || false; node2.id = maybeDefaultIdentifier || this.parseIdentifier(); this.checkIdentifier(node2.id, 4096); this.expect(29); const moduleReference = this.tsParseModuleReference(); if (node2.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") { this.raise(TSErrors.ImportAliasHasImportType, { at: moduleReference }); } node2.moduleReference = moduleReference; this.semicolon(); return this.finishNode(node2, "TSImportEqualsDeclaration"); } tsIsExternalModuleReference() { return this.isContextual(119) && this.lookaheadCharCode() === 40; } tsParseModuleReference() { return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false); } tsParseExternalModuleReference() { const node2 = this.startNode(); this.expectContextual(119); this.expect(10); if (!this.match(133)) { this.unexpected(); } node2.expression = super.parseExprAtom(); this.expect(11); this.sawUnambiguousESM = true; return this.finishNode(node2, "TSExternalModuleReference"); } tsLookAhead(f) { const state = this.state.clone(); const res = f(); this.state = state; return res; } tsTryParseAndCatch(f) { const result = this.tryParse((abort) => f() || abort()); if (result.aborted || !result.node) return; if (result.error) this.state = result.failState; return result.node; } tsTryParse(f) { const state = this.state.clone(); const result = f(); if (result !== void 0 && result !== false) { return result; } this.state = state; } tsTryParseDeclare(nany) { if (this.isLineTerminator()) { return; } let startType = this.state.type; let kind; if (this.isContextual(100)) { startType = 74; kind = "let"; } return this.tsInAmbientContext(() => { switch (startType) { case 68: nany.declare = true; return super.parseFunctionStatement(nany, false, false); case 80: nany.declare = true; return this.parseClass(nany, true, false); case 126: return this.tsParseEnumDeclaration(nany, { declare: true }); case 112: return this.tsParseAmbientExternalModuleDeclaration(nany); case 75: case 74: if (!this.match(75) || !this.isLookaheadContextual("enum")) { nany.declare = true; return this.parseVarStatement(nany, kind || this.state.value, true); } this.expect(75); return this.tsParseEnumDeclaration(nany, { const: true, declare: true }); case 129: { const result = this.tsParseInterfaceDeclaration(nany, { declare: true }); if (result) return result; } default: if (tokenIsIdentifier(startType)) { return this.tsParseDeclaration(nany, this.state.value, true, null); } } }); } tsTryParseExportDeclaration() { return this.tsParseDeclaration(this.startNode(), this.state.value, true, null); } tsParseExpressionStatement(node2, expr, decorators) { switch (expr.name) { case "declare": { const declaration = this.tsTryParseDeclare(node2); if (declaration) { declaration.declare = true; } return declaration; } case "global": if (this.match(5)) { this.scope.enter(256); this.prodParam.enter(PARAM); const mod = node2; mod.global = true; mod.id = expr; mod.body = this.tsParseModuleBlock(); this.scope.exit(); this.prodParam.exit(); return this.finishNode(mod, "TSModuleDeclaration"); } break; default: return this.tsParseDeclaration(node2, expr.name, false, decorators); } } tsParseDeclaration(node2, value, next, decorators) { switch (value) { case "abstract": if (this.tsCheckLineTerminator(next) && (this.match(80) || tokenIsIdentifier(this.state.type))) { return this.tsParseAbstractDeclaration(node2, decorators); } break; case "module": if (this.tsCheckLineTerminator(next)) { if (this.match(133)) { return this.tsParseAmbientExternalModuleDeclaration(node2); } else if (tokenIsIdentifier(this.state.type)) { return this.tsParseModuleOrNamespaceDeclaration(node2); } } break; case "namespace": if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) { return this.tsParseModuleOrNamespaceDeclaration(node2); } break; case "type": if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) { return this.tsParseTypeAliasDeclaration(node2); } break; } } tsCheckLineTerminator(next) { if (next) { if (this.hasFollowingLineBreak()) return false; this.next(); return true; } return !this.isLineTerminator(); } tsTryParseGenericAsyncArrowFunction(startLoc) { if (!this.match(47)) return; const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; this.state.maybeInArrowParameters = true; const res = this.tsTryParseAndCatch(() => { const node2 = this.startNodeAt(startLoc); node2.typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier); super.parseFunctionParams(node2); node2.returnType = this.tsTryParseTypeOrTypePredicateAnnotation(); this.expect(19); return node2; }); this.state.maybeInArrowParameters = oldMaybeInArrowParameters; if (!res) return; return super.parseArrowExpression(res, null, true); } tsParseTypeArgumentsInExpression() { if (this.reScan_lt() !== 47) return; return this.tsParseTypeArguments(); } tsParseTypeArguments() { const node2 = this.startNode(); node2.params = this.tsInType(() => this.tsInNoContext(() => { this.expect(47); return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this)); })); if (node2.params.length === 0) { this.raise(TSErrors.EmptyTypeArguments, { at: node2 }); } else if (!this.state.inType && this.curContext() === types.brace) { this.reScan_lt_gt(); } this.expect(48); return this.finishNode(node2, "TSTypeParameterInstantiation"); } tsIsDeclarationStart() { return tokenIsTSDeclarationStart(this.state.type); } isExportDefaultSpecifier() { if (this.tsIsDeclarationStart()) return false; return super.isExportDefaultSpecifier(); } parseAssignableListItem(flags, decorators) { const startLoc = this.state.startLoc; const modified = {}; this.tsParseModifiers({ allowedModifiers: ["public", "private", "protected", "override", "readonly"] }, modified); const accessibility = modified.accessibility; const override = modified.override; const readonly = modified.readonly; if (!(flags & 4) && (accessibility || readonly || override)) { this.raise(TSErrors.UnexpectedParameterModifier, { at: startLoc }); } const left = this.parseMaybeDefault(); this.parseAssignableListItemTypes(left, flags); const elt = this.parseMaybeDefault(left.loc.start, left); if (accessibility || readonly || override) { const pp = this.startNodeAt(startLoc); if (decorators.length) { pp.decorators = decorators; } if (accessibility) pp.accessibility = accessibility; if (readonly) pp.readonly = readonly; if (override) pp.override = override; if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") { this.raise(TSErrors.UnsupportedParameterPropertyKind, { at: pp }); } pp.parameter = elt; return this.finishNode(pp, "TSParameterProperty"); } if (decorators.length) { left.decorators = decorators; } return elt; } isSimpleParameter(node2) { return node2.type === "TSParameterProperty" && super.isSimpleParameter(node2.parameter) || super.isSimpleParameter(node2); } tsDisallowOptionalPattern(node2) { for (const param of node2.params) { if (param.type !== "Identifier" && param.optional && !this.state.isAmbientContext) { this.raise(TSErrors.PatternIsOptional, { at: param }); } } } setArrowFunctionParameters(node2, params, trailingCommaLoc) { super.setArrowFunctionParameters(node2, params, trailingCommaLoc); this.tsDisallowOptionalPattern(node2); } parseFunctionBodyAndFinish(node2, type2, isMethod = false) { if (this.match(14)) { node2.returnType = this.tsParseTypeOrTypePredicateAnnotation(14); } const bodilessType = type2 === "FunctionDeclaration" ? "TSDeclareFunction" : type2 === "ClassMethod" || type2 === "ClassPrivateMethod" ? "TSDeclareMethod" : void 0; if (bodilessType && !this.match(5) && this.isLineTerminator()) { return this.finishNode(node2, bodilessType); } if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) { this.raise(TSErrors.DeclareFunctionHasImplementation, { at: node2 }); if (node2.declare) { return super.parseFunctionBodyAndFinish(node2, bodilessType, isMethod); } } this.tsDisallowOptionalPattern(node2); return super.parseFunctionBodyAndFinish(node2, type2, isMethod); } registerFunctionStatementId(node2) { if (!node2.body && node2.id) { this.checkIdentifier(node2.id, 1024); } else { super.registerFunctionStatementId(node2); } } tsCheckForInvalidTypeCasts(items) { items.forEach((node2) => { if ((node2 == null ? void 0 : node2.type) === "TSTypeCastExpression") { this.raise(TSErrors.UnexpectedTypeAnnotation, { at: node2.typeAnnotation }); } }); } toReferencedList(exprList, isInParens) { this.tsCheckForInvalidTypeCasts(exprList); return exprList; } parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) { const node2 = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors); if (node2.type === "ArrayExpression") { this.tsCheckForInvalidTypeCasts(node2.elements); } return node2; } parseSubscript(base, startLoc, noCalls, state) { if (!this.hasPrecedingLineBreak() && this.match(35)) { this.state.canStartJSXElement = false; this.next(); const nonNullExpression = this.startNodeAt(startLoc); nonNullExpression.expression = base; return this.finishNode(nonNullExpression, "TSNonNullExpression"); } let isOptionalCall = false; if (this.match(18) && this.lookaheadCharCode() === 60) { if (noCalls) { state.stop = true; return base; } state.optionalChainMember = isOptionalCall = true; this.next(); } if (this.match(47) || this.match(51)) { let missingParenErrorLoc; const result = this.tsTryParseAndCatch(() => { if (!noCalls && this.atPossibleAsyncArrow(base)) { const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startLoc); if (asyncArrowFn) { return asyncArrowFn; } } const typeArguments = this.tsParseTypeArgumentsInExpression(); if (!typeArguments) return; if (isOptionalCall && !this.match(10)) { missingParenErrorLoc = this.state.curPosition(); return; } if (tokenIsTemplate(this.state.type)) { const result2 = super.parseTaggedTemplateExpression(base, startLoc, state); result2.typeParameters = typeArguments; return result2; } if (!noCalls && this.eat(10)) { const node3 = this.startNodeAt(startLoc); node3.callee = base; node3.arguments = this.parseCallExpressionArguments(11, false); this.tsCheckForInvalidTypeCasts(node3.arguments); node3.typeParameters = typeArguments; if (state.optionalChainMember) { node3.optional = isOptionalCall; } return this.finishCallExpression(node3, state.optionalChainMember); } const tokenType = this.state.type; if (tokenType === 48 || tokenType === 52 || tokenType !== 10 && tokenCanStartExpression(tokenType) && !this.hasPrecedingLineBreak()) { return; } const node2 = this.startNodeAt(startLoc); node2.expression = base; node2.typeParameters = typeArguments; return this.finishNode(node2, "TSInstantiationExpression"); }); if (missingParenErrorLoc) { this.unexpected(missingParenErrorLoc, 10); } if (result) { if (result.type === "TSInstantiationExpression" && (this.match(16) || this.match(18) && this.lookaheadCharCode() !== 40)) { this.raise(TSErrors.InvalidPropertyAccessAfterInstantiationExpression, { at: this.state.startLoc }); } return result; } } return super.parseSubscript(base, startLoc, noCalls, state); } parseNewCallee(node2) { var _callee$extra; super.parseNewCallee(node2); const { callee } = node2; if (callee.type === "TSInstantiationExpression" && !((_callee$extra = callee.extra) != null && _callee$extra.parenthesized)) { node2.typeParameters = callee.typeParameters; node2.callee = callee.expression; } } parseExprOp(left, leftStartLoc, minPrec) { let isSatisfies; if (tokenOperatorPrecedence(58) > minPrec && !this.hasPrecedingLineBreak() && (this.isContextual(93) || (isSatisfies = this.isContextual(120)))) { const node2 = this.startNodeAt(leftStartLoc); node2.expression = left; node2.typeAnnotation = this.tsInType(() => { this.next(); if (this.match(75)) { if (isSatisfies) { this.raise(Errors.UnexpectedKeyword, { at: this.state.startLoc, keyword: "const" }); } return this.tsParseTypeReference(); } return this.tsParseType(); }); this.finishNode(node2, isSatisfies ? "TSSatisfiesExpression" : "TSAsExpression"); this.reScan_lt_gt(); return this.parseExprOp(node2, leftStartLoc, minPrec); } return super.parseExprOp(left, leftStartLoc, minPrec); } checkReservedWord(word, startLoc, checkKeywords, isBinding) { if (!this.state.isAmbientContext) { super.checkReservedWord(word, startLoc, checkKeywords, isBinding); } } checkImportReflection(node2) { super.checkImportReflection(node2); if (node2.module && node2.importKind !== "value") { this.raise(TSErrors.ImportReflectionHasImportType, { at: node2.specifiers[0].loc.start }); } } checkDuplicateExports() { } isPotentialImportPhase(isExport) { if (super.isPotentialImportPhase(isExport)) return true; if (this.isContextual(130)) { const ch = this.lookaheadCharCode(); return isExport ? ch === 123 || ch === 42 : ch !== 61; } return !isExport && this.isContextual(87); } applyImportPhase(node2, isExport, phase, loc) { super.applyImportPhase(node2, isExport, phase, loc); if (isExport) { node2.exportKind = phase === "type" ? "type" : "value"; } else { node2.importKind = phase === "type" || phase === "typeof" ? phase : "value"; } } parseImport(node2) { if (this.match(133)) { node2.importKind = "value"; return super.parseImport(node2); } let importNode; if (tokenIsIdentifier(this.state.type) && this.lookaheadCharCode() === 61) { node2.importKind = "value"; return this.tsParseImportEqualsDeclaration(node2); } else if (this.isContextual(130)) { const maybeDefaultIdentifier = this.parseMaybeImportPhase(node2, false); if (this.lookaheadCharCode() === 61) { return this.tsParseImportEqualsDeclaration(node2, maybeDefaultIdentifier); } else { importNode = super.parseImportSpecifiersAndAfter(node2, maybeDefaultIdentifier); } } else { importNode = super.parseImport(node2); } if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") { this.raise(TSErrors.TypeImportCannotSpecifyDefaultAndNamed, { at: importNode }); } return importNode; } parseExport(node2, decorators) { if (this.match(83)) { this.next(); let maybeDefaultIdentifier = null; if (this.isContextual(130) && this.isPotentialImportPhase(false)) { maybeDefaultIdentifier = this.parseMaybeImportPhase(node2, false); } else { node2.importKind = "value"; } return this.tsParseImportEqualsDeclaration(node2, maybeDefaultIdentifier, true); } else if (this.eat(29)) { const assign = node2; assign.expression = super.parseExpression(); this.semicolon(); this.sawUnambiguousESM = true; return this.finishNode(assign, "TSExportAssignment"); } else if (this.eatContextual(93)) { const decl = node2; this.expectContextual(128); decl.id = this.parseIdentifier(); this.semicolon(); return this.finishNode(decl, "TSNamespaceExportDeclaration"); } else { return super.parseExport(node2, decorators); } } isAbstractClass() { return this.isContextual(124) && this.lookahead().type === 80; } parseExportDefaultExpression() { if (this.isAbstractClass()) { const cls = this.startNode(); this.next(); cls.abstract = true; return this.parseClass(cls, true, true); } if (this.match(129)) { const result = this.tsParseInterfaceDeclaration(this.startNode()); if (result) return result; } return super.parseExportDefaultExpression(); } parseVarStatement(node2, kind, allowMissingInitializer = false) { const { isAmbientContext } = this.state; const declaration = super.parseVarStatement(node2, kind, allowMissingInitializer || isAmbientContext); if (!isAmbientContext) return declaration; for (const { id, init } of declaration.declarations) { if (!init) continue; if (kind !== "const" || !!id.typeAnnotation) { this.raise(TSErrors.InitializerNotAllowedInAmbientContext, { at: init }); } else if (!isValidAmbientConstInitializer(init, this.hasPlugin("estree"))) { this.raise(TSErrors.ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference, { at: init }); } } return declaration; } parseStatementContent(flags, decorators) { if (this.match(75) && this.isLookaheadContextual("enum")) { const node2 = this.startNode(); this.expect(75); return this.tsParseEnumDeclaration(node2, { const: true }); } if (this.isContextual(126)) { return this.tsParseEnumDeclaration(this.startNode()); } if (this.isContextual(129)) { const result = this.tsParseInterfaceDeclaration(this.startNode()); if (result) return result; } return super.parseStatementContent(flags, decorators); } parseAccessModifier() { return this.tsParseModifier(["public", "protected", "private"]); } tsHasSomeModifiers(member, modifiers) { return modifiers.some((modifier) => { if (tsIsAccessModifier(modifier)) { return member.accessibility === modifier; } return !!member[modifier]; }); } tsIsStartOfStaticBlocks() { return this.isContextual(106) && this.lookaheadCharCode() === 123; } parseClassMember(classBody, member, state) { const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"]; this.tsParseModifiers({ allowedModifiers: modifiers, disallowedModifiers: ["in", "out"], stopOnStartOfClassStaticBlock: true, errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions }, member); const callParseClassMemberWithIsStatic = () => { if (this.tsIsStartOfStaticBlocks()) { this.next(); this.next(); if (this.tsHasSomeModifiers(member, modifiers)) { this.raise(TSErrors.StaticBlockCannotHaveModifier, { at: this.state.curPosition() }); } super.parseClassStaticBlock(classBody, member); } else { this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static); } }; if (member.declare) { this.tsInAmbientContext(callParseClassMemberWithIsStatic); } else { callParseClassMemberWithIsStatic(); } } parseClassMemberWithIsStatic(classBody, member, state, isStatic) { const idx = this.tsTryParseIndexSignature(member); if (idx) { classBody.body.push(idx); if (member.abstract) { this.raise(TSErrors.IndexSignatureHasAbstract, { at: member }); } if (member.accessibility) { this.raise(TSErrors.IndexSignatureHasAccessibility, { at: member, modifier: member.accessibility }); } if (member.declare) { this.raise(TSErrors.IndexSignatureHasDeclare, { at: member }); } if (member.override) { this.raise(TSErrors.IndexSignatureHasOverride, { at: member }); } return; } if (!this.state.inAbstractClass && member.abstract) { this.raise(TSErrors.NonAbstractClassHasAbstractMethod, { at: member }); } if (member.override) { if (!state.hadSuperClass) { this.raise(TSErrors.OverrideNotInSubClass, { at: member }); } } super.parseClassMemberWithIsStatic(classBody, member, state, isStatic); } parsePostMemberNameModifiers(methodOrProp) { const optional = this.eat(17); if (optional) methodOrProp.optional = true; if (methodOrProp.readonly && this.match(10)) { this.raise(TSErrors.ClassMethodHasReadonly, { at: methodOrProp }); } if (methodOrProp.declare && this.match(10)) { this.raise(TSErrors.ClassMethodHasDeclare, { at: methodOrProp }); } } parseExpressionStatement(node2, expr, decorators) { const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node2, expr, decorators) : void 0; return decl || super.parseExpressionStatement(node2, expr, decorators); } shouldParseExportDeclaration() { if (this.tsIsDeclarationStart()) return true; return super.shouldParseExportDeclaration(); } parseConditional(expr, startLoc, refExpressionErrors) { if (!this.state.maybeInArrowParameters || !this.match(17)) { return super.parseConditional(expr, startLoc, refExpressionErrors); } const result = this.tryParse(() => super.parseConditional(expr, startLoc)); if (!result.node) { if (result.error) { super.setOptionalParametersError(refExpressionErrors, result.error); } return expr; } if (result.error) this.state = result.failState; return result.node; } parseParenItem(node2, startLoc) { node2 = super.parseParenItem(node2, startLoc); if (this.eat(17)) { node2.optional = true; this.resetEndLocation(node2); } if (this.match(14)) { const typeCastNode = this.startNodeAt(startLoc); typeCastNode.expression = node2; typeCastNode.typeAnnotation = this.tsParseTypeAnnotation(); return this.finishNode(typeCastNode, "TSTypeCastExpression"); } return node2; } parseExportDeclaration(node2) { if (!this.state.isAmbientContext && this.isContextual(125)) { return this.tsInAmbientContext(() => this.parseExportDeclaration(node2)); } const startLoc = this.state.startLoc; const isDeclare = this.eatContextual(125); if (isDeclare && (this.isContextual(125) || !this.shouldParseExportDeclaration())) { throw this.raise(TSErrors.ExpectedAmbientAfterExportDeclare, { at: this.state.startLoc }); } const isIdentifier = tokenIsIdentifier(this.state.type); const declaration = isIdentifier && this.tsTryParseExportDeclaration() || super.parseExportDeclaration(node2); if (!declaration) return null; if (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare) { node2.exportKind = "type"; } if (isDeclare) { this.resetStartLocation(declaration, startLoc); declaration.declare = true; } return declaration; } parseClassId(node2, isStatement, optionalId, bindingType) { if ((!isStatement || optionalId) && this.isContextual(113)) { return; } super.parseClassId(node2, isStatement, optionalId, node2.declare ? 1024 : 8331); const typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers); if (typeParameters) node2.typeParameters = typeParameters; } parseClassPropertyAnnotation(node2) { if (!node2.optional) { if (this.eat(35)) { node2.definite = true; } else if (this.eat(17)) { node2.optional = true; } } const type2 = this.tsTryParseTypeAnnotation(); if (type2) node2.typeAnnotation = type2; } parseClassProperty(node2) { this.parseClassPropertyAnnotation(node2); if (this.state.isAmbientContext && !(node2.readonly && !node2.typeAnnotation) && this.match(29)) { this.raise(TSErrors.DeclareClassFieldHasInitializer, { at: this.state.startLoc }); } if (node2.abstract && this.match(29)) { const { key } = node2; this.raise(TSErrors.AbstractPropertyHasInitializer, { at: this.state.startLoc, propertyName: key.type === "Identifier" && !node2.computed ? key.name : `[${this.input.slice(key.start, key.end)}]` }); } return super.parseClassProperty(node2); } parseClassPrivateProperty(node2) { if (node2.abstract) { this.raise(TSErrors.PrivateElementHasAbstract, { at: node2 }); } if (node2.accessibility) { this.raise(TSErrors.PrivateElementHasAccessibility, { at: node2, modifier: node2.accessibility }); } this.parseClassPropertyAnnotation(node2); return super.parseClassPrivateProperty(node2); } parseClassAccessorProperty(node2) { this.parseClassPropertyAnnotation(node2); if (node2.optional) { this.raise(TSErrors.AccessorCannotBeOptional, { at: node2 }); } return super.parseClassAccessorProperty(node2); } pushClassMethod(classBody, method, isGenerator, isAsync2, isConstructor, allowsDirectSuper) { const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); if (typeParameters && isConstructor) { this.raise(TSErrors.ConstructorHasTypeParameters, { at: typeParameters }); } const { declare = false, kind } = method; if (declare && (kind === "get" || kind === "set")) { this.raise(TSErrors.DeclareAccessor, { at: method, kind }); } if (typeParameters) method.typeParameters = typeParameters; super.pushClassMethod(classBody, method, isGenerator, isAsync2, isConstructor, allowsDirectSuper); } pushClassPrivateMethod(classBody, method, isGenerator, isAsync2) { const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); if (typeParameters) method.typeParameters = typeParameters; super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync2); } declareClassPrivateMethodInScope(node2, kind) { if (node2.type === "TSDeclareMethod") return; if (node2.type === "MethodDefinition" && !node2.value.body) return; super.declareClassPrivateMethodInScope(node2, kind); } parseClassSuper(node2) { super.parseClassSuper(node2); if (node2.superClass && (this.match(47) || this.match(51))) { node2.superTypeParameters = this.tsParseTypeArgumentsInExpression(); } if (this.eatContextual(113)) { node2.implements = this.tsParseHeritageClause("implements"); } } parseObjPropValue(prop, startLoc, isGenerator, isAsync2, isPattern, isAccessor, refExpressionErrors) { const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); if (typeParameters) prop.typeParameters = typeParameters; return super.parseObjPropValue(prop, startLoc, isGenerator, isAsync2, isPattern, isAccessor, refExpressionErrors); } parseFunctionParams(node2, isConstructor) { const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier); if (typeParameters) node2.typeParameters = typeParameters; super.parseFunctionParams(node2, isConstructor); } parseVarId(decl, kind) { super.parseVarId(decl, kind); if (decl.id.type === "Identifier" && !this.hasPrecedingLineBreak() && this.eat(35)) { decl.definite = true; } const type2 = this.tsTryParseTypeAnnotation(); if (type2) { decl.id.typeAnnotation = type2; this.resetEndLocation(decl.id); } } parseAsyncArrowFromCallExpression(node2, call) { if (this.match(14)) { node2.returnType = this.tsParseTypeAnnotation(); } return super.parseAsyncArrowFromCallExpression(node2, call); } parseMaybeAssign(refExpressionErrors, afterLeftParse) { var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2; let state; let jsx2; let typeCast; if (this.hasPlugin("jsx") && (this.match(142) || this.match(47))) { state = this.state.clone(); jsx2 = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); if (!jsx2.error) return jsx2.node; const { context } = this.state; const currentContext = context[context.length - 1]; if (currentContext === types.j_oTag || currentContext === types.j_expr) { context.pop(); } } if (!((_jsx = jsx2) != null && _jsx.error) && !this.match(47)) { return super.parseMaybeAssign(refExpressionErrors, afterLeftParse); } if (!state || state === this.state) state = this.state.clone(); let typeParameters; const arrow = this.tryParse((abort) => { var _expr$extra, _typeParameters; typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier); const expr = super.parseMaybeAssign(refExpressionErrors, afterLeftParse); if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) { abort(); } if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) { this.resetStartLocationFromNode(expr, typeParameters); } expr.typeParameters = typeParameters; return expr; }, state); if (!arrow.error && !arrow.aborted) { if (typeParameters) this.reportReservedArrowTypeParam(typeParameters); return arrow.node; } if (!jsx2) { assert(!this.hasPlugin("jsx")); typeCast = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state); if (!typeCast.error) return typeCast.node; } if ((_jsx2 = jsx2) != null && _jsx2.node) { this.state = jsx2.failState; return jsx2.node; } if (arrow.node) { this.state = arrow.failState; if (typeParameters) this.reportReservedArrowTypeParam(typeParameters); return arrow.node; } if ((_typeCast = typeCast) != null && _typeCast.node) { this.state = typeCast.failState; return typeCast.node; } throw ((_jsx3 = jsx2) == null ? void 0 : _jsx3.error) || arrow.error || ((_typeCast2 = typeCast) == null ? void 0 : _typeCast2.error); } reportReservedArrowTypeParam(node2) { var _node$extra; if (node2.params.length === 1 && !node2.params[0].constraint && !((_node$extra = node2.extra) != null && _node$extra.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) { this.raise(TSErrors.ReservedArrowTypeParam, { at: node2 }); } } parseMaybeUnary(refExpressionErrors, sawUnary) { if (!this.hasPlugin("jsx") && this.match(47)) { return this.tsParseTypeAssertion(); } return super.parseMaybeUnary(refExpressionErrors, sawUnary); } parseArrow(node2) { if (this.match(14)) { const result = this.tryParse((abort) => { const returnType = this.tsParseTypeOrTypePredicateAnnotation(14); if (this.canInsertSemicolon() || !this.match(19)) abort(); return returnType; }); if (result.aborted) return; if (!result.thrown) { if (result.error) this.state = result.failState; node2.returnType = result.node; } } return super.parseArrow(node2); } parseAssignableListItemTypes(param, flags) { if (!(flags & 2)) return param; if (this.eat(17)) { param.optional = true; } const type2 = this.tsTryParseTypeAnnotation(); if (type2) param.typeAnnotation = type2; this.resetEndLocation(param); return param; } isAssignable(node2, isBinding) { switch (node2.type) { case "TSTypeCastExpression": return this.isAssignable(node2.expression, isBinding); case "TSParameterProperty": return true; default: return super.isAssignable(node2, isBinding); } } toAssignable(node2, isLHS = false) { switch (node2.type) { case "ParenthesizedExpression": this.toAssignableParenthesizedExpression(node2, isLHS); break; case "TSAsExpression": case "TSSatisfiesExpression": case "TSNonNullExpression": case "TSTypeAssertion": if (isLHS) { this.expressionScope.recordArrowParameterBindingError(TSErrors.UnexpectedTypeCastInParameter, { at: node2 }); } else { this.raise(TSErrors.UnexpectedTypeCastInParameter, { at: node2 }); } this.toAssignable(node2.expression, isLHS); break; case "AssignmentExpression": if (!isLHS && node2.left.type === "TSTypeCastExpression") { node2.left = this.typeCastToParameter(node2.left); } default: super.toAssignable(node2, isLHS); } } toAssignableParenthesizedExpression(node2, isLHS) { switch (node2.expression.type) { case "TSAsExpression": case "TSSatisfiesExpression": case "TSNonNullExpression": case "TSTypeAssertion": case "ParenthesizedExpression": this.toAssignable(node2.expression, isLHS); break; default: super.toAssignable(node2, isLHS); } } checkToRestConversion(node2, allowPattern) { switch (node2.type) { case "TSAsExpression": case "TSSatisfiesExpression": case "TSTypeAssertion": case "TSNonNullExpression": this.checkToRestConversion(node2.expression, false); break; default: super.checkToRestConversion(node2, allowPattern); } } isValidLVal(type2, isUnparenthesizedInAssign, binding) { return getOwn({ TSTypeCastExpression: true, TSParameterProperty: "parameter", TSNonNullExpression: "expression", TSAsExpression: (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true], TSSatisfiesExpression: (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true], TSTypeAssertion: (binding !== 64 || !isUnparenthesizedInAssign) && ["expression", true] }, type2) || super.isValidLVal(type2, isUnparenthesizedInAssign, binding); } parseBindingAtom() { if (this.state.type === 78) { return this.parseIdentifier(true); } return super.parseBindingAtom(); } parseMaybeDecoratorArguments(expr) { if (this.match(47) || this.match(51)) { const typeArguments = this.tsParseTypeArgumentsInExpression(); if (this.match(10)) { const call = super.parseMaybeDecoratorArguments(expr); call.typeParameters = typeArguments; return call; } this.unexpected(null, 10); } return super.parseMaybeDecoratorArguments(expr); } checkCommaAfterRest(close) { if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) { this.next(); return false; } return super.checkCommaAfterRest(close); } isClassMethod() { return this.match(47) || super.isClassMethod(); } isClassProperty() { return this.match(35) || this.match(14) || super.isClassProperty(); } parseMaybeDefault(startLoc, left) { const node2 = super.parseMaybeDefault(startLoc, left); if (node2.type === "AssignmentPattern" && node2.typeAnnotation && node2.right.start < node2.typeAnnotation.start) { this.raise(TSErrors.TypeAnnotationAfterAssign, { at: node2.typeAnnotation }); } return node2; } getTokenFromCode(code2) { if (this.state.inType) { if (code2 === 62) { this.finishOp(48, 1); return; } if (code2 === 60) { this.finishOp(47, 1); return; } } super.getTokenFromCode(code2); } reScan_lt_gt() { const { type: type2 } = this.state; if (type2 === 47) { this.state.pos -= 1; this.readToken_lt(); } else if (type2 === 48) { this.state.pos -= 1; this.readToken_gt(); } } reScan_lt() { const { type: type2 } = this.state; if (type2 === 51) { this.state.pos -= 2; this.finishOp(47, 1); return 47; } return type2; } toAssignableList(exprList, trailingCommaLoc, isLHS) { for (let i2 = 0; i2 < exprList.length; i2++) { const expr = exprList[i2]; if ((expr == null ? void 0 : expr.type) === "TSTypeCastExpression") { exprList[i2] = this.typeCastToParameter(expr); } } super.toAssignableList(exprList, trailingCommaLoc, isLHS); } typeCastToParameter(node2) { node2.expression.typeAnnotation = node2.typeAnnotation; this.resetEndLocation(node2.expression, node2.typeAnnotation.loc.end); return node2.expression; } shouldParseArrow(params) { if (this.match(14)) { return params.every((expr) => this.isAssignable(expr, true)); } return super.shouldParseArrow(params); } shouldParseAsyncArrow() { return this.match(14) || super.shouldParseAsyncArrow(); } canHaveLeadingDecorator() { return super.canHaveLeadingDecorator() || this.isAbstractClass(); } jsxParseOpeningElementAfterName(node2) { if (this.match(47) || this.match(51)) { const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArgumentsInExpression()); if (typeArguments) node2.typeParameters = typeArguments; } return super.jsxParseOpeningElementAfterName(node2); } getGetterSetterExpectedParamCount(method) { const baseCount = super.getGetterSetterExpectedParamCount(method); const params = this.getObjectOrClassMethodParams(method); const firstParam = params[0]; const hasContextParam = firstParam && this.isThisParam(firstParam); return hasContextParam ? baseCount + 1 : baseCount; } parseCatchClauseParam() { const param = super.parseCatchClauseParam(); const type2 = this.tsTryParseTypeAnnotation(); if (type2) { param.typeAnnotation = type2; this.resetEndLocation(param); } return param; } tsInAmbientContext(cb) { const oldIsAmbientContext = this.state.isAmbientContext; this.state.isAmbientContext = true; try { return cb(); } finally { this.state.isAmbientContext = oldIsAmbientContext; } } parseClass(node2, isStatement, optionalId) { const oldInAbstractClass = this.state.inAbstractClass; this.state.inAbstractClass = !!node2.abstract; try { return super.parseClass(node2, isStatement, optionalId); } finally { this.state.inAbstractClass = oldInAbstractClass; } } tsParseAbstractDeclaration(node2, decorators) { if (this.match(80)) { node2.abstract = true; return this.maybeTakeDecorators(decorators, this.parseClass(node2, true, false)); } else if (this.isContextual(129)) { if (!this.hasFollowingLineBreak()) { node2.abstract = true; this.raise(TSErrors.NonClassMethodPropertyHasAbstractModifer, { at: node2 }); return this.tsParseInterfaceDeclaration(node2); } } else { this.unexpected(null, 80); } } parseMethod(node2, isGenerator, isAsync2, isConstructor, allowDirectSuper, type2, inClassScope) { const method = super.parseMethod(node2, isGenerator, isAsync2, isConstructor, allowDirectSuper, type2, inClassScope); if (method.abstract) { const hasBody = this.hasPlugin("estree") ? !!method.value.body : !!method.body; if (hasBody) { const { key } = method; this.raise(TSErrors.AbstractMethodHasImplementation, { at: method, methodName: key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(key.start, key.end)}]` }); } } return method; } tsParseTypeParameterName() { const typeName = this.parseIdentifier(); return typeName.name; } shouldParseAsAmbientContext() { return !!this.getPluginOption("typescript", "dts"); } parse() { if (this.shouldParseAsAmbientContext()) { this.state.isAmbientContext = true; } return super.parse(); } getExpression() { if (this.shouldParseAsAmbientContext()) { this.state.isAmbientContext = true; } return super.getExpression(); } parseExportSpecifier(node2, isString, isInTypeExport, isMaybeTypeOnly) { if (!isString && isMaybeTypeOnly) { this.parseTypeOnlyImportExportSpecifier(node2, false, isInTypeExport); return this.finishNode(node2, "ExportSpecifier"); } node2.exportKind = "value"; return super.parseExportSpecifier(node2, isString, isInTypeExport, isMaybeTypeOnly); } parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { if (!importedIsString && isMaybeTypeOnly) { this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport); return this.finishNode(specifier, "ImportSpecifier"); } specifier.importKind = "value"; return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? 4098 : 4096); } parseTypeOnlyImportExportSpecifier(node2, isImport, isInTypeOnlyImportExport) { const leftOfAsKey = isImport ? "imported" : "local"; const rightOfAsKey = isImport ? "local" : "exported"; let leftOfAs = node2[leftOfAsKey]; let rightOfAs; let hasTypeSpecifier = false; let canParseAsKeyword = true; const loc = leftOfAs.loc.start; if (this.isContextual(93)) { const firstAs = this.parseIdentifier(); if (this.isContextual(93)) { const secondAs = this.parseIdentifier(); if (tokenIsKeywordOrIdentifier(this.state.type)) { hasTypeSpecifier = true; leftOfAs = firstAs; rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName(); canParseAsKeyword = false; } else { rightOfAs = secondAs; canParseAsKeyword = false; } } else if (tokenIsKeywordOrIdentifier(this.state.type)) { canParseAsKeyword = false; rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName(); } else { hasTypeSpecifier = true; leftOfAs = firstAs; } } else if (tokenIsKeywordOrIdentifier(this.state.type)) { hasTypeSpecifier = true; if (isImport) { leftOfAs = this.parseIdentifier(true); if (!this.isContextual(93)) { this.checkReservedWord(leftOfAs.name, leftOfAs.loc.start, true, true); } } else { leftOfAs = this.parseModuleExportName(); } } if (hasTypeSpecifier && isInTypeOnlyImportExport) { this.raise(isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports, { at: loc }); } node2[leftOfAsKey] = leftOfAs; node2[rightOfAsKey] = rightOfAs; const kindKey = isImport ? "importKind" : "exportKind"; node2[kindKey] = hasTypeSpecifier ? "type" : "value"; if (canParseAsKeyword && this.eatContextual(93)) { node2[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName(); } if (!node2[rightOfAsKey]) { node2[rightOfAsKey] = cloneIdentifier(node2[leftOfAsKey]); } if (isImport) { this.checkIdentifier(node2[rightOfAsKey], hasTypeSpecifier ? 4098 : 4096); } } }; function isPossiblyLiteralEnum(expression) { if (expression.type !== "MemberExpression") return false; const { computed, property } = expression; if (computed && property.type !== "StringLiteral" && (property.type !== "TemplateLiteral" || property.expressions.length > 0)) { return false; } return isUncomputedMemberExpressionChain(expression.object); } function isValidAmbientConstInitializer(expression, estree2) { var _expression$extra; const { type: type2 } = expression; if ((_expression$extra = expression.extra) != null && _expression$extra.parenthesized) { return false; } if (estree2) { if (type2 === "Literal") { const { value } = expression; if (typeof value === "string" || typeof value === "boolean") { return true; } } } else { if (type2 === "StringLiteral" || type2 === "BooleanLiteral") { return true; } } if (isNumber(expression, estree2) || isNegativeNumber(expression, estree2)) { return true; } if (type2 === "TemplateLiteral" && expression.expressions.length === 0) { return true; } if (isPossiblyLiteralEnum(expression)) { return true; } return false; } function isNumber(expression, estree2) { if (estree2) { return expression.type === "Literal" && (typeof expression.value === "number" || "bigint" in expression); } return expression.type === "NumericLiteral" || expression.type === "BigIntLiteral"; } function isNegativeNumber(expression, estree2) { if (expression.type === "UnaryExpression") { const { operator, argument } = expression; if (operator === "-" && isNumber(argument, estree2)) { return true; } } return false; } function isUncomputedMemberExpressionChain(expression) { if (expression.type === "Identifier") return true; if (expression.type !== "MemberExpression" || expression.computed) { return false; } return isUncomputedMemberExpressionChain(expression.object); } var PlaceholderErrors = ParseErrorEnum`placeholders`({ ClassNameIsRequired: "A class name is required.", UnexpectedSpace: "Unexpected space in placeholder." }); var placeholders = (superClass) => class PlaceholdersParserMixin extends superClass { parsePlaceholder(expectedNode) { if (this.match(144)) { const node2 = this.startNode(); this.next(); this.assertNoSpace(); node2.name = super.parseIdentifier(true); this.assertNoSpace(); this.expect(144); return this.finishPlaceholder(node2, expectedNode); } } finishPlaceholder(node2, expectedNode) { const isFinished = !!(node2.expectedNode && node2.type === "Placeholder"); node2.expectedNode = expectedNode; return isFinished ? node2 : this.finishNode(node2, "Placeholder"); } getTokenFromCode(code2) { if (code2 === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) { this.finishOp(144, 2); } else { super.getTokenFromCode(code2); } } parseExprAtom(refExpressionErrors) { return this.parsePlaceholder("Expression") || super.parseExprAtom(refExpressionErrors); } parseIdentifier(liberal) { return this.parsePlaceholder("Identifier") || super.parseIdentifier(liberal); } checkReservedWord(word, startLoc, checkKeywords, isBinding) { if (word !== void 0) { super.checkReservedWord(word, startLoc, checkKeywords, isBinding); } } parseBindingAtom() { return this.parsePlaceholder("Pattern") || super.parseBindingAtom(); } isValidLVal(type2, isParenthesized, binding) { return type2 === "Placeholder" || super.isValidLVal(type2, isParenthesized, binding); } toAssignable(node2, isLHS) { if (node2 && node2.type === "Placeholder" && node2.expectedNode === "Expression") { node2.expectedNode = "Pattern"; } else { super.toAssignable(node2, isLHS); } } chStartsBindingIdentifier(ch, pos) { if (super.chStartsBindingIdentifier(ch, pos)) { return true; } const nextToken = this.lookahead(); if (nextToken.type === 144) { return true; } return false; } verifyBreakContinue(node2, isBreak) { if (node2.label && node2.label.type === "Placeholder") return; super.verifyBreakContinue(node2, isBreak); } parseExpressionStatement(node2, expr) { var _expr$extra; if (expr.type !== "Placeholder" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) { return super.parseExpressionStatement(node2, expr); } if (this.match(14)) { const stmt = node2; stmt.label = this.finishPlaceholder(expr, "Identifier"); this.next(); stmt.body = super.parseStatementOrSloppyAnnexBFunctionDeclaration(); return this.finishNode(stmt, "LabeledStatement"); } this.semicolon(); node2.name = expr.name; return this.finishPlaceholder(node2, "Statement"); } parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse) { return this.parsePlaceholder("BlockStatement") || super.parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse); } parseFunctionId(requireId) { return this.parsePlaceholder("Identifier") || super.parseFunctionId(requireId); } parseClass(node2, isStatement, optionalId) { const type2 = isStatement ? "ClassDeclaration" : "ClassExpression"; this.next(); const oldStrict = this.state.strict; const placeholder = this.parsePlaceholder("Identifier"); if (placeholder) { if (this.match(81) || this.match(144) || this.match(5)) { node2.id = placeholder; } else if (optionalId || !isStatement) { node2.id = null; node2.body = this.finishPlaceholder(placeholder, "ClassBody"); return this.finishNode(node2, type2); } else { throw this.raise(PlaceholderErrors.ClassNameIsRequired, { at: this.state.startLoc }); } } else { this.parseClassId(node2, isStatement, optionalId); } super.parseClassSuper(node2); node2.body = this.parsePlaceholder("ClassBody") || super.parseClassBody(!!node2.superClass, oldStrict); return this.finishNode(node2, type2); } parseExport(node2, decorators) { const placeholder = this.parsePlaceholder("Identifier"); if (!placeholder) return super.parseExport(node2, decorators); if (!this.isContextual(98) && !this.match(12)) { node2.specifiers = []; node2.source = null; node2.declaration = this.finishPlaceholder(placeholder, "Declaration"); return this.finishNode(node2, "ExportNamedDeclaration"); } this.expectPlugin("exportDefaultFrom"); const specifier = this.startNode(); specifier.exported = placeholder; node2.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; return super.parseExport(node2, decorators); } isExportDefaultSpecifier() { if (this.match(65)) { const next = this.nextTokenStart(); if (this.isUnparsedContextual(next, "from")) { if (this.input.startsWith(tokenLabelName(144), this.nextTokenStartSince(next + 4))) { return true; } } } return super.isExportDefaultSpecifier(); } maybeParseExportDefaultSpecifier(node2, maybeDefaultIdentifier) { var _specifiers; if ((_specifiers = node2.specifiers) != null && _specifiers.length) { return true; } return super.maybeParseExportDefaultSpecifier(node2, maybeDefaultIdentifier); } checkExport(node2) { const { specifiers } = node2; if (specifiers != null && specifiers.length) { node2.specifiers = specifiers.filter((node3) => node3.exported.type === "Placeholder"); } super.checkExport(node2); node2.specifiers = specifiers; } parseImport(node2) { const placeholder = this.parsePlaceholder("Identifier"); if (!placeholder) return super.parseImport(node2); node2.specifiers = []; if (!this.isContextual(98) && !this.match(12)) { node2.source = this.finishPlaceholder(placeholder, "StringLiteral"); this.semicolon(); return this.finishNode(node2, "ImportDeclaration"); } const specifier = this.startNodeAtNode(placeholder); specifier.local = placeholder; node2.specifiers.push(this.finishNode(specifier, "ImportDefaultSpecifier")); if (this.eat(12)) { const hasStarImport = this.maybeParseStarImportSpecifier(node2); if (!hasStarImport) this.parseNamedImportSpecifiers(node2); } this.expectContextual(98); node2.source = this.parseImportSource(); this.semicolon(); return this.finishNode(node2, "ImportDeclaration"); } parseImportSource() { return this.parsePlaceholder("StringLiteral") || super.parseImportSource(); } assertNoSpace() { if (this.state.start > this.state.lastTokEndLoc.index) { this.raise(PlaceholderErrors.UnexpectedSpace, { at: this.state.lastTokEndLoc }); } } }; var v8intrinsic = (superClass) => class V8IntrinsicMixin extends superClass { parseV8Intrinsic() { if (this.match(54)) { const v8IntrinsicStartLoc = this.state.startLoc; const node2 = this.startNode(); this.next(); if (tokenIsIdentifier(this.state.type)) { const name = this.parseIdentifierName(); const identifier = this.createIdentifier(node2, name); identifier.type = "V8IntrinsicIdentifier"; if (this.match(10)) { return identifier; } } this.unexpected(v8IntrinsicStartLoc); } } parseExprAtom(refExpressionErrors) { return this.parseV8Intrinsic() || super.parseExprAtom(refExpressionErrors); } }; function hasPlugin(plugins, expectedConfig) { const [expectedName, expectedOptions] = typeof expectedConfig === "string" ? [expectedConfig, {}] : expectedConfig; const expectedKeys = Object.keys(expectedOptions); const expectedOptionsIsEmpty = expectedKeys.length === 0; return plugins.some((p) => { if (typeof p === "string") { return expectedOptionsIsEmpty && p === expectedName; } else { const [pluginName, pluginOptions] = p; if (pluginName !== expectedName) { return false; } for (const key of expectedKeys) { if (pluginOptions[key] !== expectedOptions[key]) { return false; } } return true; } }); } function getPluginOption(plugins, name, option) { const plugin = plugins.find((plugin2) => { if (Array.isArray(plugin2)) { return plugin2[0] === name; } else { return plugin2 === name; } }); if (plugin && Array.isArray(plugin) && plugin.length > 1) { return plugin[1][option]; } return null; } var PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"]; var TOPIC_TOKENS = ["^^", "@@", "^", "%", "#"]; var RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"]; function validatePlugins(plugins) { if (hasPlugin(plugins, "decorators")) { if (hasPlugin(plugins, "decorators-legacy")) { throw new Error("Cannot use the decorators and decorators-legacy plugin together"); } const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport"); if (decoratorsBeforeExport != null && typeof decoratorsBeforeExport !== "boolean") { throw new Error("'decoratorsBeforeExport' must be a boolean, if specified."); } const allowCallParenthesized = getPluginOption(plugins, "decorators", "allowCallParenthesized"); if (allowCallParenthesized != null && typeof allowCallParenthesized !== "boolean") { throw new Error("'allowCallParenthesized' must be a boolean."); } } if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) { throw new Error("Cannot combine flow and typescript plugins."); } if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) { throw new Error("Cannot combine placeholders and v8intrinsic plugins."); } if (hasPlugin(plugins, "pipelineOperator")) { const proposal = getPluginOption(plugins, "pipelineOperator", "proposal"); if (!PIPELINE_PROPOSALS.includes(proposal)) { const proposalList = PIPELINE_PROPOSALS.map((p) => `"${p}"`).join(", "); throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`); } const tupleSyntaxIsHash = hasPlugin(plugins, ["recordAndTuple", { syntaxType: "hash" }]); if (proposal === "hack") { if (hasPlugin(plugins, "placeholders")) { throw new Error("Cannot combine placeholders plugin and Hack-style pipes."); } if (hasPlugin(plugins, "v8intrinsic")) { throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes."); } const topicToken = getPluginOption(plugins, "pipelineOperator", "topicToken"); if (!TOPIC_TOKENS.includes(topicToken)) { const tokenList = TOPIC_TOKENS.map((t2) => `"${t2}"`).join(", "); throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`); } if (topicToken === "#" && tupleSyntaxIsHash) { throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "hack", topicToken: "#" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.'); } } else if (proposal === "smart" && tupleSyntaxIsHash) { throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "smart" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.'); } } if (hasPlugin(plugins, "moduleAttributes")) { { if (hasPlugin(plugins, "importAssertions") || hasPlugin(plugins, "importAttributes")) { throw new Error("Cannot combine importAssertions, importAttributes and moduleAttributes plugins."); } const moduleAttributesVersionPluginOption = getPluginOption(plugins, "moduleAttributes", "version"); if (moduleAttributesVersionPluginOption !== "may-2020") { throw new Error("The 'moduleAttributes' plugin requires a 'version' option, representing the last proposal update. Currently, the only supported value is 'may-2020'."); } } } if (hasPlugin(plugins, "importAssertions") && hasPlugin(plugins, "importAttributes")) { throw new Error("Cannot combine importAssertions and importAttributes plugins."); } if (hasPlugin(plugins, "recordAndTuple") && getPluginOption(plugins, "recordAndTuple", "syntaxType") != null && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) { throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map((p) => `'${p}'`).join(", ")); } if (hasPlugin(plugins, "asyncDoExpressions") && !hasPlugin(plugins, "doExpressions")) { const error = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins."); error.missingPlugins = "doExpressions"; throw error; } if (hasPlugin(plugins, "optionalChainingAssign") && getPluginOption(plugins, "optionalChainingAssign", "version") !== "2023-07") { throw new Error("The 'optionalChainingAssign' plugin requires a 'version' option, representing the last proposal update. Currently, the only supported value is '2023-07'."); } } var mixinPlugins = { estree, jsx, flow: flow3, typescript, v8intrinsic, placeholders }; var mixinPluginNames = Object.keys(mixinPlugins); var defaultOptions2 = { sourceType: "script", sourceFilename: void 0, startColumn: 0, startLine: 1, allowAwaitOutsideFunction: false, allowReturnOutsideFunction: false, allowNewTargetOutsideFunction: false, allowImportExportEverywhere: false, allowSuperOutsideMethod: false, allowUndeclaredExports: false, plugins: [], strictMode: null, ranges: false, tokens: false, createImportExpressions: false, createParenthesizedExpressions: false, errorRecovery: false, attachComment: true, annexB: true }; function getOptions(opts) { if (opts == null) { return Object.assign({}, defaultOptions2); } if (opts.annexB != null && opts.annexB !== false) { throw new Error("The `annexB` option can only be set to `false`."); } const options = {}; for (const key of Object.keys(defaultOptions2)) { var _opts$key; options[key] = (_opts$key = opts[key]) != null ? _opts$key : defaultOptions2[key]; } return options; } var ExpressionParser = class extends LValParser { checkProto(prop, isRecord, protoRef, refExpressionErrors) { if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) { return; } const key = prop.key; const name = key.type === "Identifier" ? key.name : key.value; if (name === "__proto__") { if (isRecord) { this.raise(Errors.RecordNoProto, { at: key }); return; } if (protoRef.used) { if (refExpressionErrors) { if (refExpressionErrors.doubleProtoLoc === null) { refExpressionErrors.doubleProtoLoc = key.loc.start; } } else { this.raise(Errors.DuplicateProto, { at: key }); } } protoRef.used = true; } } shouldExitDescending(expr, potentialArrowAt) { return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt; } getExpression() { this.enterInitialScopes(); this.nextToken(); const expr = this.parseExpression(); if (!this.match(139)) { this.unexpected(); } this.finalizeRemainingComments(); expr.comments = this.state.comments; expr.errors = this.state.errors; if (this.options.tokens) { expr.tokens = this.tokens; } return expr; } parseExpression(disallowIn, refExpressionErrors) { if (disallowIn) { return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors)); } return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors)); } parseExpressionBase(refExpressionErrors) { const startLoc = this.state.startLoc; const expr = this.parseMaybeAssign(refExpressionErrors); if (this.match(12)) { const node2 = this.startNodeAt(startLoc); node2.expressions = [expr]; while (this.eat(12)) { node2.expressions.push(this.parseMaybeAssign(refExpressionErrors)); } this.toReferencedList(node2.expressions); return this.finishNode(node2, "SequenceExpression"); } return expr; } parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) { return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse)); } parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) { return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse)); } setOptionalParametersError(refExpressionErrors, resultError) { var _resultError$loc; refExpressionErrors.optionalParametersLoc = (_resultError$loc = resultError == null ? void 0 : resultError.loc) != null ? _resultError$loc : this.state.startLoc; } parseMaybeAssign(refExpressionErrors, afterLeftParse) { const startLoc = this.state.startLoc; if (this.isContextual(108)) { if (this.prodParam.hasYield) { let left2 = this.parseYield(); if (afterLeftParse) { left2 = afterLeftParse.call(this, left2, startLoc); } return left2; } } let ownExpressionErrors; if (refExpressionErrors) { ownExpressionErrors = false; } else { refExpressionErrors = new ExpressionErrors(); ownExpressionErrors = true; } const { type: type2 } = this.state; if (type2 === 10 || tokenIsIdentifier(type2)) { this.state.potentialArrowAt = this.state.start; } let left = this.parseMaybeConditional(refExpressionErrors); if (afterLeftParse) { left = afterLeftParse.call(this, left, startLoc); } if (tokenIsAssignment(this.state.type)) { const node2 = this.startNodeAt(startLoc); const operator = this.state.value; node2.operator = operator; if (this.match(29)) { this.toAssignable(left, true); node2.left = left; const startIndex = startLoc.index; if (refExpressionErrors.doubleProtoLoc != null && refExpressionErrors.doubleProtoLoc.index >= startIndex) { refExpressionErrors.doubleProtoLoc = null; } if (refExpressionErrors.shorthandAssignLoc != null && refExpressionErrors.shorthandAssignLoc.index >= startIndex) { refExpressionErrors.shorthandAssignLoc = null; } if (refExpressionErrors.privateKeyLoc != null && refExpressionErrors.privateKeyLoc.index >= startIndex) { this.checkDestructuringPrivate(refExpressionErrors); refExpressionErrors.privateKeyLoc = null; } } else { node2.left = left; } this.next(); node2.right = this.parseMaybeAssign(); this.checkLVal(left, { in: this.finishNode(node2, "AssignmentExpression") }); return node2; } else if (ownExpressionErrors) { this.checkExpressionErrors(refExpressionErrors, true); } return left; } parseMaybeConditional(refExpressionErrors) { const startLoc = this.state.startLoc; const potentialArrowAt = this.state.potentialArrowAt; const expr = this.parseExprOps(refExpressionErrors); if (this.shouldExitDescending(expr, potentialArrowAt)) { return expr; } return this.parseConditional(expr, startLoc, refExpressionErrors); } parseConditional(expr, startLoc, refExpressionErrors) { if (this.eat(17)) { const node2 = this.startNodeAt(startLoc); node2.test = expr; node2.consequent = this.parseMaybeAssignAllowIn(); this.expect(14); node2.alternate = this.parseMaybeAssign(); return this.finishNode(node2, "ConditionalExpression"); } return expr; } parseMaybeUnaryOrPrivate(refExpressionErrors) { return this.match(138) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors); } parseExprOps(refExpressionErrors) { const startLoc = this.state.startLoc; const potentialArrowAt = this.state.potentialArrowAt; const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors); if (this.shouldExitDescending(expr, potentialArrowAt)) { return expr; } return this.parseExprOp(expr, startLoc, -1); } parseExprOp(left, leftStartLoc, minPrec) { if (this.isPrivateName(left)) { const value = this.getPrivateNameSV(left); if (minPrec >= tokenOperatorPrecedence(58) || !this.prodParam.hasIn || !this.match(58)) { this.raise(Errors.PrivateInExpectedIn, { at: left, identifierName: value }); } this.classScope.usePrivateName(value, left.loc.start); } const op = this.state.type; if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(58))) { let prec = tokenOperatorPrecedence(op); if (prec > minPrec) { if (op === 39) { this.expectPlugin("pipelineOperator"); if (this.state.inFSharpPipelineDirectBody) { return left; } this.checkPipelineAtInfixOperator(left, leftStartLoc); } const node2 = this.startNodeAt(leftStartLoc); node2.left = left; node2.operator = this.state.value; const logical = op === 41 || op === 42; const coalesce = op === 40; if (coalesce) { prec = tokenOperatorPrecedence(42); } this.next(); if (op === 39 && this.hasPlugin(["pipelineOperator", { proposal: "minimal" }])) { if (this.state.type === 96 && this.prodParam.hasAwait) { throw this.raise(Errors.UnexpectedAwaitAfterPipelineBody, { at: this.state.startLoc }); } } node2.right = this.parseExprOpRightExpr(op, prec); const finishedNode = this.finishNode(node2, logical || coalesce ? "LogicalExpression" : "BinaryExpression"); const nextOp = this.state.type; if (coalesce && (nextOp === 41 || nextOp === 42) || logical && nextOp === 40) { throw this.raise(Errors.MixingCoalesceWithLogical, { at: this.state.startLoc }); } return this.parseExprOp(finishedNode, leftStartLoc, minPrec); } } return left; } parseExprOpRightExpr(op, prec) { const startLoc = this.state.startLoc; switch (op) { case 39: switch (this.getPluginOption("pipelineOperator", "proposal")) { case "hack": return this.withTopicBindingContext(() => { return this.parseHackPipeBody(); }); case "smart": return this.withTopicBindingContext(() => { if (this.prodParam.hasYield && this.isContextual(108)) { throw this.raise(Errors.PipeBodyIsTighter, { at: this.state.startLoc }); } return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startLoc); }); case "fsharp": return this.withSoloAwaitPermittingContext(() => { return this.parseFSharpPipelineBody(prec); }); } default: return this.parseExprOpBaseRightExpr(op, prec); } } parseExprOpBaseRightExpr(op, prec) { const startLoc = this.state.startLoc; return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec); } parseHackPipeBody() { var _body$extra; const { startLoc } = this.state; const body = this.parseMaybeAssign(); const requiredParentheses = UnparenthesizedPipeBodyDescriptions.has(body.type); if (requiredParentheses && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) { this.raise(Errors.PipeUnparenthesizedBody, { at: startLoc, type: body.type }); } if (!this.topicReferenceWasUsedInCurrentContext()) { this.raise(Errors.PipeTopicUnused, { at: startLoc }); } return body; } checkExponentialAfterUnary(node2) { if (this.match(57)) { this.raise(Errors.UnexpectedTokenUnaryExponentiation, { at: node2.argument }); } } parseMaybeUnary(refExpressionErrors, sawUnary) { const startLoc = this.state.startLoc; const isAwait = this.isContextual(96); if (isAwait && this.isAwaitAllowed()) { this.next(); const expr2 = this.parseAwait(startLoc); if (!sawUnary) this.checkExponentialAfterUnary(expr2); return expr2; } const update = this.match(34); const node2 = this.startNode(); if (tokenIsPrefix(this.state.type)) { node2.operator = this.state.value; node2.prefix = true; if (this.match(72)) { this.expectPlugin("throwExpressions"); } const isDelete = this.match(89); this.next(); node2.argument = this.parseMaybeUnary(null, true); this.checkExpressionErrors(refExpressionErrors, true); if (this.state.strict && isDelete) { const arg = node2.argument; if (arg.type === "Identifier") { this.raise(Errors.StrictDelete, { at: node2 }); } else if (this.hasPropertyAsPrivateName(arg)) { this.raise(Errors.DeletePrivateField, { at: node2 }); } } if (!update) { if (!sawUnary) { this.checkExponentialAfterUnary(node2); } return this.finishNode(node2, "UnaryExpression"); } } const expr = this.parseUpdate(node2, update, refExpressionErrors); if (isAwait) { const { type: type2 } = this.state; const startsExpr2 = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type2) : tokenCanStartExpression(type2) && !this.match(54); if (startsExpr2 && !this.isAmbiguousAwait()) { this.raiseOverwrite(Errors.AwaitNotInAsyncContext, { at: startLoc }); return this.parseAwait(startLoc); } } return expr; } parseUpdate(node2, update, refExpressionErrors) { if (update) { const updateExpressionNode = node2; this.checkLVal(updateExpressionNode.argument, { in: this.finishNode(updateExpressionNode, "UpdateExpression") }); return node2; } const startLoc = this.state.startLoc; let expr = this.parseExprSubscripts(refExpressionErrors); if (this.checkExpressionErrors(refExpressionErrors, false)) return expr; while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) { const node3 = this.startNodeAt(startLoc); node3.operator = this.state.value; node3.prefix = false; node3.argument = expr; this.next(); this.checkLVal(expr, { in: expr = this.finishNode(node3, "UpdateExpression") }); } return expr; } parseExprSubscripts(refExpressionErrors) { const startLoc = this.state.startLoc; const potentialArrowAt = this.state.potentialArrowAt; const expr = this.parseExprAtom(refExpressionErrors); if (this.shouldExitDescending(expr, potentialArrowAt)) { return expr; } return this.parseSubscripts(expr, startLoc); } parseSubscripts(base, startLoc, noCalls) { const state = { optionalChainMember: false, maybeAsyncArrow: this.atPossibleAsyncArrow(base), stop: false }; do { base = this.parseSubscript(base, startLoc, noCalls, state); state.maybeAsyncArrow = false; } while (!state.stop); return base; } parseSubscript(base, startLoc, noCalls, state) { const { type: type2 } = this.state; if (!noCalls && type2 === 15) { return this.parseBind(base, startLoc, noCalls, state); } else if (tokenIsTemplate(type2)) { return this.parseTaggedTemplateExpression(base, startLoc, state); } let optional = false; if (type2 === 18) { if (noCalls) { this.raise(Errors.OptionalChainingNoNew, { at: this.state.startLoc }); if (this.lookaheadCharCode() === 40) { state.stop = true; return base; } } state.optionalChainMember = optional = true; this.next(); } if (!noCalls && this.match(10)) { return this.parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional); } else { const computed = this.eat(0); if (computed || optional || this.eat(16)) { return this.parseMember(base, startLoc, state, computed, optional); } else { state.stop = true; return base; } } } parseMember(base, startLoc, state, computed, optional) { const node2 = this.startNodeAt(startLoc); node2.object = base; node2.computed = computed; if (computed) { node2.property = this.parseExpression(); this.expect(3); } else if (this.match(138)) { if (base.type === "Super") { this.raise(Errors.SuperPrivateField, { at: startLoc }); } this.classScope.usePrivateName(this.state.value, this.state.startLoc); node2.property = this.parsePrivateName(); } else { node2.property = this.parseIdentifier(true); } if (state.optionalChainMember) { node2.optional = optional; return this.finishNode(node2, "OptionalMemberExpression"); } else { return this.finishNode(node2, "MemberExpression"); } } parseBind(base, startLoc, noCalls, state) { const node2 = this.startNodeAt(startLoc); node2.object = base; this.next(); node2.callee = this.parseNoCallExpr(); state.stop = true; return this.parseSubscripts(this.finishNode(node2, "BindExpression"), startLoc, noCalls); } parseCoverCallAndAsyncArrowHead(base, startLoc, state, optional) { const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; let refExpressionErrors = null; this.state.maybeInArrowParameters = true; this.next(); const node2 = this.startNodeAt(startLoc); node2.callee = base; const { maybeAsyncArrow, optionalChainMember } = state; if (maybeAsyncArrow) { this.expressionScope.enter(newAsyncArrowScope()); refExpressionErrors = new ExpressionErrors(); } if (optionalChainMember) { node2.optional = optional; } if (optional) { node2.arguments = this.parseCallExpressionArguments(11); } else { node2.arguments = this.parseCallExpressionArguments(11, base.type === "Import", base.type !== "Super", node2, refExpressionErrors); } let finishedNode = this.finishCallExpression(node2, optionalChainMember); if (maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) { state.stop = true; this.checkDestructuringPrivate(refExpressionErrors); this.expressionScope.validateAsPattern(); this.expressionScope.exit(); finishedNode = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startLoc), finishedNode); } else { if (maybeAsyncArrow) { this.checkExpressionErrors(refExpressionErrors, true); this.expressionScope.exit(); } this.toReferencedArguments(finishedNode); } this.state.maybeInArrowParameters = oldMaybeInArrowParameters; return finishedNode; } toReferencedArguments(node2, isParenthesizedExpr) { this.toReferencedListDeep(node2.arguments, isParenthesizedExpr); } parseTaggedTemplateExpression(base, startLoc, state) { const node2 = this.startNodeAt(startLoc); node2.tag = base; node2.quasi = this.parseTemplate(true); if (state.optionalChainMember) { this.raise(Errors.OptionalChainingNoTemplate, { at: startLoc }); } return this.finishNode(node2, "TaggedTemplateExpression"); } atPossibleAsyncArrow(base) { return base.type === "Identifier" && base.name === "async" && this.state.lastTokEndLoc.index === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt; } expectImportAttributesPlugin() { if (!this.hasPlugin("importAssertions")) { this.expectPlugin("importAttributes"); } } finishCallExpression(node2, optional) { if (node2.callee.type === "Import") { if (node2.arguments.length === 2) { { if (!this.hasPlugin("moduleAttributes")) { this.expectImportAttributesPlugin(); } } } if (node2.arguments.length === 0 || node2.arguments.length > 2) { this.raise(Errors.ImportCallArity, { at: node2, maxArgumentCount: this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? 2 : 1 }); } else { for (const arg of node2.arguments) { if (arg.type === "SpreadElement") { this.raise(Errors.ImportCallSpreadArgument, { at: arg }); } } } } return this.finishNode(node2, optional ? "OptionalCallExpression" : "CallExpression"); } parseCallExpressionArguments(close, dynamicImport, allowPlaceholder, nodeForExtra, refExpressionErrors) { const elts = []; let first = true; const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; this.state.inFSharpPipelineDirectBody = false; while (!this.eat(close)) { if (first) { first = false; } else { this.expect(12); if (this.match(close)) { if (dynamicImport && !this.hasPlugin("importAttributes") && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) { this.raise(Errors.ImportCallArgumentTrailingComma, { at: this.state.lastTokStartLoc }); } if (nodeForExtra) { this.addTrailingCommaExtraToNode(nodeForExtra); } this.next(); break; } } elts.push(this.parseExprListItem(false, refExpressionErrors, allowPlaceholder)); } this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; return elts; } shouldParseAsyncArrow() { return this.match(19) && !this.canInsertSemicolon(); } parseAsyncArrowFromCallExpression(node2, call) { var _call$extra; this.resetPreviousNodeTrailingComments(call); this.expect(19); this.parseArrowExpression(node2, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingCommaLoc); if (call.innerComments) { setInnerComments(node2, call.innerComments); } if (call.callee.trailingComments) { setInnerComments(node2, call.callee.trailingComments); } return node2; } parseNoCallExpr() { const startLoc = this.state.startLoc; return this.parseSubscripts(this.parseExprAtom(), startLoc, true); } parseExprAtom(refExpressionErrors) { let node2; let decorators = null; const { type: type2 } = this.state; switch (type2) { case 79: return this.parseSuper(); case 83: node2 = this.startNode(); this.next(); if (this.match(16)) { return this.parseImportMetaProperty(node2); } if (this.match(10)) { if (this.options.createImportExpressions) { return this.parseImportCall(node2); } else { return this.finishNode(node2, "Import"); } } else { this.raise(Errors.UnsupportedImport, { at: this.state.lastTokStartLoc }); return this.finishNode(node2, "Import"); } case 78: node2 = this.startNode(); this.next(); return this.finishNode(node2, "ThisExpression"); case 90: { return this.parseDo(this.startNode(), false); } case 56: case 31: { this.readRegexp(); return this.parseRegExpLiteral(this.state.value); } case 134: return this.parseNumericLiteral(this.state.value); case 135: return this.parseBigIntLiteral(this.state.value); case 136: return this.parseDecimalLiteral(this.state.value); case 133: return this.parseStringLiteral(this.state.value); case 84: return this.parseNullLiteral(); case 85: return this.parseBooleanLiteral(true); case 86: return this.parseBooleanLiteral(false); case 10: { const canBeArrow = this.state.potentialArrowAt === this.state.start; return this.parseParenAndDistinguishExpression(canBeArrow); } case 2: case 1: { return this.parseArrayLike(this.state.type === 2 ? 4 : 3, false, true); } case 0: { return this.parseArrayLike(3, true, false, refExpressionErrors); } case 6: case 7: { return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true); } case 5: { return this.parseObjectLike(8, false, false, refExpressionErrors); } case 68: return this.parseFunctionOrFunctionSent(); case 26: decorators = this.parseDecorators(); case 80: return this.parseClass(this.maybeTakeDecorators(decorators, this.startNode()), false); case 77: return this.parseNewOrNewTarget(); case 25: case 24: return this.parseTemplate(false); case 15: { node2 = this.startNode(); this.next(); node2.object = null; const callee = node2.callee = this.parseNoCallExpr(); if (callee.type === "MemberExpression") { return this.finishNode(node2, "BindExpression"); } else { throw this.raise(Errors.UnsupportedBind, { at: callee }); } } case 138: { this.raise(Errors.PrivateInExpectedIn, { at: this.state.startLoc, identifierName: this.state.value }); return this.parsePrivateName(); } case 33: { return this.parseTopicReferenceThenEqualsSign(54, "%"); } case 32: { return this.parseTopicReferenceThenEqualsSign(44, "^"); } case 37: case 38: { return this.parseTopicReference("hack"); } case 44: case 54: case 27: { const pipeProposal = this.getPluginOption("pipelineOperator", "proposal"); if (pipeProposal) { return this.parseTopicReference(pipeProposal); } this.unexpected(); break; } case 47: { const lookaheadCh = this.input.codePointAt(this.nextTokenStart()); if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) { this.expectOnePlugin(["jsx", "flow", "typescript"]); } else { this.unexpected(); } break; } default: if (tokenIsIdentifier(type2)) { if (this.isContextual(127) && this.lookaheadInLineCharCode() === 123) { return this.parseModuleExpression(); } const canBeArrow = this.state.potentialArrowAt === this.state.start; const containsEsc = this.state.containsEsc; const id = this.parseIdentifier(); if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) { const { type: type3 } = this.state; if (type3 === 68) { this.resetPreviousNodeTrailingComments(id); this.next(); return this.parseAsyncFunctionExpression(this.startNodeAtNode(id)); } else if (tokenIsIdentifier(type3)) { if (this.lookaheadCharCode() === 61) { return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id)); } else { return id; } } else if (type3 === 90) { this.resetPreviousNodeTrailingComments(id); return this.parseDo(this.startNodeAtNode(id), true); } } if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) { this.next(); return this.parseArrowExpression(this.startNodeAtNode(id), [id], false); } return id; } else { this.unexpected(); } } } parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) { const pipeProposal = this.getPluginOption("pipelineOperator", "proposal"); if (pipeProposal) { this.state.type = topicTokenType; this.state.value = topicTokenValue; this.state.pos--; this.state.end--; this.state.endLoc = createPositionWithColumnOffset(this.state.endLoc, -1); return this.parseTopicReference(pipeProposal); } else { this.unexpected(); } } parseTopicReference(pipeProposal) { const node2 = this.startNode(); const startLoc = this.state.startLoc; const tokenType = this.state.type; this.next(); return this.finishTopicReference(node2, startLoc, pipeProposal, tokenType); } finishTopicReference(node2, startLoc, pipeProposal, tokenType) { if (this.testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType)) { const nodeType = pipeProposal === "smart" ? "PipelinePrimaryTopicReference" : "TopicReference"; if (!this.topicReferenceIsAllowedInCurrentContext()) { this.raise(pipeProposal === "smart" ? Errors.PrimaryTopicNotAllowed : Errors.PipeTopicUnbound, { at: startLoc }); } this.registerTopicReference(); return this.finishNode(node2, nodeType); } else { throw this.raise(Errors.PipeTopicUnconfiguredToken, { at: startLoc, token: tokenLabelName(tokenType) }); } } testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType) { switch (pipeProposal) { case "hack": { return this.hasPlugin(["pipelineOperator", { topicToken: tokenLabelName(tokenType) }]); } case "smart": return tokenType === 27; default: throw this.raise(Errors.PipeTopicRequiresHackPipes, { at: startLoc }); } } parseAsyncArrowUnaryFunction(node2) { this.prodParam.enter(functionFlags(true, this.prodParam.hasYield)); const params = [this.parseIdentifier()]; this.prodParam.exit(); if (this.hasPrecedingLineBreak()) { this.raise(Errors.LineTerminatorBeforeArrow, { at: this.state.curPosition() }); } this.expect(19); return this.parseArrowExpression(node2, params, true); } parseDo(node2, isAsync2) { this.expectPlugin("doExpressions"); if (isAsync2) { this.expectPlugin("asyncDoExpressions"); } node2.async = isAsync2; this.next(); const oldLabels = this.state.labels; this.state.labels = []; if (isAsync2) { this.prodParam.enter(PARAM_AWAIT); node2.body = this.parseBlock(); this.prodParam.exit(); } else { node2.body = this.parseBlock(); } this.state.labels = oldLabels; return this.finishNode(node2, "DoExpression"); } parseSuper() { const node2 = this.startNode(); this.next(); if (this.match(10) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) { this.raise(Errors.SuperNotAllowed, { at: node2 }); } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) { this.raise(Errors.UnexpectedSuper, { at: node2 }); } if (!this.match(10) && !this.match(0) && !this.match(16)) { this.raise(Errors.UnsupportedSuper, { at: node2 }); } return this.finishNode(node2, "Super"); } parsePrivateName() { const node2 = this.startNode(); const id = this.startNodeAt(createPositionWithColumnOffset(this.state.startLoc, 1)); const name = this.state.value; this.next(); node2.id = this.createIdentifier(id, name); return this.finishNode(node2, "PrivateName"); } parseFunctionOrFunctionSent() { const node2 = this.startNode(); this.next(); if (this.prodParam.hasYield && this.match(16)) { const meta = this.createIdentifier(this.startNodeAtNode(node2), "function"); this.next(); if (this.match(103)) { this.expectPlugin("functionSent"); } else if (!this.hasPlugin("functionSent")) { this.unexpected(); } return this.parseMetaProperty(node2, meta, "sent"); } return this.parseFunction(node2); } parseMetaProperty(node2, meta, propertyName) { node2.meta = meta; const containsEsc = this.state.containsEsc; node2.property = this.parseIdentifier(true); if (node2.property.name !== propertyName || containsEsc) { this.raise(Errors.UnsupportedMetaProperty, { at: node2.property, target: meta.name, onlyValidPropertyName: propertyName }); } return this.finishNode(node2, "MetaProperty"); } parseImportMetaProperty(node2) { const id = this.createIdentifier(this.startNodeAtNode(node2), "import"); this.next(); if (this.isContextual(101)) { if (!this.inModule) { this.raise(Errors.ImportMetaOutsideModule, { at: id }); } this.sawUnambiguousESM = true; } else if (this.isContextual(105) || this.isContextual(97)) { const isSource = this.isContextual(105); if (!isSource) this.unexpected(); this.expectPlugin(isSource ? "sourcePhaseImports" : "deferredImportEvaluation"); if (!this.options.createImportExpressions) { throw this.raise(Errors.DynamicImportPhaseRequiresImportExpressions, { at: this.state.startLoc, phase: this.state.value }); } this.next(); node2.phase = isSource ? "source" : "defer"; return this.parseImportCall(node2); } return this.parseMetaProperty(node2, id, "meta"); } parseLiteralAtNode(value, type2, node2) { this.addExtra(node2, "rawValue", value); this.addExtra(node2, "raw", this.input.slice(node2.start, this.state.end)); node2.value = value; this.next(); return this.finishNode(node2, type2); } parseLiteral(value, type2) { const node2 = this.startNode(); return this.parseLiteralAtNode(value, type2, node2); } parseStringLiteral(value) { return this.parseLiteral(value, "StringLiteral"); } parseNumericLiteral(value) { return this.parseLiteral(value, "NumericLiteral"); } parseBigIntLiteral(value) { return this.parseLiteral(value, "BigIntLiteral"); } parseDecimalLiteral(value) { return this.parseLiteral(value, "DecimalLiteral"); } parseRegExpLiteral(value) { const node2 = this.parseLiteral(value.value, "RegExpLiteral"); node2.pattern = value.pattern; node2.flags = value.flags; return node2; } parseBooleanLiteral(value) { const node2 = this.startNode(); node2.value = value; this.next(); return this.finishNode(node2, "BooleanLiteral"); } parseNullLiteral() { const node2 = this.startNode(); this.next(); return this.finishNode(node2, "NullLiteral"); } parseParenAndDistinguishExpression(canBeArrow) { const startLoc = this.state.startLoc; let val; this.next(); this.expressionScope.enter(newArrowHeadScope()); const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; this.state.maybeInArrowParameters = true; this.state.inFSharpPipelineDirectBody = false; const innerStartLoc = this.state.startLoc; const exprList = []; const refExpressionErrors = new ExpressionErrors(); let first = true; let spreadStartLoc; let optionalCommaStartLoc; while (!this.match(11)) { if (first) { first = false; } else { this.expect(12, refExpressionErrors.optionalParametersLoc === null ? null : refExpressionErrors.optionalParametersLoc); if (this.match(11)) { optionalCommaStartLoc = this.state.startLoc; break; } } if (this.match(21)) { const spreadNodeStartLoc = this.state.startLoc; spreadStartLoc = this.state.startLoc; exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartLoc)); if (!this.checkCommaAfterRest(41)) { break; } } else { exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem)); } } const innerEndLoc = this.state.lastTokEndLoc; this.expect(11); this.state.maybeInArrowParameters = oldMaybeInArrowParameters; this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; let arrowNode = this.startNodeAt(startLoc); if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) { this.checkDestructuringPrivate(refExpressionErrors); this.expressionScope.validateAsPattern(); this.expressionScope.exit(); this.parseArrowExpression(arrowNode, exprList, false); return arrowNode; } this.expressionScope.exit(); if (!exprList.length) { this.unexpected(this.state.lastTokStartLoc); } if (optionalCommaStartLoc) this.unexpected(optionalCommaStartLoc); if (spreadStartLoc) this.unexpected(spreadStartLoc); this.checkExpressionErrors(refExpressionErrors, true); this.toReferencedListDeep(exprList, true); if (exprList.length > 1) { val = this.startNodeAt(innerStartLoc); val.expressions = exprList; this.finishNode(val, "SequenceExpression"); this.resetEndLocation(val, innerEndLoc); } else { val = exprList[0]; } return this.wrapParenthesis(startLoc, val); } wrapParenthesis(startLoc, expression) { if (!this.options.createParenthesizedExpressions) { this.addExtra(expression, "parenthesized", true); this.addExtra(expression, "parenStart", startLoc.index); this.takeSurroundingComments(expression, startLoc.index, this.state.lastTokEndLoc.index); return expression; } const parenExpression = this.startNodeAt(startLoc); parenExpression.expression = expression; return this.finishNode(parenExpression, "ParenthesizedExpression"); } shouldParseArrow(params) { return !this.canInsertSemicolon(); } parseArrow(node2) { if (this.eat(19)) { return node2; } } parseParenItem(node2, startLoc) { return node2; } parseNewOrNewTarget() { const node2 = this.startNode(); this.next(); if (this.match(16)) { const meta = this.createIdentifier(this.startNodeAtNode(node2), "new"); this.next(); const metaProp = this.parseMetaProperty(node2, meta, "target"); if (!this.scope.inNonArrowFunction && !this.scope.inClass && !this.options.allowNewTargetOutsideFunction) { this.raise(Errors.UnexpectedNewTarget, { at: metaProp }); } return metaProp; } return this.parseNew(node2); } parseNew(node2) { this.parseNewCallee(node2); if (this.eat(10)) { const args = this.parseExprList(11); this.toReferencedList(args); node2.arguments = args; } else { node2.arguments = []; } return this.finishNode(node2, "NewExpression"); } parseNewCallee(node2) { const isImport = this.match(83); const callee = this.parseNoCallExpr(); node2.callee = callee; if (isImport && (callee.type === "Import" || callee.type === "ImportExpression")) { this.raise(Errors.ImportCallNotNewExpression, { at: callee }); } } parseTemplateElement(isTagged) { const { start, startLoc, end, value } = this.state; const elemStart = start + 1; const elem = this.startNodeAt(createPositionWithColumnOffset(startLoc, 1)); if (value === null) { if (!isTagged) { this.raise(Errors.InvalidEscapeSequenceTemplate, { at: createPositionWithColumnOffset(this.state.firstInvalidTemplateEscapePos, 1) }); } } const isTail = this.match(24); const endOffset = isTail ? -1 : -2; const elemEnd = end + endOffset; elem.value = { raw: this.input.slice(elemStart, elemEnd).replace(/\r\n?/g, "\n"), cooked: value === null ? null : value.slice(1, endOffset) }; elem.tail = isTail; this.next(); const finishedNode = this.finishNode(elem, "TemplateElement"); this.resetEndLocation(finishedNode, createPositionWithColumnOffset(this.state.lastTokEndLoc, endOffset)); return finishedNode; } parseTemplate(isTagged) { const node2 = this.startNode(); node2.expressions = []; let curElt = this.parseTemplateElement(isTagged); node2.quasis = [curElt]; while (!curElt.tail) { node2.expressions.push(this.parseTemplateSubstitution()); this.readTemplateContinuation(); node2.quasis.push(curElt = this.parseTemplateElement(isTagged)); } return this.finishNode(node2, "TemplateLiteral"); } parseTemplateSubstitution() { return this.parseExpression(); } parseObjectLike(close, isPattern, isRecord, refExpressionErrors) { if (isRecord) { this.expectPlugin("recordAndTuple"); } const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; this.state.inFSharpPipelineDirectBody = false; const propHash = /* @__PURE__ */ Object.create(null); let first = true; const node2 = this.startNode(); node2.properties = []; this.next(); while (!this.match(close)) { if (first) { first = false; } else { this.expect(12); if (this.match(close)) { this.addTrailingCommaExtraToNode(node2); break; } } let prop; if (isPattern) { prop = this.parseBindingProperty(); } else { prop = this.parsePropertyDefinition(refExpressionErrors); this.checkProto(prop, isRecord, propHash, refExpressionErrors); } if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") { this.raise(Errors.InvalidRecordProperty, { at: prop }); } if (prop.shorthand) { this.addExtra(prop, "shorthand", true); } node2.properties.push(prop); } this.next(); this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; let type2 = "ObjectExpression"; if (isPattern) { type2 = "ObjectPattern"; } else if (isRecord) { type2 = "RecordExpression"; } return this.finishNode(node2, type2); } addTrailingCommaExtraToNode(node2) { this.addExtra(node2, "trailingComma", this.state.lastTokStart); this.addExtra(node2, "trailingCommaLoc", this.state.lastTokStartLoc, false); } maybeAsyncOrAccessorProp(prop) { return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(55)); } parsePropertyDefinition(refExpressionErrors) { let decorators = []; if (this.match(26)) { if (this.hasPlugin("decorators")) { this.raise(Errors.UnsupportedPropertyDecorator, { at: this.state.startLoc }); } while (this.match(26)) { decorators.push(this.parseDecorator()); } } const prop = this.startNode(); let isAsync2 = false; let isAccessor = false; let startLoc; if (this.match(21)) { if (decorators.length) this.unexpected(); return this.parseSpread(); } if (decorators.length) { prop.decorators = decorators; decorators = []; } prop.method = false; if (refExpressionErrors) { startLoc = this.state.startLoc; } let isGenerator = this.eat(55); this.parsePropertyNamePrefixOperator(prop); const containsEsc = this.state.containsEsc; const key = this.parsePropertyName(prop, refExpressionErrors); if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) { const keyName = key.name; if (keyName === "async" && !this.hasPrecedingLineBreak()) { isAsync2 = true; this.resetPreviousNodeTrailingComments(key); isGenerator = this.eat(55); this.parsePropertyName(prop); } if (keyName === "get" || keyName === "set") { isAccessor = true; this.resetPreviousNodeTrailingComments(key); prop.kind = keyName; if (this.match(55)) { isGenerator = true; this.raise(Errors.AccessorIsGenerator, { at: this.state.curPosition(), kind: keyName }); this.next(); } this.parsePropertyName(prop); } } return this.parseObjPropValue(prop, startLoc, isGenerator, isAsync2, false, isAccessor, refExpressionErrors); } getGetterSetterExpectedParamCount(method) { return method.kind === "get" ? 0 : 1; } getObjectOrClassMethodParams(method) { return method.params; } checkGetterSetterParams(method) { var _params; const paramCount = this.getGetterSetterExpectedParamCount(method); const params = this.getObjectOrClassMethodParams(method); if (params.length !== paramCount) { this.raise(method.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, { at: method }); } if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") { this.raise(Errors.BadSetterRestParameter, { at: method }); } } parseObjectMethod(prop, isGenerator, isAsync2, isPattern, isAccessor) { if (isAccessor) { const finishedProp = this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod"); this.checkGetterSetterParams(finishedProp); return finishedProp; } if (isAsync2 || isGenerator || this.match(10)) { if (isPattern) this.unexpected(); prop.kind = "method"; prop.method = true; return this.parseMethod(prop, isGenerator, isAsync2, false, false, "ObjectMethod"); } } parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) { prop.shorthand = false; if (this.eat(14)) { prop.value = isPattern ? this.parseMaybeDefault(this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors); return this.finishNode(prop, "ObjectProperty"); } if (!prop.computed && prop.key.type === "Identifier") { this.checkReservedWord(prop.key.name, prop.key.loc.start, true, false); if (isPattern) { prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key)); } else if (this.match(29)) { const shorthandAssignLoc = this.state.startLoc; if (refExpressionErrors != null) { if (refExpressionErrors.shorthandAssignLoc === null) { refExpressionErrors.shorthandAssignLoc = shorthandAssignLoc; } } else { this.raise(Errors.InvalidCoverInitializedName, { at: shorthandAssignLoc }); } prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key)); } else { prop.value = cloneIdentifier(prop.key); } prop.shorthand = true; return this.finishNode(prop, "ObjectProperty"); } } parseObjPropValue(prop, startLoc, isGenerator, isAsync2, isPattern, isAccessor, refExpressionErrors) { const node2 = this.parseObjectMethod(prop, isGenerator, isAsync2, isPattern, isAccessor) || this.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors); if (!node2) this.unexpected(); return node2; } parsePropertyName(prop, refExpressionErrors) { if (this.eat(0)) { prop.computed = true; prop.key = this.parseMaybeAssignAllowIn(); this.expect(3); } else { const { type: type2, value } = this.state; let key; if (tokenIsKeywordOrIdentifier(type2)) { key = this.parseIdentifier(true); } else { switch (type2) { case 134: key = this.parseNumericLiteral(value); break; case 133: key = this.parseStringLiteral(value); break; case 135: key = this.parseBigIntLiteral(value); break; case 136: key = this.parseDecimalLiteral(value); break; case 138: { const privateKeyLoc = this.state.startLoc; if (refExpressionErrors != null) { if (refExpressionErrors.privateKeyLoc === null) { refExpressionErrors.privateKeyLoc = privateKeyLoc; } } else { this.raise(Errors.UnexpectedPrivateField, { at: privateKeyLoc }); } key = this.parsePrivateName(); break; } default: this.unexpected(); } } prop.key = key; if (type2 !== 138) { prop.computed = false; } } return prop.key; } initFunction(node2, isAsync2) { node2.id = null; node2.generator = false; node2.async = isAsync2; } parseMethod(node2, isGenerator, isAsync2, isConstructor, allowDirectSuper, type2, inClassScope = false) { this.initFunction(node2, isAsync2); node2.generator = isGenerator; this.scope.enter(2 | 16 | (inClassScope ? 64 : 0) | (allowDirectSuper ? 32 : 0)); this.prodParam.enter(functionFlags(isAsync2, node2.generator)); this.parseFunctionParams(node2, isConstructor); const finishedNode = this.parseFunctionBodyAndFinish(node2, type2, true); this.prodParam.exit(); this.scope.exit(); return finishedNode; } parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) { if (isTuple) { this.expectPlugin("recordAndTuple"); } const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; this.state.inFSharpPipelineDirectBody = false; const node2 = this.startNode(); this.next(); node2.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node2); this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; return this.finishNode(node2, isTuple ? "TupleExpression" : "ArrayExpression"); } parseArrowExpression(node2, params, isAsync2, trailingCommaLoc) { this.scope.enter(2 | 4); let flags = functionFlags(isAsync2, false); if (!this.match(5) && this.prodParam.hasIn) { flags |= PARAM_IN; } this.prodParam.enter(flags); this.initFunction(node2, isAsync2); const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; if (params) { this.state.maybeInArrowParameters = true; this.setArrowFunctionParameters(node2, params, trailingCommaLoc); } this.state.maybeInArrowParameters = false; this.parseFunctionBody(node2, true); this.prodParam.exit(); this.scope.exit(); this.state.maybeInArrowParameters = oldMaybeInArrowParameters; return this.finishNode(node2, "ArrowFunctionExpression"); } setArrowFunctionParameters(node2, params, trailingCommaLoc) { this.toAssignableList(params, trailingCommaLoc, false); node2.params = params; } parseFunctionBodyAndFinish(node2, type2, isMethod = false) { this.parseFunctionBody(node2, false, isMethod); return this.finishNode(node2, type2); } parseFunctionBody(node2, allowExpression, isMethod = false) { const isExpression = allowExpression && !this.match(5); this.expressionScope.enter(newExpressionScope()); if (isExpression) { node2.body = this.parseMaybeAssign(); this.checkParams(node2, false, allowExpression, false); } else { const oldStrict = this.state.strict; const oldLabels = this.state.labels; this.state.labels = []; this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN); node2.body = this.parseBlock(true, false, (hasStrictModeDirective) => { const nonSimple = !this.isSimpleParamList(node2.params); if (hasStrictModeDirective && nonSimple) { this.raise(Errors.IllegalLanguageModeDirective, { at: (node2.kind === "method" || node2.kind === "constructor") && !!node2.key ? node2.key.loc.end : node2 }); } const strictModeChanged = !oldStrict && this.state.strict; this.checkParams(node2, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged); if (this.state.strict && node2.id) { this.checkIdentifier(node2.id, 65, strictModeChanged); } }); this.prodParam.exit(); this.state.labels = oldLabels; } this.expressionScope.exit(); } isSimpleParameter(node2) { return node2.type === "Identifier"; } isSimpleParamList(params) { for (let i2 = 0, len = params.length; i2 < len; i2++) { if (!this.isSimpleParameter(params[i2])) return false; } return true; } checkParams(node2, allowDuplicates, isArrowFunction, strictModeChanged = true) { const checkClashes = !allowDuplicates && /* @__PURE__ */ new Set(); const formalParameters = { type: "FormalParameters" }; for (const param of node2.params) { this.checkLVal(param, { in: formalParameters, binding: 5, checkClashes, strictModeChanged }); } } parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) { const elts = []; let first = true; while (!this.eat(close)) { if (first) { first = false; } else { this.expect(12); if (this.match(close)) { if (nodeForExtra) { this.addTrailingCommaExtraToNode(nodeForExtra); } this.next(); break; } } elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors)); } return elts; } parseExprListItem(allowEmpty, refExpressionErrors, allowPlaceholder) { let elt; if (this.match(12)) { if (!allowEmpty) { this.raise(Errors.UnexpectedToken, { at: this.state.curPosition(), unexpected: "," }); } elt = null; } else if (this.match(21)) { const spreadNodeStartLoc = this.state.startLoc; elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartLoc); } else if (this.match(17)) { this.expectPlugin("partialApplication"); if (!allowPlaceholder) { this.raise(Errors.UnexpectedArgumentPlaceholder, { at: this.state.startLoc }); } const node2 = this.startNode(); this.next(); elt = this.finishNode(node2, "ArgumentPlaceholder"); } else { elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem); } return elt; } parseIdentifier(liberal) { const node2 = this.startNode(); const name = this.parseIdentifierName(liberal); return this.createIdentifier(node2, name); } createIdentifier(node2, name) { node2.name = name; node2.loc.identifierName = name; return this.finishNode(node2, "Identifier"); } parseIdentifierName(liberal) { let name; const { startLoc, type: type2 } = this.state; if (tokenIsKeywordOrIdentifier(type2)) { name = this.state.value; } else { this.unexpected(); } const tokenIsKeyword2 = tokenKeywordOrIdentifierIsKeyword(type2); if (liberal) { if (tokenIsKeyword2) { this.replaceToken(132); } } else { this.checkReservedWord(name, startLoc, tokenIsKeyword2, false); } this.next(); return name; } checkReservedWord(word, startLoc, checkKeywords, isBinding) { if (word.length > 10) { return; } if (!canBeReservedWord(word)) { return; } if (checkKeywords && isKeyword(word)) { this.raise(Errors.UnexpectedKeyword, { at: startLoc, keyword: word }); return; } const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord; if (reservedTest(word, this.inModule)) { this.raise(Errors.UnexpectedReservedWord, { at: startLoc, reservedWord: word }); return; } else if (word === "yield") { if (this.prodParam.hasYield) { this.raise(Errors.YieldBindingIdentifier, { at: startLoc }); return; } } else if (word === "await") { if (this.prodParam.hasAwait) { this.raise(Errors.AwaitBindingIdentifier, { at: startLoc }); return; } if (this.scope.inStaticBlock) { this.raise(Errors.AwaitBindingIdentifierInStaticBlock, { at: startLoc }); return; } this.expressionScope.recordAsyncArrowParametersError({ at: startLoc }); } else if (word === "arguments") { if (this.scope.inClassAndNotInNonArrowFunction) { this.raise(Errors.ArgumentsInClass, { at: startLoc }); return; } } } isAwaitAllowed() { if (this.prodParam.hasAwait) return true; if (this.options.allowAwaitOutsideFunction && !this.scope.inFunction) { return true; } return false; } parseAwait(startLoc) { const node2 = this.startNodeAt(startLoc); this.expressionScope.recordParameterInitializerError(Errors.AwaitExpressionFormalParameter, { at: node2 }); if (this.eat(55)) { this.raise(Errors.ObsoleteAwaitStar, { at: node2 }); } if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) { if (this.isAmbiguousAwait()) { this.ambiguousScriptDifferentAst = true; } else { this.sawUnambiguousESM = true; } } if (!this.state.soloAwait) { node2.argument = this.parseMaybeUnary(null, true); } return this.finishNode(node2, "AwaitExpression"); } isAmbiguousAwait() { if (this.hasPrecedingLineBreak()) return true; const { type: type2 } = this.state; return type2 === 53 || type2 === 10 || type2 === 0 || tokenIsTemplate(type2) || type2 === 102 && !this.state.containsEsc || type2 === 137 || type2 === 56 || this.hasPlugin("v8intrinsic") && type2 === 54; } parseYield() { const node2 = this.startNode(); this.expressionScope.recordParameterInitializerError(Errors.YieldInParameter, { at: node2 }); this.next(); let delegating = false; let argument = null; if (!this.hasPrecedingLineBreak()) { delegating = this.eat(55); switch (this.state.type) { case 13: case 139: case 8: case 11: case 3: case 9: case 14: case 12: if (!delegating) break; default: argument = this.parseMaybeAssign(); } } node2.delegate = delegating; node2.argument = argument; return this.finishNode(node2, "YieldExpression"); } parseImportCall(node2) { this.next(); node2.source = this.parseMaybeAssignAllowIn(); if (this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions")) { node2.options = null; } if (this.eat(12)) { this.expectImportAttributesPlugin(); if (!this.match(11)) { node2.options = this.parseMaybeAssignAllowIn(); this.eat(12); } } this.expect(11); return this.finishNode(node2, "ImportExpression"); } checkPipelineAtInfixOperator(left, leftStartLoc) { if (this.hasPlugin(["pipelineOperator", { proposal: "smart" }])) { if (left.type === "SequenceExpression") { this.raise(Errors.PipelineHeadSequenceExpression, { at: leftStartLoc }); } } } parseSmartPipelineBodyInStyle(childExpr, startLoc) { if (this.isSimpleReference(childExpr)) { const bodyNode = this.startNodeAt(startLoc); bodyNode.callee = childExpr; return this.finishNode(bodyNode, "PipelineBareFunction"); } else { const bodyNode = this.startNodeAt(startLoc); this.checkSmartPipeTopicBodyEarlyErrors(startLoc); bodyNode.expression = childExpr; return this.finishNode(bodyNode, "PipelineTopicExpression"); } } isSimpleReference(expression) { switch (expression.type) { case "MemberExpression": return !expression.computed && this.isSimpleReference(expression.object); case "Identifier": return true; default: return false; } } checkSmartPipeTopicBodyEarlyErrors(startLoc) { if (this.match(19)) { throw this.raise(Errors.PipelineBodyNoArrow, { at: this.state.startLoc }); } if (!this.topicReferenceWasUsedInCurrentContext()) { this.raise(Errors.PipelineTopicUnused, { at: startLoc }); } } withTopicBindingContext(callback) { const outerContextTopicState = this.state.topicContext; this.state.topicContext = { maxNumOfResolvableTopics: 1, maxTopicIndex: null }; try { return callback(); } finally { this.state.topicContext = outerContextTopicState; } } withSmartMixTopicForbiddingContext(callback) { if (this.hasPlugin(["pipelineOperator", { proposal: "smart" }])) { const outerContextTopicState = this.state.topicContext; this.state.topicContext = { maxNumOfResolvableTopics: 0, maxTopicIndex: null }; try { return callback(); } finally { this.state.topicContext = outerContextTopicState; } } else { return callback(); } } withSoloAwaitPermittingContext(callback) { const outerContextSoloAwaitState = this.state.soloAwait; this.state.soloAwait = true; try { return callback(); } finally { this.state.soloAwait = outerContextSoloAwaitState; } } allowInAnd(callback) { const flags = this.prodParam.currentFlags(); const prodParamToSet = PARAM_IN & ~flags; if (prodParamToSet) { this.prodParam.enter(flags | PARAM_IN); try { return callback(); } finally { this.prodParam.exit(); } } return callback(); } disallowInAnd(callback) { const flags = this.prodParam.currentFlags(); const prodParamToClear = PARAM_IN & flags; if (prodParamToClear) { this.prodParam.enter(flags & ~PARAM_IN); try { return callback(); } finally { this.prodParam.exit(); } } return callback(); } registerTopicReference() { this.state.topicContext.maxTopicIndex = 0; } topicReferenceIsAllowedInCurrentContext() { return this.state.topicContext.maxNumOfResolvableTopics >= 1; } topicReferenceWasUsedInCurrentContext() { return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0; } parseFSharpPipelineBody(prec) { const startLoc = this.state.startLoc; this.state.potentialArrowAt = this.state.start; const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody; this.state.inFSharpPipelineDirectBody = true; const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, prec); this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody; return ret; } parseModuleExpression() { this.expectPlugin("moduleBlocks"); const node2 = this.startNode(); this.next(); if (!this.match(5)) { this.unexpected(null, 5); } const program = this.startNodeAt(this.state.endLoc); this.next(); const revertScopes = this.initializeScopes(true); this.enterInitialScopes(); try { node2.body = this.parseProgram(program, 8, "module"); } finally { revertScopes(); } return this.finishNode(node2, "ModuleExpression"); } parsePropertyNamePrefixOperator(prop) { } }; var loopLabel = { kind: "loop" }; var switchLabel = { kind: "switch" }; var loneSurrogate = /[\uD800-\uDFFF]/u; var keywordRelationalOperator = /in(?:stanceof)?/y; function babel7CompatTokens(tokens, input) { for (let i2 = 0; i2 < tokens.length; i2++) { const token = tokens[i2]; const { type: type2 } = token; if (typeof type2 === "number") { { if (type2 === 138) { const { loc, start, value, end } = token; const hashEndPos = start + 1; const hashEndLoc = createPositionWithColumnOffset(loc.start, 1); tokens.splice(i2, 1, new Token({ type: getExportedToken(27), value: "#", start, end: hashEndPos, startLoc: loc.start, endLoc: hashEndLoc }), new Token({ type: getExportedToken(132), value, start: hashEndPos, end, startLoc: hashEndLoc, endLoc: loc.end })); i2++; continue; } if (tokenIsTemplate(type2)) { const { loc, start, value, end } = token; const backquoteEnd = start + 1; const backquoteEndLoc = createPositionWithColumnOffset(loc.start, 1); let startToken; if (input.charCodeAt(start) === 96) { startToken = new Token({ type: getExportedToken(22), value: "`", start, end: backquoteEnd, startLoc: loc.start, endLoc: backquoteEndLoc }); } else { startToken = new Token({ type: getExportedToken(8), value: "}", start, end: backquoteEnd, startLoc: loc.start, endLoc: backquoteEndLoc }); } let templateValue, templateElementEnd, templateElementEndLoc, endToken; if (type2 === 24) { templateElementEnd = end - 1; templateElementEndLoc = createPositionWithColumnOffset(loc.end, -1); templateValue = value === null ? null : value.slice(1, -1); endToken = new Token({ type: getExportedToken(22), value: "`", start: templateElementEnd, end, startLoc: templateElementEndLoc, endLoc: loc.end }); } else { templateElementEnd = end - 2; templateElementEndLoc = createPositionWithColumnOffset(loc.end, -2); templateValue = value === null ? null : value.slice(1, -2); endToken = new Token({ type: getExportedToken(23), value: "${", start: templateElementEnd, end, startLoc: templateElementEndLoc, endLoc: loc.end }); } tokens.splice(i2, 1, startToken, new Token({ type: getExportedToken(20), value: templateValue, start: backquoteEnd, end: templateElementEnd, startLoc: backquoteEndLoc, endLoc: templateElementEndLoc }), endToken); i2 += 2; continue; } } token.type = getExportedToken(type2); } } return tokens; } var StatementParser = class extends ExpressionParser { parseTopLevel(file, program) { file.program = this.parseProgram(program); file.comments = this.state.comments; if (this.options.tokens) { file.tokens = babel7CompatTokens(this.tokens, this.input); } return this.finishNode(file, "File"); } parseProgram(program, end = 139, sourceType = this.options.sourceType) { program.sourceType = sourceType; program.interpreter = this.parseInterpreterDirective(); this.parseBlockBody(program, true, true, end); if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) { for (const [localName, at] of Array.from(this.scope.undefinedExports)) { this.raise(Errors.ModuleExportUndefined, { at, localName }); } } let finishedProgram; if (end === 139) { finishedProgram = this.finishNode(program, "Program"); } else { finishedProgram = this.finishNodeAt(program, "Program", createPositionWithColumnOffset(this.state.startLoc, -1)); } return finishedProgram; } stmtToDirective(stmt) { const directive = stmt; directive.type = "Directive"; directive.value = directive.expression; delete directive.expression; const directiveLiteral = directive.value; const expressionValue = directiveLiteral.value; const raw = this.input.slice(directiveLiteral.start, directiveLiteral.end); const val = directiveLiteral.value = raw.slice(1, -1); this.addExtra(directiveLiteral, "raw", raw); this.addExtra(directiveLiteral, "rawValue", val); this.addExtra(directiveLiteral, "expressionValue", expressionValue); directiveLiteral.type = "DirectiveLiteral"; return directive; } parseInterpreterDirective() { if (!this.match(28)) { return null; } const node2 = this.startNode(); node2.value = this.state.value; this.next(); return this.finishNode(node2, "InterpreterDirective"); } isLet() { if (!this.isContextual(100)) { return false; } return this.hasFollowingBindingAtom(); } chStartsBindingIdentifier(ch, pos) { if (isIdentifierStart(ch)) { keywordRelationalOperator.lastIndex = pos; if (keywordRelationalOperator.test(this.input)) { const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex); if (!isIdentifierChar(endCh) && endCh !== 92) { return false; } } return true; } else if (ch === 92) { return true; } else { return false; } } chStartsBindingPattern(ch) { return ch === 91 || ch === 123; } hasFollowingBindingAtom() { const next = this.nextTokenStart(); const nextCh = this.codePointAtPos(next); return this.chStartsBindingPattern(nextCh) || this.chStartsBindingIdentifier(nextCh, next); } hasInLineFollowingBindingIdentifier() { const next = this.nextTokenInLineStart(); const nextCh = this.codePointAtPos(next); return this.chStartsBindingIdentifier(nextCh, next); } startsUsingForOf() { const { type: type2, containsEsc } = this.lookahead(); if (type2 === 102 && !containsEsc) { return false; } else if (tokenIsIdentifier(type2) && !this.hasFollowingLineBreak()) { this.expectPlugin("explicitResourceManagement"); return true; } } startsAwaitUsing() { let next = this.nextTokenInLineStart(); if (this.isUnparsedContextual(next, "using")) { next = this.nextTokenInLineStartSince(next + 5); const nextCh = this.codePointAtPos(next); if (this.chStartsBindingIdentifier(nextCh, next)) { this.expectPlugin("explicitResourceManagement"); return true; } } return false; } parseModuleItem() { return this.parseStatementLike(1 | 2 | 4 | 8); } parseStatementListItem() { return this.parseStatementLike(2 | 4 | (!this.options.annexB || this.state.strict ? 0 : 8)); } parseStatementOrSloppyAnnexBFunctionDeclaration(allowLabeledFunction = false) { let flags = 0; if (this.options.annexB && !this.state.strict) { flags |= 4; if (allowLabeledFunction) { flags |= 8; } } return this.parseStatementLike(flags); } parseStatement() { return this.parseStatementLike(0); } parseStatementLike(flags) { let decorators = null; if (this.match(26)) { decorators = this.parseDecorators(true); } return this.parseStatementContent(flags, decorators); } parseStatementContent(flags, decorators) { const starttype = this.state.type; const node2 = this.startNode(); const allowDeclaration = !!(flags & 2); const allowFunctionDeclaration = !!(flags & 4); const topLevel = flags & 1; switch (starttype) { case 60: return this.parseBreakContinueStatement(node2, true); case 63: return this.parseBreakContinueStatement(node2, false); case 64: return this.parseDebuggerStatement(node2); case 90: return this.parseDoWhileStatement(node2); case 91: return this.parseForStatement(node2); case 68: if (this.lookaheadCharCode() === 46) break; if (!allowFunctionDeclaration) { this.raise(this.state.strict ? Errors.StrictFunction : this.options.annexB ? Errors.SloppyFunctionAnnexB : Errors.SloppyFunction, { at: this.state.startLoc }); } return this.parseFunctionStatement(node2, false, !allowDeclaration && allowFunctionDeclaration); case 80: if (!allowDeclaration) this.unexpected(); return this.parseClass(this.maybeTakeDecorators(decorators, node2), true); case 69: return this.parseIfStatement(node2); case 70: return this.parseReturnStatement(node2); case 71: return this.parseSwitchStatement(node2); case 72: return this.parseThrowStatement(node2); case 73: return this.parseTryStatement(node2); case 96: if (!this.state.containsEsc && this.startsAwaitUsing()) { if (!this.isAwaitAllowed()) { this.raise(Errors.AwaitUsingNotInAsyncContext, { at: node2 }); } else if (!allowDeclaration) { this.raise(Errors.UnexpectedLexicalDeclaration, { at: node2 }); } this.next(); return this.parseVarStatement(node2, "await using"); } break; case 107: if (this.state.containsEsc || !this.hasInLineFollowingBindingIdentifier()) { break; } this.expectPlugin("explicitResourceManagement"); if (!this.scope.inModule && this.scope.inTopLevel) { this.raise(Errors.UnexpectedUsingDeclaration, { at: this.state.startLoc }); } else if (!allowDeclaration) { this.raise(Errors.UnexpectedLexicalDeclaration, { at: this.state.startLoc }); } return this.parseVarStatement(node2, "using"); case 100: { if (this.state.containsEsc) { break; } const next = this.nextTokenStart(); const nextCh = this.codePointAtPos(next); if (nextCh !== 91) { if (!allowDeclaration && this.hasFollowingLineBreak()) break; if (!this.chStartsBindingIdentifier(nextCh, next) && nextCh !== 123) { break; } } } case 75: { if (!allowDeclaration) { this.raise(Errors.UnexpectedLexicalDeclaration, { at: this.state.startLoc }); } } case 74: { const kind = this.state.value; return this.parseVarStatement(node2, kind); } case 92: return this.parseWhileStatement(node2); case 76: return this.parseWithStatement(node2); case 5: return this.parseBlock(); case 13: return this.parseEmptyStatement(node2); case 83: { const nextTokenCharCode = this.lookaheadCharCode(); if (nextTokenCharCode === 40 || nextTokenCharCode === 46) { break; } } case 82: { if (!this.options.allowImportExportEverywhere && !topLevel) { this.raise(Errors.UnexpectedImportExport, { at: this.state.startLoc }); } this.next(); let result; if (starttype === 83) { result = this.parseImport(node2); if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) { this.sawUnambiguousESM = true; } } else { result = this.parseExport(node2, decorators); if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") { this.sawUnambiguousESM = true; } } this.assertModuleNodeAllowed(result); return result; } default: { if (this.isAsyncFunction()) { if (!allowDeclaration) { this.raise(Errors.AsyncFunctionInSingleStatementContext, { at: this.state.startLoc }); } this.next(); return this.parseFunctionStatement(node2, true, !allowDeclaration && allowFunctionDeclaration); } } } const maybeName = this.state.value; const expr = this.parseExpression(); if (tokenIsIdentifier(starttype) && expr.type === "Identifier" && this.eat(14)) { return this.parseLabeledStatement(node2, maybeName, expr, flags); } else { return this.parseExpressionStatement(node2, expr, decorators); } } assertModuleNodeAllowed(node2) { if (!this.options.allowImportExportEverywhere && !this.inModule) { this.raise(Errors.ImportOutsideModule, { at: node2 }); } } decoratorsEnabledBeforeExport() { if (this.hasPlugin("decorators-legacy")) return true; return this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") !== false; } maybeTakeDecorators(maybeDecorators, classNode, exportNode) { if (maybeDecorators) { if (classNode.decorators && classNode.decorators.length > 0) { if (typeof this.getPluginOption("decorators", "decoratorsBeforeExport") !== "boolean") { this.raise(Errors.DecoratorsBeforeAfterExport, { at: classNode.decorators[0] }); } classNode.decorators.unshift(...maybeDecorators); } else { classNode.decorators = maybeDecorators; } this.resetStartLocationFromNode(classNode, maybeDecorators[0]); if (exportNode) this.resetStartLocationFromNode(exportNode, classNode); } return classNode; } canHaveLeadingDecorator() { return this.match(80); } parseDecorators(allowExport) { const decorators = []; do { decorators.push(this.parseDecorator()); } while (this.match(26)); if (this.match(82)) { if (!allowExport) { this.unexpected(); } if (!this.decoratorsEnabledBeforeExport()) { this.raise(Errors.DecoratorExportClass, { at: this.state.startLoc }); } } else if (!this.canHaveLeadingDecorator()) { throw this.raise(Errors.UnexpectedLeadingDecorator, { at: this.state.startLoc }); } return decorators; } parseDecorator() { this.expectOnePlugin(["decorators", "decorators-legacy"]); const node2 = this.startNode(); this.next(); if (this.hasPlugin("decorators")) { const startLoc = this.state.startLoc; let expr; if (this.match(10)) { const startLoc2 = this.state.startLoc; this.next(); expr = this.parseExpression(); this.expect(11); expr = this.wrapParenthesis(startLoc2, expr); const paramsStartLoc = this.state.startLoc; node2.expression = this.parseMaybeDecoratorArguments(expr); if (this.getPluginOption("decorators", "allowCallParenthesized") === false && node2.expression !== expr) { this.raise(Errors.DecoratorArgumentsOutsideParentheses, { at: paramsStartLoc }); } } else { expr = this.parseIdentifier(false); while (this.eat(16)) { const node3 = this.startNodeAt(startLoc); node3.object = expr; if (this.match(138)) { this.classScope.usePrivateName(this.state.value, this.state.startLoc); node3.property = this.parsePrivateName(); } else { node3.property = this.parseIdentifier(true); } node3.computed = false; expr = this.finishNode(node3, "MemberExpression"); } node2.expression = this.parseMaybeDecoratorArguments(expr); } } else { node2.expression = this.parseExprSubscripts(); } return this.finishNode(node2, "Decorator"); } parseMaybeDecoratorArguments(expr) { if (this.eat(10)) { const node2 = this.startNodeAtNode(expr); node2.callee = expr; node2.arguments = this.parseCallExpressionArguments(11, false); this.toReferencedList(node2.arguments); return this.finishNode(node2, "CallExpression"); } return expr; } parseBreakContinueStatement(node2, isBreak) { this.next(); if (this.isLineTerminator()) { node2.label = null; } else { node2.label = this.parseIdentifier(); this.semicolon(); } this.verifyBreakContinue(node2, isBreak); return this.finishNode(node2, isBreak ? "BreakStatement" : "ContinueStatement"); } verifyBreakContinue(node2, isBreak) { let i2; for (i2 = 0; i2 < this.state.labels.length; ++i2) { const lab = this.state.labels[i2]; if (node2.label == null || lab.name === node2.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) break; if (node2.label && isBreak) break; } } if (i2 === this.state.labels.length) { const type2 = isBreak ? "BreakStatement" : "ContinueStatement"; this.raise(Errors.IllegalBreakContinue, { at: node2, type: type2 }); } } parseDebuggerStatement(node2) { this.next(); this.semicolon(); return this.finishNode(node2, "DebuggerStatement"); } parseHeaderExpression() { this.expect(10); const val = this.parseExpression(); this.expect(11); return val; } parseDoWhileStatement(node2) { this.next(); this.state.labels.push(loopLabel); node2.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); this.state.labels.pop(); this.expect(92); node2.test = this.parseHeaderExpression(); this.eat(13); return this.finishNode(node2, "DoWhileStatement"); } parseForStatement(node2) { this.next(); this.state.labels.push(loopLabel); let awaitAt = null; if (this.isAwaitAllowed() && this.eatContextual(96)) { awaitAt = this.state.lastTokStartLoc; } this.scope.enter(0); this.expect(10); if (this.match(13)) { if (awaitAt !== null) { this.unexpected(awaitAt); } return this.parseFor(node2, null); } const startsWithLet = this.isContextual(100); { const startsWithAwaitUsing = this.isContextual(96) && this.startsAwaitUsing(); const starsWithUsingDeclaration = startsWithAwaitUsing || this.isContextual(107) && this.startsUsingForOf(); const isLetOrUsing = startsWithLet && this.hasFollowingBindingAtom() || starsWithUsingDeclaration; if (this.match(74) || this.match(75) || isLetOrUsing) { const initNode = this.startNode(); let kind; if (startsWithAwaitUsing) { kind = "await using"; if (!this.isAwaitAllowed()) { this.raise(Errors.AwaitUsingNotInAsyncContext, { at: this.state.startLoc }); } this.next(); } else { kind = this.state.value; } this.next(); this.parseVar(initNode, true, kind); const init2 = this.finishNode(initNode, "VariableDeclaration"); const isForIn = this.match(58); if (isForIn && starsWithUsingDeclaration) { this.raise(Errors.ForInUsing, { at: init2 }); } if ((isForIn || this.isContextual(102)) && init2.declarations.length === 1) { return this.parseForIn(node2, init2, awaitAt); } if (awaitAt !== null) { this.unexpected(awaitAt); } return this.parseFor(node2, init2); } } const startsWithAsync = this.isContextual(95); const refExpressionErrors = new ExpressionErrors(); const init = this.parseExpression(true, refExpressionErrors); const isForOf = this.isContextual(102); if (isForOf) { if (startsWithLet) { this.raise(Errors.ForOfLet, { at: init }); } if (awaitAt === null && startsWithAsync && init.type === "Identifier") { this.raise(Errors.ForOfAsync, { at: init }); } } if (isForOf || this.match(58)) { this.checkDestructuringPrivate(refExpressionErrors); this.toAssignable(init, true); const type2 = isForOf ? "ForOfStatement" : "ForInStatement"; this.checkLVal(init, { in: { type: type2 } }); return this.parseForIn(node2, init, awaitAt); } else { this.checkExpressionErrors(refExpressionErrors, true); } if (awaitAt !== null) { this.unexpected(awaitAt); } return this.parseFor(node2, init); } parseFunctionStatement(node2, isAsync2, isHangingDeclaration) { this.next(); return this.parseFunction(node2, 1 | (isHangingDeclaration ? 2 : 0) | (isAsync2 ? 8 : 0)); } parseIfStatement(node2) { this.next(); node2.test = this.parseHeaderExpression(); node2.consequent = this.parseStatementOrSloppyAnnexBFunctionDeclaration(); node2.alternate = this.eat(66) ? this.parseStatementOrSloppyAnnexBFunctionDeclaration() : null; return this.finishNode(node2, "IfStatement"); } parseReturnStatement(node2) { if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) { this.raise(Errors.IllegalReturn, { at: this.state.startLoc }); } this.next(); if (this.isLineTerminator()) { node2.argument = null; } else { node2.argument = this.parseExpression(); this.semicolon(); } return this.finishNode(node2, "ReturnStatement"); } parseSwitchStatement(node2) { this.next(); node2.discriminant = this.parseHeaderExpression(); const cases = node2.cases = []; this.expect(5); this.state.labels.push(switchLabel); this.scope.enter(0); let cur; for (let sawDefault; !this.match(8); ) { if (this.match(61) || this.match(65)) { const isCase = this.match(61); if (cur) this.finishNode(cur, "SwitchCase"); cases.push(cur = this.startNode()); cur.consequent = []; this.next(); if (isCase) { cur.test = this.parseExpression(); } else { if (sawDefault) { this.raise(Errors.MultipleDefaultsInSwitch, { at: this.state.lastTokStartLoc }); } sawDefault = true; cur.test = null; } this.expect(14); } else { if (cur) { cur.consequent.push(this.parseStatementListItem()); } else { this.unexpected(); } } } this.scope.exit(); if (cur) this.finishNode(cur, "SwitchCase"); this.next(); this.state.labels.pop(); return this.finishNode(node2, "SwitchStatement"); } parseThrowStatement(node2) { this.next(); if (this.hasPrecedingLineBreak()) { this.raise(Errors.NewlineAfterThrow, { at: this.state.lastTokEndLoc }); } node2.argument = this.parseExpression(); this.semicolon(); return this.finishNode(node2, "ThrowStatement"); } parseCatchClauseParam() { const param = this.parseBindingAtom(); this.scope.enter(this.options.annexB && param.type === "Identifier" ? 8 : 0); this.checkLVal(param, { in: { type: "CatchClause" }, binding: 9 }); return param; } parseTryStatement(node2) { this.next(); node2.block = this.parseBlock(); node2.handler = null; if (this.match(62)) { const clause = this.startNode(); this.next(); if (this.match(10)) { this.expect(10); clause.param = this.parseCatchClauseParam(); this.expect(11); } else { clause.param = null; this.scope.enter(0); } clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false)); this.scope.exit(); node2.handler = this.finishNode(clause, "CatchClause"); } node2.finalizer = this.eat(67) ? this.parseBlock() : null; if (!node2.handler && !node2.finalizer) { this.raise(Errors.NoCatchOrFinally, { at: node2 }); } return this.finishNode(node2, "TryStatement"); } parseVarStatement(node2, kind, allowMissingInitializer = false) { this.next(); this.parseVar(node2, false, kind, allowMissingInitializer); this.semicolon(); return this.finishNode(node2, "VariableDeclaration"); } parseWhileStatement(node2) { this.next(); node2.test = this.parseHeaderExpression(); this.state.labels.push(loopLabel); node2.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); this.state.labels.pop(); return this.finishNode(node2, "WhileStatement"); } parseWithStatement(node2) { if (this.state.strict) { this.raise(Errors.StrictWith, { at: this.state.startLoc }); } this.next(); node2.object = this.parseHeaderExpression(); node2.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); return this.finishNode(node2, "WithStatement"); } parseEmptyStatement(node2) { this.next(); return this.finishNode(node2, "EmptyStatement"); } parseLabeledStatement(node2, maybeName, expr, flags) { for (const label of this.state.labels) { if (label.name === maybeName) { this.raise(Errors.LabelRedeclaration, { at: expr, labelName: maybeName }); } } const kind = tokenIsLoop(this.state.type) ? "loop" : this.match(71) ? "switch" : null; for (let i2 = this.state.labels.length - 1; i2 >= 0; i2--) { const label = this.state.labels[i2]; if (label.statementStart === node2.start) { label.statementStart = this.state.start; label.kind = kind; } else { break; } } this.state.labels.push({ name: maybeName, kind, statementStart: this.state.start }); node2.body = flags & 8 ? this.parseStatementOrSloppyAnnexBFunctionDeclaration(true) : this.parseStatement(); this.state.labels.pop(); node2.label = expr; return this.finishNode(node2, "LabeledStatement"); } parseExpressionStatement(node2, expr, decorators) { node2.expression = expr; this.semicolon(); return this.finishNode(node2, "ExpressionStatement"); } parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) { const node2 = this.startNode(); if (allowDirectives) { this.state.strictErrors.clear(); } this.expect(5); if (createNewLexicalScope) { this.scope.enter(0); } this.parseBlockBody(node2, allowDirectives, false, 8, afterBlockParse); if (createNewLexicalScope) { this.scope.exit(); } return this.finishNode(node2, "BlockStatement"); } isValidDirective(stmt) { return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized; } parseBlockBody(node2, allowDirectives, topLevel, end, afterBlockParse) { const body = node2.body = []; const directives = node2.directives = []; this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : void 0, topLevel, end, afterBlockParse); } parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) { const oldStrict = this.state.strict; let hasStrictModeDirective = false; let parsedNonDirective = false; while (!this.match(end)) { const stmt = topLevel ? this.parseModuleItem() : this.parseStatementListItem(); if (directives && !parsedNonDirective) { if (this.isValidDirective(stmt)) { const directive = this.stmtToDirective(stmt); directives.push(directive); if (!hasStrictModeDirective && directive.value.value === "use strict") { hasStrictModeDirective = true; this.setStrict(true); } continue; } parsedNonDirective = true; this.state.strictErrors.clear(); } body.push(stmt); } afterBlockParse == null ? void 0 : afterBlockParse.call(this, hasStrictModeDirective); if (!oldStrict) { this.setStrict(false); } this.next(); } parseFor(node2, init) { node2.init = init; this.semicolon(false); node2.test = this.match(13) ? null : this.parseExpression(); this.semicolon(false); node2.update = this.match(11) ? null : this.parseExpression(); this.expect(11); node2.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); this.scope.exit(); this.state.labels.pop(); return this.finishNode(node2, "ForStatement"); } parseForIn(node2, init, awaitAt) { const isForIn = this.match(58); this.next(); if (isForIn) { if (awaitAt !== null) this.unexpected(awaitAt); } else { node2.await = awaitAt !== null; } if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || !this.options.annexB || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) { this.raise(Errors.ForInOfLoopInitializer, { at: init, type: isForIn ? "ForInStatement" : "ForOfStatement" }); } if (init.type === "AssignmentPattern") { this.raise(Errors.InvalidLhs, { at: init, ancestor: { type: "ForStatement" } }); } node2.left = init; node2.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn(); this.expect(11); node2.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement()); this.scope.exit(); this.state.labels.pop(); return this.finishNode(node2, isForIn ? "ForInStatement" : "ForOfStatement"); } parseVar(node2, isFor, kind, allowMissingInitializer = false) { const declarations = node2.declarations = []; node2.kind = kind; for (; ; ) { const decl = this.startNode(); this.parseVarId(decl, kind); decl.init = !this.eat(29) ? null : isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn(); if (decl.init === null && !allowMissingInitializer) { if (decl.id.type !== "Identifier" && !(isFor && (this.match(58) || this.isContextual(102)))) { this.raise(Errors.DeclarationMissingInitializer, { at: this.state.lastTokEndLoc, kind: "destructuring" }); } else if (kind === "const" && !(this.match(58) || this.isContextual(102))) { this.raise(Errors.DeclarationMissingInitializer, { at: this.state.lastTokEndLoc, kind: "const" }); } } declarations.push(this.finishNode(decl, "VariableDeclarator")); if (!this.eat(12)) break; } return node2; } parseVarId(decl, kind) { const id = this.parseBindingAtom(); this.checkLVal(id, { in: { type: "VariableDeclarator" }, binding: kind === "var" ? 5 : 8201 }); decl.id = id; } parseAsyncFunctionExpression(node2) { return this.parseFunction(node2, 8); } parseFunction(node2, flags = 0) { const hangingDeclaration = flags & 2; const isDeclaration = !!(flags & 1); const requireId = isDeclaration && !(flags & 4); const isAsync2 = !!(flags & 8); this.initFunction(node2, isAsync2); if (this.match(55)) { if (hangingDeclaration) { this.raise(Errors.GeneratorInSingleStatementContext, { at: this.state.startLoc }); } this.next(); node2.generator = true; } if (isDeclaration) { node2.id = this.parseFunctionId(requireId); } const oldMaybeInArrowParameters = this.state.maybeInArrowParameters; this.state.maybeInArrowParameters = false; this.scope.enter(2); this.prodParam.enter(functionFlags(isAsync2, node2.generator)); if (!isDeclaration) { node2.id = this.parseFunctionId(); } this.parseFunctionParams(node2, false); this.withSmartMixTopicForbiddingContext(() => { this.parseFunctionBodyAndFinish(node2, isDeclaration ? "FunctionDeclaration" : "FunctionExpression"); }); this.prodParam.exit(); this.scope.exit(); if (isDeclaration && !hangingDeclaration) { this.registerFunctionStatementId(node2); } this.state.maybeInArrowParameters = oldMaybeInArrowParameters; return node2; } parseFunctionId(requireId) { return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null; } parseFunctionParams(node2, isConstructor) { this.expect(10); this.expressionScope.enter(newParameterDeclarationScope()); node2.params = this.parseBindingList(11, 41, 2 | (isConstructor ? 4 : 0)); this.expressionScope.exit(); } registerFunctionStatementId(node2) { if (!node2.id) return; this.scope.declareName(node2.id.name, !this.options.annexB || this.state.strict || node2.generator || node2.async ? this.scope.treatFunctionsAsVar ? 5 : 8201 : 17, node2.id.loc.start); } parseClass(node2, isStatement, optionalId) { this.next(); const oldStrict = this.state.strict; this.state.strict = true; this.parseClassId(node2, isStatement, optionalId); this.parseClassSuper(node2); node2.body = this.parseClassBody(!!node2.superClass, oldStrict); return this.finishNode(node2, isStatement ? "ClassDeclaration" : "ClassExpression"); } isClassProperty() { return this.match(29) || this.match(13) || this.match(8); } isClassMethod() { return this.match(10); } isNonstaticConstructor(method) { return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor"); } parseClassBody(hadSuperClass, oldStrict) { this.classScope.enter(); const state = { hadConstructor: false, hadSuperClass }; let decorators = []; const classBody = this.startNode(); classBody.body = []; this.expect(5); this.withSmartMixTopicForbiddingContext(() => { while (!this.match(8)) { if (this.eat(13)) { if (decorators.length > 0) { throw this.raise(Errors.DecoratorSemicolon, { at: this.state.lastTokEndLoc }); } continue; } if (this.match(26)) { decorators.push(this.parseDecorator()); continue; } const member = this.startNode(); if (decorators.length) { member.decorators = decorators; this.resetStartLocationFromNode(member, decorators[0]); decorators = []; } this.parseClassMember(classBody, member, state); if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) { this.raise(Errors.DecoratorConstructor, { at: member }); } } }); this.state.strict = oldStrict; this.next(); if (decorators.length) { throw this.raise(Errors.TrailingDecorator, { at: this.state.startLoc }); } this.classScope.exit(); return this.finishNode(classBody, "ClassBody"); } parseClassMemberFromModifier(classBody, member) { const key = this.parseIdentifier(true); if (this.isClassMethod()) { const method = member; method.kind = "method"; method.computed = false; method.key = key; method.static = false; this.pushClassMethod(classBody, method, false, false, false, false); return true; } else if (this.isClassProperty()) { const prop = member; prop.computed = false; prop.key = key; prop.static = false; classBody.body.push(this.parseClassProperty(prop)); return true; } this.resetPreviousNodeTrailingComments(key); return false; } parseClassMember(classBody, member, state) { const isStatic = this.isContextual(106); if (isStatic) { if (this.parseClassMemberFromModifier(classBody, member)) { return; } if (this.eat(5)) { this.parseClassStaticBlock(classBody, member); return; } } this.parseClassMemberWithIsStatic(classBody, member, state, isStatic); } parseClassMemberWithIsStatic(classBody, member, state, isStatic) { const publicMethod = member; const privateMethod = member; const publicProp = member; const privateProp = member; const accessorProp = member; const method = publicMethod; const publicMember = publicMethod; member.static = isStatic; this.parsePropertyNamePrefixOperator(member); if (this.eat(55)) { method.kind = "method"; const isPrivateName = this.match(138); this.parseClassElementName(method); if (isPrivateName) { this.pushClassPrivateMethod(classBody, privateMethod, true, false); return; } if (this.isNonstaticConstructor(publicMethod)) { this.raise(Errors.ConstructorIsGenerator, { at: publicMethod.key }); } this.pushClassMethod(classBody, publicMethod, true, false, false, false); return; } const isContextual = tokenIsIdentifier(this.state.type) && !this.state.containsEsc; const isPrivate = this.match(138); const key = this.parseClassElementName(member); const maybeQuestionTokenStartLoc = this.state.startLoc; this.parsePostMemberNameModifiers(publicMember); if (this.isClassMethod()) { method.kind = "method"; if (isPrivate) { this.pushClassPrivateMethod(classBody, privateMethod, false, false); return; } const isConstructor = this.isNonstaticConstructor(publicMethod); let allowsDirectSuper = false; if (isConstructor) { publicMethod.kind = "constructor"; if (state.hadConstructor && !this.hasPlugin("typescript")) { this.raise(Errors.DuplicateConstructor, { at: key }); } if (isConstructor && this.hasPlugin("typescript") && member.override) { this.raise(Errors.OverrideOnConstructor, { at: key }); } state.hadConstructor = true; allowsDirectSuper = state.hadSuperClass; } this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper); } else if (this.isClassProperty()) { if (isPrivate) { this.pushClassPrivateProperty(classBody, privateProp); } else { this.pushClassProperty(classBody, publicProp); } } else if (isContextual && key.name === "async" && !this.isLineTerminator()) { this.resetPreviousNodeTrailingComments(key); const isGenerator = this.eat(55); if (publicMember.optional) { this.unexpected(maybeQuestionTokenStartLoc); } method.kind = "method"; const isPrivate2 = this.match(138); this.parseClassElementName(method); this.parsePostMemberNameModifiers(publicMember); if (isPrivate2) { this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true); } else { if (this.isNonstaticConstructor(publicMethod)) { this.raise(Errors.ConstructorIsAsync, { at: publicMethod.key }); } this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false); } } else if (isContextual && (key.name === "get" || key.name === "set") && !(this.match(55) && this.isLineTerminator())) { this.resetPreviousNodeTrailingComments(key); method.kind = key.name; const isPrivate2 = this.match(138); this.parseClassElementName(publicMethod); if (isPrivate2) { this.pushClassPrivateMethod(classBody, privateMethod, false, false); } else { if (this.isNonstaticConstructor(publicMethod)) { this.raise(Errors.ConstructorIsAccessor, { at: publicMethod.key }); } this.pushClassMethod(classBody, publicMethod, false, false, false, false); } this.checkGetterSetterParams(publicMethod); } else if (isContextual && key.name === "accessor" && !this.isLineTerminator()) { this.expectPlugin("decoratorAutoAccessors"); this.resetPreviousNodeTrailingComments(key); const isPrivate2 = this.match(138); this.parseClassElementName(publicProp); this.pushClassAccessorProperty(classBody, accessorProp, isPrivate2); } else if (this.isLineTerminator()) { if (isPrivate) { this.pushClassPrivateProperty(classBody, privateProp); } else { this.pushClassProperty(classBody, publicProp); } } else { this.unexpected(); } } parseClassElementName(member) { const { type: type2, value } = this.state; if ((type2 === 132 || type2 === 133) && member.static && value === "prototype") { this.raise(Errors.StaticPrototype, { at: this.state.startLoc }); } if (type2 === 138) { if (value === "constructor") { this.raise(Errors.ConstructorClassPrivateField, { at: this.state.startLoc }); } const key = this.parsePrivateName(); member.key = key; return key; } return this.parsePropertyName(member); } parseClassStaticBlock(classBody, member) { var _member$decorators; this.scope.enter(64 | 128 | 16); const oldLabels = this.state.labels; this.state.labels = []; this.prodParam.enter(PARAM); const body = member.body = []; this.parseBlockOrModuleBlockBody(body, void 0, false, 8); this.prodParam.exit(); this.scope.exit(); this.state.labels = oldLabels; classBody.body.push(this.finishNode(member, "StaticBlock")); if ((_member$decorators = member.decorators) != null && _member$decorators.length) { this.raise(Errors.DecoratorStaticBlock, { at: member }); } } pushClassProperty(classBody, prop) { if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) { this.raise(Errors.ConstructorClassField, { at: prop.key }); } classBody.body.push(this.parseClassProperty(prop)); } pushClassPrivateProperty(classBody, prop) { const node2 = this.parseClassPrivateProperty(prop); classBody.body.push(node2); this.classScope.declarePrivateName(this.getPrivateNameSV(node2.key), 0, node2.key.loc.start); } pushClassAccessorProperty(classBody, prop, isPrivate) { if (!isPrivate && !prop.computed) { const key = prop.key; if (key.name === "constructor" || key.value === "constructor") { this.raise(Errors.ConstructorClassField, { at: key }); } } const node2 = this.parseClassAccessorProperty(prop); classBody.body.push(node2); if (isPrivate) { this.classScope.declarePrivateName(this.getPrivateNameSV(node2.key), 0, node2.key.loc.start); } } pushClassMethod(classBody, method, isGenerator, isAsync2, isConstructor, allowsDirectSuper) { classBody.body.push(this.parseMethod(method, isGenerator, isAsync2, isConstructor, allowsDirectSuper, "ClassMethod", true)); } pushClassPrivateMethod(classBody, method, isGenerator, isAsync2) { const node2 = this.parseMethod(method, isGenerator, isAsync2, false, false, "ClassPrivateMethod", true); classBody.body.push(node2); const kind = node2.kind === "get" ? node2.static ? 6 : 2 : node2.kind === "set" ? node2.static ? 5 : 1 : 0; this.declareClassPrivateMethodInScope(node2, kind); } declareClassPrivateMethodInScope(node2, kind) { this.classScope.declarePrivateName(this.getPrivateNameSV(node2.key), kind, node2.key.loc.start); } parsePostMemberNameModifiers(methodOrProp) { } parseClassPrivateProperty(node2) { this.parseInitializer(node2); this.semicolon(); return this.finishNode(node2, "ClassPrivateProperty"); } parseClassProperty(node2) { this.parseInitializer(node2); this.semicolon(); return this.finishNode(node2, "ClassProperty"); } parseClassAccessorProperty(node2) { this.parseInitializer(node2); this.semicolon(); return this.finishNode(node2, "ClassAccessorProperty"); } parseInitializer(node2) { this.scope.enter(64 | 16); this.expressionScope.enter(newExpressionScope()); this.prodParam.enter(PARAM); node2.value = this.eat(29) ? this.parseMaybeAssignAllowIn() : null; this.expressionScope.exit(); this.prodParam.exit(); this.scope.exit(); } parseClassId(node2, isStatement, optionalId, bindingType = 8331) { if (tokenIsIdentifier(this.state.type)) { node2.id = this.parseIdentifier(); if (isStatement) { this.declareNameFromIdentifier(node2.id, bindingType); } } else { if (optionalId || !isStatement) { node2.id = null; } else { throw this.raise(Errors.MissingClassName, { at: this.state.startLoc }); } } } parseClassSuper(node2) { node2.superClass = this.eat(81) ? this.parseExprSubscripts() : null; } parseExport(node2, decorators) { const maybeDefaultIdentifier = this.parseMaybeImportPhase(node2, true); const hasDefault = this.maybeParseExportDefaultSpecifier(node2, maybeDefaultIdentifier); const parseAfterDefault = !hasDefault || this.eat(12); const hasStar = parseAfterDefault && this.eatExportStar(node2); const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node2); const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12)); const isFromRequired = hasDefault || hasStar; if (hasStar && !hasNamespace) { if (hasDefault) this.unexpected(); if (decorators) { throw this.raise(Errors.UnsupportedDecoratorExport, { at: node2 }); } this.parseExportFrom(node2, true); return this.finishNode(node2, "ExportAllDeclaration"); } const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node2); if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers) { this.unexpected(null, 5); } if (hasNamespace && parseAfterNamespace) { this.unexpected(null, 98); } let hasDeclaration; if (isFromRequired || hasSpecifiers) { hasDeclaration = false; if (decorators) { throw this.raise(Errors.UnsupportedDecoratorExport, { at: node2 }); } this.parseExportFrom(node2, isFromRequired); } else { hasDeclaration = this.maybeParseExportDeclaration(node2); } if (isFromRequired || hasSpecifiers || hasDeclaration) { var _node2$declaration; const node22 = node2; this.checkExport(node22, true, false, !!node22.source); if (((_node2$declaration = node22.declaration) == null ? void 0 : _node2$declaration.type) === "ClassDeclaration") { this.maybeTakeDecorators(decorators, node22.declaration, node22); } else if (decorators) { throw this.raise(Errors.UnsupportedDecoratorExport, { at: node2 }); } return this.finishNode(node22, "ExportNamedDeclaration"); } if (this.eat(65)) { const node22 = node2; const decl = this.parseExportDefaultExpression(); node22.declaration = decl; if (decl.type === "ClassDeclaration") { this.maybeTakeDecorators(decorators, decl, node22); } else if (decorators) { throw this.raise(Errors.UnsupportedDecoratorExport, { at: node2 }); } this.checkExport(node22, true, true); return this.finishNode(node22, "ExportDefaultDeclaration"); } this.unexpected(null, 5); } eatExportStar(node2) { return this.eat(55); } maybeParseExportDefaultSpecifier(node2, maybeDefaultIdentifier) { if (maybeDefaultIdentifier || this.isExportDefaultSpecifier()) { this.expectPlugin("exportDefaultFrom", maybeDefaultIdentifier == null ? void 0 : maybeDefaultIdentifier.loc.start); const id = maybeDefaultIdentifier || this.parseIdentifier(true); const specifier = this.startNodeAtNode(id); specifier.exported = id; node2.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; return true; } return false; } maybeParseExportNamespaceSpecifier(node2) { if (this.isContextual(93)) { if (!node2.specifiers) node2.specifiers = []; const specifier = this.startNodeAt(this.state.lastTokStartLoc); this.next(); specifier.exported = this.parseModuleExportName(); node2.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier")); return true; } return false; } maybeParseExportNamedSpecifiers(node2) { if (this.match(5)) { if (!node2.specifiers) node2.specifiers = []; const isTypeExport = node2.exportKind === "type"; node2.specifiers.push(...this.parseExportSpecifiers(isTypeExport)); node2.source = null; node2.declaration = null; if (this.hasPlugin("importAssertions")) { node2.assertions = []; } return true; } return false; } maybeParseExportDeclaration(node2) { if (this.shouldParseExportDeclaration()) { node2.specifiers = []; node2.source = null; if (this.hasPlugin("importAssertions")) { node2.assertions = []; } node2.declaration = this.parseExportDeclaration(node2); return true; } return false; } isAsyncFunction() { if (!this.isContextual(95)) return false; const next = this.nextTokenInLineStart(); return this.isUnparsedContextual(next, "function"); } parseExportDefaultExpression() { const expr = this.startNode(); if (this.match(68)) { this.next(); return this.parseFunction(expr, 1 | 4); } else if (this.isAsyncFunction()) { this.next(); this.next(); return this.parseFunction(expr, 1 | 4 | 8); } if (this.match(80)) { return this.parseClass(expr, true, true); } if (this.match(26)) { if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") === true) { this.raise(Errors.DecoratorBeforeExport, { at: this.state.startLoc }); } return this.parseClass(this.maybeTakeDecorators(this.parseDecorators(false), this.startNode()), true, true); } if (this.match(75) || this.match(74) || this.isLet()) { throw this.raise(Errors.UnsupportedDefaultExport, { at: this.state.startLoc }); } const res = this.parseMaybeAssignAllowIn(); this.semicolon(); return res; } parseExportDeclaration(node2) { if (this.match(80)) { const node3 = this.parseClass(this.startNode(), true, false); return node3; } return this.parseStatementListItem(); } isExportDefaultSpecifier() { const { type: type2 } = this.state; if (tokenIsIdentifier(type2)) { if (type2 === 95 && !this.state.containsEsc || type2 === 100) { return false; } if ((type2 === 130 || type2 === 129) && !this.state.containsEsc) { const { type: nextType } = this.lookahead(); if (tokenIsIdentifier(nextType) && nextType !== 98 || nextType === 5) { this.expectOnePlugin(["flow", "typescript"]); return false; } } } else if (!this.match(65)) { return false; } const next = this.nextTokenStart(); const hasFrom = this.isUnparsedContextual(next, "from"); if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) { return true; } if (this.match(65) && hasFrom) { const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4)); return nextAfterFrom === 34 || nextAfterFrom === 39; } return false; } parseExportFrom(node2, expect) { if (this.eatContextual(98)) { node2.source = this.parseImportSource(); this.checkExport(node2); this.maybeParseImportAttributes(node2); this.checkJSONModuleImport(node2); } else if (expect) { this.unexpected(); } this.semicolon(); } shouldParseExportDeclaration() { const { type: type2 } = this.state; if (type2 === 26) { this.expectOnePlugin(["decorators", "decorators-legacy"]); if (this.hasPlugin("decorators")) { if (this.getPluginOption("decorators", "decoratorsBeforeExport") === true) { this.raise(Errors.DecoratorBeforeExport, { at: this.state.startLoc }); } return true; } } return type2 === 74 || type2 === 75 || type2 === 68 || type2 === 80 || this.isLet() || this.isAsyncFunction(); } checkExport(node2, checkNames, isDefault, isFrom) { if (checkNames) { var _node$specifiers; if (isDefault) { this.checkDuplicateExports(node2, "default"); if (this.hasPlugin("exportDefaultFrom")) { var _declaration$extra; const declaration = node2.declaration; if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) { this.raise(Errors.ExportDefaultFromAsIdentifier, { at: declaration }); } } } else if ((_node$specifiers = node2.specifiers) != null && _node$specifiers.length) { for (const specifier of node2.specifiers) { const { exported } = specifier; const exportName = exported.type === "Identifier" ? exported.name : exported.value; this.checkDuplicateExports(specifier, exportName); if (!isFrom && specifier.local) { const { local } = specifier; if (local.type !== "Identifier") { this.raise(Errors.ExportBindingIsString, { at: specifier, localName: local.value, exportName }); } else { this.checkReservedWord(local.name, local.loc.start, true, false); this.scope.checkLocalExport(local); } } } } else if (node2.declaration) { if (node2.declaration.type === "FunctionDeclaration" || node2.declaration.type === "ClassDeclaration") { const id = node2.declaration.id; if (!id) throw new Error("Assertion failure"); this.checkDuplicateExports(node2, id.name); } else if (node2.declaration.type === "VariableDeclaration") { for (const declaration of node2.declaration.declarations) { this.checkDeclaration(declaration.id); } } } } } checkDeclaration(node2) { if (node2.type === "Identifier") { this.checkDuplicateExports(node2, node2.name); } else if (node2.type === "ObjectPattern") { for (const prop of node2.properties) { this.checkDeclaration(prop); } } else if (node2.type === "ArrayPattern") { for (const elem of node2.elements) { if (elem) { this.checkDeclaration(elem); } } } else if (node2.type === "ObjectProperty") { this.checkDeclaration(node2.value); } else if (node2.type === "RestElement") { this.checkDeclaration(node2.argument); } else if (node2.type === "AssignmentPattern") { this.checkDeclaration(node2.left); } } checkDuplicateExports(node2, exportName) { if (this.exportedIdentifiers.has(exportName)) { if (exportName === "default") { this.raise(Errors.DuplicateDefaultExport, { at: node2 }); } else { this.raise(Errors.DuplicateExport, { at: node2, exportName }); } } this.exportedIdentifiers.add(exportName); } parseExportSpecifiers(isInTypeExport) { const nodes = []; let first = true; this.expect(5); while (!this.eat(8)) { if (first) { first = false; } else { this.expect(12); if (this.eat(8)) break; } const isMaybeTypeOnly = this.isContextual(130); const isString = this.match(133); const node2 = this.startNode(); node2.local = this.parseModuleExportName(); nodes.push(this.parseExportSpecifier(node2, isString, isInTypeExport, isMaybeTypeOnly)); } return nodes; } parseExportSpecifier(node2, isString, isInTypeExport, isMaybeTypeOnly) { if (this.eatContextual(93)) { node2.exported = this.parseModuleExportName(); } else if (isString) { node2.exported = cloneStringLiteral(node2.local); } else if (!node2.exported) { node2.exported = cloneIdentifier(node2.local); } return this.finishNode(node2, "ExportSpecifier"); } parseModuleExportName() { if (this.match(133)) { const result = this.parseStringLiteral(this.state.value); const surrogate = result.value.match(loneSurrogate); if (surrogate) { this.raise(Errors.ModuleExportNameHasLoneSurrogate, { at: result, surrogateCharCode: surrogate[0].charCodeAt(0) }); } return result; } return this.parseIdentifier(true); } isJSONModuleImport(node2) { if (node2.assertions != null) { return node2.assertions.some(({ key, value }) => { return value.value === "json" && (key.type === "Identifier" ? key.name === "type" : key.value === "type"); }); } return false; } checkImportReflection(node2) { const { specifiers } = node2; const singleBindingType = specifiers.length === 1 ? specifiers[0].type : null; if (node2.phase === "source") { if (singleBindingType !== "ImportDefaultSpecifier") { this.raise(Errors.SourcePhaseImportRequiresDefault, { at: specifiers[0].loc.start }); } } else if (node2.phase === "defer") { if (singleBindingType !== "ImportNamespaceSpecifier") { this.raise(Errors.DeferImportRequiresNamespace, { at: specifiers[0].loc.start }); } } else if (node2.module) { var _node$assertions; if (singleBindingType !== "ImportDefaultSpecifier") { this.raise(Errors.ImportReflectionNotBinding, { at: specifiers[0].loc.start }); } if (((_node$assertions = node2.assertions) == null ? void 0 : _node$assertions.length) > 0) { this.raise(Errors.ImportReflectionHasAssertion, { at: node2.specifiers[0].loc.start }); } } } checkJSONModuleImport(node2) { if (this.isJSONModuleImport(node2) && node2.type !== "ExportAllDeclaration") { const { specifiers } = node2; if (specifiers != null) { const nonDefaultNamedSpecifier = specifiers.find((specifier) => { let imported; if (specifier.type === "ExportSpecifier") { imported = specifier.local; } else if (specifier.type === "ImportSpecifier") { imported = specifier.imported; } if (imported !== void 0) { return imported.type === "Identifier" ? imported.name !== "default" : imported.value !== "default"; } }); if (nonDefaultNamedSpecifier !== void 0) { this.raise(Errors.ImportJSONBindingNotDefault, { at: nonDefaultNamedSpecifier.loc.start }); } } } } isPotentialImportPhase(isExport) { if (isExport) return false; return this.isContextual(105) || this.isContextual(97) || this.isContextual(127); } applyImportPhase(node2, isExport, phase, loc) { if (isExport) { return; } if (phase === "module") { this.expectPlugin("importReflection", loc); node2.module = true; } else if (this.hasPlugin("importReflection")) { node2.module = false; } if (phase === "source") { this.expectPlugin("sourcePhaseImports", loc); node2.phase = "source"; } else if (phase === "defer") { this.expectPlugin("deferredImportEvaluation", loc); node2.phase = "defer"; } else if (this.hasPlugin("sourcePhaseImports")) { node2.phase = null; } } parseMaybeImportPhase(node2, isExport) { if (!this.isPotentialImportPhase(isExport)) { this.applyImportPhase(node2, isExport, null); return null; } const phaseIdentifier = this.parseIdentifier(true); const { type: type2 } = this.state; const isImportPhase = tokenIsKeywordOrIdentifier(type2) ? type2 !== 98 || this.lookaheadCharCode() === 102 : type2 !== 12; if (isImportPhase) { this.resetPreviousIdentifierLeadingComments(phaseIdentifier); this.applyImportPhase(node2, isExport, phaseIdentifier.name, phaseIdentifier.loc.start); return null; } else { this.applyImportPhase(node2, isExport, null); return phaseIdentifier; } } isPrecedingIdImportPhase(phase) { const { type: type2 } = this.state; return tokenIsIdentifier(type2) ? type2 !== 98 || this.lookaheadCharCode() === 102 : type2 !== 12; } parseImport(node2) { if (this.match(133)) { return this.parseImportSourceAndAttributes(node2); } return this.parseImportSpecifiersAndAfter(node2, this.parseMaybeImportPhase(node2, false)); } parseImportSpecifiersAndAfter(node2, maybeDefaultIdentifier) { node2.specifiers = []; const hasDefault = this.maybeParseDefaultImportSpecifier(node2, maybeDefaultIdentifier); const parseNext = !hasDefault || this.eat(12); const hasStar = parseNext && this.maybeParseStarImportSpecifier(node2); if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node2); this.expectContextual(98); return this.parseImportSourceAndAttributes(node2); } parseImportSourceAndAttributes(node2) { var _node$specifiers2; (_node$specifiers2 = node2.specifiers) != null ? _node$specifiers2 : node2.specifiers = []; node2.source = this.parseImportSource(); this.maybeParseImportAttributes(node2); this.checkImportReflection(node2); this.checkJSONModuleImport(node2); this.semicolon(); return this.finishNode(node2, "ImportDeclaration"); } parseImportSource() { if (!this.match(133)) this.unexpected(); return this.parseExprAtom(); } parseImportSpecifierLocal(node2, specifier, type2) { specifier.local = this.parseIdentifier(); node2.specifiers.push(this.finishImportSpecifier(specifier, type2)); } finishImportSpecifier(specifier, type2, bindingType = 8201) { this.checkLVal(specifier.local, { in: { type: type2 }, binding: bindingType }); return this.finishNode(specifier, type2); } parseImportAttributes() { this.expect(5); const attrs = []; const attrNames = /* @__PURE__ */ new Set(); do { if (this.match(8)) { break; } const node2 = this.startNode(); const keyName = this.state.value; if (attrNames.has(keyName)) { this.raise(Errors.ModuleAttributesWithDuplicateKeys, { at: this.state.startLoc, key: keyName }); } attrNames.add(keyName); if (this.match(133)) { node2.key = this.parseStringLiteral(keyName); } else { node2.key = this.parseIdentifier(true); } this.expect(14); if (!this.match(133)) { throw this.raise(Errors.ModuleAttributeInvalidValue, { at: this.state.startLoc }); } node2.value = this.parseStringLiteral(this.state.value); attrs.push(this.finishNode(node2, "ImportAttribute")); } while (this.eat(12)); this.expect(8); return attrs; } parseModuleAttributes() { const attrs = []; const attributes = /* @__PURE__ */ new Set(); do { const node2 = this.startNode(); node2.key = this.parseIdentifier(true); if (node2.key.name !== "type") { this.raise(Errors.ModuleAttributeDifferentFromType, { at: node2.key }); } if (attributes.has(node2.key.name)) { this.raise(Errors.ModuleAttributesWithDuplicateKeys, { at: node2.key, key: node2.key.name }); } attributes.add(node2.key.name); this.expect(14); if (!this.match(133)) { throw this.raise(Errors.ModuleAttributeInvalidValue, { at: this.state.startLoc }); } node2.value = this.parseStringLiteral(this.state.value); attrs.push(this.finishNode(node2, "ImportAttribute")); } while (this.eat(12)); return attrs; } maybeParseImportAttributes(node2) { let attributes; let useWith = false; if (this.match(76)) { if (this.hasPrecedingLineBreak() && this.lookaheadCharCode() === 40) { return; } this.next(); { if (this.hasPlugin("moduleAttributes")) { attributes = this.parseModuleAttributes(); } else { this.expectImportAttributesPlugin(); attributes = this.parseImportAttributes(); } } useWith = true; } else if (this.isContextual(94) && !this.hasPrecedingLineBreak()) { if (this.hasPlugin("importAttributes")) { if (this.getPluginOption("importAttributes", "deprecatedAssertSyntax") !== true) { this.raise(Errors.ImportAttributesUseAssert, { at: this.state.startLoc }); } this.addExtra(node2, "deprecatedAssertSyntax", true); } else { this.expectOnePlugin(["importAttributes", "importAssertions"]); } this.next(); attributes = this.parseImportAttributes(); } else if (this.hasPlugin("importAttributes") || this.hasPlugin("importAssertions")) { attributes = []; } else { if (this.hasPlugin("moduleAttributes")) { attributes = []; } else return; } if (!useWith && this.hasPlugin("importAssertions")) { node2.assertions = attributes; } else { node2.attributes = attributes; } } maybeParseDefaultImportSpecifier(node2, maybeDefaultIdentifier) { if (maybeDefaultIdentifier) { const specifier = this.startNodeAtNode(maybeDefaultIdentifier); specifier.local = maybeDefaultIdentifier; node2.specifiers.push(this.finishImportSpecifier(specifier, "ImportDefaultSpecifier")); return true; } else if (tokenIsKeywordOrIdentifier(this.state.type)) { this.parseImportSpecifierLocal(node2, this.startNode(), "ImportDefaultSpecifier"); return true; } return false; } maybeParseStarImportSpecifier(node2) { if (this.match(55)) { const specifier = this.startNode(); this.next(); this.expectContextual(93); this.parseImportSpecifierLocal(node2, specifier, "ImportNamespaceSpecifier"); return true; } return false; } parseNamedImportSpecifiers(node2) { let first = true; this.expect(5); while (!this.eat(8)) { if (first) { first = false; } else { if (this.eat(14)) { throw this.raise(Errors.DestructureNamedImport, { at: this.state.startLoc }); } this.expect(12); if (this.eat(8)) break; } const specifier = this.startNode(); const importedIsString = this.match(133); const isMaybeTypeOnly = this.isContextual(130); specifier.imported = this.parseModuleExportName(); const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node2.importKind === "type" || node2.importKind === "typeof", isMaybeTypeOnly, void 0); node2.specifiers.push(importSpecifier); } } parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) { if (this.eatContextual(93)) { specifier.local = this.parseIdentifier(); } else { const { imported } = specifier; if (importedIsString) { throw this.raise(Errors.ImportBindingIsString, { at: specifier, importName: imported.value }); } this.checkReservedWord(imported.name, specifier.loc.start, true, true); if (!specifier.local) { specifier.local = cloneIdentifier(imported); } } return this.finishImportSpecifier(specifier, "ImportSpecifier", bindingType); } isThisParam(param) { return param.type === "Identifier" && param.name === "this"; } }; var Parser = class extends StatementParser { constructor(options, input) { options = getOptions(options); super(options, input); this.options = options; this.initializeScopes(); this.plugins = pluginsMap(this.options.plugins); this.filename = options.sourceFilename; } getScopeHandler() { return ScopeHandler; } parse() { this.enterInitialScopes(); const file = this.startNode(); const program = this.startNode(); this.nextToken(); file.errors = null; this.parseTopLevel(file, program); file.errors = this.state.errors; return file; } }; function pluginsMap(plugins) { const pluginMap = /* @__PURE__ */ new Map(); for (const plugin of plugins) { const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}]; if (!pluginMap.has(name)) pluginMap.set(name, options || {}); } return pluginMap; } function parse3(input, options) { var _options; if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") { options = Object.assign({}, options); try { options.sourceType = "module"; const parser = getParser(options, input); const ast = parser.parse(); if (parser.sawUnambiguousESM) { return ast; } if (parser.ambiguousScriptDifferentAst) { try { options.sourceType = "script"; return getParser(options, input).parse(); } catch (_unused) { } } else { ast.program.sourceType = "script"; } return ast; } catch (moduleError) { try { options.sourceType = "script"; return getParser(options, input).parse(); } catch (_unused2) { } throw moduleError; } } else { return getParser(options, input).parse(); } } function parseExpression(input, options) { const parser = getParser(options, input); if (parser.options.strictMode) { parser.state.strict = true; } return parser.getExpression(); } function generateExportedTokenTypes(internalTokenTypes) { const tokenTypes2 = {}; for (const typeName of Object.keys(internalTokenTypes)) { tokenTypes2[typeName] = getExportedToken(internalTokenTypes[typeName]); } return tokenTypes2; } var tokTypes = generateExportedTokenTypes(tt); function getParser(options, input) { let cls = Parser; if (options != null && options.plugins) { validatePlugins(options.plugins); cls = getParserClass(options.plugins); } return new cls(options, input); } var parserClassCache = {}; function getParserClass(pluginsFromOptions) { const pluginList = mixinPluginNames.filter((name) => hasPlugin(pluginsFromOptions, name)); const key = pluginList.join("/"); let cls = parserClassCache[key]; if (!cls) { cls = Parser; for (const plugin of pluginList) { cls = mixinPlugins[plugin](cls); } parserClassCache[key] = cls; } return cls; } exports.parse = parse3; exports.parseExpression = parseExpression; exports.tokTypes = tokTypes; } }); // node_modules/recast/parsers/babel.js var require_babel2 = __commonJS({ "node_modules/recast/parsers/babel.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parse = exports.parser = void 0; var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); var _babel_options_1 = tslib_1.__importDefault(require_babel_options()); exports.parser = function() { try { return require_lib2(); } catch (_a) { try { return require("babylon"); } catch (_b) { throw new Error("Install @babel/parser to use the `typescript`, `flow`, or `babel` parsers"); } } }(); function parse3(source, options) { var babelOptions = (0, _babel_options_1.default)(options); babelOptions.plugins.push("jsx", "flow", "decoratorAutoAccessors"); return exports.parser.parse(source, babelOptions); } exports.parse = parse3; } }); // src/main.ts var main_exports = {}; __export(main_exports, { DEFAULT_SETTINGS: () => DEFAULT_SETTINGS, default: () => RunPlugin }); module.exports = __toCommonJS(main_exports); var import_obsidian4 = require("obsidian"); var import_obsidian_dataview = __toESM(require_lib()); // src/utils/obsidian.ts var import_obsidian = require("obsidian"); // src/utils/regex.ts var fencedRegexTemplate = "^XXX\\.*?\n(?:((?:.|\n)*?)\n)?XXX(?=\\s|$)$"; var yamlRegex = /^---\n((?:(((?!---)(?:.|\n)*?)\n)?))---(?=\n|$)/; var backtickBlockRegexTemplate = fencedRegexTemplate.replaceAll( "X", "`" ); var tildeBlockRegexTemplate = fencedRegexTemplate.replaceAll("X", "~"); var indentedBlockRegex = "^(( |( {4})).*\n)+"; var codeBlockRegex = new RegExp( `${backtickBlockRegexTemplate}|${tildeBlockRegexTemplate}|${indentedBlockRegex}`, "gm" ); var lineStartingWithWhitespaceOrBlockquoteTemplate = `\\s*(>\\s*)*`; var customIgnoreAllStartIndicator = generateHTMLLinterCommentWithSpecificTextAndWhitespaceRegexMatch(true); var customIgnoreAllEndIndicator = generateHTMLLinterCommentWithSpecificTextAndWhitespaceRegexMatch(false); var checklistBoxIndicator = "\\[.\\]"; var checklistBoxStartsTextRegex = new RegExp( `^${checklistBoxIndicator}` ); var indentedOrBlockquoteNestedChecklistIndicatorRegex = new RegExp( `^${lineStartingWithWhitespaceOrBlockquoteTemplate}- ${checklistBoxIndicator} ` ); var nonBlockquoteChecklistRegex = new RegExp( `^\\s*- ${checklistBoxIndicator} ` ); function generateHTMLLinterCommentWithSpecificTextAndWhitespaceRegexMatch(isStart) { const regexTemplate = ""; let endingText = ""; if (isStart) { endingText += "disable"; } else { endingText += "enable"; } return new RegExp(regexTemplate.replace("{ENDING_TEXT}", endingText), "g"); } // src/utils/strings.ts function hashString53Bit(str2, seed = 0) { let h1 = 3735928559 ^ seed; let h22 = 1103547991 ^ seed; for (let i2 = 0, ch; i2 < str2.length; i2++) { ch = str2.charCodeAt(i2); h1 = Math.imul(h1 ^ ch, 2654435761); h22 = Math.imul(h22 ^ ch, 1597334677); } h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h22 ^ h22 >>> 13, 3266489909); h22 = Math.imul(h22 ^ h22 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909); return 4294967296 * (2097151 & h22) + (h1 >>> 0); } function mapStringToKeyValuePairs(inputString) { const lines = inputString.split("\n"); const result = {}; lines.forEach((line) => { const index2 = line.indexOf(":"); if (index2 !== -1) { const key = line.slice(0, index2).trim(); const value = line.slice(index2 + 1).trim(); if (key && value) result[key] = value; } }); return result; } var replaceOccurance = (text3, search2, replace, index2) => { const parts = text3.split(search2); if (parts.length <= index2) { return text3; } let result = parts[0]; for (let i2 = 1; i2 < parts.length; i2++) { result += (i2 === index2 ? replace : search2) + parts[i2]; } return result; }; // node_modules/js-yaml/dist/js-yaml.mjs function isNothing(subject) { return typeof subject === "undefined" || subject === null; } function isObject(subject) { return typeof subject === "object" && subject !== null; } function toArray(sequence) { if (Array.isArray(sequence)) return sequence; else if (isNothing(sequence)) return []; return [sequence]; } function extend(target, source) { var index2, length, key, sourceKeys; if (source) { sourceKeys = Object.keys(source); for (index2 = 0, length = sourceKeys.length; index2 < length; index2 += 1) { key = sourceKeys[index2]; target[key] = source[key]; } } return target; } function repeat(string3, count) { var result = "", cycle; for (cycle = 0; cycle < count; cycle += 1) { result += string3; } return result; } function isNegativeZero(number) { return number === 0 && Number.NEGATIVE_INFINITY === 1 / number; } var isNothing_1 = isNothing; var isObject_1 = isObject; var toArray_1 = toArray; var repeat_1 = repeat; var isNegativeZero_1 = isNegativeZero; var extend_1 = extend; var common = { isNothing: isNothing_1, isObject: isObject_1, toArray: toArray_1, repeat: repeat_1, isNegativeZero: isNegativeZero_1, extend: extend_1 }; function formatError(exception2, compact) { var where = "", message = exception2.reason || "(unknown reason)"; if (!exception2.mark) return message; if (exception2.mark.name) { where += 'in "' + exception2.mark.name + '" '; } where += "(" + (exception2.mark.line + 1) + ":" + (exception2.mark.column + 1) + ")"; if (!compact && exception2.mark.snippet) { where += "\n\n" + exception2.mark.snippet; } return message + " " + where; } function YAMLException$1(reason, mark) { Error.call(this); this.name = "YAMLException"; this.reason = reason; this.mark = mark; this.message = formatError(this, false); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { this.stack = new Error().stack || ""; } } YAMLException$1.prototype = Object.create(Error.prototype); YAMLException$1.prototype.constructor = YAMLException$1; YAMLException$1.prototype.toString = function toString(compact) { return this.name + ": " + formatError(this, compact); }; var exception = YAMLException$1; function getLine(buffer, lineStart, lineEnd, position2, maxLineLength) { var head = ""; var tail = ""; var maxHalfLength = Math.floor(maxLineLength / 2) - 1; if (position2 - lineStart > maxHalfLength) { head = " ... "; lineStart = position2 - maxHalfLength + head.length; } if (lineEnd - position2 > maxHalfLength) { tail = " ..."; lineEnd = position2 + maxHalfLength - tail.length; } return { str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail, pos: position2 - lineStart + head.length // relative position }; } function padStart(string3, max) { return common.repeat(" ", max - string3.length) + string3; } function makeSnippet(mark, options) { options = Object.create(options || null); if (!mark.buffer) return null; if (!options.maxLength) options.maxLength = 79; if (typeof options.indent !== "number") options.indent = 1; if (typeof options.linesBefore !== "number") options.linesBefore = 3; if (typeof options.linesAfter !== "number") options.linesAfter = 2; var re = /\r?\n|\r|\0/g; var lineStarts = [0]; var lineEnds = []; var match2; var foundLineNo = -1; while (match2 = re.exec(mark.buffer)) { lineEnds.push(match2.index); lineStarts.push(match2.index + match2[0].length); if (mark.position <= match2.index && foundLineNo < 0) { foundLineNo = lineStarts.length - 2; } } if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; var result = "", i2, line; var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); for (i2 = 1; i2 <= options.linesBefore; i2++) { if (foundLineNo - i2 < 0) break; line = getLine( mark.buffer, lineStarts[foundLineNo - i2], lineEnds[foundLineNo - i2], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i2]), maxLineLength ); result = common.repeat(" ", options.indent) + padStart((mark.line - i2 + 1).toString(), lineNoLength) + " | " + line.str + "\n" + result; } line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); result += common.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\n"; result += common.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\n"; for (i2 = 1; i2 <= options.linesAfter; i2++) { if (foundLineNo + i2 >= lineEnds.length) break; line = getLine( mark.buffer, lineStarts[foundLineNo + i2], lineEnds[foundLineNo + i2], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i2]), maxLineLength ); result += common.repeat(" ", options.indent) + padStart((mark.line + i2 + 1).toString(), lineNoLength) + " | " + line.str + "\n"; } return result.replace(/\n$/, ""); } var snippet = makeSnippet; var TYPE_CONSTRUCTOR_OPTIONS = [ "kind", "multi", "resolve", "construct", "instanceOf", "predicate", "represent", "representName", "defaultStyle", "styleAliases" ]; var YAML_NODE_KINDS = [ "scalar", "sequence", "mapping" ]; function compileStyleAliases(map2) { var result = {}; if (map2 !== null) { Object.keys(map2).forEach(function(style) { map2[style].forEach(function(alias) { result[String(alias)] = style; }); }); } return result; } function Type$1(tag, options) { options = options || {}; Object.keys(options).forEach(function(name) { if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); } }); this.options = options; this.tag = tag; this.kind = options["kind"] || null; this.resolve = options["resolve"] || function() { return true; }; this.construct = options["construct"] || function(data) { return data; }; this.instanceOf = options["instanceOf"] || null; this.predicate = options["predicate"] || null; this.represent = options["represent"] || null; this.representName = options["representName"] || null; this.defaultStyle = options["defaultStyle"] || null; this.multi = options["multi"] || false; this.styleAliases = compileStyleAliases(options["styleAliases"] || null); if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); } } var type = Type$1; function compileList(schema2, name) { var result = []; schema2[name].forEach(function(currentType) { var newIndex = result.length; result.forEach(function(previousType, previousIndex) { if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) { newIndex = previousIndex; } }); result[newIndex] = currentType; }); return result; } function compileMap() { var result = { scalar: {}, sequence: {}, mapping: {}, fallback: {}, multi: { scalar: [], sequence: [], mapping: [], fallback: [] } }, index2, length; function collectType(type2) { if (type2.multi) { result.multi[type2.kind].push(type2); result.multi["fallback"].push(type2); } else { result[type2.kind][type2.tag] = result["fallback"][type2.tag] = type2; } } for (index2 = 0, length = arguments.length; index2 < length; index2 += 1) { arguments[index2].forEach(collectType); } return result; } function Schema$1(definition2) { return this.extend(definition2); } Schema$1.prototype.extend = function extend2(definition2) { var implicit = []; var explicit = []; if (definition2 instanceof type) { explicit.push(definition2); } else if (Array.isArray(definition2)) { explicit = explicit.concat(definition2); } else if (definition2 && (Array.isArray(definition2.implicit) || Array.isArray(definition2.explicit))) { if (definition2.implicit) implicit = implicit.concat(definition2.implicit); if (definition2.explicit) explicit = explicit.concat(definition2.explicit); } else { throw new exception("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })"); } implicit.forEach(function(type$1) { if (!(type$1 instanceof type)) { throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object."); } if (type$1.loadKind && type$1.loadKind !== "scalar") { throw new exception("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported."); } if (type$1.multi) { throw new exception("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit."); } }); explicit.forEach(function(type$1) { if (!(type$1 instanceof type)) { throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object."); } }); var result = Object.create(Schema$1.prototype); result.implicit = (this.implicit || []).concat(implicit); result.explicit = (this.explicit || []).concat(explicit); result.compiledImplicit = compileList(result, "implicit"); result.compiledExplicit = compileList(result, "explicit"); result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); return result; }; var schema = Schema$1; var str = new type("tag:yaml.org,2002:str", { kind: "scalar", construct: function(data) { return data !== null ? data : ""; } }); var seq = new type("tag:yaml.org,2002:seq", { kind: "sequence", construct: function(data) { return data !== null ? data : []; } }); var map = new type("tag:yaml.org,2002:map", { kind: "mapping", construct: function(data) { return data !== null ? data : {}; } }); var failsafe = new schema({ explicit: [ str, seq, map ] }); function resolveYamlNull(data) { if (data === null) return true; var max = data.length; return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "NULL"); } function constructYamlNull() { return null; } function isNull(object) { return object === null; } var _null = new type("tag:yaml.org,2002:null", { kind: "scalar", resolve: resolveYamlNull, construct: constructYamlNull, predicate: isNull, represent: { canonical: function() { return "~"; }, lowercase: function() { return "null"; }, uppercase: function() { return "NULL"; }, camelcase: function() { return "Null"; }, empty: function() { return ""; } }, defaultStyle: "lowercase" }); function resolveYamlBoolean(data) { if (data === null) return false; var max = data.length; return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE"); } function constructYamlBoolean(data) { return data === "true" || data === "True" || data === "TRUE"; } function isBoolean(object) { return Object.prototype.toString.call(object) === "[object Boolean]"; } var bool = new type("tag:yaml.org,2002:bool", { kind: "scalar", resolve: resolveYamlBoolean, construct: constructYamlBoolean, predicate: isBoolean, represent: { lowercase: function(object) { return object ? "true" : "false"; }, uppercase: function(object) { return object ? "TRUE" : "FALSE"; }, camelcase: function(object) { return object ? "True" : "False"; } }, defaultStyle: "lowercase" }); function isHexCode(c2) { return 48 <= c2 && c2 <= 57 || 65 <= c2 && c2 <= 70 || 97 <= c2 && c2 <= 102; } function isOctCode(c2) { return 48 <= c2 && c2 <= 55; } function isDecCode(c2) { return 48 <= c2 && c2 <= 57; } function resolveYamlInteger(data) { if (data === null) return false; var max = data.length, index2 = 0, hasDigits = false, ch; if (!max) return false; ch = data[index2]; if (ch === "-" || ch === "+") { ch = data[++index2]; } if (ch === "0") { if (index2 + 1 === max) return true; ch = data[++index2]; if (ch === "b") { index2++; for (; index2 < max; index2++) { ch = data[index2]; if (ch === "_") continue; if (ch !== "0" && ch !== "1") return false; hasDigits = true; } return hasDigits && ch !== "_"; } if (ch === "x") { index2++; for (; index2 < max; index2++) { ch = data[index2]; if (ch === "_") continue; if (!isHexCode(data.charCodeAt(index2))) return false; hasDigits = true; } return hasDigits && ch !== "_"; } if (ch === "o") { index2++; for (; index2 < max; index2++) { ch = data[index2]; if (ch === "_") continue; if (!isOctCode(data.charCodeAt(index2))) return false; hasDigits = true; } return hasDigits && ch !== "_"; } } if (ch === "_") return false; for (; index2 < max; index2++) { ch = data[index2]; if (ch === "_") continue; if (!isDecCode(data.charCodeAt(index2))) { return false; } hasDigits = true; } if (!hasDigits || ch === "_") return false; return true; } function constructYamlInteger(data) { var value = data, sign = 1, ch; if (value.indexOf("_") !== -1) { value = value.replace(/_/g, ""); } ch = value[0]; if (ch === "-" || ch === "+") { if (ch === "-") sign = -1; value = value.slice(1); ch = value[0]; } if (value === "0") return 0; if (ch === "0") { if (value[1] === "b") return sign * parseInt(value.slice(2), 2); if (value[1] === "x") return sign * parseInt(value.slice(2), 16); if (value[1] === "o") return sign * parseInt(value.slice(2), 8); } return sign * parseInt(value, 10); } function isInteger(object) { return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 === 0 && !common.isNegativeZero(object)); } var int = new type("tag:yaml.org,2002:int", { kind: "scalar", resolve: resolveYamlInteger, construct: constructYamlInteger, predicate: isInteger, represent: { binary: function(obj) { return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1); }, octal: function(obj) { return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1); }, decimal: function(obj) { return obj.toString(10); }, /* eslint-disable max-len */ hexadecimal: function(obj) { return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1); } }, defaultStyle: "decimal", styleAliases: { binary: [2, "bin"], octal: [8, "oct"], decimal: [10, "dec"], hexadecimal: [16, "hex"] } }); var YAML_FLOAT_PATTERN = new RegExp( // 2.5e4, 2.5 and integers "^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$" ); function resolveYamlFloat(data) { if (data === null) return false; if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_` // Probably should update regexp & check speed data[data.length - 1] === "_") { return false; } return true; } function constructYamlFloat(data) { var value, sign; value = data.replace(/_/g, "").toLowerCase(); sign = value[0] === "-" ? -1 : 1; if ("+-".indexOf(value[0]) >= 0) { value = value.slice(1); } if (value === ".inf") { return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; } else if (value === ".nan") { return NaN; } return sign * parseFloat(value, 10); } var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; function representYamlFloat(object, style) { var res; if (isNaN(object)) { switch (style) { case "lowercase": return ".nan"; case "uppercase": return ".NAN"; case "camelcase": return ".NaN"; } } else if (Number.POSITIVE_INFINITY === object) { switch (style) { case "lowercase": return ".inf"; case "uppercase": return ".INF"; case "camelcase": return ".Inf"; } } else if (Number.NEGATIVE_INFINITY === object) { switch (style) { case "lowercase": return "-.inf"; case "uppercase": return "-.INF"; case "camelcase": return "-.Inf"; } } else if (common.isNegativeZero(object)) { return "-0.0"; } res = object.toString(10); return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res; } function isFloat(object) { return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common.isNegativeZero(object)); } var float = new type("tag:yaml.org,2002:float", { kind: "scalar", resolve: resolveYamlFloat, construct: constructYamlFloat, predicate: isFloat, represent: representYamlFloat, defaultStyle: "lowercase" }); var json = failsafe.extend({ implicit: [ _null, bool, int, float ] }); var core = json; var YAML_DATE_REGEXP = new RegExp( "^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$" ); var YAML_TIMESTAMP_REGEXP = new RegExp( "^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$" ); function resolveYamlTimestamp(data) { if (data === null) return false; if (YAML_DATE_REGEXP.exec(data) !== null) return true; if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; return false; } function constructYamlTimestamp(data) { var match2, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date; match2 = YAML_DATE_REGEXP.exec(data); if (match2 === null) match2 = YAML_TIMESTAMP_REGEXP.exec(data); if (match2 === null) throw new Error("Date resolve error"); year = +match2[1]; month = +match2[2] - 1; day = +match2[3]; if (!match2[4]) { return new Date(Date.UTC(year, month, day)); } hour = +match2[4]; minute = +match2[5]; second = +match2[6]; if (match2[7]) { fraction = match2[7].slice(0, 3); while (fraction.length < 3) { fraction += "0"; } fraction = +fraction; } if (match2[9]) { tz_hour = +match2[10]; tz_minute = +(match2[11] || 0); delta = (tz_hour * 60 + tz_minute) * 6e4; if (match2[9] === "-") delta = -delta; } date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); if (delta) date.setTime(date.getTime() - delta); return date; } function representYamlTimestamp(object) { return object.toISOString(); } var timestamp = new type("tag:yaml.org,2002:timestamp", { kind: "scalar", resolve: resolveYamlTimestamp, construct: constructYamlTimestamp, instanceOf: Date, represent: representYamlTimestamp }); function resolveYamlMerge(data) { return data === "<<" || data === null; } var merge = new type("tag:yaml.org,2002:merge", { kind: "scalar", resolve: resolveYamlMerge }); var BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r"; function resolveYamlBinary(data) { if (data === null) return false; var code, idx, bitlen = 0, max = data.length, map2 = BASE64_MAP; for (idx = 0; idx < max; idx++) { code = map2.indexOf(data.charAt(idx)); if (code > 64) continue; if (code < 0) return false; bitlen += 6; } return bitlen % 8 === 0; } function constructYamlBinary(data) { var idx, tailbits, input = data.replace(/[\r\n=]/g, ""), max = input.length, map2 = BASE64_MAP, bits = 0, result = []; for (idx = 0; idx < max; idx++) { if (idx % 4 === 0 && idx) { result.push(bits >> 16 & 255); result.push(bits >> 8 & 255); result.push(bits & 255); } bits = bits << 6 | map2.indexOf(input.charAt(idx)); } tailbits = max % 4 * 6; if (tailbits === 0) { result.push(bits >> 16 & 255); result.push(bits >> 8 & 255); result.push(bits & 255); } else if (tailbits === 18) { result.push(bits >> 10 & 255); result.push(bits >> 2 & 255); } else if (tailbits === 12) { result.push(bits >> 4 & 255); } return new Uint8Array(result); } function representYamlBinary(object) { var result = "", bits = 0, idx, tail, max = object.length, map2 = BASE64_MAP; for (idx = 0; idx < max; idx++) { if (idx % 3 === 0 && idx) { result += map2[bits >> 18 & 63]; result += map2[bits >> 12 & 63]; result += map2[bits >> 6 & 63]; result += map2[bits & 63]; } bits = (bits << 8) + object[idx]; } tail = max % 3; if (tail === 0) { result += map2[bits >> 18 & 63]; result += map2[bits >> 12 & 63]; result += map2[bits >> 6 & 63]; result += map2[bits & 63]; } else if (tail === 2) { result += map2[bits >> 10 & 63]; result += map2[bits >> 4 & 63]; result += map2[bits << 2 & 63]; result += map2[64]; } else if (tail === 1) { result += map2[bits >> 2 & 63]; result += map2[bits << 4 & 63]; result += map2[64]; result += map2[64]; } return result; } function isBinary(obj) { return Object.prototype.toString.call(obj) === "[object Uint8Array]"; } var binary = new type("tag:yaml.org,2002:binary", { kind: "scalar", resolve: resolveYamlBinary, construct: constructYamlBinary, predicate: isBinary, represent: representYamlBinary }); var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; var _toString$2 = Object.prototype.toString; function resolveYamlOmap(data) { if (data === null) return true; var objectKeys = [], index2, length, pair, pairKey, pairHasKey, object = data; for (index2 = 0, length = object.length; index2 < length; index2 += 1) { pair = object[index2]; pairHasKey = false; if (_toString$2.call(pair) !== "[object Object]") return false; for (pairKey in pair) { if (_hasOwnProperty$3.call(pair, pairKey)) { if (!pairHasKey) pairHasKey = true; else return false; } } if (!pairHasKey) return false; if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); else return false; } return true; } function constructYamlOmap(data) { return data !== null ? data : []; } var omap = new type("tag:yaml.org,2002:omap", { kind: "sequence", resolve: resolveYamlOmap, construct: constructYamlOmap }); var _toString$1 = Object.prototype.toString; function resolveYamlPairs(data) { if (data === null) return true; var index2, length, pair, keys, result, object = data; result = new Array(object.length); for (index2 = 0, length = object.length; index2 < length; index2 += 1) { pair = object[index2]; if (_toString$1.call(pair) !== "[object Object]") return false; keys = Object.keys(pair); if (keys.length !== 1) return false; result[index2] = [keys[0], pair[keys[0]]]; } return true; } function constructYamlPairs(data) { if (data === null) return []; var index2, length, pair, keys, result, object = data; result = new Array(object.length); for (index2 = 0, length = object.length; index2 < length; index2 += 1) { pair = object[index2]; keys = Object.keys(pair); result[index2] = [keys[0], pair[keys[0]]]; } return result; } var pairs = new type("tag:yaml.org,2002:pairs", { kind: "sequence", resolve: resolveYamlPairs, construct: constructYamlPairs }); var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; function resolveYamlSet(data) { if (data === null) return true; var key, object = data; for (key in object) { if (_hasOwnProperty$2.call(object, key)) { if (object[key] !== null) return false; } } return true; } function constructYamlSet(data) { return data !== null ? data : {}; } var set = new type("tag:yaml.org,2002:set", { kind: "mapping", resolve: resolveYamlSet, construct: constructYamlSet }); var _default = core.extend({ implicit: [ timestamp, merge ], explicit: [ binary, omap, pairs, set ] }); var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; var CONTEXT_FLOW_IN = 1; var CONTEXT_FLOW_OUT = 2; var CONTEXT_BLOCK_IN = 3; var CONTEXT_BLOCK_OUT = 4; var CHOMPING_CLIP = 1; var CHOMPING_STRIP = 2; var CHOMPING_KEEP = 3; var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; function _class(obj) { return Object.prototype.toString.call(obj); } function is_EOL(c2) { return c2 === 10 || c2 === 13; } function is_WHITE_SPACE(c2) { return c2 === 9 || c2 === 32; } function is_WS_OR_EOL(c2) { return c2 === 9 || c2 === 32 || c2 === 10 || c2 === 13; } function is_FLOW_INDICATOR(c2) { return c2 === 44 || c2 === 91 || c2 === 93 || c2 === 123 || c2 === 125; } function fromHexCode(c2) { var lc; if (48 <= c2 && c2 <= 57) { return c2 - 48; } lc = c2 | 32; if (97 <= lc && lc <= 102) { return lc - 97 + 10; } return -1; } function escapedHexLen(c2) { if (c2 === 120) { return 2; } if (c2 === 117) { return 4; } if (c2 === 85) { return 8; } return 0; } function fromDecimalCode(c2) { if (48 <= c2 && c2 <= 57) { return c2 - 48; } return -1; } function simpleEscapeSequence(c2) { return c2 === 48 ? "\0" : c2 === 97 ? "\x07" : c2 === 98 ? "\b" : c2 === 116 ? " " : c2 === 9 ? " " : c2 === 110 ? "\n" : c2 === 118 ? "\v" : c2 === 102 ? "\f" : c2 === 114 ? "\r" : c2 === 101 ? "\x1B" : c2 === 32 ? " " : c2 === 34 ? '"' : c2 === 47 ? "/" : c2 === 92 ? "\\" : c2 === 78 ? "\x85" : c2 === 95 ? "\xA0" : c2 === 76 ? "\u2028" : c2 === 80 ? "\u2029" : ""; } function charFromCodepoint(c2) { if (c2 <= 65535) { return String.fromCharCode(c2); } return String.fromCharCode( (c2 - 65536 >> 10) + 55296, (c2 - 65536 & 1023) + 56320 ); } var simpleEscapeCheck = new Array(256); var simpleEscapeMap = new Array(256); for (i2 = 0; i2 < 256; i2++) { simpleEscapeCheck[i2] = simpleEscapeSequence(i2) ? 1 : 0; simpleEscapeMap[i2] = simpleEscapeSequence(i2); } var i2; function State$1(input, options) { this.input = input; this.filename = options["filename"] || null; this.schema = options["schema"] || _default; this.onWarning = options["onWarning"] || null; this.legacy = options["legacy"] || false; this.json = options["json"] || false; this.listener = options["listener"] || null; this.implicitTypes = this.schema.compiledImplicit; this.typeMap = this.schema.compiledTypeMap; this.length = input.length; this.position = 0; this.line = 0; this.lineStart = 0; this.lineIndent = 0; this.firstTabInLine = -1; this.documents = []; } function generateError(state, message) { var mark = { name: state.filename, buffer: state.input.slice(0, -1), // omit trailing \0 position: state.position, line: state.line, column: state.position - state.lineStart }; mark.snippet = snippet(mark); return new exception(message, mark); } function throwError(state, message) { throw generateError(state, message); } function throwWarning(state, message) { if (state.onWarning) { state.onWarning.call(null, generateError(state, message)); } } var directiveHandlers = { YAML: function handleYamlDirective(state, name, args) { var match2, major, minor; if (state.version !== null) { throwError(state, "duplication of %YAML directive"); } if (args.length !== 1) { throwError(state, "YAML directive accepts exactly one argument"); } match2 = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); if (match2 === null) { throwError(state, "ill-formed argument of the YAML directive"); } major = parseInt(match2[1], 10); minor = parseInt(match2[2], 10); if (major !== 1) { throwError(state, "unacceptable YAML version of the document"); } state.version = args[0]; state.checkLineBreaks = minor < 2; if (minor !== 1 && minor !== 2) { throwWarning(state, "unsupported YAML version of the document"); } }, TAG: function handleTagDirective(state, name, args) { var handle, prefix; if (args.length !== 2) { throwError(state, "TAG directive accepts exactly two arguments"); } handle = args[0]; prefix = args[1]; if (!PATTERN_TAG_HANDLE.test(handle)) { throwError(state, "ill-formed tag handle (first argument) of the TAG directive"); } if (_hasOwnProperty$1.call(state.tagMap, handle)) { throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); } if (!PATTERN_TAG_URI.test(prefix)) { throwError(state, "ill-formed tag prefix (second argument) of the TAG directive"); } try { prefix = decodeURIComponent(prefix); } catch (err) { throwError(state, "tag prefix is malformed: " + prefix); } state.tagMap[handle] = prefix; } }; function captureSegment(state, start, end, checkJson) { var _position, _length, _character, _result; if (start < end) { _result = state.input.slice(start, end); if (checkJson) { for (_position = 0, _length = _result.length; _position < _length; _position += 1) { _character = _result.charCodeAt(_position); if (!(_character === 9 || 32 <= _character && _character <= 1114111)) { throwError(state, "expected valid JSON character"); } } } else if (PATTERN_NON_PRINTABLE.test(_result)) { throwError(state, "the stream contains non-printable characters"); } state.result += _result; } } function mergeMappings(state, destination, source, overridableKeys) { var sourceKeys, key, index2, quantity; if (!common.isObject(source)) { throwError(state, "cannot merge mappings; the provided source object is unacceptable"); } sourceKeys = Object.keys(source); for (index2 = 0, quantity = sourceKeys.length; index2 < quantity; index2 += 1) { key = sourceKeys[index2]; if (!_hasOwnProperty$1.call(destination, key)) { destination[key] = source[key]; overridableKeys[key] = true; } } } function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) { var index2, quantity; if (Array.isArray(keyNode)) { keyNode = Array.prototype.slice.call(keyNode); for (index2 = 0, quantity = keyNode.length; index2 < quantity; index2 += 1) { if (Array.isArray(keyNode[index2])) { throwError(state, "nested arrays are not supported inside keys"); } if (typeof keyNode === "object" && _class(keyNode[index2]) === "[object Object]") { keyNode[index2] = "[object Object]"; } } } if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") { keyNode = "[object Object]"; } keyNode = String(keyNode); if (_result === null) { _result = {}; } if (keyTag === "tag:yaml.org,2002:merge") { if (Array.isArray(valueNode)) { for (index2 = 0, quantity = valueNode.length; index2 < quantity; index2 += 1) { mergeMappings(state, _result, valueNode[index2], overridableKeys); } } else { mergeMappings(state, _result, valueNode, overridableKeys); } } else { if (!state.json && !_hasOwnProperty$1.call(overridableKeys, keyNode) && _hasOwnProperty$1.call(_result, keyNode)) { state.line = startLine || state.line; state.lineStart = startLineStart || state.lineStart; state.position = startPos || state.position; throwError(state, "duplicated mapping key"); } if (keyNode === "__proto__") { Object.defineProperty(_result, keyNode, { configurable: true, enumerable: true, writable: true, value: valueNode }); } else { _result[keyNode] = valueNode; } delete overridableKeys[keyNode]; } return _result; } function readLineBreak(state) { var ch; ch = state.input.charCodeAt(state.position); if (ch === 10) { state.position++; } else if (ch === 13) { state.position++; if (state.input.charCodeAt(state.position) === 10) { state.position++; } } else { throwError(state, "a line break is expected"); } state.line += 1; state.lineStart = state.position; state.firstTabInLine = -1; } function skipSeparationSpace(state, allowComments, checkIndent) { var lineBreaks = 0, ch = state.input.charCodeAt(state.position); while (ch !== 0) { while (is_WHITE_SPACE(ch)) { if (ch === 9 && state.firstTabInLine === -1) { state.firstTabInLine = state.position; } ch = state.input.charCodeAt(++state.position); } if (allowComments && ch === 35) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 10 && ch !== 13 && ch !== 0); } if (is_EOL(ch)) { readLineBreak(state); ch = state.input.charCodeAt(state.position); lineBreaks++; state.lineIndent = 0; while (ch === 32) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } } else { break; } } if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { throwWarning(state, "deficient indentation"); } return lineBreaks; } function testDocumentSeparator(state) { var _position = state.position, ch; ch = state.input.charCodeAt(_position); if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) { _position += 3; ch = state.input.charCodeAt(_position); if (ch === 0 || is_WS_OR_EOL(ch)) { return true; } } return false; } function writeFoldedLines(state, count) { if (count === 1) { state.result += " "; } else if (count > 1) { state.result += common.repeat("\n", count - 1); } } function readPlainScalar(state, nodeIndent, withinFlowCollection) { var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch; ch = state.input.charCodeAt(state.position); if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) { return false; } if (ch === 63 || ch === 45) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { return false; } } state.kind = "scalar"; state.result = ""; captureStart = captureEnd = state.position; hasPendingContent = false; while (ch !== 0) { if (ch === 58) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { break; } } else if (ch === 35) { preceding = state.input.charCodeAt(state.position - 1); if (is_WS_OR_EOL(preceding)) { break; } } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && is_FLOW_INDICATOR(ch)) { break; } else if (is_EOL(ch)) { _line = state.line; _lineStart = state.lineStart; _lineIndent = state.lineIndent; skipSeparationSpace(state, false, -1); if (state.lineIndent >= nodeIndent) { hasPendingContent = true; ch = state.input.charCodeAt(state.position); continue; } else { state.position = captureEnd; state.line = _line; state.lineStart = _lineStart; state.lineIndent = _lineIndent; break; } } if (hasPendingContent) { captureSegment(state, captureStart, captureEnd, false); writeFoldedLines(state, state.line - _line); captureStart = captureEnd = state.position; hasPendingContent = false; } if (!is_WHITE_SPACE(ch)) { captureEnd = state.position + 1; } ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, captureEnd, false); if (state.result) { return true; } state.kind = _kind; state.result = _result; return false; } function readSingleQuotedScalar(state, nodeIndent) { var ch, captureStart, captureEnd; ch = state.input.charCodeAt(state.position); if (ch !== 39) { return false; } state.kind = "scalar"; state.result = ""; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 39) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (ch === 39) { captureStart = state.position; state.position++; captureEnd = state.position; } else { return true; } } else if (is_EOL(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, "unexpected end of the document within a single quoted scalar"); } else { state.position++; captureEnd = state.position; } } throwError(state, "unexpected end of the stream within a single quoted scalar"); } function readDoubleQuotedScalar(state, nodeIndent) { var captureStart, captureEnd, hexLength, hexResult, tmp, ch; ch = state.input.charCodeAt(state.position); if (ch !== 34) { return false; } state.kind = "scalar"; state.result = ""; state.position++; captureStart = captureEnd = state.position; while ((ch = state.input.charCodeAt(state.position)) !== 0) { if (ch === 34) { captureSegment(state, captureStart, state.position, true); state.position++; return true; } else if (ch === 92) { captureSegment(state, captureStart, state.position, true); ch = state.input.charCodeAt(++state.position); if (is_EOL(ch)) { skipSeparationSpace(state, false, nodeIndent); } else if (ch < 256 && simpleEscapeCheck[ch]) { state.result += simpleEscapeMap[ch]; state.position++; } else if ((tmp = escapedHexLen(ch)) > 0) { hexLength = tmp; hexResult = 0; for (; hexLength > 0; hexLength--) { ch = state.input.charCodeAt(++state.position); if ((tmp = fromHexCode(ch)) >= 0) { hexResult = (hexResult << 4) + tmp; } else { throwError(state, "expected hexadecimal character"); } } state.result += charFromCodepoint(hexResult); state.position++; } else { throwError(state, "unknown escape sequence"); } captureStart = captureEnd = state.position; } else if (is_EOL(ch)) { captureSegment(state, captureStart, captureEnd, true); writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); captureStart = captureEnd = state.position; } else if (state.position === state.lineStart && testDocumentSeparator(state)) { throwError(state, "unexpected end of the document within a double quoted scalar"); } else { state.position++; captureEnd = state.position; } } throwError(state, "unexpected end of the stream within a double quoted scalar"); } function readFlowCollection(state, nodeIndent) { var readNext = true, _line, _lineStart, _pos, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = /* @__PURE__ */ Object.create(null), keyNode, keyTag, valueNode, ch; ch = state.input.charCodeAt(state.position); if (ch === 91) { terminator = 93; isMapping = false; _result = []; } else if (ch === 123) { terminator = 125; isMapping = true; _result = {}; } else { return false; } if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(++state.position); while (ch !== 0) { skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === terminator) { state.position++; state.tag = _tag; state.anchor = _anchor; state.kind = isMapping ? "mapping" : "sequence"; state.result = _result; return true; } else if (!readNext) { throwError(state, "missed comma between flow collection entries"); } else if (ch === 44) { throwError(state, "expected the node content, but found ','"); } keyTag = keyNode = valueNode = null; isPair = isExplicitPair = false; if (ch === 63) { following = state.input.charCodeAt(state.position + 1); if (is_WS_OR_EOL(following)) { isPair = isExplicitPair = true; state.position++; skipSeparationSpace(state, true, nodeIndent); } } _line = state.line; _lineStart = state.lineStart; _pos = state.position; composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); keyTag = state.tag; keyNode = state.result; skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if ((isExplicitPair || state.line === _line) && ch === 58) { isPair = true; ch = state.input.charCodeAt(++state.position); skipSeparationSpace(state, true, nodeIndent); composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); valueNode = state.result; } if (isMapping) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); } else if (isPair) { _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); } else { _result.push(keyNode); } skipSeparationSpace(state, true, nodeIndent); ch = state.input.charCodeAt(state.position); if (ch === 44) { readNext = true; ch = state.input.charCodeAt(++state.position); } else { readNext = false; } } throwError(state, "unexpected end of the stream within a flow collection"); } function readBlockScalar(state, nodeIndent) { var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch; ch = state.input.charCodeAt(state.position); if (ch === 124) { folding = false; } else if (ch === 62) { folding = true; } else { return false; } state.kind = "scalar"; state.result = ""; while (ch !== 0) { ch = state.input.charCodeAt(++state.position); if (ch === 43 || ch === 45) { if (CHOMPING_CLIP === chomping) { chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP; } else { throwError(state, "repeat of a chomping mode identifier"); } } else if ((tmp = fromDecimalCode(ch)) >= 0) { if (tmp === 0) { throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one"); } else if (!detectedIndent) { textIndent = nodeIndent + tmp - 1; detectedIndent = true; } else { throwError(state, "repeat of an indentation width identifier"); } } else { break; } } if (is_WHITE_SPACE(ch)) { do { ch = state.input.charCodeAt(++state.position); } while (is_WHITE_SPACE(ch)); if (ch === 35) { do { ch = state.input.charCodeAt(++state.position); } while (!is_EOL(ch) && ch !== 0); } } while (ch !== 0) { readLineBreak(state); state.lineIndent = 0; ch = state.input.charCodeAt(state.position); while ((!detectedIndent || state.lineIndent < textIndent) && ch === 32) { state.lineIndent++; ch = state.input.charCodeAt(++state.position); } if (!detectedIndent && state.lineIndent > textIndent) { textIndent = state.lineIndent; } if (is_EOL(ch)) { emptyLines++; continue; } if (state.lineIndent < textIndent) { if (chomping === CHOMPING_KEEP) { state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); } else if (chomping === CHOMPING_CLIP) { if (didReadContent) { state.result += "\n"; } } break; } if (folding) { if (is_WHITE_SPACE(ch)) { atMoreIndented = true; state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); } else if (atMoreIndented) { atMoreIndented = false; state.result += common.repeat("\n", emptyLines + 1); } else if (emptyLines === 0) { if (didReadContent) { state.result += " "; } } else { state.result += common.repeat("\n", emptyLines); } } else { state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); } didReadContent = true; detectedIndent = true; emptyLines = 0; captureStart = state.position; while (!is_EOL(ch) && ch !== 0) { ch = state.input.charCodeAt(++state.position); } captureSegment(state, captureStart, state.position, false); } return true; } function readBlockSequence(state, nodeIndent) { var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch; if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, "tab characters must not be used in indentation"); } if (ch !== 45) { break; } following = state.input.charCodeAt(state.position + 1); if (!is_WS_OR_EOL(following)) { break; } detected = true; state.position++; if (skipSeparationSpace(state, true, -1)) { if (state.lineIndent <= nodeIndent) { _result.push(null); ch = state.input.charCodeAt(state.position); continue; } } _line = state.line; composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); _result.push(state.result); skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) { throwError(state, "bad indentation of a sequence entry"); } else if (state.lineIndent < nodeIndent) { break; } } if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = "sequence"; state.result = _result; return true; } return false; } function readBlockMapping(state, nodeIndent, flowIndent) { var following, allowCompact, _line, _keyLine, _keyLineStart, _keyPos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = /* @__PURE__ */ Object.create(null), keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch; if (state.firstTabInLine !== -1) return false; if (state.anchor !== null) { state.anchorMap[state.anchor] = _result; } ch = state.input.charCodeAt(state.position); while (ch !== 0) { if (!atExplicitKey && state.firstTabInLine !== -1) { state.position = state.firstTabInLine; throwError(state, "tab characters must not be used in indentation"); } following = state.input.charCodeAt(state.position + 1); _line = state.line; if ((ch === 63 || ch === 58) && is_WS_OR_EOL(following)) { if (ch === 63) { if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = true; allowCompact = true; } else if (atExplicitKey) { atExplicitKey = false; allowCompact = true; } else { throwError(state, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"); } state.position += 1; ch = following; } else { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { break; } if (state.line === _line) { ch = state.input.charCodeAt(state.position); while (is_WHITE_SPACE(ch)) { ch = state.input.charCodeAt(++state.position); } if (ch === 58) { ch = state.input.charCodeAt(++state.position); if (!is_WS_OR_EOL(ch)) { throwError(state, "a whitespace character is expected after the key-value separator within a block mapping"); } if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } detected = true; atExplicitKey = false; allowCompact = false; keyTag = state.tag; keyNode = state.result; } else if (detected) { throwError(state, "can not read an implicit mapping pair; a colon is missed"); } else { state.tag = _tag; state.anchor = _anchor; return true; } } else if (detected) { throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key"); } else { state.tag = _tag; state.anchor = _anchor; return true; } } if (state.line === _line || state.lineIndent > nodeIndent) { if (atExplicitKey) { _keyLine = state.line; _keyLineStart = state.lineStart; _keyPos = state.position; } if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { if (atExplicitKey) { keyNode = state.result; } else { valueNode = state.result; } } if (!atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); keyTag = keyNode = valueNode = null; } skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); } if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) { throwError(state, "bad indentation of a mapping entry"); } else if (state.lineIndent < nodeIndent) { break; } } if (atExplicitKey) { storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); } if (detected) { state.tag = _tag; state.anchor = _anchor; state.kind = "mapping"; state.result = _result; } return detected; } function readTagProperty(state) { var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch; ch = state.input.charCodeAt(state.position); if (ch !== 33) return false; if (state.tag !== null) { throwError(state, "duplication of a tag property"); } ch = state.input.charCodeAt(++state.position); if (ch === 60) { isVerbatim = true; ch = state.input.charCodeAt(++state.position); } else if (ch === 33) { isNamed = true; tagHandle = "!!"; ch = state.input.charCodeAt(++state.position); } else { tagHandle = "!"; } _position = state.position; if (isVerbatim) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0 && ch !== 62); if (state.position < state.length) { tagName = state.input.slice(_position, state.position); ch = state.input.charCodeAt(++state.position); } else { throwError(state, "unexpected end of the stream within a verbatim tag"); } } else { while (ch !== 0 && !is_WS_OR_EOL(ch)) { if (ch === 33) { if (!isNamed) { tagHandle = state.input.slice(_position - 1, state.position + 1); if (!PATTERN_TAG_HANDLE.test(tagHandle)) { throwError(state, "named tag handle cannot contain such characters"); } isNamed = true; _position = state.position + 1; } else { throwError(state, "tag suffix cannot contain exclamation marks"); } } ch = state.input.charCodeAt(++state.position); } tagName = state.input.slice(_position, state.position); if (PATTERN_FLOW_INDICATORS.test(tagName)) { throwError(state, "tag suffix cannot contain flow indicator characters"); } } if (tagName && !PATTERN_TAG_URI.test(tagName)) { throwError(state, "tag name cannot contain such characters: " + tagName); } try { tagName = decodeURIComponent(tagName); } catch (err) { throwError(state, "tag name is malformed: " + tagName); } if (isVerbatim) { state.tag = tagName; } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) { state.tag = state.tagMap[tagHandle] + tagName; } else if (tagHandle === "!") { state.tag = "!" + tagName; } else if (tagHandle === "!!") { state.tag = "tag:yaml.org,2002:" + tagName; } else { throwError(state, 'undeclared tag handle "' + tagHandle + '"'); } return true; } function readAnchorProperty(state) { var _position, ch; ch = state.input.charCodeAt(state.position); if (ch !== 38) return false; if (state.anchor !== null) { throwError(state, "duplication of an anchor property"); } ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { ch = state.input.charCodeAt(++state.position); } if (state.position === _position) { throwError(state, "name of an anchor node must contain at least one character"); } state.anchor = state.input.slice(_position, state.position); return true; } function readAlias(state) { var _position, alias, ch; ch = state.input.charCodeAt(state.position); if (ch !== 42) return false; ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { ch = state.input.charCodeAt(++state.position); } if (state.position === _position) { throwError(state, "name of an alias node must contain at least one character"); } alias = state.input.slice(_position, state.position); if (!_hasOwnProperty$1.call(state.anchorMap, alias)) { throwError(state, 'unidentified alias "' + alias + '"'); } state.result = state.anchorMap[alias]; skipSeparationSpace(state, true, -1); return true; } function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, typeIndex, typeQuantity, typeList, type2, flowIndent, blockIndent; if (state.listener !== null) { state.listener("open", state); } state.tag = null; state.anchor = null; state.kind = null; state.result = null; allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext; if (allowToSeek) { if (skipSeparationSpace(state, true, -1)) { atNewLine = true; if (state.lineIndent > parentIndent) { indentStatus = 1; } else if (state.lineIndent === parentIndent) { indentStatus = 0; } else if (state.lineIndent < parentIndent) { indentStatus = -1; } } } if (indentStatus === 1) { while (readTagProperty(state) || readAnchorProperty(state)) { if (skipSeparationSpace(state, true, -1)) { atNewLine = true; allowBlockCollections = allowBlockStyles; if (state.lineIndent > parentIndent) { indentStatus = 1; } else if (state.lineIndent === parentIndent) { indentStatus = 0; } else if (state.lineIndent < parentIndent) { indentStatus = -1; } } else { allowBlockCollections = false; } } } if (allowBlockCollections) { allowBlockCollections = atNewLine || allowCompact; } if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { flowIndent = parentIndent; } else { flowIndent = parentIndent + 1; } blockIndent = state.position - state.lineStart; if (indentStatus === 1) { if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) { hasContent = true; } else { if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) { hasContent = true; } else if (readAlias(state)) { hasContent = true; if (state.tag !== null || state.anchor !== null) { throwError(state, "alias node should not have any properties"); } } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { hasContent = true; if (state.tag === null) { state.tag = "?"; } } if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } } else if (indentStatus === 0) { hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); } } if (state.tag === null) { if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } else if (state.tag === "?") { if (state.result !== null && state.kind !== "scalar") { throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); } for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { type2 = state.implicitTypes[typeIndex]; if (type2.resolve(state.result)) { state.result = type2.construct(state.result); state.tag = type2.tag; if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } break; } } } else if (state.tag !== "!") { if (_hasOwnProperty$1.call(state.typeMap[state.kind || "fallback"], state.tag)) { type2 = state.typeMap[state.kind || "fallback"][state.tag]; } else { type2 = null; typeList = state.typeMap.multi[state.kind || "fallback"]; for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { type2 = typeList[typeIndex]; break; } } } if (!type2) { throwError(state, "unknown tag !<" + state.tag + ">"); } if (state.result !== null && type2.kind !== state.kind) { throwError(state, "unacceptable node kind for !<" + state.tag + '> tag; it should be "' + type2.kind + '", not "' + state.kind + '"'); } if (!type2.resolve(state.result, state.tag)) { throwError(state, "cannot resolve a node with !<" + state.tag + "> explicit tag"); } else { state.result = type2.construct(state.result, state.tag); if (state.anchor !== null) { state.anchorMap[state.anchor] = state.result; } } } if (state.listener !== null) { state.listener("close", state); } return state.tag !== null || state.anchor !== null || hasContent; } function readDocument(state) { var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch; state.version = null; state.checkLineBreaks = state.legacy; state.tagMap = /* @__PURE__ */ Object.create(null); state.anchorMap = /* @__PURE__ */ Object.create(null); while ((ch = state.input.charCodeAt(state.position)) !== 0) { skipSeparationSpace(state, true, -1); ch = state.input.charCodeAt(state.position); if (state.lineIndent > 0 || ch !== 37) { break; } hasDirectives = true; ch = state.input.charCodeAt(++state.position); _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch)) { ch = state.input.charCodeAt(++state.position); } directiveName = state.input.slice(_position, state.position); directiveArgs = []; if (directiveName.length < 1) { throwError(state, "directive name must not be less than one character in length"); } while (ch !== 0) { while (is_WHITE_SPACE(ch)) { ch = state.input.charCodeAt(++state.position); } if (ch === 35) { do { ch = state.input.charCodeAt(++state.position); } while (ch !== 0 && !is_EOL(ch)); break; } if (is_EOL(ch)) break; _position = state.position; while (ch !== 0 && !is_WS_OR_EOL(ch)) { ch = state.input.charCodeAt(++state.position); } directiveArgs.push(state.input.slice(_position, state.position)); } if (ch !== 0) readLineBreak(state); if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) { directiveHandlers[directiveName](state, directiveName, directiveArgs); } else { throwWarning(state, 'unknown document directive "' + directiveName + '"'); } } skipSeparationSpace(state, true, -1); if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) { state.position += 3; skipSeparationSpace(state, true, -1); } else if (hasDirectives) { throwError(state, "directives end mark is expected"); } composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); skipSeparationSpace(state, true, -1); if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { throwWarning(state, "non-ASCII line breaks are interpreted as content"); } state.documents.push(state.result); if (state.position === state.lineStart && testDocumentSeparator(state)) { if (state.input.charCodeAt(state.position) === 46) { state.position += 3; skipSeparationSpace(state, true, -1); } return; } if (state.position < state.length - 1) { throwError(state, "end of the stream or a document separator is expected"); } else { return; } } function loadDocuments(input, options) { input = String(input); options = options || {}; if (input.length !== 0) { if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) { input += "\n"; } if (input.charCodeAt(0) === 65279) { input = input.slice(1); } } var state = new State$1(input, options); var nullpos = input.indexOf("\0"); if (nullpos !== -1) { state.position = nullpos; throwError(state, "null byte is not allowed in input"); } state.input += "\0"; while (state.input.charCodeAt(state.position) === 32) { state.lineIndent += 1; state.position += 1; } while (state.position < state.length - 1) { readDocument(state); } return state.documents; } function loadAll$1(input, iterator, options) { if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") { options = iterator; iterator = null; } var documents = loadDocuments(input, options); if (typeof iterator !== "function") { return documents; } for (var index2 = 0, length = documents.length; index2 < length; index2 += 1) { iterator(documents[index2]); } } function load$1(input, options) { var documents = loadDocuments(input, options); if (documents.length === 0) { return void 0; } else if (documents.length === 1) { return documents[0]; } throw new exception("expected a single document in the stream, but found more"); } var loadAll_1 = loadAll$1; var load_1 = load$1; var loader = { loadAll: loadAll_1, load: load_1 }; var _toString = Object.prototype.toString; var _hasOwnProperty = Object.prototype.hasOwnProperty; var CHAR_BOM = 65279; var CHAR_TAB = 9; var CHAR_LINE_FEED = 10; var CHAR_CARRIAGE_RETURN = 13; var CHAR_SPACE = 32; var CHAR_EXCLAMATION = 33; var CHAR_DOUBLE_QUOTE = 34; var CHAR_SHARP = 35; var CHAR_PERCENT = 37; var CHAR_AMPERSAND = 38; var CHAR_SINGLE_QUOTE = 39; var CHAR_ASTERISK = 42; var CHAR_COMMA = 44; var CHAR_MINUS = 45; var CHAR_COLON = 58; var CHAR_EQUALS = 61; var CHAR_GREATER_THAN = 62; var CHAR_QUESTION = 63; var CHAR_COMMERCIAL_AT = 64; var CHAR_LEFT_SQUARE_BRACKET = 91; var CHAR_RIGHT_SQUARE_BRACKET = 93; var CHAR_GRAVE_ACCENT = 96; var CHAR_LEFT_CURLY_BRACKET = 123; var CHAR_VERTICAL_LINE = 124; var CHAR_RIGHT_CURLY_BRACKET = 125; var ESCAPE_SEQUENCES = {}; ESCAPE_SEQUENCES[0] = "\\0"; ESCAPE_SEQUENCES[7] = "\\a"; ESCAPE_SEQUENCES[8] = "\\b"; ESCAPE_SEQUENCES[9] = "\\t"; ESCAPE_SEQUENCES[10] = "\\n"; ESCAPE_SEQUENCES[11] = "\\v"; ESCAPE_SEQUENCES[12] = "\\f"; ESCAPE_SEQUENCES[13] = "\\r"; ESCAPE_SEQUENCES[27] = "\\e"; ESCAPE_SEQUENCES[34] = '\\"'; ESCAPE_SEQUENCES[92] = "\\\\"; ESCAPE_SEQUENCES[133] = "\\N"; ESCAPE_SEQUENCES[160] = "\\_"; ESCAPE_SEQUENCES[8232] = "\\L"; ESCAPE_SEQUENCES[8233] = "\\P"; var DEPRECATED_BOOLEANS_SYNTAX = [ "y", "Y", "yes", "Yes", "YES", "on", "On", "ON", "n", "N", "no", "No", "NO", "off", "Off", "OFF" ]; var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; function compileStyleMap(schema2, map2) { var result, keys, index2, length, tag, style, type2; if (map2 === null) return {}; result = {}; keys = Object.keys(map2); for (index2 = 0, length = keys.length; index2 < length; index2 += 1) { tag = keys[index2]; style = String(map2[tag]); if (tag.slice(0, 2) === "!!") { tag = "tag:yaml.org,2002:" + tag.slice(2); } type2 = schema2.compiledTypeMap["fallback"][tag]; if (type2 && _hasOwnProperty.call(type2.styleAliases, style)) { style = type2.styleAliases[style]; } result[tag] = style; } return result; } function encodeHex(character) { var string3, handle, length; string3 = character.toString(16).toUpperCase(); if (character <= 255) { handle = "x"; length = 2; } else if (character <= 65535) { handle = "u"; length = 4; } else if (character <= 4294967295) { handle = "U"; length = 8; } else { throw new exception("code point within a string may not be greater than 0xFFFFFFFF"); } return "\\" + handle + common.repeat("0", length - string3.length) + string3; } var QUOTING_TYPE_SINGLE = 1; var QUOTING_TYPE_DOUBLE = 2; function State(options) { this.schema = options["schema"] || _default; this.indent = Math.max(1, options["indent"] || 2); this.noArrayIndent = options["noArrayIndent"] || false; this.skipInvalid = options["skipInvalid"] || false; this.flowLevel = common.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"]; this.styleMap = compileStyleMap(this.schema, options["styles"] || null); this.sortKeys = options["sortKeys"] || false; this.lineWidth = options["lineWidth"] || 80; this.noRefs = options["noRefs"] || false; this.noCompatMode = options["noCompatMode"] || false; this.condenseFlow = options["condenseFlow"] || false; this.quotingType = options["quotingType"] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; this.forceQuotes = options["forceQuotes"] || false; this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null; this.implicitTypes = this.schema.compiledImplicit; this.explicitTypes = this.schema.compiledExplicit; this.tag = null; this.result = ""; this.duplicates = []; this.usedDuplicates = null; } function indentString(string3, spaces) { var ind = common.repeat(" ", spaces), position2 = 0, next = -1, result = "", line, length = string3.length; while (position2 < length) { next = string3.indexOf("\n", position2); if (next === -1) { line = string3.slice(position2); position2 = length; } else { line = string3.slice(position2, next + 1); position2 = next + 1; } if (line.length && line !== "\n") result += ind; result += line; } return result; } function generateNextLine(state, level) { return "\n" + common.repeat(" ", state.indent * level); } function testImplicitResolving(state, str2) { var index2, length, type2; for (index2 = 0, length = state.implicitTypes.length; index2 < length; index2 += 1) { type2 = state.implicitTypes[index2]; if (type2.resolve(str2)) { return true; } } return false; } function isWhitespace(c2) { return c2 === CHAR_SPACE || c2 === CHAR_TAB; } function isPrintable(c2) { return 32 <= c2 && c2 <= 126 || 161 <= c2 && c2 <= 55295 && c2 !== 8232 && c2 !== 8233 || 57344 <= c2 && c2 <= 65533 && c2 !== CHAR_BOM || 65536 <= c2 && c2 <= 1114111; } function isNsCharOrWhitespace(c2) { return isPrintable(c2) && c2 !== CHAR_BOM && c2 !== CHAR_CARRIAGE_RETURN && c2 !== CHAR_LINE_FEED; } function isPlainSafe(c2, prev, inblock) { var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c2); var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c2); return ( // ns-plain-safe (inblock ? ( // c = flow-in cIsNsCharOrWhitespace ) : cIsNsCharOrWhitespace && c2 !== CHAR_COMMA && c2 !== CHAR_LEFT_SQUARE_BRACKET && c2 !== CHAR_RIGHT_SQUARE_BRACKET && c2 !== CHAR_LEFT_CURLY_BRACKET && c2 !== CHAR_RIGHT_CURLY_BRACKET) && c2 !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c2 === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar ); } function isPlainSafeFirst(c2) { return isPrintable(c2) && c2 !== CHAR_BOM && !isWhitespace(c2) && c2 !== CHAR_MINUS && c2 !== CHAR_QUESTION && c2 !== CHAR_COLON && c2 !== CHAR_COMMA && c2 !== CHAR_LEFT_SQUARE_BRACKET && c2 !== CHAR_RIGHT_SQUARE_BRACKET && c2 !== CHAR_LEFT_CURLY_BRACKET && c2 !== CHAR_RIGHT_CURLY_BRACKET && c2 !== CHAR_SHARP && c2 !== CHAR_AMPERSAND && c2 !== CHAR_ASTERISK && c2 !== CHAR_EXCLAMATION && c2 !== CHAR_VERTICAL_LINE && c2 !== CHAR_EQUALS && c2 !== CHAR_GREATER_THAN && c2 !== CHAR_SINGLE_QUOTE && c2 !== CHAR_DOUBLE_QUOTE && c2 !== CHAR_PERCENT && c2 !== CHAR_COMMERCIAL_AT && c2 !== CHAR_GRAVE_ACCENT; } function isPlainSafeLast(c2) { return !isWhitespace(c2) && c2 !== CHAR_COLON; } function codePointAt(string3, pos) { var first = string3.charCodeAt(pos), second; if (first >= 55296 && first <= 56319 && pos + 1 < string3.length) { second = string3.charCodeAt(pos + 1); if (second >= 56320 && second <= 57343) { return (first - 55296) * 1024 + second - 56320 + 65536; } } return first; } function needIndentIndicator(string3) { var leadingSpaceRe = /^\n* /; return leadingSpaceRe.test(string3); } var STYLE_PLAIN = 1; var STYLE_SINGLE = 2; var STYLE_LITERAL = 3; var STYLE_FOLDED = 4; var STYLE_DOUBLE = 5; function chooseScalarStyle(string3, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) { var i2; var char = 0; var prevChar = null; var hasLineBreak = false; var hasFoldableLine = false; var shouldTrackWidth = lineWidth !== -1; var previousLineBreak = -1; var plain = isPlainSafeFirst(codePointAt(string3, 0)) && isPlainSafeLast(codePointAt(string3, string3.length - 1)); if (singleLineOnly || forceQuotes) { for (i2 = 0; i2 < string3.length; char >= 65536 ? i2 += 2 : i2++) { char = codePointAt(string3, i2); if (!isPrintable(char)) { return STYLE_DOUBLE; } plain = plain && isPlainSafe(char, prevChar, inblock); prevChar = char; } } else { for (i2 = 0; i2 < string3.length; char >= 65536 ? i2 += 2 : i2++) { char = codePointAt(string3, i2); if (char === CHAR_LINE_FEED) { hasLineBreak = true; if (shouldTrackWidth) { hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented. i2 - previousLineBreak - 1 > lineWidth && string3[previousLineBreak + 1] !== " "; previousLineBreak = i2; } } else if (!isPrintable(char)) { return STYLE_DOUBLE; } plain = plain && isPlainSafe(char, prevChar, inblock); prevChar = char; } hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i2 - previousLineBreak - 1 > lineWidth && string3[previousLineBreak + 1] !== " "); } if (!hasLineBreak && !hasFoldableLine) { if (plain && !forceQuotes && !testAmbiguousType(string3)) { return STYLE_PLAIN; } return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } if (indentPerLevel > 9 && needIndentIndicator(string3)) { return STYLE_DOUBLE; } if (!forceQuotes) { return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; } return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } function writeScalar(state, string3, level, iskey, inblock) { state.dump = function() { if (string3.length === 0) { return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; } if (!state.noCompatMode) { if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string3) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string3)) { return state.quotingType === QUOTING_TYPE_DOUBLE ? '"' + string3 + '"' : "'" + string3 + "'"; } } var indent2 = state.indent * Math.max(1, level); var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent2); var singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel; function testAmbiguity(string4) { return testImplicitResolving(state, string4); } switch (chooseScalarStyle( string3, singleLineOnly, state.indent, lineWidth, testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock )) { case STYLE_PLAIN: return string3; case STYLE_SINGLE: return "'" + string3.replace(/'/g, "''") + "'"; case STYLE_LITERAL: return "|" + blockHeader(string3, state.indent) + dropEndingNewline(indentString(string3, indent2)); case STYLE_FOLDED: return ">" + blockHeader(string3, state.indent) + dropEndingNewline(indentString(foldString(string3, lineWidth), indent2)); case STYLE_DOUBLE: return '"' + escapeString(string3) + '"'; default: throw new exception("impossible error: invalid scalar style"); } }(); } function blockHeader(string3, indentPerLevel) { var indentIndicator = needIndentIndicator(string3) ? String(indentPerLevel) : ""; var clip = string3[string3.length - 1] === "\n"; var keep = clip && (string3[string3.length - 2] === "\n" || string3 === "\n"); var chomp = keep ? "+" : clip ? "" : "-"; return indentIndicator + chomp + "\n"; } function dropEndingNewline(string3) { return string3[string3.length - 1] === "\n" ? string3.slice(0, -1) : string3; } function foldString(string3, width) { var lineRe = /(\n+)([^\n]*)/g; var result = function() { var nextLF = string3.indexOf("\n"); nextLF = nextLF !== -1 ? nextLF : string3.length; lineRe.lastIndex = nextLF; return foldLine(string3.slice(0, nextLF), width); }(); var prevMoreIndented = string3[0] === "\n" || string3[0] === " "; var moreIndented; var match2; while (match2 = lineRe.exec(string3)) { var prefix = match2[1], line = match2[2]; moreIndented = line[0] === " "; result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width); prevMoreIndented = moreIndented; } return result; } function foldLine(line, width) { if (line === "" || line[0] === " ") return line; var breakRe = / [^ ]/g; var match2; var start = 0, end, curr = 0, next = 0; var result = ""; while (match2 = breakRe.exec(line)) { next = match2.index; if (next - start > width) { end = curr > start ? curr : next; result += "\n" + line.slice(start, end); start = end + 1; } curr = next; } result += "\n"; if (line.length - start > width && curr > start) { result += line.slice(start, curr) + "\n" + line.slice(curr + 1); } else { result += line.slice(start); } return result.slice(1); } function escapeString(string3) { var result = ""; var char = 0; var escapeSeq; for (var i2 = 0; i2 < string3.length; char >= 65536 ? i2 += 2 : i2++) { char = codePointAt(string3, i2); escapeSeq = ESCAPE_SEQUENCES[char]; if (!escapeSeq && isPrintable(char)) { result += string3[i2]; if (char >= 65536) result += string3[i2 + 1]; } else { result += escapeSeq || encodeHex(char); } } return result; } function writeFlowSequence(state, level, object) { var _result = "", _tag = state.tag, index2, length, value; for (index2 = 0, length = object.length; index2 < length; index2 += 1) { value = object[index2]; if (state.replacer) { value = state.replacer.call(object, String(index2), value); } if (writeNode(state, level, value, false, false) || typeof value === "undefined" && writeNode(state, level, null, false, false)) { if (_result !== "") _result += "," + (!state.condenseFlow ? " " : ""); _result += state.dump; } } state.tag = _tag; state.dump = "[" + _result + "]"; } function writeBlockSequence(state, level, object, compact) { var _result = "", _tag = state.tag, index2, length, value; for (index2 = 0, length = object.length; index2 < length; index2 += 1) { value = object[index2]; if (state.replacer) { value = state.replacer.call(object, String(index2), value); } if (writeNode(state, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state, level + 1, null, true, true, false, true)) { if (!compact || _result !== "") { _result += generateNextLine(state, level); } if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { _result += "-"; } else { _result += "- "; } _result += state.dump; } } state.tag = _tag; state.dump = _result || "[]"; } function writeFlowMapping(state, level, object) { var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index2, length, objectKey, objectValue, pairBuffer; for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) { pairBuffer = ""; if (_result !== "") pairBuffer += ", "; if (state.condenseFlow) pairBuffer += '"'; objectKey = objectKeyList[index2]; objectValue = object[objectKey]; if (state.replacer) { objectValue = state.replacer.call(object, objectKey, objectValue); } if (!writeNode(state, level, objectKey, false, false)) { continue; } if (state.dump.length > 1024) pairBuffer += "? "; pairBuffer += state.dump + (state.condenseFlow ? '"' : "") + ":" + (state.condenseFlow ? "" : " "); if (!writeNode(state, level, objectValue, false, false)) { continue; } pairBuffer += state.dump; _result += pairBuffer; } state.tag = _tag; state.dump = "{" + _result + "}"; } function writeBlockMapping(state, level, object, compact) { var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index2, length, objectKey, objectValue, explicitPair, pairBuffer; if (state.sortKeys === true) { objectKeyList.sort(); } else if (typeof state.sortKeys === "function") { objectKeyList.sort(state.sortKeys); } else if (state.sortKeys) { throw new exception("sortKeys must be a boolean or a function"); } for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) { pairBuffer = ""; if (!compact || _result !== "") { pairBuffer += generateNextLine(state, level); } objectKey = objectKeyList[index2]; objectValue = object[objectKey]; if (state.replacer) { objectValue = state.replacer.call(object, objectKey, objectValue); } if (!writeNode(state, level + 1, objectKey, true, true, true)) { continue; } explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024; if (explicitPair) { if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += "?"; } else { pairBuffer += "? "; } } pairBuffer += state.dump; if (explicitPair) { pairBuffer += generateNextLine(state, level); } if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { continue; } if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += ":"; } else { pairBuffer += ": "; } pairBuffer += state.dump; _result += pairBuffer; } state.tag = _tag; state.dump = _result || "{}"; } function detectType(state, object, explicit) { var _result, typeList, index2, length, type2, style; typeList = explicit ? state.explicitTypes : state.implicitTypes; for (index2 = 0, length = typeList.length; index2 < length; index2 += 1) { type2 = typeList[index2]; if ((type2.instanceOf || type2.predicate) && (!type2.instanceOf || typeof object === "object" && object instanceof type2.instanceOf) && (!type2.predicate || type2.predicate(object))) { if (explicit) { if (type2.multi && type2.representName) { state.tag = type2.representName(object); } else { state.tag = type2.tag; } } else { state.tag = "?"; } if (type2.represent) { style = state.styleMap[type2.tag] || type2.defaultStyle; if (_toString.call(type2.represent) === "[object Function]") { _result = type2.represent(object, style); } else if (_hasOwnProperty.call(type2.represent, style)) { _result = type2.represent[style](object, style); } else { throw new exception("!<" + type2.tag + '> tag resolver accepts not "' + style + '" style'); } state.dump = _result; } return true; } } return false; } function writeNode(state, level, object, block, compact, iskey, isblockseq) { state.tag = null; state.dump = object; if (!detectType(state, object, false)) { detectType(state, object, true); } var type2 = _toString.call(state.dump); var inblock = block; var tagStr; if (block) { block = state.flowLevel < 0 || state.flowLevel > level; } var objectOrArray = type2 === "[object Object]" || type2 === "[object Array]", duplicateIndex, duplicate; if (objectOrArray) { duplicateIndex = state.duplicates.indexOf(object); duplicate = duplicateIndex !== -1; } if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) { compact = false; } if (duplicate && state.usedDuplicates[duplicateIndex]) { state.dump = "*ref_" + duplicateIndex; } else { if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { state.usedDuplicates[duplicateIndex] = true; } if (type2 === "[object Object]") { if (block && Object.keys(state.dump).length !== 0) { writeBlockMapping(state, level, state.dump, compact); if (duplicate) { state.dump = "&ref_" + duplicateIndex + state.dump; } } else { writeFlowMapping(state, level, state.dump); if (duplicate) { state.dump = "&ref_" + duplicateIndex + " " + state.dump; } } } else if (type2 === "[object Array]") { if (block && state.dump.length !== 0) { if (state.noArrayIndent && !isblockseq && level > 0) { writeBlockSequence(state, level - 1, state.dump, compact); } else { writeBlockSequence(state, level, state.dump, compact); } if (duplicate) { state.dump = "&ref_" + duplicateIndex + state.dump; } } else { writeFlowSequence(state, level, state.dump); if (duplicate) { state.dump = "&ref_" + duplicateIndex + " " + state.dump; } } } else if (type2 === "[object String]") { if (state.tag !== "?") { writeScalar(state, state.dump, level, iskey, inblock); } } else if (type2 === "[object Undefined]") { return false; } else { if (state.skipInvalid) return false; throw new exception("unacceptable kind of an object to dump " + type2); } if (state.tag !== null && state.tag !== "?") { tagStr = encodeURI( state.tag[0] === "!" ? state.tag.slice(1) : state.tag ).replace(/!/g, "%21"); if (state.tag[0] === "!") { tagStr = "!" + tagStr; } else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") { tagStr = "!!" + tagStr.slice(18); } else { tagStr = "!<" + tagStr + ">"; } state.dump = tagStr + " " + state.dump; } } return true; } function getDuplicateReferences(object, state) { var objects = [], duplicatesIndexes = [], index2, length; inspectNode(object, objects, duplicatesIndexes); for (index2 = 0, length = duplicatesIndexes.length; index2 < length; index2 += 1) { state.duplicates.push(objects[duplicatesIndexes[index2]]); } state.usedDuplicates = new Array(length); } function inspectNode(object, objects, duplicatesIndexes) { var objectKeyList, index2, length; if (object !== null && typeof object === "object") { index2 = objects.indexOf(object); if (index2 !== -1) { if (duplicatesIndexes.indexOf(index2) === -1) { duplicatesIndexes.push(index2); } } else { objects.push(object); if (Array.isArray(object)) { for (index2 = 0, length = object.length; index2 < length; index2 += 1) { inspectNode(object[index2], objects, duplicatesIndexes); } } else { objectKeyList = Object.keys(object); for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) { inspectNode(object[objectKeyList[index2]], objects, duplicatesIndexes); } } } } } function dump$1(input, options) { options = options || {}; var state = new State(options); if (!state.noRefs) getDuplicateReferences(input, state); var value = input; if (state.replacer) { value = state.replacer.call({ "": value }, "", value); } if (writeNode(state, 0, value, true, true)) return state.dump + "\n"; return ""; } var dump_1 = dump$1; var dumper = { dump: dump_1 }; function renamed(from, to) { return function() { throw new Error("Function yaml." + from + " is removed in js-yaml 4. Use yaml." + to + " instead, which is now safe by default."); }; } var load = loader.load; var loadAll = loader.loadAll; var dump = dumper.dump; var safeLoad = renamed("safeLoad", "load"); var safeLoadAll = renamed("safeLoadAll", "loadAll"); var safeDump = renamed("safeDump", "dump"); // src/utils/yaml.ts function getYAMLText(text3) { const yaml = text3.match(yamlRegex); if (!yaml) { return null; } return yaml[1]; } var splitYamlAndBody = (markdown) => { var _a; const parts = markdown.split(/^---$/m); if (!markdown.startsWith("---") || parts.length === 1) { return { yaml: void 0, body: markdown }; } if (parts.length < 3) { return { yaml: parts[1], body: (_a = parts[2]) != null ? _a : "" }; } return { yaml: parts[1], body: parts.slice(2).join("---") }; }; // src/utils/obsidian.ts var import_diff_match_patch = __toESM(require_diff_match_patch()); function isMarkdownFile(file) { return file && file.extension === "md"; } var getDataFromTextSync = (text3) => { const yamlText = getYAMLText(text3); const { body } = splitYamlAndBody(text3); return { text: text3, yamlText, yamlObj: yamlText ? (0, import_obsidian.parseYaml)(yamlText) : null, body }; }; function writeFile(editor, oldText, newText) { const dmp = new import_diff_match_patch.diff_match_patch(); const changes = dmp.diff_main(oldText, newText); let curText = ""; changes.forEach((change) => { function endOfDocument(doc) { const lines = doc.split("\n"); return { line: lines.length - 1, // @ts-ignore ch: lines[lines.length - 1].length }; } const [type2, value] = change; if (type2 == import_diff_match_patch.DIFF_INSERT) { editor.replaceRange(value, endOfDocument(curText)); curText += value; } else if (type2 == import_diff_match_patch.DIFF_DELETE) { const start = endOfDocument(curText); let tempText = curText; tempText += value; const end = endOfDocument(tempText); editor.replaceRange("", start, end); } else { curText += value; } }); } // node_modules/micromark-util-chunked/index.js function splice(list2, start, remove, items) { const end = list2.length; let chunkStart = 0; let parameters; if (start < 0) { start = -start > end ? 0 : end + start; } else { start = start > end ? end : start; } remove = remove > 0 ? remove : 0; if (items.length < 1e4) { parameters = Array.from(items); parameters.unshift(start, remove); list2.splice(...parameters); } else { if (remove) list2.splice(start, remove); while (chunkStart < items.length) { parameters = items.slice(chunkStart, chunkStart + 1e4); parameters.unshift(start, 0); list2.splice(...parameters); chunkStart += 1e4; start += 1e4; } } } function push(list2, items) { if (list2.length > 0) { splice(list2, list2.length, 0, items); return list2; } return items; } // node_modules/micromark-util-character/lib/unicode-punctuation-regex.js var unicodePunctuationRegex = /[!-\/:-@\[-`\{-~\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1B7D\u1B7E\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]/; // node_modules/micromark-util-character/index.js var asciiAlpha = regexCheck(/[A-Za-z]/); var asciiAlphanumeric = regexCheck(/[\dA-Za-z]/); var asciiAtext = regexCheck(/[#-'*+\--9=?A-Z^-~]/); function asciiControl(code) { return ( // Special whitespace codes (which have negative values), C0 and Control // character DEL code !== null && (code < 32 || code === 127) ); } var asciiDigit = regexCheck(/\d/); var asciiHexDigit = regexCheck(/[\dA-Fa-f]/); var asciiPunctuation = regexCheck(/[!-/:-@[-`{-~]/); function markdownLineEnding(code) { return code !== null && code < -2; } function markdownLineEndingOrSpace(code) { return code !== null && (code < 0 || code === 32); } function markdownSpace(code) { return code === -2 || code === -1 || code === 32; } var unicodePunctuation = regexCheck(unicodePunctuationRegex); var unicodeWhitespace = regexCheck(/\s/); function regexCheck(regex) { return check; function check(code) { return code !== null && regex.test(String.fromCharCode(code)); } } // node_modules/micromark-util-classify-character/index.js function classifyCharacter(code) { if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) { return 1; } if (unicodePunctuation(code)) { return 2; } } // node_modules/micromark-util-resolve-all/index.js function resolveAll(constructs2, events, context) { const called = []; let index2 = -1; while (++index2 < constructs2.length) { const resolve = constructs2[index2].resolveAll; if (resolve && !called.includes(resolve)) { events = resolve(events, context); called.push(resolve); } } return events; } // node_modules/micromark-core-commonmark/lib/attention.js var attention = { name: "attention", tokenize: tokenizeAttention, resolveAll: resolveAllAttention }; function resolveAllAttention(events, context) { let index2 = -1; let open; let group; let text3; let openingSequence; let closingSequence; let use; let nextEvents; let offset; while (++index2 < events.length) { if (events[index2][0] === "enter" && events[index2][1].type === "attentionSequence" && events[index2][1]._close) { open = index2; while (open--) { if (events[open][0] === "exit" && events[open][1].type === "attentionSequence" && events[open][1]._open && // If the markers are the same: context.sliceSerialize(events[open][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) { if ((events[open][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open][1].end.offset - events[open][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3)) { continue; } use = events[open][1].end.offset - events[open][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1; const start = Object.assign({}, events[open][1].end); const end = Object.assign({}, events[index2][1].start); movePoint(start, -use); movePoint(end, use); openingSequence = { type: use > 1 ? "strongSequence" : "emphasisSequence", start, end: Object.assign({}, events[open][1].end) }; closingSequence = { type: use > 1 ? "strongSequence" : "emphasisSequence", start: Object.assign({}, events[index2][1].start), end }; text3 = { type: use > 1 ? "strongText" : "emphasisText", start: Object.assign({}, events[open][1].end), end: Object.assign({}, events[index2][1].start) }; group = { type: use > 1 ? "strong" : "emphasis", start: Object.assign({}, openingSequence.start), end: Object.assign({}, closingSequence.end) }; events[open][1].end = Object.assign({}, openingSequence.start); events[index2][1].start = Object.assign({}, closingSequence.end); nextEvents = []; if (events[open][1].end.offset - events[open][1].start.offset) { nextEvents = push(nextEvents, [ ["enter", events[open][1], context], ["exit", events[open][1], context] ]); } nextEvents = push(nextEvents, [ ["enter", group, context], ["enter", openingSequence, context], ["exit", openingSequence, context], ["enter", text3, context] ]); nextEvents = push( nextEvents, resolveAll( context.parser.constructs.insideSpan.null, events.slice(open + 1, index2), context ) ); nextEvents = push(nextEvents, [ ["exit", text3, context], ["enter", closingSequence, context], ["exit", closingSequence, context], ["exit", group, context] ]); if (events[index2][1].end.offset - events[index2][1].start.offset) { offset = 2; nextEvents = push(nextEvents, [ ["enter", events[index2][1], context], ["exit", events[index2][1], context] ]); } else { offset = 0; } splice(events, open - 1, index2 - open + 3, nextEvents); index2 = open + nextEvents.length - offset - 2; break; } } } } index2 = -1; while (++index2 < events.length) { if (events[index2][1].type === "attentionSequence") { events[index2][1].type = "data"; } } return events; } function tokenizeAttention(effects, ok) { const attentionMarkers2 = this.parser.constructs.attentionMarkers.null; const previous3 = this.previous; const before = classifyCharacter(previous3); let marker; return start; function start(code) { marker = code; effects.enter("attentionSequence"); return inside(code); } function inside(code) { if (code === marker) { effects.consume(code); return inside; } const token = effects.exit("attentionSequence"); const after = classifyCharacter(code); const open = !after || after === 2 && before || attentionMarkers2.includes(code); const close = !before || before === 2 && after || attentionMarkers2.includes(previous3); token._open = Boolean(marker === 42 ? open : open && (before || !close)); token._close = Boolean(marker === 42 ? close : close && (after || !open)); return ok(code); } } function movePoint(point3, offset) { point3.column += offset; point3.offset += offset; point3._bufferIndex += offset; } // node_modules/micromark-core-commonmark/lib/autolink.js var autolink = { name: "autolink", tokenize: tokenizeAutolink }; function tokenizeAutolink(effects, ok, nok) { let size = 0; return start; function start(code) { effects.enter("autolink"); effects.enter("autolinkMarker"); effects.consume(code); effects.exit("autolinkMarker"); effects.enter("autolinkProtocol"); return open; } function open(code) { if (asciiAlpha(code)) { effects.consume(code); return schemeOrEmailAtext; } return emailAtext(code); } function schemeOrEmailAtext(code) { if (code === 43 || code === 45 || code === 46 || asciiAlphanumeric(code)) { size = 1; return schemeInsideOrEmailAtext(code); } return emailAtext(code); } function schemeInsideOrEmailAtext(code) { if (code === 58) { effects.consume(code); size = 0; return urlInside; } if ((code === 43 || code === 45 || code === 46 || asciiAlphanumeric(code)) && size++ < 32) { effects.consume(code); return schemeInsideOrEmailAtext; } size = 0; return emailAtext(code); } function urlInside(code) { if (code === 62) { effects.exit("autolinkProtocol"); effects.enter("autolinkMarker"); effects.consume(code); effects.exit("autolinkMarker"); effects.exit("autolink"); return ok; } if (code === null || code === 32 || code === 60 || asciiControl(code)) { return nok(code); } effects.consume(code); return urlInside; } function emailAtext(code) { if (code === 64) { effects.consume(code); return emailAtSignOrDot; } if (asciiAtext(code)) { effects.consume(code); return emailAtext; } return nok(code); } function emailAtSignOrDot(code) { return asciiAlphanumeric(code) ? emailLabel(code) : nok(code); } function emailLabel(code) { if (code === 46) { effects.consume(code); size = 0; return emailAtSignOrDot; } if (code === 62) { effects.exit("autolinkProtocol").type = "autolinkEmail"; effects.enter("autolinkMarker"); effects.consume(code); effects.exit("autolinkMarker"); effects.exit("autolink"); return ok; } return emailValue(code); } function emailValue(code) { if ((code === 45 || asciiAlphanumeric(code)) && size++ < 63) { const next = code === 45 ? emailValue : emailLabel; effects.consume(code); return next; } return nok(code); } } // node_modules/micromark-factory-space/index.js function factorySpace(effects, ok, type2, max) { const limit = max ? max - 1 : Number.POSITIVE_INFINITY; let size = 0; return start; function start(code) { if (markdownSpace(code)) { effects.enter(type2); return prefix(code); } return ok(code); } function prefix(code) { if (markdownSpace(code) && size++ < limit) { effects.consume(code); return prefix; } effects.exit(type2); return ok(code); } } // node_modules/micromark-core-commonmark/lib/blank-line.js var blankLine = { tokenize: tokenizeBlankLine, partial: true }; function tokenizeBlankLine(effects, ok, nok) { return start; function start(code) { return markdownSpace(code) ? factorySpace(effects, after, "linePrefix")(code) : after(code); } function after(code) { return code === null || markdownLineEnding(code) ? ok(code) : nok(code); } } // node_modules/micromark-core-commonmark/lib/block-quote.js var blockQuote = { name: "blockQuote", tokenize: tokenizeBlockQuoteStart, continuation: { tokenize: tokenizeBlockQuoteContinuation }, exit }; function tokenizeBlockQuoteStart(effects, ok, nok) { const self2 = this; return start; function start(code) { if (code === 62) { const state = self2.containerState; if (!state.open) { effects.enter("blockQuote", { _container: true }); state.open = true; } effects.enter("blockQuotePrefix"); effects.enter("blockQuoteMarker"); effects.consume(code); effects.exit("blockQuoteMarker"); return after; } return nok(code); } function after(code) { if (markdownSpace(code)) { effects.enter("blockQuotePrefixWhitespace"); effects.consume(code); effects.exit("blockQuotePrefixWhitespace"); effects.exit("blockQuotePrefix"); return ok; } effects.exit("blockQuotePrefix"); return ok(code); } } function tokenizeBlockQuoteContinuation(effects, ok, nok) { const self2 = this; return contStart; function contStart(code) { if (markdownSpace(code)) { return factorySpace( effects, contBefore, "linePrefix", self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4 )(code); } return contBefore(code); } function contBefore(code) { return effects.attempt(blockQuote, ok, nok)(code); } } function exit(effects) { effects.exit("blockQuote"); } // node_modules/micromark-core-commonmark/lib/character-escape.js var characterEscape = { name: "characterEscape", tokenize: tokenizeCharacterEscape }; function tokenizeCharacterEscape(effects, ok, nok) { return start; function start(code) { effects.enter("characterEscape"); effects.enter("escapeMarker"); effects.consume(code); effects.exit("escapeMarker"); return inside; } function inside(code) { if (asciiPunctuation(code)) { effects.enter("characterEscapeValue"); effects.consume(code); effects.exit("characterEscapeValue"); effects.exit("characterEscape"); return ok; } return nok(code); } } // node_modules/decode-named-character-reference/index.dom.js var element = document.createElement("i"); function decodeNamedCharacterReference(value) { const characterReference2 = "&" + value + ";"; element.innerHTML = characterReference2; const char = element.textContent; if (char.charCodeAt(char.length - 1) === 59 && value !== "semi") { return false; } return char === characterReference2 ? false : char; } // node_modules/micromark-core-commonmark/lib/character-reference.js var characterReference = { name: "characterReference", tokenize: tokenizeCharacterReference }; function tokenizeCharacterReference(effects, ok, nok) { const self2 = this; let size = 0; let max; let test; return start; function start(code) { effects.enter("characterReference"); effects.enter("characterReferenceMarker"); effects.consume(code); effects.exit("characterReferenceMarker"); return open; } function open(code) { if (code === 35) { effects.enter("characterReferenceMarkerNumeric"); effects.consume(code); effects.exit("characterReferenceMarkerNumeric"); return numeric; } effects.enter("characterReferenceValue"); max = 31; test = asciiAlphanumeric; return value(code); } function numeric(code) { if (code === 88 || code === 120) { effects.enter("characterReferenceMarkerHexadecimal"); effects.consume(code); effects.exit("characterReferenceMarkerHexadecimal"); effects.enter("characterReferenceValue"); max = 6; test = asciiHexDigit; return value; } effects.enter("characterReferenceValue"); max = 7; test = asciiDigit; return value(code); } function value(code) { if (code === 59 && size) { const token = effects.exit("characterReferenceValue"); if (test === asciiAlphanumeric && !decodeNamedCharacterReference(self2.sliceSerialize(token))) { return nok(code); } effects.enter("characterReferenceMarker"); effects.consume(code); effects.exit("characterReferenceMarker"); effects.exit("characterReference"); return ok; } if (test(code) && size++ < max) { effects.consume(code); return value; } return nok(code); } } // node_modules/micromark-core-commonmark/lib/code-fenced.js var nonLazyContinuation = { tokenize: tokenizeNonLazyContinuation, partial: true }; var codeFenced = { name: "codeFenced", tokenize: tokenizeCodeFenced, concrete: true }; function tokenizeCodeFenced(effects, ok, nok) { const self2 = this; const closeStart = { tokenize: tokenizeCloseStart, partial: true }; let initialPrefix = 0; let sizeOpen = 0; let marker; return start; function start(code) { return beforeSequenceOpen(code); } function beforeSequenceOpen(code) { const tail = self2.events[self2.events.length - 1]; initialPrefix = tail && tail[1].type === "linePrefix" ? tail[2].sliceSerialize(tail[1], true).length : 0; marker = code; effects.enter("codeFenced"); effects.enter("codeFencedFence"); effects.enter("codeFencedFenceSequence"); return sequenceOpen(code); } function sequenceOpen(code) { if (code === marker) { sizeOpen++; effects.consume(code); return sequenceOpen; } if (sizeOpen < 3) { return nok(code); } effects.exit("codeFencedFenceSequence"); return markdownSpace(code) ? factorySpace(effects, infoBefore, "whitespace")(code) : infoBefore(code); } function infoBefore(code) { if (code === null || markdownLineEnding(code)) { effects.exit("codeFencedFence"); return self2.interrupt ? ok(code) : effects.check(nonLazyContinuation, atNonLazyBreak, after)(code); } effects.enter("codeFencedFenceInfo"); effects.enter("chunkString", { contentType: "string" }); return info(code); } function info(code) { if (code === null || markdownLineEnding(code)) { effects.exit("chunkString"); effects.exit("codeFencedFenceInfo"); return infoBefore(code); } if (markdownSpace(code)) { effects.exit("chunkString"); effects.exit("codeFencedFenceInfo"); return factorySpace(effects, metaBefore, "whitespace")(code); } if (code === 96 && code === marker) { return nok(code); } effects.consume(code); return info; } function metaBefore(code) { if (code === null || markdownLineEnding(code)) { return infoBefore(code); } effects.enter("codeFencedFenceMeta"); effects.enter("chunkString", { contentType: "string" }); return meta(code); } function meta(code) { if (code === null || markdownLineEnding(code)) { effects.exit("chunkString"); effects.exit("codeFencedFenceMeta"); return infoBefore(code); } if (code === 96 && code === marker) { return nok(code); } effects.consume(code); return meta; } function atNonLazyBreak(code) { return effects.attempt(closeStart, after, contentBefore)(code); } function contentBefore(code) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return contentStart; } function contentStart(code) { return initialPrefix > 0 && markdownSpace(code) ? factorySpace( effects, beforeContentChunk, "linePrefix", initialPrefix + 1 )(code) : beforeContentChunk(code); } function beforeContentChunk(code) { if (code === null || markdownLineEnding(code)) { return effects.check(nonLazyContinuation, atNonLazyBreak, after)(code); } effects.enter("codeFlowValue"); return contentChunk(code); } function contentChunk(code) { if (code === null || markdownLineEnding(code)) { effects.exit("codeFlowValue"); return beforeContentChunk(code); } effects.consume(code); return contentChunk; } function after(code) { effects.exit("codeFenced"); return ok(code); } function tokenizeCloseStart(effects2, ok2, nok2) { let size = 0; return startBefore; function startBefore(code) { effects2.enter("lineEnding"); effects2.consume(code); effects2.exit("lineEnding"); return start2; } function start2(code) { effects2.enter("codeFencedFence"); return markdownSpace(code) ? factorySpace( effects2, beforeSequenceClose, "linePrefix", self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4 )(code) : beforeSequenceClose(code); } function beforeSequenceClose(code) { if (code === marker) { effects2.enter("codeFencedFenceSequence"); return sequenceClose(code); } return nok2(code); } function sequenceClose(code) { if (code === marker) { size++; effects2.consume(code); return sequenceClose; } if (size >= sizeOpen) { effects2.exit("codeFencedFenceSequence"); return markdownSpace(code) ? factorySpace(effects2, sequenceCloseAfter, "whitespace")(code) : sequenceCloseAfter(code); } return nok2(code); } function sequenceCloseAfter(code) { if (code === null || markdownLineEnding(code)) { effects2.exit("codeFencedFence"); return ok2(code); } return nok2(code); } } } function tokenizeNonLazyContinuation(effects, ok, nok) { const self2 = this; return start; function start(code) { if (code === null) { return nok(code); } effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return lineStart; } function lineStart(code) { return self2.parser.lazy[self2.now().line] ? nok(code) : ok(code); } } // node_modules/micromark-core-commonmark/lib/code-indented.js var codeIndented = { name: "codeIndented", tokenize: tokenizeCodeIndented }; var furtherStart = { tokenize: tokenizeFurtherStart, partial: true }; function tokenizeCodeIndented(effects, ok, nok) { const self2 = this; return start; function start(code) { effects.enter("codeIndented"); return factorySpace(effects, afterPrefix, "linePrefix", 4 + 1)(code); } function afterPrefix(code) { const tail = self2.events[self2.events.length - 1]; return tail && tail[1].type === "linePrefix" && tail[2].sliceSerialize(tail[1], true).length >= 4 ? atBreak(code) : nok(code); } function atBreak(code) { if (code === null) { return after(code); } if (markdownLineEnding(code)) { return effects.attempt(furtherStart, atBreak, after)(code); } effects.enter("codeFlowValue"); return inside(code); } function inside(code) { if (code === null || markdownLineEnding(code)) { effects.exit("codeFlowValue"); return atBreak(code); } effects.consume(code); return inside; } function after(code) { effects.exit("codeIndented"); return ok(code); } } function tokenizeFurtherStart(effects, ok, nok) { const self2 = this; return furtherStart2; function furtherStart2(code) { if (self2.parser.lazy[self2.now().line]) { return nok(code); } if (markdownLineEnding(code)) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return furtherStart2; } return factorySpace(effects, afterPrefix, "linePrefix", 4 + 1)(code); } function afterPrefix(code) { const tail = self2.events[self2.events.length - 1]; return tail && tail[1].type === "linePrefix" && tail[2].sliceSerialize(tail[1], true).length >= 4 ? ok(code) : markdownLineEnding(code) ? furtherStart2(code) : nok(code); } } // node_modules/micromark-core-commonmark/lib/code-text.js var codeText = { name: "codeText", tokenize: tokenizeCodeText, resolve: resolveCodeText, previous }; function resolveCodeText(events) { let tailExitIndex = events.length - 4; let headEnterIndex = 3; let index2; let enter; if ((events[headEnterIndex][1].type === "lineEnding" || events[headEnterIndex][1].type === "space") && (events[tailExitIndex][1].type === "lineEnding" || events[tailExitIndex][1].type === "space")) { index2 = headEnterIndex; while (++index2 < tailExitIndex) { if (events[index2][1].type === "codeTextData") { events[headEnterIndex][1].type = "codeTextPadding"; events[tailExitIndex][1].type = "codeTextPadding"; headEnterIndex += 2; tailExitIndex -= 2; break; } } } index2 = headEnterIndex - 1; tailExitIndex++; while (++index2 <= tailExitIndex) { if (enter === void 0) { if (index2 !== tailExitIndex && events[index2][1].type !== "lineEnding") { enter = index2; } } else if (index2 === tailExitIndex || events[index2][1].type === "lineEnding") { events[enter][1].type = "codeTextData"; if (index2 !== enter + 2) { events[enter][1].end = events[index2 - 1][1].end; events.splice(enter + 2, index2 - enter - 2); tailExitIndex -= index2 - enter - 2; index2 = enter + 2; } enter = void 0; } } return events; } function previous(code) { return code !== 96 || this.events[this.events.length - 1][1].type === "characterEscape"; } function tokenizeCodeText(effects, ok, nok) { const self2 = this; let sizeOpen = 0; let size; let token; return start; function start(code) { effects.enter("codeText"); effects.enter("codeTextSequence"); return sequenceOpen(code); } function sequenceOpen(code) { if (code === 96) { effects.consume(code); sizeOpen++; return sequenceOpen; } effects.exit("codeTextSequence"); return between(code); } function between(code) { if (code === null) { return nok(code); } if (code === 32) { effects.enter("space"); effects.consume(code); effects.exit("space"); return between; } if (code === 96) { token = effects.enter("codeTextSequence"); size = 0; return sequenceClose(code); } if (markdownLineEnding(code)) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return between; } effects.enter("codeTextData"); return data(code); } function data(code) { if (code === null || code === 32 || code === 96 || markdownLineEnding(code)) { effects.exit("codeTextData"); return between(code); } effects.consume(code); return data; } function sequenceClose(code) { if (code === 96) { effects.consume(code); size++; return sequenceClose; } if (size === sizeOpen) { effects.exit("codeTextSequence"); effects.exit("codeText"); return ok(code); } token.type = "codeTextData"; return data(code); } } // node_modules/micromark-util-subtokenize/index.js function subtokenize(events) { const jumps = {}; let index2 = -1; let event; let lineIndex; let otherIndex; let otherEvent; let parameters; let subevents; let more; while (++index2 < events.length) { while (index2 in jumps) { index2 = jumps[index2]; } event = events[index2]; if (index2 && event[1].type === "chunkFlow" && events[index2 - 1][1].type === "listItemPrefix") { subevents = event[1]._tokenizer.events; otherIndex = 0; if (otherIndex < subevents.length && subevents[otherIndex][1].type === "lineEndingBlank") { otherIndex += 2; } if (otherIndex < subevents.length && subevents[otherIndex][1].type === "content") { while (++otherIndex < subevents.length) { if (subevents[otherIndex][1].type === "content") { break; } if (subevents[otherIndex][1].type === "chunkText") { subevents[otherIndex][1]._isInFirstContentOfListItem = true; otherIndex++; } } } } if (event[0] === "enter") { if (event[1].contentType) { Object.assign(jumps, subcontent(events, index2)); index2 = jumps[index2]; more = true; } } else if (event[1]._container) { otherIndex = index2; lineIndex = void 0; while (otherIndex--) { otherEvent = events[otherIndex]; if (otherEvent[1].type === "lineEnding" || otherEvent[1].type === "lineEndingBlank") { if (otherEvent[0] === "enter") { if (lineIndex) { events[lineIndex][1].type = "lineEndingBlank"; } otherEvent[1].type = "lineEnding"; lineIndex = otherIndex; } } else { break; } } if (lineIndex) { event[1].end = Object.assign({}, events[lineIndex][1].start); parameters = events.slice(lineIndex, index2); parameters.unshift(event); splice(events, lineIndex, index2 - lineIndex + 1, parameters); } } } return !more; } function subcontent(events, eventIndex) { const token = events[eventIndex][1]; const context = events[eventIndex][2]; let startPosition = eventIndex - 1; const startPositions = []; const tokenizer = token._tokenizer || context.parser[token.contentType](token.start); const childEvents = tokenizer.events; const jumps = []; const gaps = {}; let stream; let previous3; let index2 = -1; let current = token; let adjust = 0; let start = 0; const breaks = [start]; while (current) { while (events[++startPosition][1] !== current) { } startPositions.push(startPosition); if (!current._tokenizer) { stream = context.sliceStream(current); if (!current.next) { stream.push(null); } if (previous3) { tokenizer.defineSkip(current.start); } if (current._isInFirstContentOfListItem) { tokenizer._gfmTasklistFirstContentOfListItem = true; } tokenizer.write(stream); if (current._isInFirstContentOfListItem) { tokenizer._gfmTasklistFirstContentOfListItem = void 0; } } previous3 = current; current = current.next; } current = token; while (++index2 < childEvents.length) { if ( // Find a void token that includes a break. childEvents[index2][0] === "exit" && childEvents[index2 - 1][0] === "enter" && childEvents[index2][1].type === childEvents[index2 - 1][1].type && childEvents[index2][1].start.line !== childEvents[index2][1].end.line ) { start = index2 + 1; breaks.push(start); current._tokenizer = void 0; current.previous = void 0; current = current.next; } } tokenizer.events = []; if (current) { current._tokenizer = void 0; current.previous = void 0; } else { breaks.pop(); } index2 = breaks.length; while (index2--) { const slice = childEvents.slice(breaks[index2], breaks[index2 + 1]); const start2 = startPositions.pop(); jumps.unshift([start2, start2 + slice.length - 1]); splice(events, start2, 2, slice); } index2 = -1; while (++index2 < jumps.length) { gaps[adjust + jumps[index2][0]] = adjust + jumps[index2][1]; adjust += jumps[index2][1] - jumps[index2][0] - 1; } return gaps; } // node_modules/micromark-core-commonmark/lib/content.js var content = { tokenize: tokenizeContent, resolve: resolveContent }; var continuationConstruct = { tokenize: tokenizeContinuation, partial: true }; function resolveContent(events) { subtokenize(events); return events; } function tokenizeContent(effects, ok) { let previous3; return chunkStart; function chunkStart(code) { effects.enter("content"); previous3 = effects.enter("chunkContent", { contentType: "content" }); return chunkInside(code); } function chunkInside(code) { if (code === null) { return contentEnd(code); } if (markdownLineEnding(code)) { return effects.check( continuationConstruct, contentContinue, contentEnd )(code); } effects.consume(code); return chunkInside; } function contentEnd(code) { effects.exit("chunkContent"); effects.exit("content"); return ok(code); } function contentContinue(code) { effects.consume(code); effects.exit("chunkContent"); previous3.next = effects.enter("chunkContent", { contentType: "content", previous: previous3 }); previous3 = previous3.next; return chunkInside; } } function tokenizeContinuation(effects, ok, nok) { const self2 = this; return startLookahead; function startLookahead(code) { effects.exit("chunkContent"); effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return factorySpace(effects, prefixed, "linePrefix"); } function prefixed(code) { if (code === null || markdownLineEnding(code)) { return nok(code); } const tail = self2.events[self2.events.length - 1]; if (!self2.parser.constructs.disable.null.includes("codeIndented") && tail && tail[1].type === "linePrefix" && tail[2].sliceSerialize(tail[1], true).length >= 4) { return ok(code); } return effects.interrupt(self2.parser.constructs.flow, nok, ok)(code); } } // node_modules/micromark-factory-destination/index.js function factoryDestination(effects, ok, nok, type2, literalType2, literalMarkerType, rawType, stringType2, max) { const limit = max || Number.POSITIVE_INFINITY; let balance = 0; return start; function start(code) { if (code === 60) { effects.enter(type2); effects.enter(literalType2); effects.enter(literalMarkerType); effects.consume(code); effects.exit(literalMarkerType); return enclosedBefore; } if (code === null || code === 32 || code === 41 || asciiControl(code)) { return nok(code); } effects.enter(type2); effects.enter(rawType); effects.enter(stringType2); effects.enter("chunkString", { contentType: "string" }); return raw(code); } function enclosedBefore(code) { if (code === 62) { effects.enter(literalMarkerType); effects.consume(code); effects.exit(literalMarkerType); effects.exit(literalType2); effects.exit(type2); return ok; } effects.enter(stringType2); effects.enter("chunkString", { contentType: "string" }); return enclosed(code); } function enclosed(code) { if (code === 62) { effects.exit("chunkString"); effects.exit(stringType2); return enclosedBefore(code); } if (code === null || code === 60 || markdownLineEnding(code)) { return nok(code); } effects.consume(code); return code === 92 ? enclosedEscape : enclosed; } function enclosedEscape(code) { if (code === 60 || code === 62 || code === 92) { effects.consume(code); return enclosed; } return enclosed(code); } function raw(code) { if (!balance && (code === null || code === 41 || markdownLineEndingOrSpace(code))) { effects.exit("chunkString"); effects.exit(stringType2); effects.exit(rawType); effects.exit(type2); return ok(code); } if (balance < limit && code === 40) { effects.consume(code); balance++; return raw; } if (code === 41) { effects.consume(code); balance--; return raw; } if (code === null || code === 32 || code === 40 || asciiControl(code)) { return nok(code); } effects.consume(code); return code === 92 ? rawEscape : raw; } function rawEscape(code) { if (code === 40 || code === 41 || code === 92) { effects.consume(code); return raw; } return raw(code); } } // node_modules/micromark-factory-label/index.js function factoryLabel(effects, ok, nok, type2, markerType, stringType2) { const self2 = this; let size = 0; let seen; return start; function start(code) { effects.enter(type2); effects.enter(markerType); effects.consume(code); effects.exit(markerType); effects.enter(stringType2); return atBreak; } function atBreak(code) { if (size > 999 || code === null || code === 91 || code === 93 && !seen || // To do: remove in the future once we’ve switched from // `micromark-extension-footnote` to `micromark-extension-gfm-footnote`, // which doesn’t need this. // Hidden footnotes hook. /* c8 ignore next 3 */ code === 94 && !size && "_hiddenFootnoteSupport" in self2.parser.constructs) { return nok(code); } if (code === 93) { effects.exit(stringType2); effects.enter(markerType); effects.consume(code); effects.exit(markerType); effects.exit(type2); return ok; } if (markdownLineEnding(code)) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return atBreak; } effects.enter("chunkString", { contentType: "string" }); return labelInside(code); } function labelInside(code) { if (code === null || code === 91 || code === 93 || markdownLineEnding(code) || size++ > 999) { effects.exit("chunkString"); return atBreak(code); } effects.consume(code); if (!seen) seen = !markdownSpace(code); return code === 92 ? labelEscape : labelInside; } function labelEscape(code) { if (code === 91 || code === 92 || code === 93) { effects.consume(code); size++; return labelInside; } return labelInside(code); } } // node_modules/micromark-factory-title/index.js function factoryTitle(effects, ok, nok, type2, markerType, stringType2) { let marker; return start; function start(code) { if (code === 34 || code === 39 || code === 40) { effects.enter(type2); effects.enter(markerType); effects.consume(code); effects.exit(markerType); marker = code === 40 ? 41 : code; return begin; } return nok(code); } function begin(code) { if (code === marker) { effects.enter(markerType); effects.consume(code); effects.exit(markerType); effects.exit(type2); return ok; } effects.enter(stringType2); return atBreak(code); } function atBreak(code) { if (code === marker) { effects.exit(stringType2); return begin(marker); } if (code === null) { return nok(code); } if (markdownLineEnding(code)) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return factorySpace(effects, atBreak, "linePrefix"); } effects.enter("chunkString", { contentType: "string" }); return inside(code); } function inside(code) { if (code === marker || code === null || markdownLineEnding(code)) { effects.exit("chunkString"); return atBreak(code); } effects.consume(code); return code === 92 ? escape : inside; } function escape(code) { if (code === marker || code === 92) { effects.consume(code); return inside; } return inside(code); } } // node_modules/micromark-factory-whitespace/index.js function factoryWhitespace(effects, ok) { let seen; return start; function start(code) { if (markdownLineEnding(code)) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); seen = true; return start; } if (markdownSpace(code)) { return factorySpace( effects, start, seen ? "linePrefix" : "lineSuffix" )(code); } return ok(code); } } // node_modules/micromark-util-normalize-identifier/index.js function normalizeIdentifier(value) { return value.replace(/[\t\n\r ]+/g, " ").replace(/^ | $/g, "").toLowerCase().toUpperCase(); } // node_modules/micromark-core-commonmark/lib/definition.js var definition = { name: "definition", tokenize: tokenizeDefinition }; var titleBefore = { tokenize: tokenizeTitleBefore, partial: true }; function tokenizeDefinition(effects, ok, nok) { const self2 = this; let identifier; return start; function start(code) { effects.enter("definition"); return before(code); } function before(code) { return factoryLabel.call( self2, effects, labelAfter, // Note: we don’t need to reset the way `markdown-rs` does. nok, "definitionLabel", "definitionLabelMarker", "definitionLabelString" )(code); } function labelAfter(code) { identifier = normalizeIdentifier( self2.sliceSerialize(self2.events[self2.events.length - 1][1]).slice(1, -1) ); if (code === 58) { effects.enter("definitionMarker"); effects.consume(code); effects.exit("definitionMarker"); return markerAfter; } return nok(code); } function markerAfter(code) { return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, destinationBefore)(code) : destinationBefore(code); } function destinationBefore(code) { return factoryDestination( effects, destinationAfter, // Note: we don’t need to reset the way `markdown-rs` does. nok, "definitionDestination", "definitionDestinationLiteral", "definitionDestinationLiteralMarker", "definitionDestinationRaw", "definitionDestinationString" )(code); } function destinationAfter(code) { return effects.attempt(titleBefore, after, after)(code); } function after(code) { return markdownSpace(code) ? factorySpace(effects, afterWhitespace, "whitespace")(code) : afterWhitespace(code); } function afterWhitespace(code) { if (code === null || markdownLineEnding(code)) { effects.exit("definition"); self2.parser.defined.push(identifier); return ok(code); } return nok(code); } } function tokenizeTitleBefore(effects, ok, nok) { return titleBefore2; function titleBefore2(code) { return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, beforeMarker)(code) : nok(code); } function beforeMarker(code) { return factoryTitle( effects, titleAfter, nok, "definitionTitle", "definitionTitleMarker", "definitionTitleString" )(code); } function titleAfter(code) { return markdownSpace(code) ? factorySpace(effects, titleAfterOptionalWhitespace, "whitespace")(code) : titleAfterOptionalWhitespace(code); } function titleAfterOptionalWhitespace(code) { return code === null || markdownLineEnding(code) ? ok(code) : nok(code); } } // node_modules/micromark-core-commonmark/lib/hard-break-escape.js var hardBreakEscape = { name: "hardBreakEscape", tokenize: tokenizeHardBreakEscape }; function tokenizeHardBreakEscape(effects, ok, nok) { return start; function start(code) { effects.enter("hardBreakEscape"); effects.consume(code); return after; } function after(code) { if (markdownLineEnding(code)) { effects.exit("hardBreakEscape"); return ok(code); } return nok(code); } } // node_modules/micromark-core-commonmark/lib/heading-atx.js var headingAtx = { name: "headingAtx", tokenize: tokenizeHeadingAtx, resolve: resolveHeadingAtx }; function resolveHeadingAtx(events, context) { let contentEnd = events.length - 2; let contentStart = 3; let content3; let text3; if (events[contentStart][1].type === "whitespace") { contentStart += 2; } if (contentEnd - 2 > contentStart && events[contentEnd][1].type === "whitespace") { contentEnd -= 2; } if (events[contentEnd][1].type === "atxHeadingSequence" && (contentStart === contentEnd - 1 || contentEnd - 4 > contentStart && events[contentEnd - 2][1].type === "whitespace")) { contentEnd -= contentStart + 1 === contentEnd ? 2 : 4; } if (contentEnd > contentStart) { content3 = { type: "atxHeadingText", start: events[contentStart][1].start, end: events[contentEnd][1].end }; text3 = { type: "chunkText", start: events[contentStart][1].start, end: events[contentEnd][1].end, contentType: "text" }; splice(events, contentStart, contentEnd - contentStart + 1, [ ["enter", content3, context], ["enter", text3, context], ["exit", text3, context], ["exit", content3, context] ]); } return events; } function tokenizeHeadingAtx(effects, ok, nok) { let size = 0; return start; function start(code) { effects.enter("atxHeading"); return before(code); } function before(code) { effects.enter("atxHeadingSequence"); return sequenceOpen(code); } function sequenceOpen(code) { if (code === 35 && size++ < 6) { effects.consume(code); return sequenceOpen; } if (code === null || markdownLineEndingOrSpace(code)) { effects.exit("atxHeadingSequence"); return atBreak(code); } return nok(code); } function atBreak(code) { if (code === 35) { effects.enter("atxHeadingSequence"); return sequenceFurther(code); } if (code === null || markdownLineEnding(code)) { effects.exit("atxHeading"); return ok(code); } if (markdownSpace(code)) { return factorySpace(effects, atBreak, "whitespace")(code); } effects.enter("atxHeadingText"); return data(code); } function sequenceFurther(code) { if (code === 35) { effects.consume(code); return sequenceFurther; } effects.exit("atxHeadingSequence"); return atBreak(code); } function data(code) { if (code === null || code === 35 || markdownLineEndingOrSpace(code)) { effects.exit("atxHeadingText"); return atBreak(code); } effects.consume(code); return data; } } // node_modules/micromark-util-html-tag-name/index.js var htmlBlockNames = [ "address", "article", "aside", "base", "basefont", "blockquote", "body", "caption", "center", "col", "colgroup", "dd", "details", "dialog", "dir", "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hr", "html", "iframe", "legend", "li", "link", "main", "menu", "menuitem", "nav", "noframes", "ol", "optgroup", "option", "p", "param", "search", "section", "summary", "table", "tbody", "td", "tfoot", "th", "thead", "title", "tr", "track", "ul" ]; var htmlRawNames = ["pre", "script", "style", "textarea"]; // node_modules/micromark-core-commonmark/lib/html-flow.js var htmlFlow = { name: "htmlFlow", tokenize: tokenizeHtmlFlow, resolveTo: resolveToHtmlFlow, concrete: true }; var blankLineBefore = { tokenize: tokenizeBlankLineBefore, partial: true }; var nonLazyContinuationStart = { tokenize: tokenizeNonLazyContinuationStart, partial: true }; function resolveToHtmlFlow(events) { let index2 = events.length; while (index2--) { if (events[index2][0] === "enter" && events[index2][1].type === "htmlFlow") { break; } } if (index2 > 1 && events[index2 - 2][1].type === "linePrefix") { events[index2][1].start = events[index2 - 2][1].start; events[index2 + 1][1].start = events[index2 - 2][1].start; events.splice(index2 - 2, 2); } return events; } function tokenizeHtmlFlow(effects, ok, nok) { const self2 = this; let marker; let closingTag; let buffer; let index2; let markerB; return start; function start(code) { return before(code); } function before(code) { effects.enter("htmlFlow"); effects.enter("htmlFlowData"); effects.consume(code); return open; } function open(code) { if (code === 33) { effects.consume(code); return declarationOpen; } if (code === 47) { effects.consume(code); closingTag = true; return tagCloseStart; } if (code === 63) { effects.consume(code); marker = 3; return self2.interrupt ? ok : continuationDeclarationInside; } if (asciiAlpha(code)) { effects.consume(code); buffer = String.fromCharCode(code); return tagName; } return nok(code); } function declarationOpen(code) { if (code === 45) { effects.consume(code); marker = 2; return commentOpenInside; } if (code === 91) { effects.consume(code); marker = 5; index2 = 0; return cdataOpenInside; } if (asciiAlpha(code)) { effects.consume(code); marker = 4; return self2.interrupt ? ok : continuationDeclarationInside; } return nok(code); } function commentOpenInside(code) { if (code === 45) { effects.consume(code); return self2.interrupt ? ok : continuationDeclarationInside; } return nok(code); } function cdataOpenInside(code) { const value = "CDATA["; if (code === value.charCodeAt(index2++)) { effects.consume(code); if (index2 === value.length) { return self2.interrupt ? ok : continuation; } return cdataOpenInside; } return nok(code); } function tagCloseStart(code) { if (asciiAlpha(code)) { effects.consume(code); buffer = String.fromCharCode(code); return tagName; } return nok(code); } function tagName(code) { if (code === null || code === 47 || code === 62 || markdownLineEndingOrSpace(code)) { const slash = code === 47; const name = buffer.toLowerCase(); if (!slash && !closingTag && htmlRawNames.includes(name)) { marker = 1; return self2.interrupt ? ok(code) : continuation(code); } if (htmlBlockNames.includes(buffer.toLowerCase())) { marker = 6; if (slash) { effects.consume(code); return basicSelfClosing; } return self2.interrupt ? ok(code) : continuation(code); } marker = 7; return self2.interrupt && !self2.parser.lazy[self2.now().line] ? nok(code) : closingTag ? completeClosingTagAfter(code) : completeAttributeNameBefore(code); } if (code === 45 || asciiAlphanumeric(code)) { effects.consume(code); buffer += String.fromCharCode(code); return tagName; } return nok(code); } function basicSelfClosing(code) { if (code === 62) { effects.consume(code); return self2.interrupt ? ok : continuation; } return nok(code); } function completeClosingTagAfter(code) { if (markdownSpace(code)) { effects.consume(code); return completeClosingTagAfter; } return completeEnd(code); } function completeAttributeNameBefore(code) { if (code === 47) { effects.consume(code); return completeEnd; } if (code === 58 || code === 95 || asciiAlpha(code)) { effects.consume(code); return completeAttributeName; } if (markdownSpace(code)) { effects.consume(code); return completeAttributeNameBefore; } return completeEnd(code); } function completeAttributeName(code) { if (code === 45 || code === 46 || code === 58 || code === 95 || asciiAlphanumeric(code)) { effects.consume(code); return completeAttributeName; } return completeAttributeNameAfter(code); } function completeAttributeNameAfter(code) { if (code === 61) { effects.consume(code); return completeAttributeValueBefore; } if (markdownSpace(code)) { effects.consume(code); return completeAttributeNameAfter; } return completeAttributeNameBefore(code); } function completeAttributeValueBefore(code) { if (code === null || code === 60 || code === 61 || code === 62 || code === 96) { return nok(code); } if (code === 34 || code === 39) { effects.consume(code); markerB = code; return completeAttributeValueQuoted; } if (markdownSpace(code)) { effects.consume(code); return completeAttributeValueBefore; } return completeAttributeValueUnquoted(code); } function completeAttributeValueQuoted(code) { if (code === markerB) { effects.consume(code); markerB = null; return completeAttributeValueQuotedAfter; } if (code === null || markdownLineEnding(code)) { return nok(code); } effects.consume(code); return completeAttributeValueQuoted; } function completeAttributeValueUnquoted(code) { if (code === null || code === 34 || code === 39 || code === 47 || code === 60 || code === 61 || code === 62 || code === 96 || markdownLineEndingOrSpace(code)) { return completeAttributeNameAfter(code); } effects.consume(code); return completeAttributeValueUnquoted; } function completeAttributeValueQuotedAfter(code) { if (code === 47 || code === 62 || markdownSpace(code)) { return completeAttributeNameBefore(code); } return nok(code); } function completeEnd(code) { if (code === 62) { effects.consume(code); return completeAfter; } return nok(code); } function completeAfter(code) { if (code === null || markdownLineEnding(code)) { return continuation(code); } if (markdownSpace(code)) { effects.consume(code); return completeAfter; } return nok(code); } function continuation(code) { if (code === 45 && marker === 2) { effects.consume(code); return continuationCommentInside; } if (code === 60 && marker === 1) { effects.consume(code); return continuationRawTagOpen; } if (code === 62 && marker === 4) { effects.consume(code); return continuationClose; } if (code === 63 && marker === 3) { effects.consume(code); return continuationDeclarationInside; } if (code === 93 && marker === 5) { effects.consume(code); return continuationCdataInside; } if (markdownLineEnding(code) && (marker === 6 || marker === 7)) { effects.exit("htmlFlowData"); return effects.check( blankLineBefore, continuationAfter, continuationStart )(code); } if (code === null || markdownLineEnding(code)) { effects.exit("htmlFlowData"); return continuationStart(code); } effects.consume(code); return continuation; } function continuationStart(code) { return effects.check( nonLazyContinuationStart, continuationStartNonLazy, continuationAfter )(code); } function continuationStartNonLazy(code) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return continuationBefore; } function continuationBefore(code) { if (code === null || markdownLineEnding(code)) { return continuationStart(code); } effects.enter("htmlFlowData"); return continuation(code); } function continuationCommentInside(code) { if (code === 45) { effects.consume(code); return continuationDeclarationInside; } return continuation(code); } function continuationRawTagOpen(code) { if (code === 47) { effects.consume(code); buffer = ""; return continuationRawEndTag; } return continuation(code); } function continuationRawEndTag(code) { if (code === 62) { const name = buffer.toLowerCase(); if (htmlRawNames.includes(name)) { effects.consume(code); return continuationClose; } return continuation(code); } if (asciiAlpha(code) && buffer.length < 8) { effects.consume(code); buffer += String.fromCharCode(code); return continuationRawEndTag; } return continuation(code); } function continuationCdataInside(code) { if (code === 93) { effects.consume(code); return continuationDeclarationInside; } return continuation(code); } function continuationDeclarationInside(code) { if (code === 62) { effects.consume(code); return continuationClose; } if (code === 45 && marker === 2) { effects.consume(code); return continuationDeclarationInside; } return continuation(code); } function continuationClose(code) { if (code === null || markdownLineEnding(code)) { effects.exit("htmlFlowData"); return continuationAfter(code); } effects.consume(code); return continuationClose; } function continuationAfter(code) { effects.exit("htmlFlow"); return ok(code); } } function tokenizeNonLazyContinuationStart(effects, ok, nok) { const self2 = this; return start; function start(code) { if (markdownLineEnding(code)) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return after; } return nok(code); } function after(code) { return self2.parser.lazy[self2.now().line] ? nok(code) : ok(code); } } function tokenizeBlankLineBefore(effects, ok, nok) { return start; function start(code) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return effects.attempt(blankLine, ok, nok); } } // node_modules/micromark-core-commonmark/lib/html-text.js var htmlText = { name: "htmlText", tokenize: tokenizeHtmlText }; function tokenizeHtmlText(effects, ok, nok) { const self2 = this; let marker; let index2; let returnState; return start; function start(code) { effects.enter("htmlText"); effects.enter("htmlTextData"); effects.consume(code); return open; } function open(code) { if (code === 33) { effects.consume(code); return declarationOpen; } if (code === 47) { effects.consume(code); return tagCloseStart; } if (code === 63) { effects.consume(code); return instruction; } if (asciiAlpha(code)) { effects.consume(code); return tagOpen; } return nok(code); } function declarationOpen(code) { if (code === 45) { effects.consume(code); return commentOpenInside; } if (code === 91) { effects.consume(code); index2 = 0; return cdataOpenInside; } if (asciiAlpha(code)) { effects.consume(code); return declaration; } return nok(code); } function commentOpenInside(code) { if (code === 45) { effects.consume(code); return commentEnd; } return nok(code); } function comment(code) { if (code === null) { return nok(code); } if (code === 45) { effects.consume(code); return commentClose; } if (markdownLineEnding(code)) { returnState = comment; return lineEndingBefore(code); } effects.consume(code); return comment; } function commentClose(code) { if (code === 45) { effects.consume(code); return commentEnd; } return comment(code); } function commentEnd(code) { return code === 62 ? end(code) : code === 45 ? commentClose(code) : comment(code); } function cdataOpenInside(code) { const value = "CDATA["; if (code === value.charCodeAt(index2++)) { effects.consume(code); return index2 === value.length ? cdata : cdataOpenInside; } return nok(code); } function cdata(code) { if (code === null) { return nok(code); } if (code === 93) { effects.consume(code); return cdataClose; } if (markdownLineEnding(code)) { returnState = cdata; return lineEndingBefore(code); } effects.consume(code); return cdata; } function cdataClose(code) { if (code === 93) { effects.consume(code); return cdataEnd; } return cdata(code); } function cdataEnd(code) { if (code === 62) { return end(code); } if (code === 93) { effects.consume(code); return cdataEnd; } return cdata(code); } function declaration(code) { if (code === null || code === 62) { return end(code); } if (markdownLineEnding(code)) { returnState = declaration; return lineEndingBefore(code); } effects.consume(code); return declaration; } function instruction(code) { if (code === null) { return nok(code); } if (code === 63) { effects.consume(code); return instructionClose; } if (markdownLineEnding(code)) { returnState = instruction; return lineEndingBefore(code); } effects.consume(code); return instruction; } function instructionClose(code) { return code === 62 ? end(code) : instruction(code); } function tagCloseStart(code) { if (asciiAlpha(code)) { effects.consume(code); return tagClose; } return nok(code); } function tagClose(code) { if (code === 45 || asciiAlphanumeric(code)) { effects.consume(code); return tagClose; } return tagCloseBetween(code); } function tagCloseBetween(code) { if (markdownLineEnding(code)) { returnState = tagCloseBetween; return lineEndingBefore(code); } if (markdownSpace(code)) { effects.consume(code); return tagCloseBetween; } return end(code); } function tagOpen(code) { if (code === 45 || asciiAlphanumeric(code)) { effects.consume(code); return tagOpen; } if (code === 47 || code === 62 || markdownLineEndingOrSpace(code)) { return tagOpenBetween(code); } return nok(code); } function tagOpenBetween(code) { if (code === 47) { effects.consume(code); return end; } if (code === 58 || code === 95 || asciiAlpha(code)) { effects.consume(code); return tagOpenAttributeName; } if (markdownLineEnding(code)) { returnState = tagOpenBetween; return lineEndingBefore(code); } if (markdownSpace(code)) { effects.consume(code); return tagOpenBetween; } return end(code); } function tagOpenAttributeName(code) { if (code === 45 || code === 46 || code === 58 || code === 95 || asciiAlphanumeric(code)) { effects.consume(code); return tagOpenAttributeName; } return tagOpenAttributeNameAfter(code); } function tagOpenAttributeNameAfter(code) { if (code === 61) { effects.consume(code); return tagOpenAttributeValueBefore; } if (markdownLineEnding(code)) { returnState = tagOpenAttributeNameAfter; return lineEndingBefore(code); } if (markdownSpace(code)) { effects.consume(code); return tagOpenAttributeNameAfter; } return tagOpenBetween(code); } function tagOpenAttributeValueBefore(code) { if (code === null || code === 60 || code === 61 || code === 62 || code === 96) { return nok(code); } if (code === 34 || code === 39) { effects.consume(code); marker = code; return tagOpenAttributeValueQuoted; } if (markdownLineEnding(code)) { returnState = tagOpenAttributeValueBefore; return lineEndingBefore(code); } if (markdownSpace(code)) { effects.consume(code); return tagOpenAttributeValueBefore; } effects.consume(code); return tagOpenAttributeValueUnquoted; } function tagOpenAttributeValueQuoted(code) { if (code === marker) { effects.consume(code); marker = void 0; return tagOpenAttributeValueQuotedAfter; } if (code === null) { return nok(code); } if (markdownLineEnding(code)) { returnState = tagOpenAttributeValueQuoted; return lineEndingBefore(code); } effects.consume(code); return tagOpenAttributeValueQuoted; } function tagOpenAttributeValueUnquoted(code) { if (code === null || code === 34 || code === 39 || code === 60 || code === 61 || code === 96) { return nok(code); } if (code === 47 || code === 62 || markdownLineEndingOrSpace(code)) { return tagOpenBetween(code); } effects.consume(code); return tagOpenAttributeValueUnquoted; } function tagOpenAttributeValueQuotedAfter(code) { if (code === 47 || code === 62 || markdownLineEndingOrSpace(code)) { return tagOpenBetween(code); } return nok(code); } function end(code) { if (code === 62) { effects.consume(code); effects.exit("htmlTextData"); effects.exit("htmlText"); return ok; } return nok(code); } function lineEndingBefore(code) { effects.exit("htmlTextData"); effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return lineEndingAfter; } function lineEndingAfter(code) { return markdownSpace(code) ? factorySpace( effects, lineEndingAfterPrefix, "linePrefix", self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4 )(code) : lineEndingAfterPrefix(code); } function lineEndingAfterPrefix(code) { effects.enter("htmlTextData"); return returnState(code); } } // node_modules/micromark-core-commonmark/lib/label-end.js var labelEnd = { name: "labelEnd", tokenize: tokenizeLabelEnd, resolveTo: resolveToLabelEnd, resolveAll: resolveAllLabelEnd }; var resourceConstruct = { tokenize: tokenizeResource }; var referenceFullConstruct = { tokenize: tokenizeReferenceFull }; var referenceCollapsedConstruct = { tokenize: tokenizeReferenceCollapsed }; function resolveAllLabelEnd(events) { let index2 = -1; while (++index2 < events.length) { const token = events[index2][1]; if (token.type === "labelImage" || token.type === "labelLink" || token.type === "labelEnd") { events.splice(index2 + 1, token.type === "labelImage" ? 4 : 2); token.type = "data"; index2++; } } return events; } function resolveToLabelEnd(events, context) { let index2 = events.length; let offset = 0; let token; let open; let close; let media; while (index2--) { token = events[index2][1]; if (open) { if (token.type === "link" || token.type === "labelLink" && token._inactive) { break; } if (events[index2][0] === "enter" && token.type === "labelLink") { token._inactive = true; } } else if (close) { if (events[index2][0] === "enter" && (token.type === "labelImage" || token.type === "labelLink") && !token._balanced) { open = index2; if (token.type !== "labelLink") { offset = 2; break; } } } else if (token.type === "labelEnd") { close = index2; } } const group = { type: events[open][1].type === "labelLink" ? "link" : "image", start: Object.assign({}, events[open][1].start), end: Object.assign({}, events[events.length - 1][1].end) }; const label = { type: "label", start: Object.assign({}, events[open][1].start), end: Object.assign({}, events[close][1].end) }; const text3 = { type: "labelText", start: Object.assign({}, events[open + offset + 2][1].end), end: Object.assign({}, events[close - 2][1].start) }; media = [ ["enter", group, context], ["enter", label, context] ]; media = push(media, events.slice(open + 1, open + offset + 3)); media = push(media, [["enter", text3, context]]); media = push( media, resolveAll( context.parser.constructs.insideSpan.null, events.slice(open + offset + 4, close - 3), context ) ); media = push(media, [ ["exit", text3, context], events[close - 2], events[close - 1], ["exit", label, context] ]); media = push(media, events.slice(close + 1)); media = push(media, [["exit", group, context]]); splice(events, open, events.length, media); return events; } function tokenizeLabelEnd(effects, ok, nok) { const self2 = this; let index2 = self2.events.length; let labelStart; let defined; while (index2--) { if ((self2.events[index2][1].type === "labelImage" || self2.events[index2][1].type === "labelLink") && !self2.events[index2][1]._balanced) { labelStart = self2.events[index2][1]; break; } } return start; function start(code) { if (!labelStart) { return nok(code); } if (labelStart._inactive) { return labelEndNok(code); } defined = self2.parser.defined.includes( normalizeIdentifier( self2.sliceSerialize({ start: labelStart.end, end: self2.now() }) ) ); effects.enter("labelEnd"); effects.enter("labelMarker"); effects.consume(code); effects.exit("labelMarker"); effects.exit("labelEnd"); return after; } function after(code) { if (code === 40) { return effects.attempt( resourceConstruct, labelEndOk, defined ? labelEndOk : labelEndNok )(code); } if (code === 91) { return effects.attempt( referenceFullConstruct, labelEndOk, defined ? referenceNotFull : labelEndNok )(code); } return defined ? labelEndOk(code) : labelEndNok(code); } function referenceNotFull(code) { return effects.attempt( referenceCollapsedConstruct, labelEndOk, labelEndNok )(code); } function labelEndOk(code) { return ok(code); } function labelEndNok(code) { labelStart._balanced = true; return nok(code); } } function tokenizeResource(effects, ok, nok) { return resourceStart; function resourceStart(code) { effects.enter("resource"); effects.enter("resourceMarker"); effects.consume(code); effects.exit("resourceMarker"); return resourceBefore; } function resourceBefore(code) { return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, resourceOpen)(code) : resourceOpen(code); } function resourceOpen(code) { if (code === 41) { return resourceEnd(code); } return factoryDestination( effects, resourceDestinationAfter, resourceDestinationMissing, "resourceDestination", "resourceDestinationLiteral", "resourceDestinationLiteralMarker", "resourceDestinationRaw", "resourceDestinationString", 32 )(code); } function resourceDestinationAfter(code) { return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, resourceBetween)(code) : resourceEnd(code); } function resourceDestinationMissing(code) { return nok(code); } function resourceBetween(code) { if (code === 34 || code === 39 || code === 40) { return factoryTitle( effects, resourceTitleAfter, nok, "resourceTitle", "resourceTitleMarker", "resourceTitleString" )(code); } return resourceEnd(code); } function resourceTitleAfter(code) { return markdownLineEndingOrSpace(code) ? factoryWhitespace(effects, resourceEnd)(code) : resourceEnd(code); } function resourceEnd(code) { if (code === 41) { effects.enter("resourceMarker"); effects.consume(code); effects.exit("resourceMarker"); effects.exit("resource"); return ok; } return nok(code); } } function tokenizeReferenceFull(effects, ok, nok) { const self2 = this; return referenceFull; function referenceFull(code) { return factoryLabel.call( self2, effects, referenceFullAfter, referenceFullMissing, "reference", "referenceMarker", "referenceString" )(code); } function referenceFullAfter(code) { return self2.parser.defined.includes( normalizeIdentifier( self2.sliceSerialize(self2.events[self2.events.length - 1][1]).slice(1, -1) ) ) ? ok(code) : nok(code); } function referenceFullMissing(code) { return nok(code); } } function tokenizeReferenceCollapsed(effects, ok, nok) { return referenceCollapsedStart; function referenceCollapsedStart(code) { effects.enter("reference"); effects.enter("referenceMarker"); effects.consume(code); effects.exit("referenceMarker"); return referenceCollapsedOpen; } function referenceCollapsedOpen(code) { if (code === 93) { effects.enter("referenceMarker"); effects.consume(code); effects.exit("referenceMarker"); effects.exit("reference"); return ok; } return nok(code); } } // node_modules/micromark-core-commonmark/lib/label-start-image.js var labelStartImage = { name: "labelStartImage", tokenize: tokenizeLabelStartImage, resolveAll: labelEnd.resolveAll }; function tokenizeLabelStartImage(effects, ok, nok) { const self2 = this; return start; function start(code) { effects.enter("labelImage"); effects.enter("labelImageMarker"); effects.consume(code); effects.exit("labelImageMarker"); return open; } function open(code) { if (code === 91) { effects.enter("labelMarker"); effects.consume(code); effects.exit("labelMarker"); effects.exit("labelImage"); return after; } return nok(code); } function after(code) { return code === 94 && "_hiddenFootnoteSupport" in self2.parser.constructs ? nok(code) : ok(code); } } // node_modules/micromark-core-commonmark/lib/label-start-link.js var labelStartLink = { name: "labelStartLink", tokenize: tokenizeLabelStartLink, resolveAll: labelEnd.resolveAll }; function tokenizeLabelStartLink(effects, ok, nok) { const self2 = this; return start; function start(code) { effects.enter("labelLink"); effects.enter("labelMarker"); effects.consume(code); effects.exit("labelMarker"); effects.exit("labelLink"); return after; } function after(code) { return code === 94 && "_hiddenFootnoteSupport" in self2.parser.constructs ? nok(code) : ok(code); } } // node_modules/micromark-core-commonmark/lib/line-ending.js var lineEnding = { name: "lineEnding", tokenize: tokenizeLineEnding }; function tokenizeLineEnding(effects, ok) { return start; function start(code) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return factorySpace(effects, ok, "linePrefix"); } } // node_modules/micromark-core-commonmark/lib/thematic-break.js var thematicBreak = { name: "thematicBreak", tokenize: tokenizeThematicBreak }; function tokenizeThematicBreak(effects, ok, nok) { let size = 0; let marker; return start; function start(code) { effects.enter("thematicBreak"); return before(code); } function before(code) { marker = code; return atBreak(code); } function atBreak(code) { if (code === marker) { effects.enter("thematicBreakSequence"); return sequence(code); } if (size >= 3 && (code === null || markdownLineEnding(code))) { effects.exit("thematicBreak"); return ok(code); } return nok(code); } function sequence(code) { if (code === marker) { effects.consume(code); size++; return sequence; } effects.exit("thematicBreakSequence"); return markdownSpace(code) ? factorySpace(effects, atBreak, "whitespace")(code) : atBreak(code); } } // node_modules/micromark-core-commonmark/lib/list.js var list = { name: "list", tokenize: tokenizeListStart, continuation: { tokenize: tokenizeListContinuation }, exit: tokenizeListEnd }; var listItemPrefixWhitespaceConstruct = { tokenize: tokenizeListItemPrefixWhitespace, partial: true }; var indentConstruct = { tokenize: tokenizeIndent, partial: true }; function tokenizeListStart(effects, ok, nok) { const self2 = this; const tail = self2.events[self2.events.length - 1]; let initialSize = tail && tail[1].type === "linePrefix" ? tail[2].sliceSerialize(tail[1], true).length : 0; let size = 0; return start; function start(code) { const kind = self2.containerState.type || (code === 42 || code === 43 || code === 45 ? "listUnordered" : "listOrdered"); if (kind === "listUnordered" ? !self2.containerState.marker || code === self2.containerState.marker : asciiDigit(code)) { if (!self2.containerState.type) { self2.containerState.type = kind; effects.enter(kind, { _container: true }); } if (kind === "listUnordered") { effects.enter("listItemPrefix"); return code === 42 || code === 45 ? effects.check(thematicBreak, nok, atMarker)(code) : atMarker(code); } if (!self2.interrupt || code === 49) { effects.enter("listItemPrefix"); effects.enter("listItemValue"); return inside(code); } } return nok(code); } function inside(code) { if (asciiDigit(code) && ++size < 10) { effects.consume(code); return inside; } if ((!self2.interrupt || size < 2) && (self2.containerState.marker ? code === self2.containerState.marker : code === 41 || code === 46)) { effects.exit("listItemValue"); return atMarker(code); } return nok(code); } function atMarker(code) { effects.enter("listItemMarker"); effects.consume(code); effects.exit("listItemMarker"); self2.containerState.marker = self2.containerState.marker || code; return effects.check( blankLine, // Can’t be empty when interrupting. self2.interrupt ? nok : onBlank, effects.attempt( listItemPrefixWhitespaceConstruct, endOfPrefix, otherPrefix ) ); } function onBlank(code) { self2.containerState.initialBlankLine = true; initialSize++; return endOfPrefix(code); } function otherPrefix(code) { if (markdownSpace(code)) { effects.enter("listItemPrefixWhitespace"); effects.consume(code); effects.exit("listItemPrefixWhitespace"); return endOfPrefix; } return nok(code); } function endOfPrefix(code) { self2.containerState.size = initialSize + self2.sliceSerialize(effects.exit("listItemPrefix"), true).length; return ok(code); } } function tokenizeListContinuation(effects, ok, nok) { const self2 = this; self2.containerState._closeFlow = void 0; return effects.check(blankLine, onBlank, notBlank); function onBlank(code) { self2.containerState.furtherBlankLines = self2.containerState.furtherBlankLines || self2.containerState.initialBlankLine; return factorySpace( effects, ok, "listItemIndent", self2.containerState.size + 1 )(code); } function notBlank(code) { if (self2.containerState.furtherBlankLines || !markdownSpace(code)) { self2.containerState.furtherBlankLines = void 0; self2.containerState.initialBlankLine = void 0; return notInCurrentItem(code); } self2.containerState.furtherBlankLines = void 0; self2.containerState.initialBlankLine = void 0; return effects.attempt(indentConstruct, ok, notInCurrentItem)(code); } function notInCurrentItem(code) { self2.containerState._closeFlow = true; self2.interrupt = void 0; return factorySpace( effects, effects.attempt(list, ok, nok), "linePrefix", self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4 )(code); } } function tokenizeIndent(effects, ok, nok) { const self2 = this; return factorySpace( effects, afterPrefix, "listItemIndent", self2.containerState.size + 1 ); function afterPrefix(code) { const tail = self2.events[self2.events.length - 1]; return tail && tail[1].type === "listItemIndent" && tail[2].sliceSerialize(tail[1], true).length === self2.containerState.size ? ok(code) : nok(code); } } function tokenizeListEnd(effects) { effects.exit(this.containerState.type); } function tokenizeListItemPrefixWhitespace(effects, ok, nok) { const self2 = this; return factorySpace( effects, afterPrefix, "listItemPrefixWhitespace", self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4 + 1 ); function afterPrefix(code) { const tail = self2.events[self2.events.length - 1]; return !markdownSpace(code) && tail && tail[1].type === "listItemPrefixWhitespace" ? ok(code) : nok(code); } } // node_modules/micromark-core-commonmark/lib/setext-underline.js var setextUnderline = { name: "setextUnderline", tokenize: tokenizeSetextUnderline, resolveTo: resolveToSetextUnderline }; function resolveToSetextUnderline(events, context) { let index2 = events.length; let content3; let text3; let definition2; while (index2--) { if (events[index2][0] === "enter") { if (events[index2][1].type === "content") { content3 = index2; break; } if (events[index2][1].type === "paragraph") { text3 = index2; } } else { if (events[index2][1].type === "content") { events.splice(index2, 1); } if (!definition2 && events[index2][1].type === "definition") { definition2 = index2; } } } const heading = { type: "setextHeading", start: Object.assign({}, events[text3][1].start), end: Object.assign({}, events[events.length - 1][1].end) }; events[text3][1].type = "setextHeadingText"; if (definition2) { events.splice(text3, 0, ["enter", heading, context]); events.splice(definition2 + 1, 0, ["exit", events[content3][1], context]); events[content3][1].end = Object.assign({}, events[definition2][1].end); } else { events[content3][1] = heading; } events.push(["exit", heading, context]); return events; } function tokenizeSetextUnderline(effects, ok, nok) { const self2 = this; let marker; return start; function start(code) { let index2 = self2.events.length; let paragraph; while (index2--) { if (self2.events[index2][1].type !== "lineEnding" && self2.events[index2][1].type !== "linePrefix" && self2.events[index2][1].type !== "content") { paragraph = self2.events[index2][1].type === "paragraph"; break; } } if (!self2.parser.lazy[self2.now().line] && (self2.interrupt || paragraph)) { effects.enter("setextHeadingLine"); marker = code; return before(code); } return nok(code); } function before(code) { effects.enter("setextHeadingLineSequence"); return inside(code); } function inside(code) { if (code === marker) { effects.consume(code); return inside; } effects.exit("setextHeadingLineSequence"); return markdownSpace(code) ? factorySpace(effects, after, "lineSuffix")(code) : after(code); } function after(code) { if (code === null || markdownLineEnding(code)) { effects.exit("setextHeadingLine"); return ok(code); } return nok(code); } } // node_modules/micromark-extension-gfm-footnote/lib/syntax.js var indent = { tokenize: tokenizeIndent2, partial: true }; function gfmFootnote() { return { document: { [91]: { tokenize: tokenizeDefinitionStart, continuation: { tokenize: tokenizeDefinitionContinuation }, exit: gfmFootnoteDefinitionEnd } }, text: { [91]: { tokenize: tokenizeGfmFootnoteCall }, [93]: { add: "after", tokenize: tokenizePotentialGfmFootnoteCall, resolveTo: resolveToPotentialGfmFootnoteCall } } }; } function tokenizePotentialGfmFootnoteCall(effects, ok, nok) { const self2 = this; let index2 = self2.events.length; const defined = self2.parser.gfmFootnotes || (self2.parser.gfmFootnotes = []); let labelStart; while (index2--) { const token = self2.events[index2][1]; if (token.type === "labelImage") { labelStart = token; break; } if (token.type === "gfmFootnoteCall" || token.type === "labelLink" || token.type === "label" || token.type === "image" || token.type === "link") { break; } } return start; function start(code) { if (!labelStart || !labelStart._balanced) { return nok(code); } const id = normalizeIdentifier( self2.sliceSerialize({ start: labelStart.end, end: self2.now() }) ); if (id.codePointAt(0) !== 94 || !defined.includes(id.slice(1))) { return nok(code); } effects.enter("gfmFootnoteCallLabelMarker"); effects.consume(code); effects.exit("gfmFootnoteCallLabelMarker"); return ok(code); } } function resolveToPotentialGfmFootnoteCall(events, context) { let index2 = events.length; let labelStart; while (index2--) { if (events[index2][1].type === "labelImage" && events[index2][0] === "enter") { labelStart = events[index2][1]; break; } } events[index2 + 1][1].type = "data"; events[index2 + 3][1].type = "gfmFootnoteCallLabelMarker"; const call = { type: "gfmFootnoteCall", start: Object.assign({}, events[index2 + 3][1].start), end: Object.assign({}, events[events.length - 1][1].end) }; const marker = { type: "gfmFootnoteCallMarker", start: Object.assign({}, events[index2 + 3][1].end), end: Object.assign({}, events[index2 + 3][1].end) }; marker.end.column++; marker.end.offset++; marker.end._bufferIndex++; const string3 = { type: "gfmFootnoteCallString", start: Object.assign({}, marker.end), end: Object.assign({}, events[events.length - 1][1].start) }; const chunk = { type: "chunkString", contentType: "string", start: Object.assign({}, string3.start), end: Object.assign({}, string3.end) }; const replacement = [ // Take the `labelImageMarker` (now `data`, the `!`) events[index2 + 1], events[index2 + 2], ["enter", call, context], // The `[` events[index2 + 3], events[index2 + 4], // The `^`. ["enter", marker, context], ["exit", marker, context], // Everything in between. ["enter", string3, context], ["enter", chunk, context], ["exit", chunk, context], ["exit", string3, context], // The ending (`]`, properly parsed and labelled). events[events.length - 2], events[events.length - 1], ["exit", call, context] ]; events.splice(index2, events.length - index2 + 1, ...replacement); return events; } function tokenizeGfmFootnoteCall(effects, ok, nok) { const self2 = this; const defined = self2.parser.gfmFootnotes || (self2.parser.gfmFootnotes = []); let size = 0; let data; return start; function start(code) { effects.enter("gfmFootnoteCall"); effects.enter("gfmFootnoteCallLabelMarker"); effects.consume(code); effects.exit("gfmFootnoteCallLabelMarker"); return callStart; } function callStart(code) { if (code !== 94) return nok(code); effects.enter("gfmFootnoteCallMarker"); effects.consume(code); effects.exit("gfmFootnoteCallMarker"); effects.enter("gfmFootnoteCallString"); effects.enter("chunkString").contentType = "string"; return callData; } function callData(code) { if ( // Too long. size > 999 || // Closing brace with nothing. code === 93 && !data || // Space or tab is not supported by GFM for some reason. // `\n` and `[` not being supported makes sense. code === null || code === 91 || markdownLineEndingOrSpace(code) ) { return nok(code); } if (code === 93) { effects.exit("chunkString"); const token = effects.exit("gfmFootnoteCallString"); if (!defined.includes(normalizeIdentifier(self2.sliceSerialize(token)))) { return nok(code); } effects.enter("gfmFootnoteCallLabelMarker"); effects.consume(code); effects.exit("gfmFootnoteCallLabelMarker"); effects.exit("gfmFootnoteCall"); return ok; } if (!markdownLineEndingOrSpace(code)) { data = true; } size++; effects.consume(code); return code === 92 ? callEscape : callData; } function callEscape(code) { if (code === 91 || code === 92 || code === 93) { effects.consume(code); size++; return callData; } return callData(code); } } function tokenizeDefinitionStart(effects, ok, nok) { const self2 = this; const defined = self2.parser.gfmFootnotes || (self2.parser.gfmFootnotes = []); let identifier; let size = 0; let data; return start; function start(code) { effects.enter("gfmFootnoteDefinition")._container = true; effects.enter("gfmFootnoteDefinitionLabel"); effects.enter("gfmFootnoteDefinitionLabelMarker"); effects.consume(code); effects.exit("gfmFootnoteDefinitionLabelMarker"); return labelAtMarker; } function labelAtMarker(code) { if (code === 94) { effects.enter("gfmFootnoteDefinitionMarker"); effects.consume(code); effects.exit("gfmFootnoteDefinitionMarker"); effects.enter("gfmFootnoteDefinitionLabelString"); effects.enter("chunkString").contentType = "string"; return labelInside; } return nok(code); } function labelInside(code) { if ( // Too long. size > 999 || // Closing brace with nothing. code === 93 && !data || // Space or tab is not supported by GFM for some reason. // `\n` and `[` not being supported makes sense. code === null || code === 91 || markdownLineEndingOrSpace(code) ) { return nok(code); } if (code === 93) { effects.exit("chunkString"); const token = effects.exit("gfmFootnoteDefinitionLabelString"); identifier = normalizeIdentifier(self2.sliceSerialize(token)); effects.enter("gfmFootnoteDefinitionLabelMarker"); effects.consume(code); effects.exit("gfmFootnoteDefinitionLabelMarker"); effects.exit("gfmFootnoteDefinitionLabel"); return labelAfter; } if (!markdownLineEndingOrSpace(code)) { data = true; } size++; effects.consume(code); return code === 92 ? labelEscape : labelInside; } function labelEscape(code) { if (code === 91 || code === 92 || code === 93) { effects.consume(code); size++; return labelInside; } return labelInside(code); } function labelAfter(code) { if (code === 58) { effects.enter("definitionMarker"); effects.consume(code); effects.exit("definitionMarker"); if (!defined.includes(identifier)) { defined.push(identifier); } return factorySpace( effects, whitespaceAfter, "gfmFootnoteDefinitionWhitespace" ); } return nok(code); } function whitespaceAfter(code) { return ok(code); } } function tokenizeDefinitionContinuation(effects, ok, nok) { return effects.check(blankLine, ok, effects.attempt(indent, ok, nok)); } function gfmFootnoteDefinitionEnd(effects) { effects.exit("gfmFootnoteDefinition"); } function tokenizeIndent2(effects, ok, nok) { const self2 = this; return factorySpace( effects, afterPrefix, "gfmFootnoteDefinitionIndent", 4 + 1 ); function afterPrefix(code) { const tail = self2.events[self2.events.length - 1]; return tail && tail[1].type === "gfmFootnoteDefinitionIndent" && tail[2].sliceSerialize(tail[1], true).length === 4 ? ok(code) : nok(code); } } // node_modules/micromark-extension-gfm-task-list-item/lib/syntax.js var tasklistCheck = { tokenize: tokenizeTasklistCheck }; var gfmTaskListItem = { text: { [91]: tasklistCheck } }; function tokenizeTasklistCheck(effects, ok, nok) { const self2 = this; return open; function open(code) { if ( // Exit if there’s stuff before. self2.previous !== null || // Exit if not in the first content that is the first child of a list // item. !self2._gfmTasklistFirstContentOfListItem ) { return nok(code); } effects.enter("taskListCheck"); effects.enter("taskListCheckMarker"); effects.consume(code); effects.exit("taskListCheckMarker"); return inside; } function inside(code) { if (markdownLineEndingOrSpace(code)) { effects.enter("taskListCheckValueUnchecked"); effects.consume(code); effects.exit("taskListCheckValueUnchecked"); return close; } if (code === 88 || code === 120) { effects.enter("taskListCheckValueChecked"); effects.consume(code); effects.exit("taskListCheckValueChecked"); return close; } return nok(code); } function close(code) { if (code === 93) { effects.enter("taskListCheckMarker"); effects.consume(code); effects.exit("taskListCheckMarker"); effects.exit("taskListCheck"); return after; } return nok(code); } function after(code) { if (markdownLineEnding(code)) { return ok(code); } if (markdownSpace(code)) { return effects.check( { tokenize: spaceThenNonSpace }, ok, nok )(code); } return nok(code); } } function spaceThenNonSpace(effects, ok, nok) { return factorySpace(effects, after, "whitespace"); function after(code) { return code === null ? nok(code) : ok(code); } } // node_modules/micromark-util-combine-extensions/index.js var hasOwnProperty = {}.hasOwnProperty; function combineExtensions(extensions) { const all2 = {}; let index2 = -1; while (++index2 < extensions.length) { syntaxExtension(all2, extensions[index2]); } return all2; } function syntaxExtension(all2, extension2) { let hook; for (hook in extension2) { const maybe = hasOwnProperty.call(all2, hook) ? all2[hook] : void 0; const left = maybe || (all2[hook] = {}); const right = extension2[hook]; let code; if (right) { for (code in right) { if (!hasOwnProperty.call(left, code)) left[code] = []; const value = right[code]; constructs( // @ts-expect-error Looks like a list. left[code], Array.isArray(value) ? value : value ? [value] : [] ); } } } } function constructs(existing, list2) { let index2 = -1; const before = []; while (++index2 < list2.length) { ; (list2[index2].add === "after" ? existing : before).push(list2[index2]); } splice(existing, 0, 0, before); } // node_modules/micromark-extension-math/lib/math-flow.js var mathFlow = { tokenize: tokenizeMathFenced, concrete: true }; var nonLazyContinuation2 = { tokenize: tokenizeNonLazyContinuation2, partial: true }; function tokenizeMathFenced(effects, ok, nok) { const self2 = this; const tail = self2.events[self2.events.length - 1]; const initialSize = tail && tail[1].type === "linePrefix" ? tail[2].sliceSerialize(tail[1], true).length : 0; let sizeOpen = 0; return start; function start(code) { effects.enter("mathFlow"); effects.enter("mathFlowFence"); effects.enter("mathFlowFenceSequence"); return sequenceOpen(code); } function sequenceOpen(code) { if (code === 36) { effects.consume(code); sizeOpen++; return sequenceOpen; } if (sizeOpen < 2) { return nok(code); } effects.exit("mathFlowFenceSequence"); return factorySpace(effects, metaBefore, "whitespace")(code); } function metaBefore(code) { if (code === null || markdownLineEnding(code)) { return metaAfter(code); } effects.enter("mathFlowFenceMeta"); effects.enter("chunkString", { contentType: "string" }); return meta(code); } function meta(code) { if (code === null || markdownLineEnding(code)) { effects.exit("chunkString"); effects.exit("mathFlowFenceMeta"); return metaAfter(code); } if (code === 36) { return nok(code); } effects.consume(code); return meta; } function metaAfter(code) { effects.exit("mathFlowFence"); if (self2.interrupt) { return ok(code); } return effects.attempt( nonLazyContinuation2, beforeNonLazyContinuation, after )(code); } function beforeNonLazyContinuation(code) { return effects.attempt( { tokenize: tokenizeClosingFence, partial: true }, after, contentStart )(code); } function contentStart(code) { return (initialSize ? factorySpace( effects, beforeContentChunk, "linePrefix", initialSize + 1 ) : beforeContentChunk)(code); } function beforeContentChunk(code) { if (code === null) { return after(code); } if (markdownLineEnding(code)) { return effects.attempt( nonLazyContinuation2, beforeNonLazyContinuation, after )(code); } effects.enter("mathFlowValue"); return contentChunk(code); } function contentChunk(code) { if (code === null || markdownLineEnding(code)) { effects.exit("mathFlowValue"); return beforeContentChunk(code); } effects.consume(code); return contentChunk; } function after(code) { effects.exit("mathFlow"); return ok(code); } function tokenizeClosingFence(effects2, ok2, nok2) { let size = 0; return factorySpace( effects2, beforeSequenceClose, "linePrefix", self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4 ); function beforeSequenceClose(code) { effects2.enter("mathFlowFence"); effects2.enter("mathFlowFenceSequence"); return sequenceClose(code); } function sequenceClose(code) { if (code === 36) { size++; effects2.consume(code); return sequenceClose; } if (size < sizeOpen) { return nok2(code); } effects2.exit("mathFlowFenceSequence"); return factorySpace(effects2, afterSequenceClose, "whitespace")(code); } function afterSequenceClose(code) { if (code === null || markdownLineEnding(code)) { effects2.exit("mathFlowFence"); return ok2(code); } return nok2(code); } } } function tokenizeNonLazyContinuation2(effects, ok, nok) { const self2 = this; return start; function start(code) { if (code === null) { return ok(code); } effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return lineStart; } function lineStart(code) { return self2.parser.lazy[self2.now().line] ? nok(code) : ok(code); } } // node_modules/micromark-extension-math/lib/math-text.js function mathText(options) { const options_ = options || {}; let single = options_.singleDollarTextMath; if (single === null || single === void 0) { single = true; } return { tokenize: tokenizeMathText, resolve: resolveMathText, previous: previous2 }; function tokenizeMathText(effects, ok, nok) { const self2 = this; let sizeOpen = 0; let size; let token; return start; function start(code) { effects.enter("mathText"); effects.enter("mathTextSequence"); return sequenceOpen(code); } function sequenceOpen(code) { if (code === 36) { effects.consume(code); sizeOpen++; return sequenceOpen; } if (sizeOpen < 2 && !single) { return nok(code); } effects.exit("mathTextSequence"); return between(code); } function between(code) { if (code === null) { return nok(code); } if (code === 36) { token = effects.enter("mathTextSequence"); size = 0; return sequenceClose(code); } if (code === 32) { effects.enter("space"); effects.consume(code); effects.exit("space"); return between; } if (markdownLineEnding(code)) { effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return between; } effects.enter("mathTextData"); return data(code); } function data(code) { if (code === null || code === 32 || code === 36 || markdownLineEnding(code)) { effects.exit("mathTextData"); return between(code); } effects.consume(code); return data; } function sequenceClose(code) { if (code === 36) { effects.consume(code); size++; return sequenceClose; } if (size === sizeOpen) { effects.exit("mathTextSequence"); effects.exit("mathText"); return ok(code); } token.type = "mathTextData"; return data(code); } } } function resolveMathText(events) { let tailExitIndex = events.length - 4; let headEnterIndex = 3; let index2; let enter; if ((events[headEnterIndex][1].type === "lineEnding" || events[headEnterIndex][1].type === "space") && (events[tailExitIndex][1].type === "lineEnding" || events[tailExitIndex][1].type === "space")) { index2 = headEnterIndex; while (++index2 < tailExitIndex) { if (events[index2][1].type === "mathTextData") { events[tailExitIndex][1].type = "mathTextPadding"; events[headEnterIndex][1].type = "mathTextPadding"; headEnterIndex += 2; tailExitIndex -= 2; break; } } } index2 = headEnterIndex - 1; tailExitIndex++; while (++index2 <= tailExitIndex) { if (enter === void 0) { if (index2 !== tailExitIndex && events[index2][1].type !== "lineEnding") { enter = index2; } } else if (index2 === tailExitIndex || events[index2][1].type === "lineEnding") { events[enter][1].type = "mathTextData"; if (index2 !== enter + 2) { events[enter][1].end = events[index2 - 1][1].end; events.splice(enter + 2, index2 - enter - 2); tailExitIndex -= index2 - enter - 2; index2 = enter + 2; } enter = void 0; } } return events; } function previous2(code) { return code !== 36 || this.events[this.events.length - 1][1].type === "characterEscape"; } // node_modules/micromark-extension-math/lib/syntax.js function math(options) { return { flow: { [36]: mathFlow }, text: { [36]: mathText(options) } }; } // node_modules/mdast-util-to-markdown/lib/util/pattern-compile.js function patternCompile(pattern) { if (!pattern._compiled) { const before = (pattern.atBreak ? "[\\r\\n][\\t ]*" : "") + (pattern.before ? "(?:" + pattern.before + ")" : ""); pattern._compiled = new RegExp( (before ? "(" + before + ")" : "") + (/[|\\{}()[\]^$+*?.-]/.test(pattern.character) ? "\\" : "") + pattern.character + (pattern.after ? "(?:" + pattern.after + ")" : ""), "g" ); } return pattern._compiled; } // node_modules/mdast-util-to-markdown/lib/util/pattern-in-scope.js function patternInScope(stack, pattern) { return listInScope(stack, pattern.inConstruct, true) && !listInScope(stack, pattern.notInConstruct, false); } function listInScope(stack, list2, none) { if (typeof list2 === "string") { list2 = [list2]; } if (!list2 || list2.length === 0) { return none; } let index2 = -1; while (++index2 < list2.length) { if (stack.includes(list2[index2])) { return true; } } return false; } // node_modules/mdast-util-to-markdown/lib/util/safe.js function safe(state, input, config) { const value = (config.before || "") + (input || "") + (config.after || ""); const positions = []; const result = []; const infos = {}; let index2 = -1; while (++index2 < state.unsafe.length) { const pattern = state.unsafe[index2]; if (!patternInScope(state.stack, pattern)) { continue; } const expression = patternCompile(pattern); let match2; while (match2 = expression.exec(value)) { const before = "before" in pattern || Boolean(pattern.atBreak); const after = "after" in pattern; const position2 = match2.index + (before ? match2[1].length : 0); if (positions.includes(position2)) { if (infos[position2].before && !before) { infos[position2].before = false; } if (infos[position2].after && !after) { infos[position2].after = false; } } else { positions.push(position2); infos[position2] = { before, after }; } } } positions.sort(numerical); let start = config.before ? config.before.length : 0; const end = value.length - (config.after ? config.after.length : 0); index2 = -1; while (++index2 < positions.length) { const position2 = positions[index2]; if (position2 < start || position2 >= end) { continue; } if (position2 + 1 < end && positions[index2 + 1] === position2 + 1 && infos[position2].after && !infos[position2 + 1].before && !infos[position2 + 1].after || positions[index2 - 1] === position2 - 1 && infos[position2].before && !infos[position2 - 1].before && !infos[position2 - 1].after) { continue; } if (start !== position2) { result.push(escapeBackslashes(value.slice(start, position2), "\\")); } start = position2; if (/[!-/:-@[-`{-~]/.test(value.charAt(position2)) && (!config.encode || !config.encode.includes(value.charAt(position2)))) { result.push("\\"); } else { result.push( "&#x" + value.charCodeAt(position2).toString(16).toUpperCase() + ";" ); start++; } } result.push(escapeBackslashes(value.slice(start, end), config.after)); return result.join(""); } function numerical(a3, b2) { return a3 - b2; } function escapeBackslashes(value, after) { const expression = /\\(?=[!-/:-@[-`{-~])/g; const positions = []; const results = []; const whole = value + after; let index2 = -1; let start = 0; let match2; while (match2 = expression.exec(whole)) { positions.push(match2.index); } while (++index2 < positions.length) { if (start !== positions[index2]) { results.push(value.slice(start, positions[index2])); } results.push("\\"); start = positions[index2]; } results.push(value.slice(start)); return results.join(""); } // node_modules/mdast-util-to-markdown/lib/util/track.js function track(config) { const options = config || {}; const now = options.now || {}; let lineShift = options.lineShift || 0; let line = now.line || 1; let column = now.column || 1; return { move, current, shift }; function current() { return { now: { line, column }, lineShift }; } function shift(value) { lineShift += value; } function move(input) { const value = input || ""; const chunks = value.split(/\r?\n|\r/g); const tail = chunks[chunks.length - 1]; line += chunks.length - 1; column = chunks.length === 1 ? column + tail.length : 1 + tail.length + lineShift; return value; } } // node_modules/mdast-util-math/lib/index.js function mathFromMarkdown() { return { enter: { mathFlow: enterMathFlow, mathFlowFenceMeta: enterMathFlowMeta, mathText: enterMathText }, exit: { mathFlow: exitMathFlow, mathFlowFence: exitMathFlowFence, mathFlowFenceMeta: exitMathFlowMeta, mathFlowValue: exitMathData, mathText: exitMathText, mathTextData: exitMathData } }; function enterMathFlow(token) { this.enter( { type: "math", meta: null, value: "", data: { hName: "div", hProperties: { className: ["math", "math-display"] }, hChildren: [{ type: "text", value: "" }] } }, token ); } function enterMathFlowMeta() { this.buffer(); } function exitMathFlowMeta() { const data = this.resume(); const node2 = ( /** @type {Math} */ this.stack[this.stack.length - 1] ); node2.meta = data; } function exitMathFlowFence() { if (this.getData("mathFlowInside")) return; this.buffer(); this.setData("mathFlowInside", true); } function exitMathFlow(token) { const data = this.resume().replace(/^(\r?\n|\r)|(\r?\n|\r)$/g, ""); const node2 = ( /** @type {Math} */ this.exit(token) ); node2.value = data; node2.data.hChildren[0].value = data; this.setData("mathFlowInside"); } function enterMathText(token) { this.enter( { type: "inlineMath", value: "", data: { hName: "span", hProperties: { className: ["math", "math-inline"] }, hChildren: [{ type: "text", value: "" }] } }, token ); this.buffer(); } function exitMathText(token) { const data = this.resume(); const node2 = ( /** @type {Math} */ this.exit(token) ); node2.value = data; node2.data.hChildren[0].value = data; } function exitMathData(token) { this.config.enter.data.call(this, token); this.config.exit.data.call(this, token); } } // node_modules/mdast-util-to-string/lib/index.js var emptyOptions = {}; function toString2(value, options) { const settings = options || emptyOptions; const includeImageAlt = typeof settings.includeImageAlt === "boolean" ? settings.includeImageAlt : true; const includeHtml = typeof settings.includeHtml === "boolean" ? settings.includeHtml : true; return one(value, includeImageAlt, includeHtml); } function one(value, includeImageAlt, includeHtml) { if (node(value)) { if ("value" in value) { return value.type === "html" && !includeHtml ? "" : value.value; } if (includeImageAlt && "alt" in value && value.alt) { return value.alt; } if ("children" in value) { return all(value.children, includeImageAlt, includeHtml); } } if (Array.isArray(value)) { return all(value, includeImageAlt, includeHtml); } return ""; } function all(values, includeImageAlt, includeHtml) { const result = []; let index2 = -1; while (++index2 < values.length) { result[index2] = one(values[index2], includeImageAlt, includeHtml); } return result.join(""); } function node(value) { return Boolean(value && typeof value === "object"); } // node_modules/micromark/lib/initialize/content.js var content2 = { tokenize: initializeContent }; function initializeContent(effects) { const contentStart = effects.attempt( this.parser.constructs.contentInitial, afterContentStartConstruct, paragraphInitial ); let previous3; return contentStart; function afterContentStartConstruct(code) { if (code === null) { effects.consume(code); return; } effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); return factorySpace(effects, contentStart, "linePrefix"); } function paragraphInitial(code) { effects.enter("paragraph"); return lineStart(code); } function lineStart(code) { const token = effects.enter("chunkText", { contentType: "text", previous: previous3 }); if (previous3) { previous3.next = token; } previous3 = token; return data(code); } function data(code) { if (code === null) { effects.exit("chunkText"); effects.exit("paragraph"); effects.consume(code); return; } if (markdownLineEnding(code)) { effects.consume(code); effects.exit("chunkText"); return lineStart; } effects.consume(code); return data; } } // node_modules/micromark/lib/initialize/document.js var document2 = { tokenize: initializeDocument }; var containerConstruct = { tokenize: tokenizeContainer }; function initializeDocument(effects) { const self2 = this; const stack = []; let continued = 0; let childFlow; let childToken; let lineStartOffset; return start; function start(code) { if (continued < stack.length) { const item = stack[continued]; self2.containerState = item[1]; return effects.attempt( item[0].continuation, documentContinue, checkNewContainers )(code); } return checkNewContainers(code); } function documentContinue(code) { continued++; if (self2.containerState._closeFlow) { self2.containerState._closeFlow = void 0; if (childFlow) { closeFlow(); } const indexBeforeExits = self2.events.length; let indexBeforeFlow = indexBeforeExits; let point3; while (indexBeforeFlow--) { if (self2.events[indexBeforeFlow][0] === "exit" && self2.events[indexBeforeFlow][1].type === "chunkFlow") { point3 = self2.events[indexBeforeFlow][1].end; break; } } exitContainers(continued); let index2 = indexBeforeExits; while (index2 < self2.events.length) { self2.events[index2][1].end = Object.assign({}, point3); index2++; } splice( self2.events, indexBeforeFlow + 1, 0, self2.events.slice(indexBeforeExits) ); self2.events.length = index2; return checkNewContainers(code); } return start(code); } function checkNewContainers(code) { if (continued === stack.length) { if (!childFlow) { return documentContinued(code); } if (childFlow.currentConstruct && childFlow.currentConstruct.concrete) { return flowStart(code); } self2.interrupt = Boolean( childFlow.currentConstruct && !childFlow._gfmTableDynamicInterruptHack ); } self2.containerState = {}; return effects.check( containerConstruct, thereIsANewContainer, thereIsNoNewContainer )(code); } function thereIsANewContainer(code) { if (childFlow) closeFlow(); exitContainers(continued); return documentContinued(code); } function thereIsNoNewContainer(code) { self2.parser.lazy[self2.now().line] = continued !== stack.length; lineStartOffset = self2.now().offset; return flowStart(code); } function documentContinued(code) { self2.containerState = {}; return effects.attempt( containerConstruct, containerContinue, flowStart )(code); } function containerContinue(code) { continued++; stack.push([self2.currentConstruct, self2.containerState]); return documentContinued(code); } function flowStart(code) { if (code === null) { if (childFlow) closeFlow(); exitContainers(0); effects.consume(code); return; } childFlow = childFlow || self2.parser.flow(self2.now()); effects.enter("chunkFlow", { contentType: "flow", previous: childToken, _tokenizer: childFlow }); return flowContinue(code); } function flowContinue(code) { if (code === null) { writeToChild(effects.exit("chunkFlow"), true); exitContainers(0); effects.consume(code); return; } if (markdownLineEnding(code)) { effects.consume(code); writeToChild(effects.exit("chunkFlow")); continued = 0; self2.interrupt = void 0; return start; } effects.consume(code); return flowContinue; } function writeToChild(token, eof) { const stream = self2.sliceStream(token); if (eof) stream.push(null); token.previous = childToken; if (childToken) childToken.next = token; childToken = token; childFlow.defineSkip(token.start); childFlow.write(stream); if (self2.parser.lazy[token.start.line]) { let index2 = childFlow.events.length; while (index2--) { if ( // The token starts before the line ending… childFlow.events[index2][1].start.offset < lineStartOffset && // …and either is not ended yet… (!childFlow.events[index2][1].end || // …or ends after it. childFlow.events[index2][1].end.offset > lineStartOffset) ) { return; } } const indexBeforeExits = self2.events.length; let indexBeforeFlow = indexBeforeExits; let seen; let point3; while (indexBeforeFlow--) { if (self2.events[indexBeforeFlow][0] === "exit" && self2.events[indexBeforeFlow][1].type === "chunkFlow") { if (seen) { point3 = self2.events[indexBeforeFlow][1].end; break; } seen = true; } } exitContainers(continued); index2 = indexBeforeExits; while (index2 < self2.events.length) { self2.events[index2][1].end = Object.assign({}, point3); index2++; } splice( self2.events, indexBeforeFlow + 1, 0, self2.events.slice(indexBeforeExits) ); self2.events.length = index2; } } function exitContainers(size) { let index2 = stack.length; while (index2-- > size) { const entry = stack[index2]; self2.containerState = entry[1]; entry[0].exit.call(self2, effects); } stack.length = size; } function closeFlow() { childFlow.write([null]); childToken = void 0; childFlow = void 0; self2.containerState._closeFlow = void 0; } } function tokenizeContainer(effects, ok, nok) { return factorySpace( effects, effects.attempt(this.parser.constructs.document, ok, nok), "linePrefix", this.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4 ); } // node_modules/micromark/lib/initialize/flow.js var flow = { tokenize: initializeFlow }; function initializeFlow(effects) { const self2 = this; const initial = effects.attempt( // Try to parse a blank line. blankLine, atBlankEnding, // Try to parse initial flow (essentially, only code). effects.attempt( this.parser.constructs.flowInitial, afterConstruct, factorySpace( effects, effects.attempt( this.parser.constructs.flow, afterConstruct, effects.attempt(content, afterConstruct) ), "linePrefix" ) ) ); return initial; function atBlankEnding(code) { if (code === null) { effects.consume(code); return; } effects.enter("lineEndingBlank"); effects.consume(code); effects.exit("lineEndingBlank"); self2.currentConstruct = void 0; return initial; } function afterConstruct(code) { if (code === null) { effects.consume(code); return; } effects.enter("lineEnding"); effects.consume(code); effects.exit("lineEnding"); self2.currentConstruct = void 0; return initial; } } // node_modules/micromark/lib/initialize/text.js var resolver = { resolveAll: createResolver() }; var string = initializeFactory("string"); var text = initializeFactory("text"); function initializeFactory(field) { return { tokenize: initializeText, resolveAll: createResolver( field === "text" ? resolveAllLineSuffixes : void 0 ) }; function initializeText(effects) { const self2 = this; const constructs2 = this.parser.constructs[field]; const text3 = effects.attempt(constructs2, start, notText); return start; function start(code) { return atBreak(code) ? text3(code) : notText(code); } function notText(code) { if (code === null) { effects.consume(code); return; } effects.enter("data"); effects.consume(code); return data; } function data(code) { if (atBreak(code)) { effects.exit("data"); return text3(code); } effects.consume(code); return data; } function atBreak(code) { if (code === null) { return true; } const list2 = constructs2[code]; let index2 = -1; if (list2) { while (++index2 < list2.length) { const item = list2[index2]; if (!item.previous || item.previous.call(self2, self2.previous)) { return true; } } } return false; } } } function createResolver(extraResolver) { return resolveAllText; function resolveAllText(events, context) { let index2 = -1; let enter; while (++index2 <= events.length) { if (enter === void 0) { if (events[index2] && events[index2][1].type === "data") { enter = index2; index2++; } } else if (!events[index2] || events[index2][1].type !== "data") { if (index2 !== enter + 2) { events[enter][1].end = events[index2 - 1][1].end; events.splice(enter + 2, index2 - enter - 2); index2 = enter + 2; } enter = void 0; } } return extraResolver ? extraResolver(events, context) : events; } } function resolveAllLineSuffixes(events, context) { let eventIndex = 0; while (++eventIndex <= events.length) { if ((eventIndex === events.length || events[eventIndex][1].type === "lineEnding") && events[eventIndex - 1][1].type === "data") { const data = events[eventIndex - 1][1]; const chunks = context.sliceStream(data); let index2 = chunks.length; let bufferIndex = -1; let size = 0; let tabs; while (index2--) { const chunk = chunks[index2]; if (typeof chunk === "string") { bufferIndex = chunk.length; while (chunk.charCodeAt(bufferIndex - 1) === 32) { size++; bufferIndex--; } if (bufferIndex) break; bufferIndex = -1; } else if (chunk === -2) { tabs = true; size++; } else if (chunk === -1) { } else { index2++; break; } } if (size) { const token = { type: eventIndex === events.length || tabs || size < 2 ? "lineSuffix" : "hardBreakTrailing", start: { line: data.end.line, column: data.end.column - size, offset: data.end.offset - size, _index: data.start._index + index2, _bufferIndex: index2 ? bufferIndex : data.start._bufferIndex + bufferIndex }, end: Object.assign({}, data.end) }; data.end = Object.assign({}, token.start); if (data.start.offset === data.end.offset) { Object.assign(data, token); } else { events.splice( eventIndex, 0, ["enter", token, context], ["exit", token, context] ); eventIndex += 2; } } eventIndex++; } } return events; } // node_modules/micromark/lib/create-tokenizer.js function createTokenizer(parser, initialize, from) { let point3 = Object.assign( from ? Object.assign({}, from) : { line: 1, column: 1, offset: 0 }, { _index: 0, _bufferIndex: -1 } ); const columnStart = {}; const resolveAllConstructs = []; let chunks = []; let stack = []; let consumed = true; const effects = { consume, enter, exit: exit2, attempt: constructFactory(onsuccessfulconstruct), check: constructFactory(onsuccessfulcheck), interrupt: constructFactory(onsuccessfulcheck, { interrupt: true }) }; const context = { previous: null, code: null, containerState: {}, events: [], parser, sliceStream, sliceSerialize, now, defineSkip, write }; let state = initialize.tokenize.call(context, effects); let expectedCode; if (initialize.resolveAll) { resolveAllConstructs.push(initialize); } return context; function write(slice) { chunks = push(chunks, slice); main(); if (chunks[chunks.length - 1] !== null) { return []; } addResult(initialize, 0); context.events = resolveAll(resolveAllConstructs, context.events, context); return context.events; } function sliceSerialize(token, expandTabs) { return serializeChunks(sliceStream(token), expandTabs); } function sliceStream(token) { return sliceChunks(chunks, token); } function now() { const { line, column, offset, _index, _bufferIndex } = point3; return { line, column, offset, _index, _bufferIndex }; } function defineSkip(value) { columnStart[value.line] = value.column; accountForPotentialSkip(); } function main() { let chunkIndex; while (point3._index < chunks.length) { const chunk = chunks[point3._index]; if (typeof chunk === "string") { chunkIndex = point3._index; if (point3._bufferIndex < 0) { point3._bufferIndex = 0; } while (point3._index === chunkIndex && point3._bufferIndex < chunk.length) { go(chunk.charCodeAt(point3._bufferIndex)); } } else { go(chunk); } } } function go(code) { consumed = void 0; expectedCode = code; state = state(code); } function consume(code) { if (markdownLineEnding(code)) { point3.line++; point3.column = 1; point3.offset += code === -3 ? 2 : 1; accountForPotentialSkip(); } else if (code !== -1) { point3.column++; point3.offset++; } if (point3._bufferIndex < 0) { point3._index++; } else { point3._bufferIndex++; if (point3._bufferIndex === chunks[point3._index].length) { point3._bufferIndex = -1; point3._index++; } } context.previous = code; consumed = true; } function enter(type2, fields) { const token = fields || {}; token.type = type2; token.start = now(); context.events.push(["enter", token, context]); stack.push(token); return token; } function exit2(type2) { const token = stack.pop(); token.end = now(); context.events.push(["exit", token, context]); return token; } function onsuccessfulconstruct(construct, info) { addResult(construct, info.from); } function onsuccessfulcheck(_, info) { info.restore(); } function constructFactory(onreturn, fields) { return hook; function hook(constructs2, returnState, bogusState) { let listOfConstructs; let constructIndex; let currentConstruct; let info; return Array.isArray(constructs2) ? handleListOfConstructs(constructs2) : "tokenize" in constructs2 ? ( // @ts-expect-error Looks like a construct. handleListOfConstructs([constructs2]) ) : handleMapOfConstructs(constructs2); function handleMapOfConstructs(map2) { return start; function start(code) { const def = code !== null && map2[code]; const all2 = code !== null && map2.null; const list2 = [ // To do: add more extension tests. /* c8 ignore next 2 */ ...Array.isArray(def) ? def : def ? [def] : [], ...Array.isArray(all2) ? all2 : all2 ? [all2] : [] ]; return handleListOfConstructs(list2)(code); } } function handleListOfConstructs(list2) { listOfConstructs = list2; constructIndex = 0; if (list2.length === 0) { return bogusState; } return handleConstruct(list2[constructIndex]); } function handleConstruct(construct) { return start; function start(code) { info = store(); currentConstruct = construct; if (!construct.partial) { context.currentConstruct = construct; } if (construct.name && context.parser.constructs.disable.null.includes(construct.name)) { return nok(code); } return construct.tokenize.call( // If we do have fields, create an object w/ `context` as its // prototype. // This allows a “live binding”, which is needed for `interrupt`. fields ? Object.assign(Object.create(context), fields) : context, effects, ok, nok )(code); } } function ok(code) { consumed = true; onreturn(currentConstruct, info); return returnState; } function nok(code) { consumed = true; info.restore(); if (++constructIndex < listOfConstructs.length) { return handleConstruct(listOfConstructs[constructIndex]); } return bogusState; } } } function addResult(construct, from2) { if (construct.resolveAll && !resolveAllConstructs.includes(construct)) { resolveAllConstructs.push(construct); } if (construct.resolve) { splice( context.events, from2, context.events.length - from2, construct.resolve(context.events.slice(from2), context) ); } if (construct.resolveTo) { context.events = construct.resolveTo(context.events, context); } } function store() { const startPoint = now(); const startPrevious = context.previous; const startCurrentConstruct = context.currentConstruct; const startEventsIndex = context.events.length; const startStack = Array.from(stack); return { restore, from: startEventsIndex }; function restore() { point3 = startPoint; context.previous = startPrevious; context.currentConstruct = startCurrentConstruct; context.events.length = startEventsIndex; stack = startStack; accountForPotentialSkip(); } } function accountForPotentialSkip() { if (point3.line in columnStart && point3.column < 2) { point3.column = columnStart[point3.line]; point3.offset += columnStart[point3.line] - 1; } } } function sliceChunks(chunks, token) { const startIndex = token.start._index; const startBufferIndex = token.start._bufferIndex; const endIndex = token.end._index; const endBufferIndex = token.end._bufferIndex; let view; if (startIndex === endIndex) { view = [chunks[startIndex].slice(startBufferIndex, endBufferIndex)]; } else { view = chunks.slice(startIndex, endIndex); if (startBufferIndex > -1) { const head = view[0]; if (typeof head === "string") { view[0] = head.slice(startBufferIndex); } else { view.shift(); } } if (endBufferIndex > 0) { view.push(chunks[endIndex].slice(0, endBufferIndex)); } } return view; } function serializeChunks(chunks, expandTabs) { let index2 = -1; const result = []; let atTab; while (++index2 < chunks.length) { const chunk = chunks[index2]; let value; if (typeof chunk === "string") { value = chunk; } else switch (chunk) { case -5: { value = "\r"; break; } case -4: { value = "\n"; break; } case -3: { value = "\r\n"; break; } case -2: { value = expandTabs ? " " : " "; break; } case -1: { if (!expandTabs && atTab) continue; value = " "; break; } default: { value = String.fromCharCode(chunk); } } atTab = chunk === -2; result.push(value); } return result.join(""); } // node_modules/micromark/lib/constructs.js var constructs_exports = {}; __export(constructs_exports, { attentionMarkers: () => attentionMarkers, contentInitial: () => contentInitial, disable: () => disable, document: () => document3, flow: () => flow2, flowInitial: () => flowInitial, insideSpan: () => insideSpan, string: () => string2, text: () => text2 }); var document3 = { [42]: list, [43]: list, [45]: list, [48]: list, [49]: list, [50]: list, [51]: list, [52]: list, [53]: list, [54]: list, [55]: list, [56]: list, [57]: list, [62]: blockQuote }; var contentInitial = { [91]: definition }; var flowInitial = { [-2]: codeIndented, [-1]: codeIndented, [32]: codeIndented }; var flow2 = { [35]: headingAtx, [42]: thematicBreak, [45]: [setextUnderline, thematicBreak], [60]: htmlFlow, [61]: setextUnderline, [95]: thematicBreak, [96]: codeFenced, [126]: codeFenced }; var string2 = { [38]: characterReference, [92]: characterEscape }; var text2 = { [-5]: lineEnding, [-4]: lineEnding, [-3]: lineEnding, [33]: labelStartImage, [38]: characterReference, [42]: attention, [60]: [autolink, htmlText], [91]: labelStartLink, [92]: [hardBreakEscape, characterEscape], [93]: labelEnd, [95]: attention, [96]: codeText }; var insideSpan = { null: [attention, resolver] }; var attentionMarkers = { null: [42, 95] }; var disable = { null: [] }; // node_modules/micromark/lib/parse.js function parse(options) { const settings = options || {}; const constructs2 = ( /** @type {FullNormalizedExtension} */ combineExtensions([constructs_exports, ...settings.extensions || []]) ); const parser = { defined: [], lazy: {}, constructs: constructs2, content: create(content2), document: create(document2), flow: create(flow), string: create(string), text: create(text) }; return parser; function create(initial) { return creator; function creator(from) { return createTokenizer(parser, initial, from); } } } // node_modules/micromark/lib/preprocess.js var search = /[\0\t\n\r]/g; function preprocess() { let column = 1; let buffer = ""; let start = true; let atCarriageReturn; return preprocessor; function preprocessor(value, encoding, end) { const chunks = []; let match2; let next; let startPosition; let endPosition; let code; value = buffer + value.toString(encoding); startPosition = 0; buffer = ""; if (start) { if (value.charCodeAt(0) === 65279) { startPosition++; } start = void 0; } while (startPosition < value.length) { search.lastIndex = startPosition; match2 = search.exec(value); endPosition = match2 && match2.index !== void 0 ? match2.index : value.length; code = value.charCodeAt(endPosition); if (!match2) { buffer = value.slice(startPosition); break; } if (code === 10 && startPosition === endPosition && atCarriageReturn) { chunks.push(-3); atCarriageReturn = void 0; } else { if (atCarriageReturn) { chunks.push(-5); atCarriageReturn = void 0; } if (startPosition < endPosition) { chunks.push(value.slice(startPosition, endPosition)); column += endPosition - startPosition; } switch (code) { case 0: { chunks.push(65533); column++; break; } case 9: { next = Math.ceil(column / 4) * 4; chunks.push(-2); while (column++ < next) chunks.push(-1); break; } case 10: { chunks.push(-4); column = 1; break; } default: { atCarriageReturn = true; column = 1; } } } startPosition = endPosition + 1; } if (end) { if (atCarriageReturn) chunks.push(-5); if (buffer) chunks.push(buffer); chunks.push(null); } return chunks; } } // node_modules/micromark/lib/postprocess.js function postprocess(events) { while (!subtokenize(events)) { } return events; } // node_modules/micromark-util-decode-numeric-character-reference/index.js function decodeNumericCharacterReference(value, base) { const code = Number.parseInt(value, base); if ( // C0 except for HT, LF, FF, CR, space. code < 9 || code === 11 || code > 13 && code < 32 || // Control character (DEL) of C0, and C1 controls. code > 126 && code < 160 || // Lone high surrogates and low surrogates. code > 55295 && code < 57344 || // Noncharacters. code > 64975 && code < 65008 || (code & 65535) === 65535 || (code & 65535) === 65534 || // Out of range code > 1114111 ) { return "\uFFFD"; } return String.fromCharCode(code); } // node_modules/micromark-util-decode-string/index.js var characterEscapeOrReference = /\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi; function decodeString(value) { return value.replace(characterEscapeOrReference, decode); } function decode($0, $1, $2) { if ($1) { return $1; } const head = $2.charCodeAt(0); if (head === 35) { const head2 = $2.charCodeAt(1); const hex = head2 === 120 || head2 === 88; return decodeNumericCharacterReference($2.slice(hex ? 2 : 1), hex ? 16 : 10); } return decodeNamedCharacterReference($2) || $0; } // node_modules/unist-util-stringify-position/lib/index.js function stringifyPosition(value) { if (!value || typeof value !== "object") { return ""; } if ("position" in value || "type" in value) { return position(value.position); } if ("start" in value || "end" in value) { return position(value); } if ("line" in value || "column" in value) { return point(value); } return ""; } function point(point3) { return index(point3 && point3.line) + ":" + index(point3 && point3.column); } function position(pos) { return point(pos && pos.start) + "-" + point(pos && pos.end); } function index(value) { return value && typeof value === "number" ? value : 1; } // node_modules/mdast-util-from-markdown/lib/index.js var own = {}.hasOwnProperty; var fromMarkdown = ( /** * @type {( * ((value: Value, encoding: Encoding, options?: Options | null | undefined) => Root) & * ((value: Value, options?: Options | null | undefined) => Root) * )} */ /** * @param {Value} value * @param {Encoding | Options | null | undefined} [encoding] * @param {Options | null | undefined} [options] * @returns {Root} */ function(value, encoding, options) { if (typeof encoding !== "string") { options = encoding; encoding = void 0; } return compiler(options)( postprocess( parse(options).document().write(preprocess()(value, encoding, true)) ) ); } ); function compiler(options) { const config = { transforms: [], canContainEols: ["emphasis", "fragment", "heading", "paragraph", "strong"], enter: { autolink: opener(link), autolinkProtocol: onenterdata, autolinkEmail: onenterdata, atxHeading: opener(heading), blockQuote: opener(blockQuote2), characterEscape: onenterdata, characterReference: onenterdata, codeFenced: opener(codeFlow), codeFencedFenceInfo: buffer, codeFencedFenceMeta: buffer, codeIndented: opener(codeFlow, buffer), codeText: opener(codeText2, buffer), codeTextData: onenterdata, data: onenterdata, codeFlowValue: onenterdata, definition: opener(definition2), definitionDestinationString: buffer, definitionLabelString: buffer, definitionTitleString: buffer, emphasis: opener(emphasis), hardBreakEscape: opener(hardBreak), hardBreakTrailing: opener(hardBreak), htmlFlow: opener(html, buffer), htmlFlowData: onenterdata, htmlText: opener(html, buffer), htmlTextData: onenterdata, image: opener(image), label: buffer, link: opener(link), listItem: opener(listItem), listItemValue: onenterlistitemvalue, listOrdered: opener(list2, onenterlistordered), listUnordered: opener(list2), paragraph: opener(paragraph), reference: onenterreference, referenceString: buffer, resourceDestinationString: buffer, resourceTitleString: buffer, setextHeading: opener(heading), strong: opener(strong), thematicBreak: opener(thematicBreak2) }, exit: { atxHeading: closer(), atxHeadingSequence: onexitatxheadingsequence, autolink: closer(), autolinkEmail: onexitautolinkemail, autolinkProtocol: onexitautolinkprotocol, blockQuote: closer(), characterEscapeValue: onexitdata, characterReferenceMarkerHexadecimal: onexitcharacterreferencemarker, characterReferenceMarkerNumeric: onexitcharacterreferencemarker, characterReferenceValue: onexitcharacterreferencevalue, codeFenced: closer(onexitcodefenced), codeFencedFence: onexitcodefencedfence, codeFencedFenceInfo: onexitcodefencedfenceinfo, codeFencedFenceMeta: onexitcodefencedfencemeta, codeFlowValue: onexitdata, codeIndented: closer(onexitcodeindented), codeText: closer(onexitcodetext), codeTextData: onexitdata, data: onexitdata, definition: closer(), definitionDestinationString: onexitdefinitiondestinationstring, definitionLabelString: onexitdefinitionlabelstring, definitionTitleString: onexitdefinitiontitlestring, emphasis: closer(), hardBreakEscape: closer(onexithardbreak), hardBreakTrailing: closer(onexithardbreak), htmlFlow: closer(onexithtmlflow), htmlFlowData: onexitdata, htmlText: closer(onexithtmltext), htmlTextData: onexitdata, image: closer(onexitimage), label: onexitlabel, labelText: onexitlabeltext, lineEnding: onexitlineending, link: closer(onexitlink), listItem: closer(), listOrdered: closer(), listUnordered: closer(), paragraph: closer(), referenceString: onexitreferencestring, resourceDestinationString: onexitresourcedestinationstring, resourceTitleString: onexitresourcetitlestring, resource: onexitresource, setextHeading: closer(onexitsetextheading), setextHeadingLineSequence: onexitsetextheadinglinesequence, setextHeadingText: onexitsetextheadingtext, strong: closer(), thematicBreak: closer() } }; configure(config, (options || {}).mdastExtensions || []); const data = {}; return compile; function compile(events) { let tree = { type: "root", children: [] }; const context = { stack: [tree], tokenStack: [], config, enter, exit: exit2, buffer, resume, setData, getData }; const listStack = []; let index2 = -1; while (++index2 < events.length) { if (events[index2][1].type === "listOrdered" || events[index2][1].type === "listUnordered") { if (events[index2][0] === "enter") { listStack.push(index2); } else { const tail = listStack.pop(); index2 = prepareList(events, tail, index2); } } } index2 = -1; while (++index2 < events.length) { const handler = config[events[index2][0]]; if (own.call(handler, events[index2][1].type)) { handler[events[index2][1].type].call( Object.assign( { sliceSerialize: events[index2][2].sliceSerialize }, context ), events[index2][1] ); } } if (context.tokenStack.length > 0) { const tail = context.tokenStack[context.tokenStack.length - 1]; const handler = tail[1] || defaultOnError; handler.call(context, void 0, tail[0]); } tree.position = { start: point2( events.length > 0 ? events[0][1].start : { line: 1, column: 1, offset: 0 } ), end: point2( events.length > 0 ? events[events.length - 2][1].end : { line: 1, column: 1, offset: 0 } ) }; index2 = -1; while (++index2 < config.transforms.length) { tree = config.transforms[index2](tree) || tree; } return tree; } function prepareList(events, start, length) { let index2 = start - 1; let containerBalance = -1; let listSpread = false; let listItem2; let lineIndex; let firstBlankLineIndex; let atMarker; while (++index2 <= length) { const event = events[index2]; if (event[1].type === "listUnordered" || event[1].type === "listOrdered" || event[1].type === "blockQuote") { if (event[0] === "enter") { containerBalance++; } else { containerBalance--; } atMarker = void 0; } else if (event[1].type === "lineEndingBlank") { if (event[0] === "enter") { if (listItem2 && !atMarker && !containerBalance && !firstBlankLineIndex) { firstBlankLineIndex = index2; } atMarker = void 0; } } else if (event[1].type === "linePrefix" || event[1].type === "listItemValue" || event[1].type === "listItemMarker" || event[1].type === "listItemPrefix" || event[1].type === "listItemPrefixWhitespace") { } else { atMarker = void 0; } if (!containerBalance && event[0] === "enter" && event[1].type === "listItemPrefix" || containerBalance === -1 && event[0] === "exit" && (event[1].type === "listUnordered" || event[1].type === "listOrdered")) { if (listItem2) { let tailIndex = index2; lineIndex = void 0; while (tailIndex--) { const tailEvent = events[tailIndex]; if (tailEvent[1].type === "lineEnding" || tailEvent[1].type === "lineEndingBlank") { if (tailEvent[0] === "exit") continue; if (lineIndex) { events[lineIndex][1].type = "lineEndingBlank"; listSpread = true; } tailEvent[1].type = "lineEnding"; lineIndex = tailIndex; } else if (tailEvent[1].type === "linePrefix" || tailEvent[1].type === "blockQuotePrefix" || tailEvent[1].type === "blockQuotePrefixWhitespace" || tailEvent[1].type === "blockQuoteMarker" || tailEvent[1].type === "listItemIndent") { } else { break; } } if (firstBlankLineIndex && (!lineIndex || firstBlankLineIndex < lineIndex)) { listItem2._spread = true; } listItem2.end = Object.assign( {}, lineIndex ? events[lineIndex][1].start : event[1].end ); events.splice(lineIndex || index2, 0, ["exit", listItem2, event[2]]); index2++; length++; } if (event[1].type === "listItemPrefix") { listItem2 = { type: "listItem", _spread: false, start: Object.assign({}, event[1].start), // @ts-expect-error: we’ll add `end` in a second. end: void 0 }; events.splice(index2, 0, ["enter", listItem2, event[2]]); index2++; length++; firstBlankLineIndex = void 0; atMarker = true; } } } events[start][1]._spread = listSpread; return length; } function setData(key, value) { data[key] = value; } function getData(key) { return data[key]; } function opener(create, and) { return open; function open(token) { enter.call(this, create(token), token); if (and) and.call(this, token); } } function buffer() { this.stack.push({ type: "fragment", children: [] }); } function enter(node2, token, errorHandler) { const parent = this.stack[this.stack.length - 1]; parent.children.push(node2); this.stack.push(node2); this.tokenStack.push([token, errorHandler]); node2.position = { start: point2(token.start) }; return node2; } function closer(and) { return close; function close(token) { if (and) and.call(this, token); exit2.call(this, token); } } function exit2(token, onExitError) { const node2 = this.stack.pop(); const open = this.tokenStack.pop(); if (!open) { throw new Error( "Cannot close `" + token.type + "` (" + stringifyPosition({ start: token.start, end: token.end }) + "): it\u2019s not open" ); } else if (open[0].type !== token.type) { if (onExitError) { onExitError.call(this, token, open[0]); } else { const handler = open[1] || defaultOnError; handler.call(this, token, open[0]); } } node2.position.end = point2(token.end); return node2; } function resume() { return toString2(this.stack.pop()); } function onenterlistordered() { setData("expectingFirstListItemValue", true); } function onenterlistitemvalue(token) { if (getData("expectingFirstListItemValue")) { const ancestor = this.stack[this.stack.length - 2]; ancestor.start = Number.parseInt(this.sliceSerialize(token), 10); setData("expectingFirstListItemValue"); } } function onexitcodefencedfenceinfo() { const data2 = this.resume(); const node2 = this.stack[this.stack.length - 1]; node2.lang = data2; } function onexitcodefencedfencemeta() { const data2 = this.resume(); const node2 = this.stack[this.stack.length - 1]; node2.meta = data2; } function onexitcodefencedfence() { if (getData("flowCodeInside")) return; this.buffer(); setData("flowCodeInside", true); } function onexitcodefenced() { const data2 = this.resume(); const node2 = this.stack[this.stack.length - 1]; node2.value = data2.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g, ""); setData("flowCodeInside"); } function onexitcodeindented() { const data2 = this.resume(); const node2 = this.stack[this.stack.length - 1]; node2.value = data2.replace(/(\r?\n|\r)$/g, ""); } function onexitdefinitionlabelstring(token) { const label = this.resume(); const node2 = this.stack[this.stack.length - 1]; node2.label = label; node2.identifier = normalizeIdentifier( this.sliceSerialize(token) ).toLowerCase(); } function onexitdefinitiontitlestring() { const data2 = this.resume(); const node2 = this.stack[this.stack.length - 1]; node2.title = data2; } function onexitdefinitiondestinationstring() { const data2 = this.resume(); const node2 = this.stack[this.stack.length - 1]; node2.url = data2; } function onexitatxheadingsequence(token) { const node2 = this.stack[this.stack.length - 1]; if (!node2.depth) { const depth = this.sliceSerialize(token).length; node2.depth = depth; } } function onexitsetextheadingtext() { setData("setextHeadingSlurpLineEnding", true); } function onexitsetextheadinglinesequence(token) { const node2 = this.stack[this.stack.length - 1]; node2.depth = this.sliceSerialize(token).charCodeAt(0) === 61 ? 1 : 2; } function onexitsetextheading() { setData("setextHeadingSlurpLineEnding"); } function onenterdata(token) { const node2 = this.stack[this.stack.length - 1]; let tail = node2.children[node2.children.length - 1]; if (!tail || tail.type !== "text") { tail = text3(); tail.position = { start: point2(token.start) }; node2.children.push(tail); } this.stack.push(tail); } function onexitdata(token) { const tail = this.stack.pop(); tail.value += this.sliceSerialize(token); tail.position.end = point2(token.end); } function onexitlineending(token) { const context = this.stack[this.stack.length - 1]; if (getData("atHardBreak")) { const tail = context.children[context.children.length - 1]; tail.position.end = point2(token.end); setData("atHardBreak"); return; } if (!getData("setextHeadingSlurpLineEnding") && config.canContainEols.includes(context.type)) { onenterdata.call(this, token); onexitdata.call(this, token); } } function onexithardbreak() { setData("atHardBreak", true); } function onexithtmlflow() { const data2 = this.resume(); const node2 = this.stack[this.stack.length - 1]; node2.value = data2; } function onexithtmltext() { const data2 = this.resume(); const node2 = this.stack[this.stack.length - 1]; node2.value = data2; } function onexitcodetext() { const data2 = this.resume(); const node2 = this.stack[this.stack.length - 1]; node2.value = data2; } function onexitlink() { const node2 = this.stack[this.stack.length - 1]; if (getData("inReference")) { const referenceType = getData("referenceType") || "shortcut"; node2.type += "Reference"; node2.referenceType = referenceType; delete node2.url; delete node2.title; } else { delete node2.identifier; delete node2.label; } setData("referenceType"); } function onexitimage() { const node2 = this.stack[this.stack.length - 1]; if (getData("inReference")) { const referenceType = getData("referenceType") || "shortcut"; node2.type += "Reference"; node2.referenceType = referenceType; delete node2.url; delete node2.title; } else { delete node2.identifier; delete node2.label; } setData("referenceType"); } function onexitlabeltext(token) { const string3 = this.sliceSerialize(token); const ancestor = this.stack[this.stack.length - 2]; ancestor.label = decodeString(string3); ancestor.identifier = normalizeIdentifier(string3).toLowerCase(); } function onexitlabel() { const fragment = this.stack[this.stack.length - 1]; const value = this.resume(); const node2 = this.stack[this.stack.length - 1]; setData("inReference", true); if (node2.type === "link") { const children = fragment.children; node2.children = children; } else { node2.alt = value; } } function onexitresourcedestinationstring() { const data2 = this.resume(); const node2 = this.stack[this.stack.length - 1]; node2.url = data2; } function onexitresourcetitlestring() { const data2 = this.resume(); const node2 = this.stack[this.stack.length - 1]; node2.title = data2; } function onexitresource() { setData("inReference"); } function onenterreference() { setData("referenceType", "collapsed"); } function onexitreferencestring(token) { const label = this.resume(); const node2 = this.stack[this.stack.length - 1]; node2.label = label; node2.identifier = normalizeIdentifier( this.sliceSerialize(token) ).toLowerCase(); setData("referenceType", "full"); } function onexitcharacterreferencemarker(token) { setData("characterReferenceType", token.type); } function onexitcharacterreferencevalue(token) { const data2 = this.sliceSerialize(token); const type2 = getData("characterReferenceType"); let value; if (type2) { value = decodeNumericCharacterReference( data2, type2 === "characterReferenceMarkerNumeric" ? 10 : 16 ); setData("characterReferenceType"); } else { const result = decodeNamedCharacterReference(data2); value = result; } const tail = this.stack.pop(); tail.value += value; tail.position.end = point2(token.end); } function onexitautolinkprotocol(token) { onexitdata.call(this, token); const node2 = this.stack[this.stack.length - 1]; node2.url = this.sliceSerialize(token); } function onexitautolinkemail(token) { onexitdata.call(this, token); const node2 = this.stack[this.stack.length - 1]; node2.url = "mailto:" + this.sliceSerialize(token); } function blockQuote2() { return { type: "blockquote", children: [] }; } function codeFlow() { return { type: "code", lang: null, meta: null, value: "" }; } function codeText2() { return { type: "inlineCode", value: "" }; } function definition2() { return { type: "definition", identifier: "", label: null, title: null, url: "" }; } function emphasis() { return { type: "emphasis", children: [] }; } function heading() { return { type: "heading", depth: void 0, children: [] }; } function hardBreak() { return { type: "break" }; } function html() { return { type: "html", value: "" }; } function image() { return { type: "image", title: null, url: "", alt: null }; } function link() { return { type: "link", title: null, url: "", children: [] }; } function list2(token) { return { type: "list", ordered: token.type === "listOrdered", start: null, spread: token._spread, children: [] }; } function listItem(token) { return { type: "listItem", spread: token._spread, checked: null, children: [] }; } function paragraph() { return { type: "paragraph", children: [] }; } function strong() { return { type: "strong", children: [] }; } function text3() { return { type: "text", value: "" }; } function thematicBreak2() { return { type: "thematicBreak" }; } } function point2(d3) { return { line: d3.line, column: d3.column, offset: d3.offset }; } function configure(combined, extensions) { let index2 = -1; while (++index2 < extensions.length) { const value = extensions[index2]; if (Array.isArray(value)) { configure(combined, value); } else { extension(combined, value); } } } function extension(combined, extension2) { let key; for (key in extension2) { if (own.call(extension2, key)) { if (key === "canContainEols") { const right = extension2[key]; if (right) { combined[key].push(...right); } } else if (key === "transforms") { const right = extension2[key]; if (right) { combined[key].push(...right); } } else if (key === "enter" || key === "exit") { const right = extension2[key]; if (right) { Object.assign(combined[key], right); } } } } } function defaultOnError(left, right) { if (left) { throw new Error( "Cannot close `" + left.type + "` (" + stringifyPosition({ start: left.start, end: left.end }) + "): a different token (`" + right.type + "`, " + stringifyPosition({ start: right.start, end: right.end }) + ") is open" ); } else { throw new Error( "Cannot close document, a token (`" + right.type + "`, " + stringifyPosition({ start: right.start, end: right.end }) + ") is still open" ); } } // node_modules/mdast-util-to-markdown/lib/util/association.js function association(node2) { if (node2.label || !node2.identifier) { return node2.label || ""; } return decodeString(node2.identifier); } // node_modules/mdast-util-gfm-footnote/lib/index.js footnoteReference.peek = footnoteReferencePeek; function gfmFootnoteFromMarkdown() { return { enter: { gfmFootnoteDefinition: enterFootnoteDefinition, gfmFootnoteDefinitionLabelString: enterFootnoteDefinitionLabelString, gfmFootnoteCall: enterFootnoteCall, gfmFootnoteCallString: enterFootnoteCallString }, exit: { gfmFootnoteDefinition: exitFootnoteDefinition, gfmFootnoteDefinitionLabelString: exitFootnoteDefinitionLabelString, gfmFootnoteCall: exitFootnoteCall, gfmFootnoteCallString: exitFootnoteCallString } }; } function enterFootnoteDefinition(token) { this.enter( { type: "footnoteDefinition", identifier: "", label: "", children: [] }, token ); } function enterFootnoteDefinitionLabelString() { this.buffer(); } function exitFootnoteDefinitionLabelString(token) { const label = this.resume(); const node2 = ( /** @type {FootnoteDefinition} */ this.stack[this.stack.length - 1] ); node2.label = label; node2.identifier = normalizeIdentifier( this.sliceSerialize(token) ).toLowerCase(); } function exitFootnoteDefinition(token) { this.exit(token); } function enterFootnoteCall(token) { this.enter({ type: "footnoteReference", identifier: "", label: "" }, token); } function enterFootnoteCallString() { this.buffer(); } function exitFootnoteCallString(token) { const label = this.resume(); const node2 = ( /** @type {FootnoteDefinition} */ this.stack[this.stack.length - 1] ); node2.label = label; node2.identifier = normalizeIdentifier( this.sliceSerialize(token) ).toLowerCase(); } function exitFootnoteCall(token) { this.exit(token); } function footnoteReference(node2, _, context, safeOptions) { const tracker = track(safeOptions); let value = tracker.move("[^"); const exit2 = context.enter("footnoteReference"); const subexit = context.enter("reference"); value += tracker.move( safe(context, association(node2), { ...tracker.current(), before: value, after: "]" }) ); subexit(); exit2(); value += tracker.move("]"); return value; } function footnoteReferencePeek() { return "["; } // node_modules/mdast-util-gfm-task-list-item/lib/index.js var gfmTaskListItemFromMarkdown = { exit: { taskListCheckValueChecked: exitCheck, taskListCheckValueUnchecked: exitCheck, paragraph: exitParagraphWithTaskListItem } }; function exitCheck(token) { const node2 = ( /** @type {ListItem} */ this.stack[this.stack.length - 2] ); node2.checked = token.type === "taskListCheckValueChecked"; } function exitParagraphWithTaskListItem(token) { const parent = ( /** @type {Parents} */ this.stack[this.stack.length - 2] ); if (parent && parent.type === "listItem" && typeof parent.checked === "boolean") { const node2 = ( /** @type {Paragraph} */ this.stack[this.stack.length - 1] ); const head = node2.children[0]; if (head && head.type === "text") { const siblings = parent.children; let index2 = -1; let firstParaghraph; while (++index2 < siblings.length) { const sibling = siblings[index2]; if (sibling.type === "paragraph") { firstParaghraph = sibling; break; } } if (firstParaghraph === node2) { head.value = head.value.slice(1); if (head.value.length === 0) { node2.children.shift(); } else if (node2.position && head.position && typeof head.position.start.offset === "number") { head.position.start.column++; head.position.start.offset++; node2.position.start = Object.assign({}, head.position.start); } } } } this.exit(token); } // node_modules/quick-lru/index.js var QuickLRU = class extends Map { constructor(options = {}) { super(); if (!(options.maxSize && options.maxSize > 0)) { throw new TypeError("`maxSize` must be a number greater than 0"); } if (typeof options.maxAge === "number" && options.maxAge === 0) { throw new TypeError("`maxAge` must be a number greater than 0"); } this.maxSize = options.maxSize; this.maxAge = options.maxAge || Number.POSITIVE_INFINITY; this.onEviction = options.onEviction; this.cache = /* @__PURE__ */ new Map(); this.oldCache = /* @__PURE__ */ new Map(); this._size = 0; } // TODO: Use private class methods when targeting Node.js 16. _emitEvictions(cache) { if (typeof this.onEviction !== "function") { return; } for (const [key, item] of cache) { this.onEviction(key, item.value); } } _deleteIfExpired(key, item) { if (typeof item.expiry === "number" && item.expiry <= Date.now()) { if (typeof this.onEviction === "function") { this.onEviction(key, item.value); } return this.delete(key); } return false; } _getOrDeleteIfExpired(key, item) { const deleted = this._deleteIfExpired(key, item); if (deleted === false) { return item.value; } } _getItemValue(key, item) { return item.expiry ? this._getOrDeleteIfExpired(key, item) : item.value; } _peek(key, cache) { const item = cache.get(key); return this._getItemValue(key, item); } _set(key, value) { this.cache.set(key, value); this._size++; if (this._size >= this.maxSize) { this._size = 0; this._emitEvictions(this.oldCache); this.oldCache = this.cache; this.cache = /* @__PURE__ */ new Map(); } } _moveToRecent(key, item) { this.oldCache.delete(key); this._set(key, item); } *_entriesAscending() { for (const item of this.oldCache) { const [key, value] = item; if (!this.cache.has(key)) { const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield item; } } } for (const item of this.cache) { const [key, value] = item; const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield item; } } } get(key) { if (this.cache.has(key)) { const item = this.cache.get(key); return this._getItemValue(key, item); } if (this.oldCache.has(key)) { const item = this.oldCache.get(key); if (this._deleteIfExpired(key, item) === false) { this._moveToRecent(key, item); return item.value; } } } set(key, value, { maxAge = this.maxAge } = {}) { const expiry = typeof maxAge === "number" && maxAge !== Number.POSITIVE_INFINITY ? Date.now() + maxAge : void 0; if (this.cache.has(key)) { this.cache.set(key, { value, expiry }); } else { this._set(key, { value, expiry }); } return this; } has(key) { if (this.cache.has(key)) { return !this._deleteIfExpired(key, this.cache.get(key)); } if (this.oldCache.has(key)) { return !this._deleteIfExpired(key, this.oldCache.get(key)); } return false; } peek(key) { if (this.cache.has(key)) { return this._peek(key, this.cache); } if (this.oldCache.has(key)) { return this._peek(key, this.oldCache); } } delete(key) { const deleted = this.cache.delete(key); if (deleted) { this._size--; } return this.oldCache.delete(key) || deleted; } clear() { this.cache.clear(); this.oldCache.clear(); this._size = 0; } resize(newSize) { if (!(newSize && newSize > 0)) { throw new TypeError("`maxSize` must be a number greater than 0"); } const items = [...this._entriesAscending()]; const removeCount = items.length - newSize; if (removeCount < 0) { this.cache = new Map(items); this.oldCache = /* @__PURE__ */ new Map(); this._size = items.length; } else { if (removeCount > 0) { this._emitEvictions(items.slice(0, removeCount)); } this.oldCache = new Map(items.slice(removeCount)); this.cache = /* @__PURE__ */ new Map(); this._size = 0; } this.maxSize = newSize; } *keys() { for (const [key] of this) { yield key; } } *values() { for (const [, value] of this) { yield value; } } *[Symbol.iterator]() { for (const item of this.cache) { const [key, value] = item; const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield [key, value.value]; } } for (const item of this.oldCache) { const [key, value] = item; if (!this.cache.has(key)) { const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield [key, value.value]; } } } } *entriesDescending() { let items = [...this.cache]; for (let i2 = items.length - 1; i2 >= 0; --i2) { const item = items[i2]; const [key, value] = item; const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield [key, value.value]; } } items = [...this.oldCache]; for (let i2 = items.length - 1; i2 >= 0; --i2) { const item = items[i2]; const [key, value] = item; if (!this.cache.has(key)) { const deleted = this._deleteIfExpired(key, value); if (deleted === false) { yield [key, value.value]; } } } } *entriesAscending() { for (const [key, value] of this._entriesAscending()) { yield [key, value.value]; } } get size() { if (!this._size) { return this.oldCache.size; } let oldCacheSize = 0; for (const key of this.oldCache.keys()) { if (!this.cache.has(key)) { oldCacheSize++; } } return Math.min(this._size + oldCacheSize, this.maxSize); } entries() { return this.entriesAscending(); } forEach(callbackFunction, thisArgument = this) { for (const [key, value] of this.entriesAscending()) { callbackFunction.call(thisArgument, value, key, this); } } get [Symbol.toStringTag]() { return JSON.stringify([...this.entriesAscending()]); } }; // src/utils/mdast.ts var LRU = new QuickLRU({ maxSize: 200 }); function parseTextToAST(text3) { const textHash = hashString53Bit(text3); if (LRU.has(textHash)) { return LRU.get(textHash); } const ast = fromMarkdown(text3, { extensions: [ combineExtensions([gfmFootnote(), gfmTaskListItem]), math() ], mdastExtensions: [ [gfmFootnoteFromMarkdown(), gfmTaskListItemFromMarkdown], mathFromMarkdown() ] }); LRU.set(textHash, ast); return ast; } // src/extractTextFromPattern.ts var startPattern = /%%\s*run start\s*([\s\S]*?)%%/g; var codeBlockPattern = /(```|~~~)([\s\S]*?)\n([\s\S]*?)\n(```|~~~)/; var endPattern = /%%\s*run end\s*([\s\S]*?)%%/g; var extractCode = (text3) => { var _a; const matches = new RegExp(codeBlockPattern).exec(text3); if (matches) { const ast = parseTextToAST(text3); const code = ast.children.find((c2) => c2.type === "code"); if ((code == null ? void 0 : code.type) === "code") return { meta: code.meta, languageCode: (_a = code.lang) != null ? _a : "js", code: code.value }; } return void 0; }; var extractId = (text3) => { const matches = text3.match(/^(\d+)(\s+)([\s\S]*)$/); if (matches && matches.length === 4) { return { id: parseInt(matches[1]), text: matches[3] }; } return { id: void 0, text: text3 }; }; function extractSectionsFromPattern(text3) { var _a, _b, _c, _d, _e, _f, _g; const sections = []; const sectionSummary = {}; const allMatches = Array.from(text3.matchAll(new RegExp(startPattern))); for (let i2 = 0; i2 < allMatches.length; i2++) { const startMatch = allMatches[i2]; const nextMatch = allMatches[i2 + 1]; const { text: startingTag } = extractId((_b = (_a = startMatch[1]) == null ? void 0 : _a.trim()) != null ? _b : ""); const id = sectionSummary[startingTag] = ((_c = sectionSummary[startingTag]) != null ? _c : 0) + 1; const codeBlock = extractCode(startingTag); const _endPattern = new RegExp(endPattern); _endPattern.lastIndex = (_e = startMatch.index) != null ? _e : 0 + ((_d = startMatch[0]) == null ? void 0 : _d.length); const endMatch = _endPattern.exec(text3); if (endMatch !== null && (nextMatch === void 0 || endMatch.index < nextMatch.index)) { const endingTag = (_g = (_f = endMatch[1]) == null ? void 0 : _f.trim()) != null ? _g : ""; const content3 = text3.slice(startMatch.index + startMatch[0].length, endMatch.index).trim(); sections.push({ startingTag, id, codeBlock, content: content3, endingTag, endingObject: mapStringToKeyValuePairs(endingTag), startMatch, endMatch, text: text3.substring( startMatch.index, endMatch.index + endMatch[0].length ) }); } else { sections.push({ id, startingTag, startMatch, codeBlock, text: text3.substring( startMatch.index, startMatch.index + startMatch[0].length ) }); } } return { sections, sectionSummary }; } // node_modules/ts-dedent/esm/index.js function dedent(templ) { var values = []; for (var _i = 1; _i < arguments.length; _i++) { values[_i - 1] = arguments[_i]; } var strings = Array.from(typeof templ === "string" ? [templ] : templ); strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, ""); var indentLengths = strings.reduce(function(arr, str2) { var matches = str2.match(/\n([\t ]+|(?!\s).)/g); if (matches) { return arr.concat(matches.map(function(match2) { var _a, _b; return (_b = (_a = match2.match(/[\t ]/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0; })); } return arr; }, []); if (indentLengths.length) { var pattern_1 = new RegExp("\n[ ]{" + Math.min.apply(Math, indentLengths) + "}", "g"); strings = strings.map(function(str2) { return str2.replace(pattern_1, "\n"); }); } strings[0] = strings[0].replace(/^\r?\n/, ""); var string3 = strings[0]; values.forEach(function(value, i2) { var endentations = string3.match(/(?:^|\n)( *)$/); var endentation = endentations ? endentations[1] : ""; var indentedValue = value; if (typeof value === "string" && value.includes("\n")) { indentedValue = String(value).split("\n").map(function(str2, i3) { return i3 === 0 ? str2 : "" + endentation + str2; }).join("\n"); } string3 += indentedValue + strings[i2 + 1]; }); return string3; } var esm_default = dedent; // src/utils/evalFromExpression.ts var import_recast = __toESM(require_main2()); // node_modules/zod/lib/index.mjs var util; (function(util2) { util2.assertEqual = (val) => val; function assertIs(_arg) { } util2.assertIs = assertIs; function assertNever(_x) { throw new Error(); } util2.assertNever = assertNever; util2.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util2.getValidEnumValues = (obj) => { const validKeys = util2.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] !== "number"); const filtered = {}; for (const k2 of validKeys) { filtered[k2] = obj[k2]; } return util2.objectValues(filtered); }; util2.objectValues = (obj) => { return util2.objectKeys(obj).map(function(e2) { return obj[e2]; }); }; util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { const keys = []; for (const key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { keys.push(key); } } return keys; }; util2.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return void 0; }; util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; function joinValues(array, separator = " | ") { return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); } util2.joinValues = joinValues; util2.jsonStringifyReplacer = (_, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util || (util = {})); var objectUtil; (function(objectUtil2) { objectUtil2.mergeShapes = (first, second) => { return { ...first, ...second // second overwrites first }; }; })(objectUtil || (objectUtil = {})); var ZodParsedType = util.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set" ]); var getParsedType = (data) => { const t2 = typeof data; switch (t2) { case "undefined": return ZodParsedType.undefined; case "string": return ZodParsedType.string; case "number": return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; case "boolean": return ZodParsedType.boolean; case "function": return ZodParsedType.function; case "bigint": return ZodParsedType.bigint; case "symbol": return ZodParsedType.symbol; case "object": if (Array.isArray(data)) { return ZodParsedType.array; } if (data === null) { return ZodParsedType.null; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return ZodParsedType.promise; } if (typeof Map !== "undefined" && data instanceof Map) { return ZodParsedType.map; } if (typeof Set !== "undefined" && data instanceof Set) { return ZodParsedType.set; } if (typeof Date !== "undefined" && data instanceof Date) { return ZodParsedType.date; } return ZodParsedType.object; default: return ZodParsedType.unknown; } }; var ZodIssueCode = util.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite" ]); var quotelessJson = (obj) => { const json2 = JSON.stringify(obj, null, 2); return json2.replace(/"([^"]+)":/g, "$1:"); }; var ZodError = class extends Error { constructor(issues) { super(); this.issues = []; this.addIssue = (sub) => { this.issues = [...this.issues, sub]; }; this.addIssues = (subs = []) => { this.issues = [...this.issues, ...subs]; }; const actualProto = new.target.prototype; if (Object.setPrototypeOf) { Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } get errors() { return this.issues; } format(_mapper) { const mapper = _mapper || function(issue) { return issue.message; }; const fieldErrors = { _errors: [] }; const processError = (error) => { for (const issue of error.issues) { if (issue.code === "invalid_union") { issue.unionErrors.map(processError); } else if (issue.code === "invalid_return_type") { processError(issue.returnTypeError); } else if (issue.code === "invalid_arguments") { processError(issue.argumentsError); } else if (issue.path.length === 0) { fieldErrors._errors.push(mapper(issue)); } else { let curr = fieldErrors; let i2 = 0; while (i2 < issue.path.length) { const el = issue.path[i2]; const terminal = i2 === issue.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper(issue)); } curr = curr[el]; i2++; } } } }; processError(this); return fieldErrors; } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper = (issue) => issue.message) { const fieldErrors = {}; const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; fieldErrors[sub.path[0]].push(mapper(sub)); } else { formErrors.push(mapper(sub)); } } return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } }; ZodError.create = (issues) => { const error = new ZodError(issues); return error; }; var errorMap = (issue, _ctx) => { let message; switch (issue.code) { case ZodIssueCode.invalid_type: if (issue.received === ZodParsedType.undefined) { message = "Required"; } else { message = `Expected ${issue.expected}, received ${issue.received}`; } break; case ZodIssueCode.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; break; case ZodIssueCode.unrecognized_keys: message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; break; case ZodIssueCode.invalid_union: message = `Invalid input`; break; case ZodIssueCode.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; break; case ZodIssueCode.invalid_enum_value: message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; break; case ZodIssueCode.invalid_arguments: message = `Invalid function arguments`; break; case ZodIssueCode.invalid_return_type: message = `Invalid function return type`; break; case ZodIssueCode.invalid_date: message = `Invalid date`; break; case ZodIssueCode.invalid_string: if (typeof issue.validation === "object") { if ("includes" in issue.validation) { message = `Invalid input: must include "${issue.validation.includes}"`; if (typeof issue.validation.position === "number") { message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; } } else if ("startsWith" in issue.validation) { message = `Invalid input: must start with "${issue.validation.startsWith}"`; } else if ("endsWith" in issue.validation) { message = `Invalid input: must end with "${issue.validation.endsWith}"`; } else { util.assertNever(issue.validation); } } else if (issue.validation !== "regex") { message = `Invalid ${issue.validation}`; } else { message = "Invalid"; } break; case ZodIssueCode.too_small: if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; else message = "Invalid input"; break; case ZodIssueCode.too_big: if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; else message = "Invalid input"; break; case ZodIssueCode.custom: message = `Invalid input`; break; case ZodIssueCode.invalid_intersection_types: message = `Intersection results could not be merged`; break; case ZodIssueCode.not_multiple_of: message = `Number must be a multiple of ${issue.multipleOf}`; break; case ZodIssueCode.not_finite: message = "Number must be finite"; break; default: message = _ctx.defaultError; util.assertNever(issue); } return { message }; }; var overrideErrorMap = errorMap; function setErrorMap(map2) { overrideErrorMap = map2; } function getErrorMap() { return overrideErrorMap; } var makeIssue = (params) => { const { data, path, errorMaps, issueData } = params; const fullPath = [...path, ...issueData.path || []]; const fullIssue = { ...issueData, path: fullPath }; let errorMessage = ""; const maps = errorMaps.filter((m3) => !!m3).slice().reverse(); for (const map2 of maps) { errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message; } return { ...issueData, path: fullPath, message: issueData.message || errorMessage }; }; var EMPTY_PATH = []; function addIssueToContext(ctx, issueData) { const issue = makeIssue({ issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap // then global default map ].filter((x2) => !!x2) }); ctx.common.issues.push(issue); } var ParseStatus = class { constructor() { this.value = "valid"; } dirty() { if (this.value === "valid") this.value = "dirty"; } abort() { if (this.value !== "aborted") this.value = "aborted"; } static mergeArray(status, results) { const arrayValue = []; for (const s3 of results) { if (s3.status === "aborted") return INVALID; if (s3.status === "dirty") status.dirty(); arrayValue.push(s3.value); } return { status: status.value, value: arrayValue }; } static async mergeObjectAsync(status, pairs2) { const syncPairs = []; for (const pair of pairs2) { syncPairs.push({ key: await pair.key, value: await pair.value }); } return ParseStatus.mergeObjectSync(status, syncPairs); } static mergeObjectSync(status, pairs2) { const finalObject = {}; for (const pair of pairs2) { const { key, value } = pair; if (key.status === "aborted") return INVALID; if (value.status === "aborted") return INVALID; if (key.status === "dirty") status.dirty(); if (value.status === "dirty") status.dirty(); if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { finalObject[key.value] = value.value; } } return { status: status.value, value: finalObject }; } }; var INVALID = Object.freeze({ status: "aborted" }); var DIRTY = (value) => ({ status: "dirty", value }); var OK = (value) => ({ status: "valid", value }); var isAborted = (x2) => x2.status === "aborted"; var isDirty = (x2) => x2.status === "dirty"; var isValid = (x2) => x2.status === "valid"; var isAsync = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise; var errorUtil; (function(errorUtil2) { errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; })(errorUtil || (errorUtil = {})); var ParseInputLazyPath = class { constructor(parent, value, path, key) { this._cachedPath = []; this.parent = parent; this.data = value; this._path = path; this._key = key; } get path() { if (!this._cachedPath.length) { if (this._key instanceof Array) { this._cachedPath.push(...this._path, ...this._key); } else { this._cachedPath.push(...this._path, this._key); } } return this._cachedPath; } }; var handleResult = (ctx, result) => { if (isValid(result)) { return { success: true, data: result.value }; } else { if (!ctx.common.issues.length) { throw new Error("Validation failed but no issues detected."); } return { success: false, get error() { if (this._error) return this._error; const error = new ZodError(ctx.common.issues); this._error = error; return this._error; } }; } }; function processCreateParams(params) { if (!params) return {}; const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; if (errorMap2 && (invalid_type_error || required_error)) { throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } if (errorMap2) return { errorMap: errorMap2, description }; const customMap = (iss, ctx) => { if (iss.code !== "invalid_type") return { message: ctx.defaultError }; if (typeof ctx.data === "undefined") { return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError }; } return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError }; }; return { errorMap: customMap, description }; } var ZodType = class { constructor(def) { this.spa = this.safeParseAsync; this._def = def; this.parse = this.parse.bind(this); this.safeParse = this.safeParse.bind(this); this.parseAsync = this.parseAsync.bind(this); this.safeParseAsync = this.safeParseAsync.bind(this); this.spa = this.spa.bind(this); this.refine = this.refine.bind(this); this.refinement = this.refinement.bind(this); this.superRefine = this.superRefine.bind(this); this.optional = this.optional.bind(this); this.nullable = this.nullable.bind(this); this.nullish = this.nullish.bind(this); this.array = this.array.bind(this); this.promise = this.promise.bind(this); this.or = this.or.bind(this); this.and = this.and.bind(this); this.transform = this.transform.bind(this); this.brand = this.brand.bind(this); this.default = this.default.bind(this); this.catch = this.catch.bind(this); this.describe = this.describe.bind(this); this.pipe = this.pipe.bind(this); this.readonly = this.readonly.bind(this); this.isNullable = this.isNullable.bind(this); this.isOptional = this.isOptional.bind(this); } get description() { return this._def.description; } _getType(input) { return getParsedType(input.data); } _getOrReturnCtx(input, ctx) { return ctx || { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent }; } _processInputParams(input) { return { status: new ParseStatus(), ctx: { common: input.parent.common, data: input.data, parsedType: getParsedType(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent } }; } _parseSync(input) { const result = this._parse(input); if (isAsync(result)) { throw new Error("Synchronous parse encountered promise."); } return result; } _parseAsync(input) { const result = this._parse(input); return Promise.resolve(result); } parse(data, params) { const result = this.safeParse(data, params); if (result.success) return result.data; throw result.error; } safeParse(data, params) { var _a; const ctx = { common: { issues: [], async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap }, path: (params === null || params === void 0 ? void 0 : params.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }; const result = this._parseSync({ data, path: ctx.path, parent: ctx }); return handleResult(ctx, result); } async parseAsync(data, params) { const result = await this.safeParseAsync(data, params); if (result.success) return result.data; throw result.error; } async safeParseAsync(data, params) { const ctx = { common: { issues: [], contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, async: true }, path: (params === null || params === void 0 ? void 0 : params.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: getParsedType(data) }; const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); return handleResult(ctx, result); } refine(check, message) { const getIssueProperties = (val) => { if (typeof message === "string" || typeof message === "undefined") { return { message }; } else if (typeof message === "function") { return message(val); } else { return message; } }; return this._refinement((val, ctx) => { const result = check(val); const setError = () => ctx.addIssue({ code: ZodIssueCode.custom, ...getIssueProperties(val) }); if (typeof Promise !== "undefined" && result instanceof Promise) { return result.then((data) => { if (!data) { setError(); return false; } else { return true; } }); } if (!result) { setError(); return false; } else { return true; } }); } refinement(check, refinementData) { return this._refinement((val, ctx) => { if (!check(val)) { ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); return false; } else { return true; } }); } _refinement(refinement) { return new ZodEffects({ schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "refinement", refinement } }); } superRefine(refinement) { return this._refinement(refinement); } optional() { return ZodOptional.create(this, this._def); } nullable() { return ZodNullable.create(this, this._def); } nullish() { return this.nullable().optional(); } array() { return ZodArray.create(this, this._def); } promise() { return ZodPromise.create(this, this._def); } or(option) { return ZodUnion.create([this, option], this._def); } and(incoming) { return ZodIntersection.create(this, incoming, this._def); } transform(transform) { return new ZodEffects({ ...processCreateParams(this._def), schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "transform", transform } }); } default(def) { const defaultValueFunc = typeof def === "function" ? def : () => def; return new ZodDefault({ ...processCreateParams(this._def), innerType: this, defaultValue: defaultValueFunc, typeName: ZodFirstPartyTypeKind.ZodDefault }); } brand() { return new ZodBranded({ typeName: ZodFirstPartyTypeKind.ZodBranded, type: this, ...processCreateParams(this._def) }); } catch(def) { const catchValueFunc = typeof def === "function" ? def : () => def; return new ZodCatch({ ...processCreateParams(this._def), innerType: this, catchValue: catchValueFunc, typeName: ZodFirstPartyTypeKind.ZodCatch }); } describe(description) { const This = this.constructor; return new This({ ...this._def, description }); } pipe(target) { return ZodPipeline.create(this, target); } readonly() { return ZodReadonly.create(this); } isOptional() { return this.safeParse(void 0).success; } isNullable() { return this.safeParse(null).success; } }; var cuidRegex = /^c[^\s-]{8,}$/i; var cuid2Regex = /^[a-z][a-z0-9]*$/; var ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/; var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; var emailRegex = /^([A-Z0-9_+-]+\.?)*[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; var emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u; var ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/; var ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; var datetimeRegex = (args) => { if (args.precision) { if (args.offset) { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); } else { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`); } } else if (args.precision === 0) { if (args.offset) { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); } else { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`); } } else { if (args.offset) { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`); } else { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`); } } }; function isValidIP(ip, version) { if ((version === "v4" || !version) && ipv4Regex.test(ip)) { return true; } if ((version === "v6" || !version) && ipv6Regex.test(ip)) { return true; } return false; } var ZodString = class extends ZodType { constructor() { super(...arguments); this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), { validation, code: ZodIssueCode.invalid_string, ...errorUtil.errToObj(message) }); this.nonempty = (message) => this.min(1, errorUtil.errToObj(message)); this.trim = () => new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "trim" }] }); this.toLowerCase = () => new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }] }); this.toUpperCase = () => new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }] }); } _parse(input) { if (this._def.coerce) { input.data = String(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.string) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext( ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.string, received: ctx2.parsedType } // ); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const check of this._def.checks) { if (check.kind === "min") { if (input.data.length < check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, exact: false, message: check.message }); status.dirty(); } } else if (check.kind === "max") { if (input.data.length > check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, exact: false, message: check.message }); status.dirty(); } } else if (check.kind === "length") { const tooBig = input.data.length > check.value; const tooSmall = input.data.length < check.value; if (tooBig || tooSmall) { ctx = this._getOrReturnCtx(input, ctx); if (tooBig) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, exact: true, message: check.message }); } else if (tooSmall) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, exact: true, message: check.message }); } status.dirty(); } } else if (check.kind === "email") { if (!emailRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "email", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "emoji") { if (!emojiRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "emoji", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "uuid") { if (!uuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "uuid", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "cuid") { if (!cuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "cuid2") { if (!cuid2Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "cuid2", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "ulid") { if (!ulidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ulid", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "url") { try { new URL(input.data); } catch (_a) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "url", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "regex") { check.regex.lastIndex = 0; const testResult = check.regex.test(input.data); if (!testResult) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "regex", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "trim") { input.data = input.data.trim(); } else if (check.kind === "includes") { if (!input.data.includes(check.value, check.position)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { includes: check.value, position: check.position }, message: check.message }); status.dirty(); } } else if (check.kind === "toLowerCase") { input.data = input.data.toLowerCase(); } else if (check.kind === "toUpperCase") { input.data = input.data.toUpperCase(); } else if (check.kind === "startsWith") { if (!input.data.startsWith(check.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { startsWith: check.value }, message: check.message }); status.dirty(); } } else if (check.kind === "endsWith") { if (!input.data.endsWith(check.value)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { endsWith: check.value }, message: check.message }); status.dirty(); } } else if (check.kind === "datetime") { const regex = datetimeRegex(check); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "datetime", message: check.message }); status.dirty(); } } else if (check.kind === "ip") { if (!isValidIP(input.data, check.version)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { validation: "ip", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: input.data }; } _addCheck(check) { return new ZodString({ ...this._def, checks: [...this._def.checks, check] }); } email(message) { return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); } url(message) { return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); } emoji(message) { return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); } uuid(message) { return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); } cuid(message) { return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); } cuid2(message) { return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); } ulid(message) { return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); } ip(options) { return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); } datetime(options) { var _a; if (typeof options === "string") { return this._addCheck({ kind: "datetime", precision: null, offset: false, message: options }); } return this._addCheck({ kind: "datetime", precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) }); } regex(regex, message) { return this._addCheck({ kind: "regex", regex, ...errorUtil.errToObj(message) }); } includes(value, options) { return this._addCheck({ kind: "includes", value, position: options === null || options === void 0 ? void 0 : options.position, ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) }); } startsWith(value, message) { return this._addCheck({ kind: "startsWith", value, ...errorUtil.errToObj(message) }); } endsWith(value, message) { return this._addCheck({ kind: "endsWith", value, ...errorUtil.errToObj(message) }); } min(minLength, message) { return this._addCheck({ kind: "min", value: minLength, ...errorUtil.errToObj(message) }); } max(maxLength, message) { return this._addCheck({ kind: "max", value: maxLength, ...errorUtil.errToObj(message) }); } length(len, message) { return this._addCheck({ kind: "length", value: len, ...errorUtil.errToObj(message) }); } get isDatetime() { return !!this._def.checks.find((ch) => ch.kind === "datetime"); } get isEmail() { return !!this._def.checks.find((ch) => ch.kind === "email"); } get isURL() { return !!this._def.checks.find((ch) => ch.kind === "url"); } get isEmoji() { return !!this._def.checks.find((ch) => ch.kind === "emoji"); } get isUUID() { return !!this._def.checks.find((ch) => ch.kind === "uuid"); } get isCUID() { return !!this._def.checks.find((ch) => ch.kind === "cuid"); } get isCUID2() { return !!this._def.checks.find((ch) => ch.kind === "cuid2"); } get isULID() { return !!this._def.checks.find((ch) => ch.kind === "ulid"); } get isIP() { return !!this._def.checks.find((ch) => ch.kind === "ip"); } get minLength() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxLength() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } }; ZodString.create = (params) => { var _a; return new ZodString({ checks: [], typeName: ZodFirstPartyTypeKind.ZodString, coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, ...processCreateParams(params) }); }; function floatSafeRemainder(val, step) { const valDecCount = (val.toString().split(".")[1] || "").length; const stepDecCount = (step.toString().split(".")[1] || "").length; const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); return valInt % stepInt / Math.pow(10, decCount); } var ZodNumber = class extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; this.step = this.multipleOf; } _parse(input) { if (this._def.coerce) { input.data = Number(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.number) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.number, received: ctx2.parsedType }); return INVALID; } let ctx = void 0; const status = new ParseStatus(); for (const check of this._def.checks) { if (check.kind === "int") { if (!util.isInteger(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: "integer", received: "float", message: check.message }); status.dirty(); } } else if (check.kind === "min") { const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: check.value, type: "number", inclusive: check.inclusive, exact: false, message: check.message }); status.dirty(); } } else if (check.kind === "max") { const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: check.value, type: "number", inclusive: check.inclusive, exact: false, message: check.message }); status.dirty(); } } else if (check.kind === "multipleOf") { if (floatSafeRemainder(input.data, check.value) !== 0) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message }); status.dirty(); } } else if (check.kind === "finite") { if (!Number.isFinite(input.data)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_finite, message: check.message }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message) } ] }); } _addCheck(check) { return new ZodNumber({ ...this._def, checks: [...this._def.checks, check] }); } int(message) { return this._addCheck({ kind: "int", message: errorUtil.toString(message) }); } positive(message) { return this._addCheck({ kind: "min", value: 0, inclusive: false, message: errorUtil.toString(message) }); } negative(message) { return this._addCheck({ kind: "max", value: 0, inclusive: false, message: errorUtil.toString(message) }); } nonpositive(message) { return this._addCheck({ kind: "max", value: 0, inclusive: true, message: errorUtil.toString(message) }); } nonnegative(message) { return this._addCheck({ kind: "min", value: 0, inclusive: true, message: errorUtil.toString(message) }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil.toString(message) }); } finite(message) { return this._addCheck({ kind: "finite", message: errorUtil.toString(message) }); } safe(message) { return this._addCheck({ kind: "min", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: errorUtil.toString(message) })._addCheck({ kind: "max", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: errorUtil.toString(message) }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } get isInt() { return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); } get isFinite() { let max = null, min = null; for (const ch of this._def.checks) { if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { return true; } else if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } else if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return Number.isFinite(min) && Number.isFinite(max); } }; ZodNumber.create = (params) => { return new ZodNumber({ checks: [], typeName: ZodFirstPartyTypeKind.ZodNumber, coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, ...processCreateParams(params) }); }; var ZodBigInt = class extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; } _parse(input) { if (this._def.coerce) { input.data = BigInt(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.bigint) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.bigint, received: ctx2.parsedType }); return INVALID; } let ctx = void 0; const status = new ParseStatus(); for (const check of this._def.checks) { if (check.kind === "min") { const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, type: "bigint", minimum: check.value, inclusive: check.inclusive, message: check.message }); status.dirty(); } } else if (check.kind === "max") { const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, type: "bigint", maximum: check.value, inclusive: check.inclusive, message: check.message }); status.dirty(); } } else if (check.kind === "multipleOf") { if (input.data % check.value !== BigInt(0)) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new ZodBigInt({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil.toString(message) } ] }); } _addCheck(check) { return new ZodBigInt({ ...this._def, checks: [...this._def.checks, check] }); } positive(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: false, message: errorUtil.toString(message) }); } negative(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: false, message: errorUtil.toString(message) }); } nonpositive(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: true, message: errorUtil.toString(message) }); } nonnegative(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: true, message: errorUtil.toString(message) }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil.toString(message) }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } }; ZodBigInt.create = (params) => { var _a; return new ZodBigInt({ checks: [], typeName: ZodFirstPartyTypeKind.ZodBigInt, coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, ...processCreateParams(params) }); }; var ZodBoolean = class extends ZodType { _parse(input) { if (this._def.coerce) { input.data = Boolean(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.boolean) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.boolean, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodBoolean.create = (params) => { return new ZodBoolean({ typeName: ZodFirstPartyTypeKind.ZodBoolean, coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, ...processCreateParams(params) }); }; var ZodDate = class extends ZodType { _parse(input) { if (this._def.coerce) { input.data = new Date(input.data); } const parsedType = this._getType(input); if (parsedType !== ZodParsedType.date) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.date, received: ctx2.parsedType }); return INVALID; } if (isNaN(input.data.getTime())) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_date }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const check of this._def.checks) { if (check.kind === "min") { if (input.data.getTime() < check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_small, message: check.message, inclusive: true, exact: false, minimum: check.value, type: "date" }); status.dirty(); } } else if (check.kind === "max") { if (input.data.getTime() > check.value) { ctx = this._getOrReturnCtx(input, ctx); addIssueToContext(ctx, { code: ZodIssueCode.too_big, message: check.message, inclusive: true, exact: false, maximum: check.value, type: "date" }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: new Date(input.data.getTime()) }; } _addCheck(check) { return new ZodDate({ ...this._def, checks: [...this._def.checks, check] }); } min(minDate, message) { return this._addCheck({ kind: "min", value: minDate.getTime(), message: errorUtil.toString(message) }); } max(maxDate, message) { return this._addCheck({ kind: "max", value: maxDate.getTime(), message: errorUtil.toString(message) }); } get minDate() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min != null ? new Date(min) : null; } get maxDate() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max != null ? new Date(max) : null; } }; ZodDate.create = (params) => { return new ZodDate({ checks: [], coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, typeName: ZodFirstPartyTypeKind.ZodDate, ...processCreateParams(params) }); }; var ZodSymbol = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.symbol) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.symbol, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodSymbol.create = (params) => { return new ZodSymbol({ typeName: ZodFirstPartyTypeKind.ZodSymbol, ...processCreateParams(params) }); }; var ZodUndefined = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.undefined, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodUndefined.create = (params) => { return new ZodUndefined({ typeName: ZodFirstPartyTypeKind.ZodUndefined, ...processCreateParams(params) }); }; var ZodNull = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.null) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.null, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodNull.create = (params) => { return new ZodNull({ typeName: ZodFirstPartyTypeKind.ZodNull, ...processCreateParams(params) }); }; var ZodAny = class extends ZodType { constructor() { super(...arguments); this._any = true; } _parse(input) { return OK(input.data); } }; ZodAny.create = (params) => { return new ZodAny({ typeName: ZodFirstPartyTypeKind.ZodAny, ...processCreateParams(params) }); }; var ZodUnknown = class extends ZodType { constructor() { super(...arguments); this._unknown = true; } _parse(input) { return OK(input.data); } }; ZodUnknown.create = (params) => { return new ZodUnknown({ typeName: ZodFirstPartyTypeKind.ZodUnknown, ...processCreateParams(params) }); }; var ZodNever = class extends ZodType { _parse(input) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.never, received: ctx.parsedType }); return INVALID; } }; ZodNever.create = (params) => { return new ZodNever({ typeName: ZodFirstPartyTypeKind.ZodNever, ...processCreateParams(params) }); }; var ZodVoid = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.void, received: ctx.parsedType }); return INVALID; } return OK(input.data); } }; ZodVoid.create = (params) => { return new ZodVoid({ typeName: ZodFirstPartyTypeKind.ZodVoid, ...processCreateParams(params) }); }; var ZodArray = class extends ZodType { _parse(input) { const { ctx, status } = this._processInputParams(input); const def = this._def; if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType }); return INVALID; } if (def.exactLength !== null) { const tooBig = ctx.data.length > def.exactLength.value; const tooSmall = ctx.data.length < def.exactLength.value; if (tooBig || tooSmall) { addIssueToContext(ctx, { code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, minimum: tooSmall ? def.exactLength.value : void 0, maximum: tooBig ? def.exactLength.value : void 0, type: "array", inclusive: true, exact: true, message: def.exactLength.message }); status.dirty(); } } if (def.minLength !== null) { if (ctx.data.length < def.minLength.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minLength.value, type: "array", inclusive: true, exact: false, message: def.minLength.message }); status.dirty(); } } if (def.maxLength !== null) { if (ctx.data.length > def.maxLength.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxLength.value, type: "array", inclusive: true, exact: false, message: def.maxLength.message }); status.dirty(); } } if (ctx.common.async) { return Promise.all([...ctx.data].map((item, i2) => { return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i2)); })).then((result2) => { return ParseStatus.mergeArray(status, result2); }); } const result = [...ctx.data].map((item, i2) => { return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i2)); }); return ParseStatus.mergeArray(status, result); } get element() { return this._def.type; } min(minLength, message) { return new ZodArray({ ...this._def, minLength: { value: minLength, message: errorUtil.toString(message) } }); } max(maxLength, message) { return new ZodArray({ ...this._def, maxLength: { value: maxLength, message: errorUtil.toString(message) } }); } length(len, message) { return new ZodArray({ ...this._def, exactLength: { value: len, message: errorUtil.toString(message) } }); } nonempty(message) { return this.min(1, message); } }; ZodArray.create = (schema2, params) => { return new ZodArray({ type: schema2, minLength: null, maxLength: null, exactLength: null, typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(params) }); }; function deepPartialify(schema2) { if (schema2 instanceof ZodObject) { const newShape = {}; for (const key in schema2.shape) { const fieldSchema = schema2.shape[key]; newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); } return new ZodObject({ ...schema2._def, shape: () => newShape }); } else if (schema2 instanceof ZodArray) { return new ZodArray({ ...schema2._def, type: deepPartialify(schema2.element) }); } else if (schema2 instanceof ZodOptional) { return ZodOptional.create(deepPartialify(schema2.unwrap())); } else if (schema2 instanceof ZodNullable) { return ZodNullable.create(deepPartialify(schema2.unwrap())); } else if (schema2 instanceof ZodTuple) { return ZodTuple.create(schema2.items.map((item) => deepPartialify(item))); } else { return schema2; } } var ZodObject = class extends ZodType { constructor() { super(...arguments); this._cached = null; this.nonstrict = this.passthrough; this.augment = this.extend; } _getCached() { if (this._cached !== null) return this._cached; const shape = this._def.shape(); const keys = util.objectKeys(shape); return this._cached = { shape, keys }; } _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.object) { const ctx2 = this._getOrReturnCtx(input); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx2.parsedType }); return INVALID; } const { status, ctx } = this._processInputParams(input); const { shape, keys: shapeKeys } = this._getCached(); const extraKeys = []; if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { for (const key in ctx.data) { if (!shapeKeys.includes(key)) { extraKeys.push(key); } } } const pairs2 = []; for (const key of shapeKeys) { const keyValidator = shape[key]; const value = ctx.data[key]; pairs2.push({ key: { status: "valid", value: key }, value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), alwaysSet: key in ctx.data }); } if (this._def.catchall instanceof ZodNever) { const unknownKeys = this._def.unknownKeys; if (unknownKeys === "passthrough") { for (const key of extraKeys) { pairs2.push({ key: { status: "valid", value: key }, value: { status: "valid", value: ctx.data[key] } }); } } else if (unknownKeys === "strict") { if (extraKeys.length > 0) { addIssueToContext(ctx, { code: ZodIssueCode.unrecognized_keys, keys: extraKeys }); status.dirty(); } } else if (unknownKeys === "strip") ; else { throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } } else { const catchall = this._def.catchall; for (const key of extraKeys) { const value = ctx.data[key]; pairs2.push({ key: { status: "valid", value: key }, value: catchall._parse( new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) ), alwaysSet: key in ctx.data }); } } if (ctx.common.async) { return Promise.resolve().then(async () => { const syncPairs = []; for (const pair of pairs2) { const key = await pair.key; syncPairs.push({ key, value: await pair.value, alwaysSet: pair.alwaysSet }); } return syncPairs; }).then((syncPairs) => { return ParseStatus.mergeObjectSync(status, syncPairs); }); } else { return ParseStatus.mergeObjectSync(status, pairs2); } } get shape() { return this._def.shape(); } strict(message) { errorUtil.errToObj; return new ZodObject({ ...this._def, unknownKeys: "strict", ...message !== void 0 ? { errorMap: (issue, ctx) => { var _a, _b, _c, _d; const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; if (issue.code === "unrecognized_keys") return { message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError }; return { message: defaultError }; } } : {} }); } strip() { return new ZodObject({ ...this._def, unknownKeys: "strip" }); } passthrough() { return new ZodObject({ ...this._def, unknownKeys: "passthrough" }); } // const AugmentFactory = // (def: Def) => // ( // augmentation: Augmentation // ): ZodObject< // extendShape, Augmentation>, // Def["unknownKeys"], // Def["catchall"] // > => { // return new ZodObject({ // ...def, // shape: () => ({ // ...def.shape(), // ...augmentation, // }), // }) as any; // }; extend(augmentation) { return new ZodObject({ ...this._def, shape: () => ({ ...this._def.shape(), ...augmentation }) }); } /** * Prior to zod@1.0.12 there was a bug in the * inferred type of merged objects. Please * upgrade if you are experiencing issues. */ merge(merging) { const merged = new ZodObject({ unknownKeys: merging._def.unknownKeys, catchall: merging._def.catchall, shape: () => ({ ...this._def.shape(), ...merging._def.shape() }), typeName: ZodFirstPartyTypeKind.ZodObject }); return merged; } // merge< // Incoming extends AnyZodObject, // Augmentation extends Incoming["shape"], // NewOutput extends { // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation // ? Augmentation[k]["_output"] // : k extends keyof Output // ? Output[k] // : never; // }, // NewInput extends { // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation // ? Augmentation[k]["_input"] // : k extends keyof Input // ? Input[k] // : never; // } // >( // merging: Incoming // ): ZodObject< // extendShape>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"], // NewOutput, // NewInput // > { // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } setKey(key, schema2) { return this.augment({ [key]: schema2 }); } // merge( // merging: Incoming // ): //ZodObject = (merging) => { // ZodObject< // extendShape>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"] // > { // // const mergedShape = objectUtil.mergeShapes( // // this._def.shape(), // // merging._def.shape() // // ); // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } catchall(index2) { return new ZodObject({ ...this._def, catchall: index2 }); } pick(mask) { const shape = {}; util.objectKeys(mask).forEach((key) => { if (mask[key] && this.shape[key]) { shape[key] = this.shape[key]; } }); return new ZodObject({ ...this._def, shape: () => shape }); } omit(mask) { const shape = {}; util.objectKeys(this.shape).forEach((key) => { if (!mask[key]) { shape[key] = this.shape[key]; } }); return new ZodObject({ ...this._def, shape: () => shape }); } /** * @deprecated */ deepPartial() { return deepPartialify(this); } partial(mask) { const newShape = {}; util.objectKeys(this.shape).forEach((key) => { const fieldSchema = this.shape[key]; if (mask && !mask[key]) { newShape[key] = fieldSchema; } else { newShape[key] = fieldSchema.optional(); } }); return new ZodObject({ ...this._def, shape: () => newShape }); } required(mask) { const newShape = {}; util.objectKeys(this.shape).forEach((key) => { if (mask && !mask[key]) { newShape[key] = this.shape[key]; } else { const fieldSchema = this.shape[key]; let newField = fieldSchema; while (newField instanceof ZodOptional) { newField = newField._def.innerType; } newShape[key] = newField; } }); return new ZodObject({ ...this._def, shape: () => newShape }); } keyof() { return createZodEnum(util.objectKeys(this.shape)); } }; ZodObject.create = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject.strictCreate = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strict", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject.lazycreate = (shape, params) => { return new ZodObject({ shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; var ZodUnion = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const options = this._def.options; function handleResults(results) { for (const result of results) { if (result.result.status === "valid") { return result.result; } } for (const result of results) { if (result.result.status === "dirty") { ctx.common.issues.push(...result.ctx.common.issues); return result.result; } } const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors }); return INVALID; } if (ctx.common.async) { return Promise.all(options.map(async (option) => { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; return { result: await option._parseAsync({ data: ctx.data, path: ctx.path, parent: childCtx }), ctx: childCtx }; })).then(handleResults); } else { let dirty = void 0; const issues = []; for (const option of options) { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; const result = option._parseSync({ data: ctx.data, path: ctx.path, parent: childCtx }); if (result.status === "valid") { return result; } else if (result.status === "dirty" && !dirty) { dirty = { result, ctx: childCtx }; } if (childCtx.common.issues.length) { issues.push(childCtx.common.issues); } } if (dirty) { ctx.common.issues.push(...dirty.ctx.common.issues); return dirty.result; } const unionErrors = issues.map((issues2) => new ZodError(issues2)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors }); return INVALID; } } get options() { return this._def.options; } }; ZodUnion.create = (types, params) => { return new ZodUnion({ options: types, typeName: ZodFirstPartyTypeKind.ZodUnion, ...processCreateParams(params) }); }; var getDiscriminator = (type2) => { if (type2 instanceof ZodLazy) { return getDiscriminator(type2.schema); } else if (type2 instanceof ZodEffects) { return getDiscriminator(type2.innerType()); } else if (type2 instanceof ZodLiteral) { return [type2.value]; } else if (type2 instanceof ZodEnum) { return type2.options; } else if (type2 instanceof ZodNativeEnum) { return Object.keys(type2.enum); } else if (type2 instanceof ZodDefault) { return getDiscriminator(type2._def.innerType); } else if (type2 instanceof ZodUndefined) { return [void 0]; } else if (type2 instanceof ZodNull) { return [null]; } else { return null; } }; var ZodDiscriminatedUnion = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType }); return INVALID; } const discriminator = this.discriminator; const discriminatorValue = ctx.data[discriminator]; const option = this.optionsMap.get(discriminatorValue); if (!option) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [discriminator] }); return INVALID; } if (ctx.common.async) { return option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); } else { return option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); } } get discriminator() { return this._def.discriminator; } get options() { return this._def.options; } get optionsMap() { return this._def.optionsMap; } /** * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must * have a different value for each object in the union. * @param discriminator the name of the discriminator property * @param types an array of object schemas * @param params */ static create(discriminator, options, params) { const optionsMap = /* @__PURE__ */ new Map(); for (const type2 of options) { const discriminatorValues = getDiscriminator(type2.shape[discriminator]); if (!discriminatorValues) { throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); } for (const value of discriminatorValues) { if (optionsMap.has(value)) { throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); } optionsMap.set(value, type2); } } return new ZodDiscriminatedUnion({ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, discriminator, options, optionsMap, ...processCreateParams(params) }); } }; function mergeValues(a3, b2) { const aType = getParsedType(a3); const bType = getParsedType(b2); if (a3 === b2) { return { valid: true, data: a3 }; } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { const bKeys = util.objectKeys(b2); const sharedKeys = util.objectKeys(a3).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a3, ...b2 }; for (const key of sharedKeys) { const sharedValue = mergeValues(a3[key], b2[key]); if (!sharedValue.valid) { return { valid: false }; } newObj[key] = sharedValue.data; } return { valid: true, data: newObj }; } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { if (a3.length !== b2.length) { return { valid: false }; } const newArray = []; for (let index2 = 0; index2 < a3.length; index2++) { const itemA = a3[index2]; const itemB = b2[index2]; const sharedValue = mergeValues(itemA, itemB); if (!sharedValue.valid) { return { valid: false }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a3 === +b2) { return { valid: true, data: a3 }; } else { return { valid: false }; } } var ZodIntersection = class extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); const handleParsed = (parsedLeft, parsedRight) => { if (isAborted(parsedLeft) || isAborted(parsedRight)) { return INVALID; } const merged = mergeValues(parsedLeft.value, parsedRight.value); if (!merged.valid) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_intersection_types }); return INVALID; } if (isDirty(parsedLeft) || isDirty(parsedRight)) { status.dirty(); } return { status: status.value, value: merged.data }; }; if (ctx.common.async) { return Promise.all([ this._def.left._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) ]).then(([left, right]) => handleParsed(left, right)); } else { return handleParsed(this._def.left._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseSync({ data: ctx.data, path: ctx.path, parent: ctx })); } } }; ZodIntersection.create = (left, right, params) => { return new ZodIntersection({ left, right, typeName: ZodFirstPartyTypeKind.ZodIntersection, ...processCreateParams(params) }); }; var ZodTuple = class extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType }); return INVALID; } if (ctx.data.length < this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array" }); return INVALID; } const rest = this._def.rest; if (!rest && ctx.data.length > this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array" }); status.dirty(); } const items = [...ctx.data].map((item, itemIndex) => { const schema2 = this._def.items[itemIndex] || this._def.rest; if (!schema2) return null; return schema2._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); }).filter((x2) => !!x2); if (ctx.common.async) { return Promise.all(items).then((results) => { return ParseStatus.mergeArray(status, results); }); } else { return ParseStatus.mergeArray(status, items); } } get items() { return this._def.items; } rest(rest) { return new ZodTuple({ ...this._def, rest }); } }; ZodTuple.create = (schemas, params) => { if (!Array.isArray(schemas)) { throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } return new ZodTuple({ items: schemas, typeName: ZodFirstPartyTypeKind.ZodTuple, rest: null, ...processCreateParams(params) }); }; var ZodRecord = class extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.object) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx.parsedType }); return INVALID; } const pairs2 = []; const keyType = this._def.keyType; const valueType = this._def.valueType; for (const key in ctx.data) { pairs2.push({ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)) }); } if (ctx.common.async) { return ParseStatus.mergeObjectAsync(status, pairs2); } else { return ParseStatus.mergeObjectSync(status, pairs2); } } get element() { return this._def.valueType; } static create(first, second, third) { if (second instanceof ZodType) { return new ZodRecord({ keyType: first, valueType: second, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(third) }); } return new ZodRecord({ keyType: ZodString.create(), valueType: first, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(second) }); } }; var ZodMap = class extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.map) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.map, received: ctx.parsedType }); return INVALID; } const keyType = this._def.keyType; const valueType = this._def.valueType; const pairs2 = [...ctx.data.entries()].map(([key, value], index2) => { return { key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])), value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"])) }; }); if (ctx.common.async) { const finalMap = /* @__PURE__ */ new Map(); return Promise.resolve().then(async () => { for (const pair of pairs2) { const key = await pair.key; const value = await pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; }); } else { const finalMap = /* @__PURE__ */ new Map(); for (const pair of pairs2) { const key = pair.key; const value = pair.value; if (key.status === "aborted" || value.status === "aborted") { return INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; } } }; ZodMap.create = (keyType, valueType, params) => { return new ZodMap({ valueType, keyType, typeName: ZodFirstPartyTypeKind.ZodMap, ...processCreateParams(params) }); }; var ZodSet = class extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.set) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.set, received: ctx.parsedType }); return INVALID; } const def = this._def; if (def.minSize !== null) { if (ctx.data.size < def.minSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def.minSize.value, type: "set", inclusive: true, exact: false, message: def.minSize.message }); status.dirty(); } } if (def.maxSize !== null) { if (ctx.data.size > def.maxSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def.maxSize.value, type: "set", inclusive: true, exact: false, message: def.maxSize.message }); status.dirty(); } } const valueType = this._def.valueType; function finalizeSet(elements2) { const parsedSet = /* @__PURE__ */ new Set(); for (const element2 of elements2) { if (element2.status === "aborted") return INVALID; if (element2.status === "dirty") status.dirty(); parsedSet.add(element2.value); } return { status: status.value, value: parsedSet }; } const elements = [...ctx.data.values()].map((item, i2) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i2))); if (ctx.common.async) { return Promise.all(elements).then((elements2) => finalizeSet(elements2)); } else { return finalizeSet(elements); } } min(minSize, message) { return new ZodSet({ ...this._def, minSize: { value: minSize, message: errorUtil.toString(message) } }); } max(maxSize, message) { return new ZodSet({ ...this._def, maxSize: { value: maxSize, message: errorUtil.toString(message) } }); } size(size, message) { return this.min(size, message).max(size, message); } nonempty(message) { return this.min(1, message); } }; ZodSet.create = (valueType, params) => { return new ZodSet({ valueType, minSize: null, maxSize: null, typeName: ZodFirstPartyTypeKind.ZodSet, ...processCreateParams(params) }); }; var ZodFunction = class extends ZodType { constructor() { super(...arguments); this.validate = this.implement; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.function) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.function, received: ctx.parsedType }); return INVALID; } function makeArgsIssue(args, error) { return makeIssue({ data: args, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap ].filter((x2) => !!x2), issueData: { code: ZodIssueCode.invalid_arguments, argumentsError: error } }); } function makeReturnsIssue(returns, error) { return makeIssue({ data: returns, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), errorMap ].filter((x2) => !!x2), issueData: { code: ZodIssueCode.invalid_return_type, returnTypeError: error } }); } const params = { errorMap: ctx.common.contextualErrorMap }; const fn = ctx.data; if (this._def.returns instanceof ZodPromise) { const me = this; return OK(async function(...args) { const error = new ZodError([]); const parsedArgs = await me._def.args.parseAsync(args, params).catch((e2) => { error.addIssue(makeArgsIssue(args, e2)); throw error; }); const result = await Reflect.apply(fn, this, parsedArgs); const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e2) => { error.addIssue(makeReturnsIssue(result, e2)); throw error; }); return parsedReturns; }); } else { const me = this; return OK(function(...args) { const parsedArgs = me._def.args.safeParse(args, params); if (!parsedArgs.success) { throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); } const result = Reflect.apply(fn, this, parsedArgs.data); const parsedReturns = me._def.returns.safeParse(result, params); if (!parsedReturns.success) { throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); } return parsedReturns.data; }); } } parameters() { return this._def.args; } returnType() { return this._def.returns; } args(...items) { return new ZodFunction({ ...this._def, args: ZodTuple.create(items).rest(ZodUnknown.create()) }); } returns(returnType) { return new ZodFunction({ ...this._def, returns: returnType }); } implement(func) { const validatedFunc = this.parse(func); return validatedFunc; } strictImplement(func) { const validatedFunc = this.parse(func); return validatedFunc; } static create(args, returns, params) { return new ZodFunction({ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), returns: returns || ZodUnknown.create(), typeName: ZodFirstPartyTypeKind.ZodFunction, ...processCreateParams(params) }); } }; var ZodLazy = class extends ZodType { get schema() { return this._def.getter(); } _parse(input) { const { ctx } = this._processInputParams(input); const lazySchema = this._def.getter(); return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } }; ZodLazy.create = (getter, params) => { return new ZodLazy({ getter, typeName: ZodFirstPartyTypeKind.ZodLazy, ...processCreateParams(params) }); }; var ZodLiteral = class extends ZodType { _parse(input) { if (input.data !== this._def.value) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_literal, expected: this._def.value }); return INVALID; } return { status: "valid", value: input.data }; } get value() { return this._def.value; } }; ZodLiteral.create = (value, params) => { return new ZodLiteral({ value, typeName: ZodFirstPartyTypeKind.ZodLiteral, ...processCreateParams(params) }); }; function createZodEnum(values, params) { return new ZodEnum({ values, typeName: ZodFirstPartyTypeKind.ZodEnum, ...processCreateParams(params) }); } var ZodEnum = class extends ZodType { _parse(input) { if (typeof input.data !== "string") { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type }); return INVALID; } if (this._def.values.indexOf(input.data) === -1) { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input.data); } get options() { return this._def.values; } get enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Values() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } extract(values) { return ZodEnum.create(values); } exclude(values) { return ZodEnum.create(this.options.filter((opt) => !values.includes(opt))); } }; ZodEnum.create = createZodEnum; var ZodNativeEnum = class extends ZodType { _parse(input) { const nativeEnumValues = util.getValidEnumValues(this._def.values); const ctx = this._getOrReturnCtx(input); if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { expected: util.joinValues(expectedValues), received: ctx.parsedType, code: ZodIssueCode.invalid_type }); return INVALID; } if (nativeEnumValues.indexOf(input.data) === -1) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input.data); } get enum() { return this._def.values; } }; ZodNativeEnum.create = (values, params) => { return new ZodNativeEnum({ values, typeName: ZodFirstPartyTypeKind.ZodNativeEnum, ...processCreateParams(params) }); }; var ZodPromise = class extends ZodType { unwrap() { return this._def.type; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.promise, received: ctx.parsedType }); return INVALID; } const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); return OK(promisified.then((data) => { return this._def.type.parseAsync(data, { path: ctx.path, errorMap: ctx.common.contextualErrorMap }); })); } }; ZodPromise.create = (schema2, params) => { return new ZodPromise({ type: schema2, typeName: ZodFirstPartyTypeKind.ZodPromise, ...processCreateParams(params) }); }; var ZodEffects = class extends ZodType { innerType() { return this._def.schema; } sourceType() { return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; } _parse(input) { const { status, ctx } = this._processInputParams(input); const effect = this._def.effect || null; const checkCtx = { addIssue: (arg) => { addIssueToContext(ctx, arg); if (arg.fatal) { status.abort(); } else { status.dirty(); } }, get path() { return ctx.path; } }; checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); if (effect.type === "preprocess") { const processed = effect.transform(ctx.data, checkCtx); if (ctx.common.issues.length) { return { status: "dirty", value: ctx.data }; } if (ctx.common.async) { return Promise.resolve(processed).then((processed2) => { return this._def.schema._parseAsync({ data: processed2, path: ctx.path, parent: ctx }); }); } else { return this._def.schema._parseSync({ data: processed, path: ctx.path, parent: ctx }); } } if (effect.type === "refinement") { const executeRefinement = (acc) => { const result = effect.refinement(acc, checkCtx); if (ctx.common.async) { return Promise.resolve(result); } if (result instanceof Promise) { throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); } return acc; }; if (ctx.common.async === false) { const inner = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); executeRefinement(inner.value); return { status: status.value, value: inner.value }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); return executeRefinement(inner.value).then(() => { return { status: status.value, value: inner.value }; }); }); } } if (effect.type === "transform") { if (ctx.common.async === false) { const base = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (!isValid(base)) return base; const result = effect.transform(base.value, checkCtx); if (result instanceof Promise) { throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); } return { status: status.value, value: result }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { if (!isValid(base)) return base; return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); }); } } util.assertNever(effect); } }; ZodEffects.create = (schema2, effect, params) => { return new ZodEffects({ schema: schema2, typeName: ZodFirstPartyTypeKind.ZodEffects, effect, ...processCreateParams(params) }); }; ZodEffects.createWithPreprocess = (preprocess2, schema2, params) => { return new ZodEffects({ schema: schema2, effect: { type: "preprocess", transform: preprocess2 }, typeName: ZodFirstPartyTypeKind.ZodEffects, ...processCreateParams(params) }); }; var ZodOptional = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.undefined) { return OK(void 0); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; ZodOptional.create = (type2, params) => { return new ZodOptional({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(params) }); }; var ZodNullable = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === ZodParsedType.null) { return OK(null); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; ZodNullable.create = (type2, params) => { return new ZodNullable({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodNullable, ...processCreateParams(params) }); }; var ZodDefault = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); let data = ctx.data; if (ctx.parsedType === ZodParsedType.undefined) { data = this._def.defaultValue(); } return this._def.innerType._parse({ data, path: ctx.path, parent: ctx }); } removeDefault() { return this._def.innerType; } }; ZodDefault.create = (type2, params) => { return new ZodDefault({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodDefault, defaultValue: typeof params.default === "function" ? params.default : () => params.default, ...processCreateParams(params) }); }; var ZodCatch = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const newCtx = { ...ctx, common: { ...ctx.common, issues: [] } }; const result = this._def.innerType._parse({ data: newCtx.data, path: newCtx.path, parent: { ...newCtx } }); if (isAsync(result)) { return result.then((result2) => { return { status: "valid", value: result2.status === "valid" ? result2.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data }) }; }); } else { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data }) }; } } removeCatch() { return this._def.innerType; } }; ZodCatch.create = (type2, params) => { return new ZodCatch({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodCatch, catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, ...processCreateParams(params) }); }; var ZodNaN = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== ZodParsedType.nan) { const ctx = this._getOrReturnCtx(input); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.nan, received: ctx.parsedType }); return INVALID; } return { status: "valid", value: input.data }; } }; ZodNaN.create = (params) => { return new ZodNaN({ typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(params) }); }; var BRAND = Symbol("zod_brand"); var ZodBranded = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const data = ctx.data; return this._def.type._parse({ data, path: ctx.path, parent: ctx }); } unwrap() { return this._def.type; } }; var ZodPipeline = class extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.common.async) { const handleAsync = async () => { const inResult = await this._def.in._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return DIRTY(inResult.value); } else { return this._def.out._parseAsync({ data: inResult.value, path: ctx.path, parent: ctx }); } }; return handleAsync(); } else { const inResult = this._def.in._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return INVALID; if (inResult.status === "dirty") { status.dirty(); return { status: "dirty", value: inResult.value }; } else { return this._def.out._parseSync({ data: inResult.value, path: ctx.path, parent: ctx }); } } } static create(a3, b2) { return new ZodPipeline({ in: a3, out: b2, typeName: ZodFirstPartyTypeKind.ZodPipeline }); } }; var ZodReadonly = class extends ZodType { _parse(input) { const result = this._def.innerType._parse(input); if (isValid(result)) { result.value = Object.freeze(result.value); } return result; } }; ZodReadonly.create = (type2, params) => { return new ZodReadonly({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodReadonly, ...processCreateParams(params) }); }; var custom = (check, params = {}, fatal) => { if (check) return ZodAny.create().superRefine((data, ctx) => { var _a, _b; if (!check(data)) { const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; const p2 = typeof p === "string" ? { message: p } : p; ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); } }); return ZodAny.create(); }; var late = { object: ZodObject.lazycreate }; var ZodFirstPartyTypeKind; (function(ZodFirstPartyTypeKind2) { ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); var instanceOfType = (cls, params = { message: `Input not instance of ${cls.name}` }) => custom((data) => data instanceof cls, params); var stringType = ZodString.create; var numberType = ZodNumber.create; var nanType = ZodNaN.create; var bigIntType = ZodBigInt.create; var booleanType = ZodBoolean.create; var dateType = ZodDate.create; var symbolType = ZodSymbol.create; var undefinedType = ZodUndefined.create; var nullType = ZodNull.create; var anyType = ZodAny.create; var unknownType = ZodUnknown.create; var neverType = ZodNever.create; var voidType = ZodVoid.create; var arrayType = ZodArray.create; var objectType = ZodObject.create; var strictObjectType = ZodObject.strictCreate; var unionType = ZodUnion.create; var discriminatedUnionType = ZodDiscriminatedUnion.create; var intersectionType = ZodIntersection.create; var tupleType = ZodTuple.create; var recordType = ZodRecord.create; var mapType = ZodMap.create; var setType = ZodSet.create; var functionType = ZodFunction.create; var lazyType = ZodLazy.create; var literalType = ZodLiteral.create; var enumType = ZodEnum.create; var nativeEnumType = ZodNativeEnum.create; var promiseType = ZodPromise.create; var effectsType = ZodEffects.create; var optionalType = ZodOptional.create; var nullableType = ZodNullable.create; var preprocessType = ZodEffects.createWithPreprocess; var pipelineType = ZodPipeline.create; var ostring = () => stringType().optional(); var onumber = () => numberType().optional(); var oboolean = () => booleanType().optional(); var coerce = { string: (arg) => ZodString.create({ ...arg, coerce: true }), number: (arg) => ZodNumber.create({ ...arg, coerce: true }), boolean: (arg) => ZodBoolean.create({ ...arg, coerce: true }), bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }), date: (arg) => ZodDate.create({ ...arg, coerce: true }) }; var NEVER = INVALID; var z = /* @__PURE__ */ Object.freeze({ __proto__: null, defaultErrorMap: errorMap, setErrorMap, getErrorMap, makeIssue, EMPTY_PATH, addIssueToContext, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync, get util() { return util; }, get objectUtil() { return objectUtil; }, ZodParsedType, getParsedType, ZodType, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodTransformer: ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, custom, Schema: ZodType, ZodSchema: ZodType, late, get ZodFirstPartyTypeKind() { return ZodFirstPartyTypeKind; }, coerce, any: anyType, array: arrayType, bigint: bigIntType, boolean: booleanType, date: dateType, discriminatedUnion: discriminatedUnionType, effect: effectsType, "enum": enumType, "function": functionType, "instanceof": instanceOfType, intersection: intersectionType, lazy: lazyType, literal: literalType, map: mapType, nan: nanType, nativeEnum: nativeEnumType, never: neverType, "null": nullType, nullable: nullableType, number: numberType, object: objectType, oboolean, onumber, optional: optionalType, ostring, pipeline: pipelineType, preprocess: preprocessType, promise: promiseType, record: recordType, set: setType, strictObject: strictObjectType, string: stringType, symbol: symbolType, transformer: effectsType, tuple: tupleType, "undefined": undefinedType, union: unionType, unknown: unknownType, "void": voidType, NEVER, ZodIssueCode, quotelessJson, ZodError }); // src/utils/evalFromExpression.ts var AsyncFunction = Object.getPrototypeOf(async function() { }).constructor; var primativeSchema = z.string().or(z.number()).or(z.boolean()).or(z.bigint()).or(z.date()).or(z.undefined()).or(z.null()); function evalFromExpression(expression, isFunctionBody, context) { var _a; try { const ast = (0, import_recast.parse)(expression, { parser: require_babel2() }); const func = new (((_a = JSON.stringify(ast.program.body)) == null ? void 0 : _a.includes("AwaitExpression")) ? AsyncFunction : Function)( ...Object.keys(context).sort(), esm_default(!isFunctionBody ? `return ${expression}` : expression) ); const result = func( ...Object.keys(context).sort().map((key) => context[key]) ); return { success: true, result }; } catch (e2) { return { success: false, error: { cause: e2, message: e2.message } }; } } // node_modules/@babel/runtime/helpers/esm/typeof.js function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) { return typeof o2; } : function(o2) { return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2; }, _typeof(o); } // node_modules/date-fns/esm/_lib/toInteger/index.js function toInteger(dirtyNumber) { if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) { return NaN; } var number = Number(dirtyNumber); if (isNaN(number)) { return number; } return number < 0 ? Math.ceil(number) : Math.floor(number); } // node_modules/date-fns/esm/_lib/requiredArgs/index.js function requiredArgs(required, args) { if (args.length < required) { throw new TypeError(required + " argument" + (required > 1 ? "s" : "") + " required, but only " + args.length + " present"); } } // node_modules/date-fns/esm/toDate/index.js function toDate(argument) { requiredArgs(1, arguments); var argStr = Object.prototype.toString.call(argument); if (argument instanceof Date || _typeof(argument) === "object" && argStr === "[object Date]") { return new Date(argument.getTime()); } else if (typeof argument === "number" || argStr === "[object Number]") { return new Date(argument); } else { if ((typeof argument === "string" || argStr === "[object String]") && typeof console !== "undefined") { console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"); console.warn(new Error().stack); } return new Date(NaN); } } // node_modules/date-fns/esm/addMilliseconds/index.js function addMilliseconds(dirtyDate, dirtyAmount) { requiredArgs(2, arguments); var timestamp2 = toDate(dirtyDate).getTime(); var amount = toInteger(dirtyAmount); return new Date(timestamp2 + amount); } // node_modules/date-fns/esm/_lib/defaultOptions/index.js var defaultOptions = {}; function getDefaultOptions() { return defaultOptions; } // node_modules/date-fns/esm/_lib/getTimezoneOffsetInMilliseconds/index.js function getTimezoneOffsetInMilliseconds(date) { var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds())); utcDate.setUTCFullYear(date.getFullYear()); return date.getTime() - utcDate.getTime(); } // node_modules/date-fns/esm/isDate/index.js function isDate(value) { requiredArgs(1, arguments); return value instanceof Date || _typeof(value) === "object" && Object.prototype.toString.call(value) === "[object Date]"; } // node_modules/date-fns/esm/isValid/index.js function isValid2(dirtyDate) { requiredArgs(1, arguments); if (!isDate(dirtyDate) && typeof dirtyDate !== "number") { return false; } var date = toDate(dirtyDate); return !isNaN(Number(date)); } // node_modules/date-fns/esm/subMilliseconds/index.js function subMilliseconds(dirtyDate, dirtyAmount) { requiredArgs(2, arguments); var amount = toInteger(dirtyAmount); return addMilliseconds(dirtyDate, -amount); } // node_modules/date-fns/esm/_lib/getUTCDayOfYear/index.js var MILLISECONDS_IN_DAY = 864e5; function getUTCDayOfYear(dirtyDate) { requiredArgs(1, arguments); var date = toDate(dirtyDate); var timestamp2 = date.getTime(); date.setUTCMonth(0, 1); date.setUTCHours(0, 0, 0, 0); var startOfYearTimestamp = date.getTime(); var difference = timestamp2 - startOfYearTimestamp; return Math.floor(difference / MILLISECONDS_IN_DAY) + 1; } // node_modules/date-fns/esm/_lib/startOfUTCISOWeek/index.js function startOfUTCISOWeek(dirtyDate) { requiredArgs(1, arguments); var weekStartsOn = 1; var date = toDate(dirtyDate); var day = date.getUTCDay(); var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; date.setUTCDate(date.getUTCDate() - diff); date.setUTCHours(0, 0, 0, 0); return date; } // node_modules/date-fns/esm/_lib/getUTCISOWeekYear/index.js function getUTCISOWeekYear(dirtyDate) { requiredArgs(1, arguments); var date = toDate(dirtyDate); var year = date.getUTCFullYear(); var fourthOfJanuaryOfNextYear = new Date(0); fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4); fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0); var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear); var fourthOfJanuaryOfThisYear = new Date(0); fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4); fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0); var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear); if (date.getTime() >= startOfNextYear.getTime()) { return year + 1; } else if (date.getTime() >= startOfThisYear.getTime()) { return year; } else { return year - 1; } } // node_modules/date-fns/esm/_lib/startOfUTCISOWeekYear/index.js function startOfUTCISOWeekYear(dirtyDate) { requiredArgs(1, arguments); var year = getUTCISOWeekYear(dirtyDate); var fourthOfJanuary = new Date(0); fourthOfJanuary.setUTCFullYear(year, 0, 4); fourthOfJanuary.setUTCHours(0, 0, 0, 0); var date = startOfUTCISOWeek(fourthOfJanuary); return date; } // node_modules/date-fns/esm/_lib/getUTCISOWeek/index.js var MILLISECONDS_IN_WEEK = 6048e5; function getUTCISOWeek(dirtyDate) { requiredArgs(1, arguments); var date = toDate(dirtyDate); var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime(); return Math.round(diff / MILLISECONDS_IN_WEEK) + 1; } // node_modules/date-fns/esm/_lib/startOfUTCWeek/index.js function startOfUTCWeek(dirtyDate, options) { var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; requiredArgs(1, arguments); var defaultOptions2 = getDefaultOptions(); var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions2.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions2.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { throw new RangeError("weekStartsOn must be between 0 and 6 inclusively"); } var date = toDate(dirtyDate); var day = date.getUTCDay(); var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; date.setUTCDate(date.getUTCDate() - diff); date.setUTCHours(0, 0, 0, 0); return date; } // node_modules/date-fns/esm/_lib/getUTCWeekYear/index.js function getUTCWeekYear(dirtyDate, options) { var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; requiredArgs(1, arguments); var date = toDate(dirtyDate); var year = date.getUTCFullYear(); var defaultOptions2 = getDefaultOptions(); var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions2.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively"); } var firstWeekOfNextYear = new Date(0); firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate); firstWeekOfNextYear.setUTCHours(0, 0, 0, 0); var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, options); var firstWeekOfThisYear = new Date(0); firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate); firstWeekOfThisYear.setUTCHours(0, 0, 0, 0); var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, options); if (date.getTime() >= startOfNextYear.getTime()) { return year + 1; } else if (date.getTime() >= startOfThisYear.getTime()) { return year; } else { return year - 1; } } // node_modules/date-fns/esm/_lib/startOfUTCWeekYear/index.js function startOfUTCWeekYear(dirtyDate, options) { var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2; requiredArgs(1, arguments); var defaultOptions2 = getDefaultOptions(); var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions2.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); var year = getUTCWeekYear(dirtyDate, options); var firstWeek = new Date(0); firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate); firstWeek.setUTCHours(0, 0, 0, 0); var date = startOfUTCWeek(firstWeek, options); return date; } // node_modules/date-fns/esm/_lib/getUTCWeek/index.js var MILLISECONDS_IN_WEEK2 = 6048e5; function getUTCWeek(dirtyDate, options) { requiredArgs(1, arguments); var date = toDate(dirtyDate); var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime(); return Math.round(diff / MILLISECONDS_IN_WEEK2) + 1; } // node_modules/date-fns/esm/_lib/addLeadingZeros/index.js function addLeadingZeros(number, targetLength) { var sign = number < 0 ? "-" : ""; var output = Math.abs(number).toString(); while (output.length < targetLength) { output = "0" + output; } return sign + output; } // node_modules/date-fns/esm/_lib/format/lightFormatters/index.js var formatters = { // Year y: function y(date, token) { var signedYear = date.getUTCFullYear(); var year = signedYear > 0 ? signedYear : 1 - signedYear; return addLeadingZeros(token === "yy" ? year % 100 : year, token.length); }, // Month M: function M(date, token) { var month = date.getUTCMonth(); return token === "M" ? String(month + 1) : addLeadingZeros(month + 1, 2); }, // Day of the month d: function d(date, token) { return addLeadingZeros(date.getUTCDate(), token.length); }, // AM or PM a: function a(date, token) { var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? "pm" : "am"; switch (token) { case "a": case "aa": return dayPeriodEnumValue.toUpperCase(); case "aaa": return dayPeriodEnumValue; case "aaaaa": return dayPeriodEnumValue[0]; case "aaaa": default: return dayPeriodEnumValue === "am" ? "a.m." : "p.m."; } }, // Hour [1-12] h: function h(date, token) { return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length); }, // Hour [0-23] H: function H(date, token) { return addLeadingZeros(date.getUTCHours(), token.length); }, // Minute m: function m(date, token) { return addLeadingZeros(date.getUTCMinutes(), token.length); }, // Second s: function s(date, token) { return addLeadingZeros(date.getUTCSeconds(), token.length); }, // Fraction of second S: function S(date, token) { var numberOfDigits = token.length; var milliseconds = date.getUTCMilliseconds(); var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3)); return addLeadingZeros(fractionalSeconds, token.length); } }; var lightFormatters_default = formatters; // node_modules/date-fns/esm/_lib/format/formatters/index.js var dayPeriodEnum = { am: "am", pm: "pm", midnight: "midnight", noon: "noon", morning: "morning", afternoon: "afternoon", evening: "evening", night: "night" }; var formatters2 = { // Era G: function G(date, token, localize2) { var era = date.getUTCFullYear() > 0 ? 1 : 0; switch (token) { case "G": case "GG": case "GGG": return localize2.era(era, { width: "abbreviated" }); case "GGGGG": return localize2.era(era, { width: "narrow" }); case "GGGG": default: return localize2.era(era, { width: "wide" }); } }, // Year y: function y2(date, token, localize2) { if (token === "yo") { var signedYear = date.getUTCFullYear(); var year = signedYear > 0 ? signedYear : 1 - signedYear; return localize2.ordinalNumber(year, { unit: "year" }); } return lightFormatters_default.y(date, token); }, // Local week-numbering year Y: function Y(date, token, localize2, options) { var signedWeekYear = getUTCWeekYear(date, options); var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear; if (token === "YY") { var twoDigitYear = weekYear % 100; return addLeadingZeros(twoDigitYear, 2); } if (token === "Yo") { return localize2.ordinalNumber(weekYear, { unit: "year" }); } return addLeadingZeros(weekYear, token.length); }, // ISO week-numbering year R: function R(date, token) { var isoWeekYear = getUTCISOWeekYear(date); return addLeadingZeros(isoWeekYear, token.length); }, // Extended year. This is a single number designating the year of this calendar system. // The main difference between `y` and `u` localizers are B.C. years: // | Year | `y` | `u` | // |------|-----|-----| // | AC 1 | 1 | 1 | // | BC 1 | 1 | 0 | // | BC 2 | 2 | -1 | // Also `yy` always returns the last two digits of a year, // while `uu` pads single digit years to 2 characters and returns other years unchanged. u: function u(date, token) { var year = date.getUTCFullYear(); return addLeadingZeros(year, token.length); }, // Quarter Q: function Q(date, token, localize2) { var quarter = Math.ceil((date.getUTCMonth() + 1) / 3); switch (token) { case "Q": return String(quarter); case "QQ": return addLeadingZeros(quarter, 2); case "Qo": return localize2.ordinalNumber(quarter, { unit: "quarter" }); case "QQQ": return localize2.quarter(quarter, { width: "abbreviated", context: "formatting" }); case "QQQQQ": return localize2.quarter(quarter, { width: "narrow", context: "formatting" }); case "QQQQ": default: return localize2.quarter(quarter, { width: "wide", context: "formatting" }); } }, // Stand-alone quarter q: function q(date, token, localize2) { var quarter = Math.ceil((date.getUTCMonth() + 1) / 3); switch (token) { case "q": return String(quarter); case "qq": return addLeadingZeros(quarter, 2); case "qo": return localize2.ordinalNumber(quarter, { unit: "quarter" }); case "qqq": return localize2.quarter(quarter, { width: "abbreviated", context: "standalone" }); case "qqqqq": return localize2.quarter(quarter, { width: "narrow", context: "standalone" }); case "qqqq": default: return localize2.quarter(quarter, { width: "wide", context: "standalone" }); } }, // Month M: function M2(date, token, localize2) { var month = date.getUTCMonth(); switch (token) { case "M": case "MM": return lightFormatters_default.M(date, token); case "Mo": return localize2.ordinalNumber(month + 1, { unit: "month" }); case "MMM": return localize2.month(month, { width: "abbreviated", context: "formatting" }); case "MMMMM": return localize2.month(month, { width: "narrow", context: "formatting" }); case "MMMM": default: return localize2.month(month, { width: "wide", context: "formatting" }); } }, // Stand-alone month L: function L(date, token, localize2) { var month = date.getUTCMonth(); switch (token) { case "L": return String(month + 1); case "LL": return addLeadingZeros(month + 1, 2); case "Lo": return localize2.ordinalNumber(month + 1, { unit: "month" }); case "LLL": return localize2.month(month, { width: "abbreviated", context: "standalone" }); case "LLLLL": return localize2.month(month, { width: "narrow", context: "standalone" }); case "LLLL": default: return localize2.month(month, { width: "wide", context: "standalone" }); } }, // Local week of year w: function w(date, token, localize2, options) { var week = getUTCWeek(date, options); if (token === "wo") { return localize2.ordinalNumber(week, { unit: "week" }); } return addLeadingZeros(week, token.length); }, // ISO week of year I: function I(date, token, localize2) { var isoWeek = getUTCISOWeek(date); if (token === "Io") { return localize2.ordinalNumber(isoWeek, { unit: "week" }); } return addLeadingZeros(isoWeek, token.length); }, // Day of the month d: function d2(date, token, localize2) { if (token === "do") { return localize2.ordinalNumber(date.getUTCDate(), { unit: "date" }); } return lightFormatters_default.d(date, token); }, // Day of year D: function D(date, token, localize2) { var dayOfYear = getUTCDayOfYear(date); if (token === "Do") { return localize2.ordinalNumber(dayOfYear, { unit: "dayOfYear" }); } return addLeadingZeros(dayOfYear, token.length); }, // Day of week E: function E(date, token, localize2) { var dayOfWeek = date.getUTCDay(); switch (token) { case "E": case "EE": case "EEE": return localize2.day(dayOfWeek, { width: "abbreviated", context: "formatting" }); case "EEEEE": return localize2.day(dayOfWeek, { width: "narrow", context: "formatting" }); case "EEEEEE": return localize2.day(dayOfWeek, { width: "short", context: "formatting" }); case "EEEE": default: return localize2.day(dayOfWeek, { width: "wide", context: "formatting" }); } }, // Local day of week e: function e(date, token, localize2, options) { var dayOfWeek = date.getUTCDay(); var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7; switch (token) { case "e": return String(localDayOfWeek); case "ee": return addLeadingZeros(localDayOfWeek, 2); case "eo": return localize2.ordinalNumber(localDayOfWeek, { unit: "day" }); case "eee": return localize2.day(dayOfWeek, { width: "abbreviated", context: "formatting" }); case "eeeee": return localize2.day(dayOfWeek, { width: "narrow", context: "formatting" }); case "eeeeee": return localize2.day(dayOfWeek, { width: "short", context: "formatting" }); case "eeee": default: return localize2.day(dayOfWeek, { width: "wide", context: "formatting" }); } }, // Stand-alone local day of week c: function c(date, token, localize2, options) { var dayOfWeek = date.getUTCDay(); var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7; switch (token) { case "c": return String(localDayOfWeek); case "cc": return addLeadingZeros(localDayOfWeek, token.length); case "co": return localize2.ordinalNumber(localDayOfWeek, { unit: "day" }); case "ccc": return localize2.day(dayOfWeek, { width: "abbreviated", context: "standalone" }); case "ccccc": return localize2.day(dayOfWeek, { width: "narrow", context: "standalone" }); case "cccccc": return localize2.day(dayOfWeek, { width: "short", context: "standalone" }); case "cccc": default: return localize2.day(dayOfWeek, { width: "wide", context: "standalone" }); } }, // ISO day of week i: function i(date, token, localize2) { var dayOfWeek = date.getUTCDay(); var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek; switch (token) { case "i": return String(isoDayOfWeek); case "ii": return addLeadingZeros(isoDayOfWeek, token.length); case "io": return localize2.ordinalNumber(isoDayOfWeek, { unit: "day" }); case "iii": return localize2.day(dayOfWeek, { width: "abbreviated", context: "formatting" }); case "iiiii": return localize2.day(dayOfWeek, { width: "narrow", context: "formatting" }); case "iiiiii": return localize2.day(dayOfWeek, { width: "short", context: "formatting" }); case "iiii": default: return localize2.day(dayOfWeek, { width: "wide", context: "formatting" }); } }, // AM or PM a: function a2(date, token, localize2) { var hours = date.getUTCHours(); var dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am"; switch (token) { case "a": case "aa": return localize2.dayPeriod(dayPeriodEnumValue, { width: "abbreviated", context: "formatting" }); case "aaa": return localize2.dayPeriod(dayPeriodEnumValue, { width: "abbreviated", context: "formatting" }).toLowerCase(); case "aaaaa": return localize2.dayPeriod(dayPeriodEnumValue, { width: "narrow", context: "formatting" }); case "aaaa": default: return localize2.dayPeriod(dayPeriodEnumValue, { width: "wide", context: "formatting" }); } }, // AM, PM, midnight, noon b: function b(date, token, localize2) { var hours = date.getUTCHours(); var dayPeriodEnumValue; if (hours === 12) { dayPeriodEnumValue = dayPeriodEnum.noon; } else if (hours === 0) { dayPeriodEnumValue = dayPeriodEnum.midnight; } else { dayPeriodEnumValue = hours / 12 >= 1 ? "pm" : "am"; } switch (token) { case "b": case "bb": return localize2.dayPeriod(dayPeriodEnumValue, { width: "abbreviated", context: "formatting" }); case "bbb": return localize2.dayPeriod(dayPeriodEnumValue, { width: "abbreviated", context: "formatting" }).toLowerCase(); case "bbbbb": return localize2.dayPeriod(dayPeriodEnumValue, { width: "narrow", context: "formatting" }); case "bbbb": default: return localize2.dayPeriod(dayPeriodEnumValue, { width: "wide", context: "formatting" }); } }, // in the morning, in the afternoon, in the evening, at night B: function B(date, token, localize2) { var hours = date.getUTCHours(); var dayPeriodEnumValue; if (hours >= 17) { dayPeriodEnumValue = dayPeriodEnum.evening; } else if (hours >= 12) { dayPeriodEnumValue = dayPeriodEnum.afternoon; } else if (hours >= 4) { dayPeriodEnumValue = dayPeriodEnum.morning; } else { dayPeriodEnumValue = dayPeriodEnum.night; } switch (token) { case "B": case "BB": case "BBB": return localize2.dayPeriod(dayPeriodEnumValue, { width: "abbreviated", context: "formatting" }); case "BBBBB": return localize2.dayPeriod(dayPeriodEnumValue, { width: "narrow", context: "formatting" }); case "BBBB": default: return localize2.dayPeriod(dayPeriodEnumValue, { width: "wide", context: "formatting" }); } }, // Hour [1-12] h: function h2(date, token, localize2) { if (token === "ho") { var hours = date.getUTCHours() % 12; if (hours === 0) hours = 12; return localize2.ordinalNumber(hours, { unit: "hour" }); } return lightFormatters_default.h(date, token); }, // Hour [0-23] H: function H2(date, token, localize2) { if (token === "Ho") { return localize2.ordinalNumber(date.getUTCHours(), { unit: "hour" }); } return lightFormatters_default.H(date, token); }, // Hour [0-11] K: function K(date, token, localize2) { var hours = date.getUTCHours() % 12; if (token === "Ko") { return localize2.ordinalNumber(hours, { unit: "hour" }); } return addLeadingZeros(hours, token.length); }, // Hour [1-24] k: function k(date, token, localize2) { var hours = date.getUTCHours(); if (hours === 0) hours = 24; if (token === "ko") { return localize2.ordinalNumber(hours, { unit: "hour" }); } return addLeadingZeros(hours, token.length); }, // Minute m: function m2(date, token, localize2) { if (token === "mo") { return localize2.ordinalNumber(date.getUTCMinutes(), { unit: "minute" }); } return lightFormatters_default.m(date, token); }, // Second s: function s2(date, token, localize2) { if (token === "so") { return localize2.ordinalNumber(date.getUTCSeconds(), { unit: "second" }); } return lightFormatters_default.s(date, token); }, // Fraction of second S: function S2(date, token) { return lightFormatters_default.S(date, token); }, // Timezone (ISO-8601. If offset is 0, output is always `'Z'`) X: function X(date, token, _localize, options) { var originalDate = options._originalDate || date; var timezoneOffset = originalDate.getTimezoneOffset(); if (timezoneOffset === 0) { return "Z"; } switch (token) { case "X": return formatTimezoneWithOptionalMinutes(timezoneOffset); case "XXXX": case "XX": return formatTimezone(timezoneOffset); case "XXXXX": case "XXX": default: return formatTimezone(timezoneOffset, ":"); } }, // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent) x: function x(date, token, _localize, options) { var originalDate = options._originalDate || date; var timezoneOffset = originalDate.getTimezoneOffset(); switch (token) { case "x": return formatTimezoneWithOptionalMinutes(timezoneOffset); case "xxxx": case "xx": return formatTimezone(timezoneOffset); case "xxxxx": case "xxx": default: return formatTimezone(timezoneOffset, ":"); } }, // Timezone (GMT) O: function O(date, token, _localize, options) { var originalDate = options._originalDate || date; var timezoneOffset = originalDate.getTimezoneOffset(); switch (token) { case "O": case "OO": case "OOO": return "GMT" + formatTimezoneShort(timezoneOffset, ":"); case "OOOO": default: return "GMT" + formatTimezone(timezoneOffset, ":"); } }, // Timezone (specific non-location) z: function z2(date, token, _localize, options) { var originalDate = options._originalDate || date; var timezoneOffset = originalDate.getTimezoneOffset(); switch (token) { case "z": case "zz": case "zzz": return "GMT" + formatTimezoneShort(timezoneOffset, ":"); case "zzzz": default: return "GMT" + formatTimezone(timezoneOffset, ":"); } }, // Seconds timestamp t: function t(date, token, _localize, options) { var originalDate = options._originalDate || date; var timestamp2 = Math.floor(originalDate.getTime() / 1e3); return addLeadingZeros(timestamp2, token.length); }, // Milliseconds timestamp T: function T(date, token, _localize, options) { var originalDate = options._originalDate || date; var timestamp2 = originalDate.getTime(); return addLeadingZeros(timestamp2, token.length); } }; function formatTimezoneShort(offset, dirtyDelimiter) { var sign = offset > 0 ? "-" : "+"; var absOffset = Math.abs(offset); var hours = Math.floor(absOffset / 60); var minutes = absOffset % 60; if (minutes === 0) { return sign + String(hours); } var delimiter = dirtyDelimiter || ""; return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2); } function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) { if (offset % 60 === 0) { var sign = offset > 0 ? "-" : "+"; return sign + addLeadingZeros(Math.abs(offset) / 60, 2); } return formatTimezone(offset, dirtyDelimiter); } function formatTimezone(offset, dirtyDelimiter) { var delimiter = dirtyDelimiter || ""; var sign = offset > 0 ? "-" : "+"; var absOffset = Math.abs(offset); var hours = addLeadingZeros(Math.floor(absOffset / 60), 2); var minutes = addLeadingZeros(absOffset % 60, 2); return sign + hours + delimiter + minutes; } var formatters_default = formatters2; // node_modules/date-fns/esm/_lib/format/longFormatters/index.js var dateLongFormatter = function dateLongFormatter2(pattern, formatLong2) { switch (pattern) { case "P": return formatLong2.date({ width: "short" }); case "PP": return formatLong2.date({ width: "medium" }); case "PPP": return formatLong2.date({ width: "long" }); case "PPPP": default: return formatLong2.date({ width: "full" }); } }; var timeLongFormatter = function timeLongFormatter2(pattern, formatLong2) { switch (pattern) { case "p": return formatLong2.time({ width: "short" }); case "pp": return formatLong2.time({ width: "medium" }); case "ppp": return formatLong2.time({ width: "long" }); case "pppp": default: return formatLong2.time({ width: "full" }); } }; var dateTimeLongFormatter = function dateTimeLongFormatter2(pattern, formatLong2) { var matchResult = pattern.match(/(P+)(p+)?/) || []; var datePattern = matchResult[1]; var timePattern = matchResult[2]; if (!timePattern) { return dateLongFormatter(pattern, formatLong2); } var dateTimeFormat; switch (datePattern) { case "P": dateTimeFormat = formatLong2.dateTime({ width: "short" }); break; case "PP": dateTimeFormat = formatLong2.dateTime({ width: "medium" }); break; case "PPP": dateTimeFormat = formatLong2.dateTime({ width: "long" }); break; case "PPPP": default: dateTimeFormat = formatLong2.dateTime({ width: "full" }); break; } return dateTimeFormat.replace("{{date}}", dateLongFormatter(datePattern, formatLong2)).replace("{{time}}", timeLongFormatter(timePattern, formatLong2)); }; var longFormatters = { p: timeLongFormatter, P: dateTimeLongFormatter }; var longFormatters_default = longFormatters; // node_modules/date-fns/esm/_lib/protectedTokens/index.js var protectedDayOfYearTokens = ["D", "DD"]; var protectedWeekYearTokens = ["YY", "YYYY"]; function isProtectedDayOfYearToken(token) { return protectedDayOfYearTokens.indexOf(token) !== -1; } function isProtectedWeekYearToken(token) { return protectedWeekYearTokens.indexOf(token) !== -1; } function throwProtectedError(token, format2, input) { if (token === "YYYY") { throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format2, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); } else if (token === "YY") { throw new RangeError("Use `yy` instead of `YY` (in `".concat(format2, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); } else if (token === "D") { throw new RangeError("Use `d` instead of `D` (in `".concat(format2, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); } else if (token === "DD") { throw new RangeError("Use `dd` instead of `DD` (in `".concat(format2, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md")); } } // node_modules/date-fns/esm/locale/en-US/_lib/formatDistance/index.js var formatDistanceLocale = { lessThanXSeconds: { one: "less than a second", other: "less than {{count}} seconds" }, xSeconds: { one: "1 second", other: "{{count}} seconds" }, halfAMinute: "half a minute", lessThanXMinutes: { one: "less than a minute", other: "less than {{count}} minutes" }, xMinutes: { one: "1 minute", other: "{{count}} minutes" }, aboutXHours: { one: "about 1 hour", other: "about {{count}} hours" }, xHours: { one: "1 hour", other: "{{count}} hours" }, xDays: { one: "1 day", other: "{{count}} days" }, aboutXWeeks: { one: "about 1 week", other: "about {{count}} weeks" }, xWeeks: { one: "1 week", other: "{{count}} weeks" }, aboutXMonths: { one: "about 1 month", other: "about {{count}} months" }, xMonths: { one: "1 month", other: "{{count}} months" }, aboutXYears: { one: "about 1 year", other: "about {{count}} years" }, xYears: { one: "1 year", other: "{{count}} years" }, overXYears: { one: "over 1 year", other: "over {{count}} years" }, almostXYears: { one: "almost 1 year", other: "almost {{count}} years" } }; var formatDistance = function formatDistance2(token, count, options) { var result; var tokenValue = formatDistanceLocale[token]; if (typeof tokenValue === "string") { result = tokenValue; } else if (count === 1) { result = tokenValue.one; } else { result = tokenValue.other.replace("{{count}}", count.toString()); } if (options !== null && options !== void 0 && options.addSuffix) { if (options.comparison && options.comparison > 0) { return "in " + result; } else { return result + " ago"; } } return result; }; var formatDistance_default = formatDistance; // node_modules/date-fns/esm/locale/_lib/buildFormatLongFn/index.js function buildFormatLongFn(args) { return function() { var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; var width = options.width ? String(options.width) : args.defaultWidth; var format2 = args.formats[width] || args.formats[args.defaultWidth]; return format2; }; } // node_modules/date-fns/esm/locale/en-US/_lib/formatLong/index.js var dateFormats = { full: "EEEE, MMMM do, y", long: "MMMM do, y", medium: "MMM d, y", short: "MM/dd/yyyy" }; var timeFormats = { full: "h:mm:ss a zzzz", long: "h:mm:ss a z", medium: "h:mm:ss a", short: "h:mm a" }; var dateTimeFormats = { full: "{{date}} 'at' {{time}}", long: "{{date}} 'at' {{time}}", medium: "{{date}}, {{time}}", short: "{{date}}, {{time}}" }; var formatLong = { date: buildFormatLongFn({ formats: dateFormats, defaultWidth: "full" }), time: buildFormatLongFn({ formats: timeFormats, defaultWidth: "full" }), dateTime: buildFormatLongFn({ formats: dateTimeFormats, defaultWidth: "full" }) }; var formatLong_default = formatLong; // node_modules/date-fns/esm/locale/en-US/_lib/formatRelative/index.js var formatRelativeLocale = { lastWeek: "'last' eeee 'at' p", yesterday: "'yesterday at' p", today: "'today at' p", tomorrow: "'tomorrow at' p", nextWeek: "eeee 'at' p", other: "P" }; var formatRelative = function formatRelative2(token, _date, _baseDate, _options) { return formatRelativeLocale[token]; }; var formatRelative_default = formatRelative; // node_modules/date-fns/esm/locale/_lib/buildLocalizeFn/index.js function buildLocalizeFn(args) { return function(dirtyIndex, options) { var context = options !== null && options !== void 0 && options.context ? String(options.context) : "standalone"; var valuesArray; if (context === "formatting" && args.formattingValues) { var defaultWidth = args.defaultFormattingWidth || args.defaultWidth; var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth; valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth]; } else { var _defaultWidth = args.defaultWidth; var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth; valuesArray = args.values[_width] || args.values[_defaultWidth]; } var index2 = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex; return valuesArray[index2]; }; } // node_modules/date-fns/esm/locale/en-US/_lib/localize/index.js var eraValues = { narrow: ["B", "A"], abbreviated: ["BC", "AD"], wide: ["Before Christ", "Anno Domini"] }; var quarterValues = { narrow: ["1", "2", "3", "4"], abbreviated: ["Q1", "Q2", "Q3", "Q4"], wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"] }; var monthValues = { narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"], abbreviated: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], wide: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] }; var dayValues = { narrow: ["S", "M", "T", "W", "T", "F", "S"], short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], wide: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] }; var dayPeriodValues = { narrow: { am: "a", pm: "p", midnight: "mi", noon: "n", morning: "morning", afternoon: "afternoon", evening: "evening", night: "night" }, abbreviated: { am: "AM", pm: "PM", midnight: "midnight", noon: "noon", morning: "morning", afternoon: "afternoon", evening: "evening", night: "night" }, wide: { am: "a.m.", pm: "p.m.", midnight: "midnight", noon: "noon", morning: "morning", afternoon: "afternoon", evening: "evening", night: "night" } }; var formattingDayPeriodValues = { narrow: { am: "a", pm: "p", midnight: "mi", noon: "n", morning: "in the morning", afternoon: "in the afternoon", evening: "in the evening", night: "at night" }, abbreviated: { am: "AM", pm: "PM", midnight: "midnight", noon: "noon", morning: "in the morning", afternoon: "in the afternoon", evening: "in the evening", night: "at night" }, wide: { am: "a.m.", pm: "p.m.", midnight: "midnight", noon: "noon", morning: "in the morning", afternoon: "in the afternoon", evening: "in the evening", night: "at night" } }; var ordinalNumber = function ordinalNumber2(dirtyNumber, _options) { var number = Number(dirtyNumber); var rem100 = number % 100; if (rem100 > 20 || rem100 < 10) { switch (rem100 % 10) { case 1: return number + "st"; case 2: return number + "nd"; case 3: return number + "rd"; } } return number + "th"; }; var localize = { ordinalNumber, era: buildLocalizeFn({ values: eraValues, defaultWidth: "wide" }), quarter: buildLocalizeFn({ values: quarterValues, defaultWidth: "wide", argumentCallback: function argumentCallback(quarter) { return quarter - 1; } }), month: buildLocalizeFn({ values: monthValues, defaultWidth: "wide" }), day: buildLocalizeFn({ values: dayValues, defaultWidth: "wide" }), dayPeriod: buildLocalizeFn({ values: dayPeriodValues, defaultWidth: "wide", formattingValues: formattingDayPeriodValues, defaultFormattingWidth: "wide" }) }; var localize_default = localize; // node_modules/date-fns/esm/locale/_lib/buildMatchFn/index.js function buildMatchFn(args) { return function(string3) { var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; var width = options.width; var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth]; var matchResult = string3.match(matchPattern); if (!matchResult) { return null; } var matchedString = matchResult[0]; var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth]; var key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function(pattern) { return pattern.test(matchedString); }) : findKey(parsePatterns, function(pattern) { return pattern.test(matchedString); }); var value; value = args.valueCallback ? args.valueCallback(key) : key; value = options.valueCallback ? options.valueCallback(value) : value; var rest = string3.slice(matchedString.length); return { value, rest }; }; } function findKey(object, predicate) { for (var key in object) { if (object.hasOwnProperty(key) && predicate(object[key])) { return key; } } return void 0; } function findIndex(array, predicate) { for (var key = 0; key < array.length; key++) { if (predicate(array[key])) { return key; } } return void 0; } // node_modules/date-fns/esm/locale/_lib/buildMatchPatternFn/index.js function buildMatchPatternFn(args) { return function(string3) { var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; var matchResult = string3.match(args.matchPattern); if (!matchResult) return null; var matchedString = matchResult[0]; var parseResult = string3.match(args.parsePattern); if (!parseResult) return null; var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0]; value = options.valueCallback ? options.valueCallback(value) : value; var rest = string3.slice(matchedString.length); return { value, rest }; }; } // node_modules/date-fns/esm/locale/en-US/_lib/match/index.js var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i; var parseOrdinalNumberPattern = /\d+/i; var matchEraPatterns = { narrow: /^(b|a)/i, abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i, wide: /^(before christ|before common era|anno domini|common era)/i }; var parseEraPatterns = { any: [/^b/i, /^(a|c)/i] }; var matchQuarterPatterns = { narrow: /^[1234]/i, abbreviated: /^q[1234]/i, wide: /^[1234](th|st|nd|rd)? quarter/i }; var parseQuarterPatterns = { any: [/1/i, /2/i, /3/i, /4/i] }; var matchMonthPatterns = { narrow: /^[jfmasond]/i, abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i, wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i }; var parseMonthPatterns = { narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i], any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i] }; var matchDayPatterns = { narrow: /^[smtwf]/i, short: /^(su|mo|tu|we|th|fr|sa)/i, abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i, wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i }; var parseDayPatterns = { narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i], any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i] }; var matchDayPeriodPatterns = { narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i, any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i }; var parseDayPeriodPatterns = { any: { am: /^a/i, pm: /^p/i, midnight: /^mi/i, noon: /^no/i, morning: /morning/i, afternoon: /afternoon/i, evening: /evening/i, night: /night/i } }; var match = { ordinalNumber: buildMatchPatternFn({ matchPattern: matchOrdinalNumberPattern, parsePattern: parseOrdinalNumberPattern, valueCallback: function valueCallback(value) { return parseInt(value, 10); } }), era: buildMatchFn({ matchPatterns: matchEraPatterns, defaultMatchWidth: "wide", parsePatterns: parseEraPatterns, defaultParseWidth: "any" }), quarter: buildMatchFn({ matchPatterns: matchQuarterPatterns, defaultMatchWidth: "wide", parsePatterns: parseQuarterPatterns, defaultParseWidth: "any", valueCallback: function valueCallback2(index2) { return index2 + 1; } }), month: buildMatchFn({ matchPatterns: matchMonthPatterns, defaultMatchWidth: "wide", parsePatterns: parseMonthPatterns, defaultParseWidth: "any" }), day: buildMatchFn({ matchPatterns: matchDayPatterns, defaultMatchWidth: "wide", parsePatterns: parseDayPatterns, defaultParseWidth: "any" }), dayPeriod: buildMatchFn({ matchPatterns: matchDayPeriodPatterns, defaultMatchWidth: "any", parsePatterns: parseDayPeriodPatterns, defaultParseWidth: "any" }) }; var match_default = match; // node_modules/date-fns/esm/locale/en-US/index.js var locale = { code: "en-US", formatDistance: formatDistance_default, formatLong: formatLong_default, formatRelative: formatRelative_default, localize: localize_default, match: match_default, options: { weekStartsOn: 0, firstWeekContainsDate: 1 } }; var en_US_default = locale; // node_modules/date-fns/esm/_lib/defaultLocale/index.js var defaultLocale_default = en_US_default; // node_modules/date-fns/esm/format/index.js var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g; var escapedStringRegExp = /^'([^]*?)'?$/; var doubleQuoteRegExp = /''/g; var unescapedLatinCharacterRegExp = /[a-zA-Z]/; function format(dirtyDate, dirtyFormatStr, options) { var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4; requiredArgs(2, arguments); var formatStr = String(dirtyFormatStr); var defaultOptions2 = getDefaultOptions(); var locale2 = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions2.locale) !== null && _ref !== void 0 ? _ref : defaultLocale_default; var firstWeekContainsDate = toInteger((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions2.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions2.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1); if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) { throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively"); } var weekStartsOn = toInteger((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions2.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions2.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0); if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) { throw new RangeError("weekStartsOn must be between 0 and 6 inclusively"); } if (!locale2.localize) { throw new RangeError("locale must contain localize property"); } if (!locale2.formatLong) { throw new RangeError("locale must contain formatLong property"); } var originalDate = toDate(dirtyDate); if (!isValid2(originalDate)) { throw new RangeError("Invalid time value"); } var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate); var utcDate = subMilliseconds(originalDate, timezoneOffset); var formatterOptions = { firstWeekContainsDate, weekStartsOn, locale: locale2, _originalDate: originalDate }; var result = formatStr.match(longFormattingTokensRegExp).map(function(substring) { var firstCharacter = substring[0]; if (firstCharacter === "p" || firstCharacter === "P") { var longFormatter = longFormatters_default[firstCharacter]; return longFormatter(substring, locale2.formatLong); } return substring; }).join("").match(formattingTokensRegExp).map(function(substring) { if (substring === "''") { return "'"; } var firstCharacter = substring[0]; if (firstCharacter === "'") { return cleanEscapedString(substring); } var formatter = formatters_default[firstCharacter]; if (formatter) { if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(substring)) { throwProtectedError(substring, dirtyFormatStr, String(dirtyDate)); } if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) { throwProtectedError(substring, dirtyFormatStr, String(dirtyDate)); } return formatter(utcDate, substring, locale2.localize, formatterOptions); } if (firstCharacter.match(unescapedLatinCharacterRegExp)) { throw new RangeError("Format string contains an unescaped latin alphabet character `" + firstCharacter + "`"); } return substring; }).join(""); return result; } function cleanEscapedString(input) { var matched = input.match(escapedStringRegExp); if (!matched) { return input; } return matched[1].replace(doubleQuoteRegExp, "'"); } // src/getNewTextFromResults.ts var getEndingTag = (generateEndingTagMetadata, section, errorMessage) => { if (errorMessage) return esm_default( generateEndingTagMetadata ? esm_default` %% run end ${_getEndingTag("endingTag" in section ? section.endingObject : {}, { error: errorMessage })} %% ` : `%% run end %%` ); return esm_default( generateEndingTagMetadata ? esm_default` %% run end ${_getEndingTag( {}, { "last update": format(new Date(), "yyyy-MM-dd HH:mm:ss") } )} %%` : `%% run end %%` ); }; var _getEndingTag = (endingObject, newObject) => { const test = { ...endingObject, ...newObject }; const string3 = Object.entries(test).map(([key, value]) => `${key}: ${value}`).join("\n"); return string3; }; function getNewTextFromResults(data, results, s3, options) { let resultedText = data.text; const remainingPromises = []; const errors = []; for (let i2 = 0; i2 < results.length; i2++) { const result = results[i2]; const section = s3.sections[i2]; if (result.success) { const content3 = result.result instanceof Promise ? "Loading..." : result.result; const newSectionText = esm_default` %% run start ${section.startingTag} %% ${content3} ${getEndingTag(Boolean(options == null ? void 0 : options.generateEndingTagMetadata), section)} `; resultedText = replaceOccurance( resultedText, section.text, newSectionText, section.id ); if (result.result instanceof Promise) { remainingPromises.push({ section: { ...section, text: newSectionText }, promise: result.result }); } } else { console.error(result.error.message); const newSectionText = esm_default` %% run start ${section.startingTag} %% ${"content" in section ? section.content : ""} ${getEndingTag( Boolean(options == null ? void 0 : options.generateEndingTagMetadata), section, result.error.message )} `; resultedText = replaceOccurance( resultedText, section.text, newSectionText, section.id ); errors.push({ section, message: result.error.message }); } } return { resultedText, remainingPromises, errors }; } // src/createNotice.ts var import_obsidian2 = require("obsidian"); function createNotice(message, color = "white", duration) { const fragment = new DocumentFragment(); const desc = document.createElement("div"); desc.setText(esm_default`Obsidian Run: ${message}`); desc.style.color = color; fragment.appendChild(desc); new import_obsidian2.Notice(fragment, (duration != null ? duration : color === "red") ? 1e4 : void 0); } // src/ui/settingsTab.ts var import_obsidian3 = require("obsidian"); var SettingTab = class extends import_obsidian3.PluginSettingTab { constructor(app, plugin) { super(app, plugin); this.plugin = plugin; } async display() { const { containerEl } = this; containerEl.empty(); new import_obsidian3.Setting(containerEl).setName("Generate ending tag metadata").addToggle((toggle) => { toggle.setValue(this.plugin.settings.generateEndingTagMetadata).onChange(async (value) => { this.plugin.settings.generateEndingTagMetadata = value; await this.plugin.saveSettings(); }); return toggle; }); new import_obsidian3.Setting(containerEl).setName("Ignore folders").setDesc("Folders to ignore. One folder per line.").addTextArea((text3) => { text3.setPlaceholder("Enter folders to ignore").setValue(this.plugin.settings.ignoredFolders.join("\n")).onChange(async (_value) => { const folders = _value.trim().split("\n").filter((p) => p !== ""); this.plugin.settings.ignoredFolders = folders; await this.plugin.saveSettings(); }); text3.inputEl.style.minWidth = text3.inputEl.style.maxWidth = "300px"; text3.inputEl.style.minHeight = "200px"; return text3; }); } }; // src/main.ts var isIgnoredByFolder = (settings, file) => { var _a; return settings.ignoredFolders.includes((_a = file.parent) == null ? void 0 : _a.path); }; function isFileIgnored(settings, file, data) { if (isIgnoredByFolder(settings, file)) return true; if (data) { if (data.yamlObj && data.yamlObj["run-ignore" /* IGNORE */]) return true; } return false; } var DEFAULT_SETTINGS = { generateEndingTagMetadata: false, ignoredFolders: [] }; var RunPlugin = class extends import_obsidian4.Plugin { runFileSync(file, editor) { var _a; const data = getDataFromTextSync(editor.getValue()); const s3 = extractSectionsFromPattern(data.text); if (s3.sections.length === 0) return; const context = { file: { ...file, properties: data.yamlObj }, dv: (0, import_obsidian_dataview.getAPI)(this.app), tp: (_a = this.app.plugins.plugins["templater-obsidian"]) == null ? void 0 : _a.templater.current_functions_object }; const results = s3.sections.map(({ startingTag, codeBlock }) => { return evalFromExpression( codeBlock ? codeBlock.code : startingTag, codeBlock ? true : false, context ); }); const { resultedText: newText, remainingPromises, errors } = getNewTextFromResults(data, results, s3, { generateEndingTagMetadata: this.settings.generateEndingTagMetadata }); if (newText !== data.text) { writeFile(editor, data.text, newText); } remainingPromises.forEach(({ section, promise }) => { promise.then((result) => { const data2 = getDataFromTextSync(editor.getValue()); const { resultedText } = getNewTextFromResults( data2, [{ success: true, result }], { sections: [section], sectionSummary: s3.sectionSummary }, { generateEndingTagMetadata: this.settings.generateEndingTagMetadata } ); writeFile(editor, data2.text, resultedText); }).catch((e2) => { console.error(e2); const { resultedText } = getNewTextFromResults( data, [ { success: false, error: { message: e2.message, cause: e2 } } ], { sections: [section], sectionSummary: s3.sectionSummary }, { generateEndingTagMetadata: this.settings.generateEndingTagMetadata } ); writeFile(editor, data.text, resultedText); createNotice( `Error when resolving run ${section.id}: ${e2.message}`, "red" ); }); }); createNotice( esm_default` Completed: ${results.length - errors.length - remainingPromises.length} out of ${results.length} Promise: ${remainingPromises.length} Error: ${errors.length} `, errors.length > 0 ? "red" : "white" ); } async onload() { await this.loadSettings(); this.addCommand({ id: "run-file", name: "Run file", editorCheckCallback: this.runFile.bind(this) }); this.addSettingTab(new SettingTab(this.app, this)); } runFile(checking, editor, ctx) { if (!ctx.file) return; if (checking) { return isMarkdownFile(ctx.file); } if (!editor) return; const data = getDataFromTextSync(editor.getValue()); if (isFileIgnored(this.settings, ctx.file, data)) return; this.runFileSync(ctx.file, editor); } async saveSettings() { await this.saveData(this.settings); } async loadSettings() { this.settings = Object.assign( {}, DEFAULT_SETTINGS, await this.loadData() ); } }; /*! Bundled license information: js-yaml/dist/js-yaml.mjs: (*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT *) */