/* THIS IS A GENERATED/BUNDLED FILE BY ESBUILD */ if(typeof global === 'undefined'){var global = window;} if(typeof Buffer === 'undefined'){var Buffer = require('buffer').Buffer;} if(typeof process === 'undefined'){var process = require('process');} 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 __typeError = (msg) => { throw TypeError(msg); }; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value); var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); // node_modules/cron-parser/dist/fields/types.js var require_types = __commonJS({ "node_modules/cron-parser/dist/fields/types.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); } }); // node_modules/cron-parser/dist/fields/CronField.js var require_CronField = __commonJS({ "node_modules/cron-parser/dist/fields/CronField.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CronField = void 0; var _hasLastChar, _hasQuestionMarkChar, _wildcard, _values, _CronField_instances, isWildcardValue_fn; var _CronField = class _CronField { /** * CronField constructor. Initializes the field with the provided values. * @param {number[] | string[]} values - Values for this field * @param {CronFieldOptions} [options] - Options provided by the parser * @throws {TypeError} if the constructor is called directly * @throws {Error} if validation fails */ constructor(values, options = { rawValue: "" }) { __privateAdd(this, _CronField_instances); __privateAdd(this, _hasLastChar, false); __privateAdd(this, _hasQuestionMarkChar, false); __privateAdd(this, _wildcard, false); __privateAdd(this, _values, []); __publicField(this, "options", { rawValue: "" }); var _a5; if (!Array.isArray(values)) { throw new Error(`${this.constructor.name} Validation error, values is not an array`); } if (!(values.length > 0)) { throw new Error(`${this.constructor.name} Validation error, values contains no values`); } this.options = { ...options, rawValue: (_a5 = options.rawValue) != null ? _a5 : "" }; __privateSet(this, _values, values.sort(_CronField.sorter)); __privateSet(this, _wildcard, this.options.wildcard !== void 0 ? this.options.wildcard : __privateMethod(this, _CronField_instances, isWildcardValue_fn).call(this)); __privateSet(this, _hasLastChar, this.options.rawValue.includes("L") || values.includes("L")); __privateSet(this, _hasQuestionMarkChar, this.options.rawValue.includes("?") || values.includes("?")); } /** * Returns the minimum value allowed for this field. */ /* istanbul ignore next */ static get min() { throw new Error("min must be overridden"); } /** * Returns the maximum value allowed for this field. */ /* istanbul ignore next */ static get max() { throw new Error("max must be overridden"); } /** * Returns the allowed characters for this field. */ /* istanbul ignore next */ static get chars() { return Object.freeze([]); } /** * Returns the regular expression used to validate this field. */ static get validChars() { return /^[?,*\dH/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/; } /** * Returns the constraints for this field. */ static get constraints() { return { min: this.min, max: this.max, chars: this.chars, validChars: this.validChars }; } /** * Returns the minimum value allowed for this field. * @returns {number} */ get min() { return this.constructor.min; } /** * Returns the maximum value allowed for this field. * @returns {number} */ get max() { return this.constructor.max; } /** * Returns an array of allowed special characters for this field. * @returns {string[]} */ get chars() { return this.constructor.chars; } /** * Indicates whether this field has a "last" character. * @returns {boolean} */ get hasLastChar() { return __privateGet(this, _hasLastChar); } /** * Indicates whether this field has a "question mark" character. * @returns {boolean} */ get hasQuestionMarkChar() { return __privateGet(this, _hasQuestionMarkChar); } /** * Indicates whether this field is a wildcard. * @returns {boolean} */ get isWildcard() { return __privateGet(this, _wildcard); } /** * Returns an array of allowed values for this field. * @returns {CronFieldType} */ get values() { return __privateGet(this, _values); } /** * Helper function to sort values in ascending order. * @param {number | string} a - First value to compare * @param {number | string} b - Second value to compare * @returns {number} - A negative, zero, or positive value, depending on the sort order */ static sorter(a, b2) { const aIsNumber = typeof a === "number"; const bIsNumber = typeof b2 === "number"; if (aIsNumber && bIsNumber) return a - b2; if (!aIsNumber && !bIsNumber) return a.localeCompare(b2); return aIsNumber ? ( /* istanbul ignore next - A will always be a number until L-2 is supported */ -1 ) : 1; } /** * Find the next (or previous when `reverse` is true) numeric value in a sorted list. * Returns null if there's no value strictly after/before the current one. * * @param values - Sorted numeric values * @param currentValue - Current value to compare against * @param reverse - When true, search in reverse for previous smaller value */ static findNearestValueInList(values, currentValue, reverse = false) { if (reverse) { for (let i = values.length - 1; i >= 0; i--) { if (values[i] < currentValue) return values[i]; } return null; } for (let i = 0; i < values.length; i++) { if (values[i] > currentValue) return values[i]; } return null; } /** * Instance helper that operates on this field's numeric `values`. * * @param currentValue - Current value to compare against * @param reverse - When true, search in reverse for previous smaller value */ findNearestValue(currentValue, reverse = false) { return this.constructor.findNearestValueInList(this.values, currentValue, reverse); } /** * Serializes the field to an object. * @returns {SerializedCronField} */ serialize() { return { wildcard: __privateGet(this, _wildcard), values: __privateGet(this, _values) }; } /** * Validates the field values against the allowed range and special characters. * @throws {Error} if validation fails */ validate() { let badValue; const charsString = this.chars.length > 0 ? ` or chars ${this.chars.join("")}` : ""; const charTest = (value) => (char) => new RegExp(`^\\d{0,2}${char}$`).test(value); const rangeTest = (value) => { badValue = value; return typeof value === "number" ? value >= this.min && value <= this.max : this.chars.some(charTest(value)); }; const isValidRange = __privateGet(this, _values).every(rangeTest); if (!isValidRange) { throw new Error(`${this.constructor.name} Validation error, got value ${badValue} expected range ${this.min}-${this.max}${charsString}`); } const duplicate = __privateGet(this, _values).find((value, index) => __privateGet(this, _values).indexOf(value) !== index); if (duplicate) { throw new Error(`${this.constructor.name} Validation error, duplicate values found: ${duplicate}`); } } }; _hasLastChar = new WeakMap(); _hasQuestionMarkChar = new WeakMap(); _wildcard = new WeakMap(); _values = new WeakMap(); _CronField_instances = new WeakSet(); /** * Determines if the field is a wildcard based on the values. * When options.rawValue is not empty, it checks if the raw value is a wildcard, otherwise it checks if all values in the range are included. * @returns {boolean} */ isWildcardValue_fn = function() { if (this.options.rawValue.length > 0) { return ["*", "?"].includes(this.options.rawValue); } return Array.from({ length: this.max - this.min + 1 }, (_2, i) => i + this.min).every((value) => __privateGet(this, _values).includes(value)); }; var CronField = _CronField; exports.CronField = CronField; } }); // node_modules/cron-parser/dist/fields/CronDayOfMonth.js var require_CronDayOfMonth = __commonJS({ "node_modules/cron-parser/dist/fields/CronDayOfMonth.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CronDayOfMonth = void 0; var CronField_1 = require_CronField(); var MIN_DAY = 1; var MAX_DAY = 31; var DAY_CHARS = Object.freeze(["L"]); var CronDayOfMonth = class extends CronField_1.CronField { static get min() { return MIN_DAY; } static get max() { return MAX_DAY; } static get chars() { return DAY_CHARS; } static get validChars() { return /^[?,*\dLH/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/; } /** * CronDayOfMonth constructor. Initializes the "day of the month" field with the provided values. * @param {DayOfMonthRange[]} values - Values for the "day of the month" field * @param {CronFieldOptions} [options] - Options provided by the parser * @throws {Error} if validation fails */ constructor(values, options) { super(values, options); this.validate(); } /** * Returns an array of allowed values for the "day of the month" field. * @returns {DayOfMonthRange[]} */ get values() { return super.values; } }; exports.CronDayOfMonth = CronDayOfMonth; } }); // node_modules/cron-parser/dist/fields/CronDayOfWeek.js var require_CronDayOfWeek = __commonJS({ "node_modules/cron-parser/dist/fields/CronDayOfWeek.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CronDayOfWeek = void 0; var CronField_1 = require_CronField(); var MIN_DAY = 0; var MAX_DAY = 7; var DAY_CHARS = Object.freeze(["L"]); var CronDayOfWeek = class extends CronField_1.CronField { static get min() { return MIN_DAY; } static get max() { return MAX_DAY; } static get chars() { return DAY_CHARS; } static get validChars() { return /^[?,*\dLH#/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/; } /** * CronDayOfTheWeek constructor. Initializes the "day of the week" field with the provided values. * @param {DayOfWeekRange[]} values - Values for the "day of the week" field * @param {CronFieldOptions} [options] - Options provided by the parser */ constructor(values, options) { super(values, options); this.validate(); } /** * Returns an array of allowed values for the "day of the week" field. * @returns {DayOfWeekRange[]} */ get values() { return super.values; } /** * Returns the nth day of the week if specified in the cron expression. * This is used for the '#' character in the cron expression. * @returns {number} The nth day of the week (1-5) or 0 if not specified. */ get nthDay() { var _a5; return (_a5 = this.options.nthDayOfWeek) != null ? _a5 : 0; } }; exports.CronDayOfWeek = CronDayOfWeek; } }); // node_modules/cron-parser/dist/fields/CronHour.js var require_CronHour = __commonJS({ "node_modules/cron-parser/dist/fields/CronHour.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CronHour = void 0; var CronField_1 = require_CronField(); var MIN_HOUR = 0; var MAX_HOUR = 23; var HOUR_CHARS = Object.freeze([]); var CronHour = class extends CronField_1.CronField { static get min() { return MIN_HOUR; } static get max() { return MAX_HOUR; } static get chars() { return HOUR_CHARS; } /** * CronHour constructor. Initializes the "hour" field with the provided values. * @param {HourRange[]} values - Values for the "hour" field * @param {CronFieldOptions} [options] - Options provided by the parser */ constructor(values, options) { super(values, options); this.validate(); } /** * Returns an array of allowed values for the "hour" field. * @returns {HourRange[]} */ get values() { return super.values; } }; exports.CronHour = CronHour; } }); // node_modules/cron-parser/dist/fields/CronMinute.js var require_CronMinute = __commonJS({ "node_modules/cron-parser/dist/fields/CronMinute.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CronMinute = void 0; var CronField_1 = require_CronField(); var MIN_MINUTE = 0; var MAX_MINUTE = 59; var MINUTE_CHARS = Object.freeze([]); var CronMinute = class extends CronField_1.CronField { static get min() { return MIN_MINUTE; } static get max() { return MAX_MINUTE; } static get chars() { return MINUTE_CHARS; } /** * CronSecond constructor. Initializes the "second" field with the provided values. * @param {SixtyRange[]} values - Values for the "second" field * @param {CronFieldOptions} [options] - Options provided by the parser */ constructor(values, options) { super(values, options); this.validate(); } /** * Returns an array of allowed values for the "second" field. * @returns {SixtyRange[]} */ get values() { return super.values; } }; exports.CronMinute = CronMinute; } }); // node_modules/luxon/build/node/luxon.js var require_luxon = __commonJS({ "node_modules/luxon/build/node/luxon.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LuxonError = class extends Error { }; var InvalidDateTimeError = class extends LuxonError { constructor(reason) { super(`Invalid DateTime: ${reason.toMessage()}`); } }; var InvalidIntervalError = class extends LuxonError { constructor(reason) { super(`Invalid Interval: ${reason.toMessage()}`); } }; var InvalidDurationError = class extends LuxonError { constructor(reason) { super(`Invalid Duration: ${reason.toMessage()}`); } }; var ConflictingSpecificationError = class extends LuxonError { }; var InvalidUnitError = class extends LuxonError { constructor(unit) { super(`Invalid unit ${unit}`); } }; var InvalidArgumentError = class extends LuxonError { }; var ZoneIsAbstractError = class extends LuxonError { constructor() { super("Zone is an abstract class"); } }; var n = "numeric"; var s15 = "short"; var l = "long"; var DATE_SHORT = { year: n, month: n, day: n }; var DATE_MED = { year: n, month: s15, day: n }; var DATE_MED_WITH_WEEKDAY = { year: n, month: s15, day: n, weekday: s15 }; 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: s15 }; 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: s15 }; 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: s15, day: n, hour: n, minute: n }; var DATETIME_MED_WITH_SECONDS = { year: n, month: s15, day: n, hour: n, minute: n, second: n }; var DATETIME_MED_WITH_WEEKDAY = { year: n, month: s15, day: n, weekday: s15, hour: n, minute: n }; var DATETIME_FULL = { year: n, month: l, day: n, hour: n, minute: n, timeZoneName: s15 }; var DATETIME_FULL_WITH_SECONDS = { year: n, month: l, day: n, hour: n, minute: n, second: n, timeZoneName: s15 }; 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(); } /** * The IANA name of this zone. * Defaults to `name` if not overwritten by a subclass. * @abstract * @type {string} */ 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(ts2, 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(ts2, format) { throw new ZoneIsAbstractError(); } /** * Return the offset in minutes for this zone at the specified timestamp. * @abstract * @param {number} ts - Epoch milliseconds for which to compute the offset * @return {number} */ offset(ts2) { 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 _SystemZone 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(ts2, { format, locale }) { return parseZoneInfo(ts2, format, locale); } /** @override **/ formatOffset(ts2, format) { return formatOffset(this.offset(ts2), format); } /** @override **/ offset(ts2) { return -new Date(ts2).getTimezoneOffset(); } /** @override **/ equals(otherZone) { return otherZone.type === "system"; } /** @override **/ get isValid() { return true; } }; var dtfCache = /* @__PURE__ */ new Map(); function makeDTF(zoneName) { let dtf = dtfCache.get(zoneName); if (dtf === void 0) { dtf = new Intl.DateTimeFormat("en-US", { hour12: false, timeZone: zoneName, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", era: "short" }); dtfCache.set(zoneName, dtf); } return dtf; } var typeToPos = { year: 0, month: 1, day: 2, era: 3, hour: 4, minute: 5, second: 6 }; function hackyOffset(dtf, date) { const formatted = dtf.format(date).replace(/\u200E/g, ""), parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted), [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed; return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond]; } function partsOffset(dtf, date) { const formatted = dtf.formatToParts(date); const filled = []; for (let i = 0; i < formatted.length; i++) { const { type, value } = formatted[i]; const pos = typeToPos[type]; if (type === "era") { filled[pos] = value; } else if (!isUndefined(pos)) { filled[pos] = parseInt(value, 10); } } return filled; } var ianaZoneCache = /* @__PURE__ */ new Map(); var IANAZone = class _IANAZone extends Zone { /** * @param {string} name - Zone name * @return {IANAZone} */ static create(name) { let zone = ianaZoneCache.get(name); if (zone === void 0) { ianaZoneCache.set(name, zone = new _IANAZone(name)); } return zone; } /** * Reset local caches. Should only be necessary in testing scenarios. * @return {void} */ static resetCache() { ianaZoneCache.clear(); dtfCache.clear(); } /** * 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 For backward compatibility, this forwards to isValidZone, better use `isValidZone()` directly instead. * @return {boolean} */ static isValidSpecifier(s16) { return this.isValidZone(s16); } /** * Returns whether the provided string identifies a real zone * @param {string} zone - The string to check * @example IANAZone.isValidZone("America/New_York") //=> true * @example IANAZone.isValidZone("Fantasia/Castle") //=> false * @example IANAZone.isValidZone("Sport~~blorp") //=> false * @return {boolean} */ static isValidZone(zone) { if (!zone) { return false; } try { new Intl.DateTimeFormat("en-US", { timeZone: zone }).format(); return true; } catch (e) { return false; } } constructor(name) { super(); this.zoneName = name; this.valid = _IANAZone.isValidZone(name); } /** * The type of zone. `iana` for all instances of `IANAZone`. * @override * @type {string} */ get type() { return "iana"; } /** * The name of this zone (i.e. the IANA zone name). * @override * @type {string} */ get name() { return this.zoneName; } /** * Returns whether the offset is known to be fixed for the whole year: * Always returns false for all IANA zones. * @override * @type {boolean} */ get isUniversal() { return false; } /** * Returns the offset's common name (such as EST) at the specified timestamp * @override * @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(ts2, { format, locale }) { return parseZoneInfo(ts2, format, locale, this.name); } /** * Returns the offset's value as a string * @override * @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(ts2, format) { return formatOffset(this.offset(ts2), format); } /** * Return the offset in minutes for this zone at the specified timestamp. * @override * @param {number} ts - Epoch milliseconds for which to compute the offset * @return {number} */ offset(ts2) { if (!this.valid) return NaN; const date = new Date(ts2); 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); } /** * Return whether this Zone is equal to another zone * @override * @param {Zone} otherZone - the zone to compare * @return {boolean} */ equals(otherZone) { return otherZone.type === "iana" && otherZone.name === this.name; } /** * Return whether this Zone is valid. * @override * @type {boolean} */ 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 = /* @__PURE__ */ new Map(); function getCachedDTF(locString, opts = {}) { const key = JSON.stringify([locString, opts]); let dtf = intlDTCache.get(key); if (dtf === void 0) { dtf = new Intl.DateTimeFormat(locString, opts); intlDTCache.set(key, dtf); } return dtf; } var intlNumCache = /* @__PURE__ */ new Map(); function getCachedINF(locString, opts = {}) { const key = JSON.stringify([locString, opts]); let inf = intlNumCache.get(key); if (inf === void 0) { inf = new Intl.NumberFormat(locString, opts); intlNumCache.set(key, inf); } return inf; } var intlRelCache = /* @__PURE__ */ new Map(); function getCachedRTF(locString, opts = {}) { const { base, ...cacheKeyOpts } = opts; const key = JSON.stringify([locString, cacheKeyOpts]); let inf = intlRelCache.get(key); if (inf === void 0) { inf = new Intl.RelativeTimeFormat(locString, opts); intlRelCache.set(key, inf); } return inf; } var sysLocaleCache = null; function systemLocale() { if (sysLocaleCache) { return sysLocaleCache; } else { sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale; return sysLocaleCache; } } var intlResolvedOptionsCache = /* @__PURE__ */ new Map(); function getCachedIntResolvedOptions(locString) { let opts = intlResolvedOptionsCache.get(locString); if (opts === void 0) { opts = new Intl.DateTimeFormat(locString).resolvedOptions(); intlResolvedOptionsCache.set(locString, opts); } return opts; } var weekInfoCache = /* @__PURE__ */ new Map(); function getCachedWeekInfo(locString) { let data = weekInfoCache.get(locString); if (!data) { const locale = new Intl.Locale(locString); data = "getWeekInfo" in locale ? locale.getWeekInfo() : locale.weekInfo; if (!("minimalDays" in data)) { data = { ...fallbackWeekSettings, ...data }; } weekInfoCache.set(locString, data); } return data; } function parseLocaleString(localeStr) { const xIndex = localeStr.indexOf("-x-"); if (xIndex !== -1) { localeStr = localeStr.substring(0, xIndex); } const uIndex = localeStr.indexOf("-u-"); if (uIndex === -1) { return [localeStr]; } else { let options; let selectedStr; try { options = getCachedDTF(localeStr).resolvedOptions(); selectedStr = localeStr; } catch (e) { const smaller = localeStr.substring(0, uIndex); options = getCachedDTF(smaller).resolvedOptions(); selectedStr = smaller; } const { numberingSystem, calendar } = options; return [selectedStr, numberingSystem, calendar]; } } function intlConfigString(localeStr, numberingSystem, outputCalendar) { if (outputCalendar || numberingSystem) { if (!localeStr.includes("-u-")) { localeStr += "-u"; } if (outputCalendar) { localeStr += `-ca-${outputCalendar}`; } if (numberingSystem) { localeStr += `-nu-${numberingSystem}`; } return localeStr; } else { return localeStr; } } function mapMonths(f) { const ms2 = []; for (let i = 1; i <= 12; i++) { const dt2 = DateTime.utc(2009, i, 1); ms2.push(f(dt2)); } return ms2; } function mapWeekdays(f) { const ms2 = []; for (let i = 1; i <= 7; i++) { const dt2 = DateTime.utc(2016, 11, 13 + i); ms2.push(f(dt2)); } return ms2; } 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") || getCachedIntResolvedOptions(loc.locale).numberingSystem === "latn"; } } var PolyNumberFormatter = class { constructor(intl, forceSimple, opts) { this.padTo = opts.padTo || 0; this.floor = opts.floor || false; const { padTo, floor, ...otherOpts } = opts; if (!forceSimple || Object.keys(otherOpts).length > 0) { const intlOpts = { useGrouping: false, ...opts }; if (opts.padTo > 0) intlOpts.minimumIntegerDigits = opts.padTo; this.inf = getCachedINF(intl, intlOpts); } } format(i) { if (this.inf) { const fixed = this.floor ? Math.floor(i) : i; return this.inf.format(fixed); } else { const fixed = this.floor ? Math.floor(i) : roundTo(i, 3); return padStart(fixed, this.padTo); } } }; var PolyDateFormatter = class { constructor(dt2, intl, opts) { this.opts = opts; this.originalZone = void 0; let z2 = void 0; if (this.opts.timeZone) { this.dt = dt2; } else if (dt2.zone.type === "fixed") { const gmtOffset = -1 * (dt2.offset / 60); const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`; if (dt2.offset !== 0 && IANAZone.create(offsetZ).valid) { z2 = offsetZ; this.dt = dt2; } else { z2 = "UTC"; this.dt = dt2.offset === 0 ? dt2 : dt2.setZone("UTC").plus({ minutes: dt2.offset }); this.originalZone = dt2.zone; } } else if (dt2.zone.type === "system") { this.dt = dt2; } else if (dt2.zone.type === "iana") { this.dt = dt2; z2 = dt2.zone.name; } else { z2 = "UTC"; this.dt = dt2.setZone("UTC").plus({ minutes: dt2.offset }); this.originalZone = dt2.zone; } const intlOpts = { ...this.opts }; intlOpts.timeZone = intlOpts.timeZone || z2; 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 fallbackWeekSettings = { firstDay: 1, minimalDays: 4, weekend: [6, 7] }; var Locale = class _Locale { static fromOpts(opts) { return _Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.weekSettings, opts.defaultToEN); } static create(locale, numberingSystem, outputCalendar, weekSettings, defaultToEN = false) { const specifiedLocale = locale || Settings.defaultLocale; const localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale()); const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem; const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar; const weekSettingsR = validateWeekSettings(weekSettings) || Settings.defaultWeekSettings; return new _Locale(localeR, numberingSystemR, outputCalendarR, weekSettingsR, specifiedLocale); } static resetCache() { sysLocaleCache = null; intlDTCache.clear(); intlNumCache.clear(); intlRelCache.clear(); intlResolvedOptionsCache.clear(); weekInfoCache.clear(); } static fromObject({ locale, numberingSystem, outputCalendar, weekSettings } = {}) { return _Locale.create(locale, numberingSystem, outputCalendar, weekSettings); } constructor(locale, numbering, outputCalendar, weekSettings, specifiedLocale) { const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale); this.locale = parsedLocale; this.numberingSystem = numbering || parsedNumberingSystem || null; this.outputCalendar = outputCalendar || parsedOutputCalendar || null; this.weekSettings = weekSettings; 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, validateWeekSettings(alts.weekSettings) || this.weekSettings, alts.defaultToEN || false); } } redefaultToEN(alts = {}) { return this.clone({ ...alts, defaultToEN: true }); } redefaultToSystem(alts = {}) { return this.clone({ ...alts, defaultToEN: false }); } months(length, format = false) { return listStuff(this, length, months, () => { const monthSpecialCase = this.intl === "ja" || this.intl.startsWith("ja-"); format &= !monthSpecialCase; const intl = format ? { month: length, day: "numeric" } : { month: length }, formatStr = format ? "format" : "standalone"; if (!this.monthsCache[formatStr][length]) { const mapper = !monthSpecialCase ? (dt2) => this.extract(dt2, intl, "month") : (dt2) => this.dtFormatter(dt2, intl).format(); this.monthsCache[formatStr][length] = mapMonths(mapper); } return this.monthsCache[formatStr][length]; }); } weekdays(length, format = false) { return listStuff(this, length, weekdays, () => { const intl = format ? { weekday: length, year: "numeric", month: "long", day: "numeric" } : { weekday: length }, formatStr = format ? "format" : "standalone"; if (!this.weekdaysCache[formatStr][length]) { this.weekdaysCache[formatStr][length] = mapWeekdays((dt2) => this.extract(dt2, 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((dt2) => this.extract(dt2, 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((dt2) => this.extract(dt2, intl, "era")); } return this.eraCache[length]; }); } extract(dt2, intlOpts, field) { const df = this.dtFormatter(dt2, intlOpts), results = df.formatToParts(), matching = results.find((m) => m.type.toLowerCase() === field); return matching ? matching.value : null; } numberFormatter(opts = {}) { return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts); } dtFormatter(dt2, intlOpts = {}) { return new PolyDateFormatter(dt2, 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" || getCachedIntResolvedOptions(this.intl).locale.startsWith("en-us"); } getWeekSettings() { if (this.weekSettings) { return this.weekSettings; } else if (!hasLocaleWeekInfo()) { return fallbackWeekSettings; } else { return getCachedWeekInfo(this.locale); } } getStartOfWeek() { return this.getWeekSettings().firstDay; } getMinDaysInFirstWeek() { return this.getWeekSettings().minimalDays; } getWeekendDays() { return this.getWeekSettings().weekend; } equals(other) { return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar; } toString() { return `Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`; } }; var singleton = null; var FixedOffsetZone = class _FixedOffsetZone 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(s16) { if (s16) { const r = s16.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; } /** * The type of zone. `fixed` for all instances of `FixedOffsetZone`. * @override * @type {string} */ get type() { return "fixed"; } /** * The name of this zone. * All fixed zones' names always start with "UTC" (plus optional offset) * @override * @type {string} */ get name() { return this.fixed === 0 ? "UTC" : `UTC${formatOffset(this.fixed, "narrow")}`; } /** * The IANA name of this zone, i.e. `Etc/UTC` or `Etc/GMT+/-nn` * * @override * @type {string} */ get ianaName() { if (this.fixed === 0) { return "Etc/UTC"; } else { return `Etc/GMT${formatOffset(-this.fixed, "narrow")}`; } } /** * Returns the offset's common name at the specified timestamp. * * For fixed offset zones this equals to the zone name. * @override */ offsetName() { return this.name; } /** * Returns the offset's value as a string * @override * @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(ts2, format) { return formatOffset(this.fixed, format); } /** * Returns whether the offset is known to be fixed for the whole year: * Always returns true for all fixed offset zones. * @override * @type {boolean} */ get isUniversal() { return true; } /** * Return the offset in minutes for this zone at the specified timestamp. * * For fixed offset zones, this is constant and does not depend on a timestamp. * @override * @return {number} */ offset() { return this.fixed; } /** * Return whether this Zone is equal to another zone (i.e. also fixed and same offset) * @override * @param {Zone} otherZone - the zone to compare * @return {boolean} */ equals(otherZone) { return otherZone.type === "fixed" && otherZone.fixed === this.fixed; } /** * Return whether this Zone is valid: * All fixed offset zones are valid. * @override * @type {boolean} */ 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 numberingSystems = { arab: "[\u0660-\u0669]", arabext: "[\u06F0-\u06F9]", bali: "[\u1B50-\u1B59]", beng: "[\u09E6-\u09EF]", deva: "[\u0966-\u096F]", fullwide: "[\uFF10-\uFF19]", gujr: "[\u0AE6-\u0AEF]", hanidec: "[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]", khmr: "[\u17E0-\u17E9]", knda: "[\u0CE6-\u0CEF]", laoo: "[\u0ED0-\u0ED9]", limb: "[\u1946-\u194F]", mlym: "[\u0D66-\u0D6F]", mong: "[\u1810-\u1819]", mymr: "[\u1040-\u1049]", orya: "[\u0B66-\u0B6F]", tamldec: "[\u0BE6-\u0BEF]", telu: "[\u0C66-\u0C6F]", thai: "[\u0E50-\u0E59]", tibt: "[\u0F20-\u0F29]", latn: "\\d" }; var numberingSystemsUTF16 = { arab: [1632, 1641], arabext: [1776, 1785], bali: [6992, 7001], beng: [2534, 2543], deva: [2406, 2415], fullwide: [65296, 65303], gujr: [2790, 2799], khmr: [6112, 6121], knda: [3302, 3311], laoo: [3792, 3801], limb: [6470, 6479], mlym: [3430, 3439], mong: [6160, 6169], mymr: [4160, 4169], orya: [2918, 2927], tamldec: [3046, 3055], telu: [3174, 3183], thai: [3664, 3673], tibt: [3872, 3881] }; var hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split(""); function parseDigits(str) { let value = parseInt(str, 10); if (isNaN(value)) { value = ""; for (let i = 0; i < str.length; i++) { const code = str.charCodeAt(i); if (str[i].search(numberingSystems.hanidec) !== -1) { value += hanidecChars.indexOf(str[i]); } else { for (const key in numberingSystemsUTF16) { const [min, max] = numberingSystemsUTF16[key]; if (code >= min && code <= max) { value += code - min; } } } } return parseInt(value, 10); } else { return value; } } var digitRegexCache = /* @__PURE__ */ new Map(); function resetDigitRegexCache() { digitRegexCache.clear(); } function digitRegex({ numberingSystem }, append = "") { const ns2 = numberingSystem || "latn"; let appendCache = digitRegexCache.get(ns2); if (appendCache === void 0) { appendCache = /* @__PURE__ */ new Map(); digitRegexCache.set(ns2, appendCache); } let regex = appendCache.get(append); if (regex === void 0) { regex = new RegExp(`${numberingSystems[ns2]}${append}`); appendCache.set(append, regex); } return regex; } var now = () => Date.now(); var defaultZone = "system"; var defaultLocale = null; var defaultNumberingSystem = null; var defaultOutputCalendar = null; var twoDigitCutoffYear = 60; var throwOnInvalid; var defaultWeekSettings = null; var Settings = class { /** * Get the callback for returning the current timestamp. * @type {function} */ static get now() { return now; } /** * Set the callback for returning the current timestamp. * The function should return a number, which will be interpreted as an Epoch millisecond count * @type {function} * @example Settings.now = () => Date.now() + 3000 // pretend it is 3 seconds in the future * @example Settings.now = () => 0 // always pretend it's Jan 1, 1970 at midnight in UTC time */ static set now(n2) { now = n2; } /** * Set the default time zone to create DateTimes in. Does not affect existing instances. * Use the value "system" to reset this value to the system's time zone. * @type {string} */ static set defaultZone(zone) { defaultZone = zone; } /** * Get the default time zone object currently used to create DateTimes. Does not affect existing instances. * The default value is the system's time zone (the one set on the machine that runs this code). * @type {Zone} */ static get defaultZone() { return normalizeZone(defaultZone, SystemZone.instance); } /** * Get the default locale to create DateTimes with. Does not affect existing instances. * @type {string} */ static get defaultLocale() { return defaultLocale; } /** * Set the default locale to create DateTimes with. Does not affect existing instances. * @type {string} */ static set defaultLocale(locale) { defaultLocale = locale; } /** * Get the default numbering system to create DateTimes with. Does not affect existing instances. * @type {string} */ static get defaultNumberingSystem() { return defaultNumberingSystem; } /** * Set the default numbering system to create DateTimes with. Does not affect existing instances. * @type {string} */ static set defaultNumberingSystem(numberingSystem) { defaultNumberingSystem = numberingSystem; } /** * Get the default output calendar to create DateTimes with. Does not affect existing instances. * @type {string} */ static get defaultOutputCalendar() { return defaultOutputCalendar; } /** * Set the default output calendar to create DateTimes with. Does not affect existing instances. * @type {string} */ static set defaultOutputCalendar(outputCalendar) { defaultOutputCalendar = outputCalendar; } /** * @typedef {Object} WeekSettings * @property {number} firstDay * @property {number} minimalDays * @property {number[]} weekend */ /** * @return {WeekSettings|null} */ static get defaultWeekSettings() { return defaultWeekSettings; } /** * Allows overriding the default locale week settings, i.e. the start of the week, the weekend and * how many days are required in the first week of a year. * Does not affect existing instances. * * @param {WeekSettings|null} weekSettings */ static set defaultWeekSettings(weekSettings) { defaultWeekSettings = validateWeekSettings(weekSettings); } /** * Get the cutoff year for whether a 2-digit year string is interpreted in the current or previous century. Numbers higher than the cutoff will be considered to mean 19xx and numbers lower or equal to the cutoff will be considered 20xx. * @type {number} */ static get twoDigitCutoffYear() { return twoDigitCutoffYear; } /** * Set the cutoff year for whether a 2-digit year string is interpreted in the current or previous century. Numbers higher than the cutoff will be considered to mean 19xx and numbers lower or equal to the cutoff will be considered 20xx. * @type {number} * @example Settings.twoDigitCutoffYear = 0 // all 'yy' are interpreted as 20th century * @example Settings.twoDigitCutoffYear = 99 // all 'yy' are interpreted as 21st century * @example Settings.twoDigitCutoffYear = 50 // '49' -> 2049; '50' -> 1950 * @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(t) { throwOnInvalid = t; } /** * Reset Luxon's global caches. Should only be necessary in testing scenarios. * @return {void} */ static resetCaches() { Locale.resetCache(); IANAZone.resetCache(); DateTime.resetCache(); resetDigitRegexCache(); } }; 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 nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; var leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]; function unitOutOfRange(unit, value) { return new Invalid("unit out of range", `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`); } function dayOfWeek(year, month, day) { const d = new Date(Date.UTC(year, month - 1, day)); if (year < 100 && year >= 0) { d.setUTCFullYear(d.getUTCFullYear() - 1900); } const js2 = d.getUTCDay(); return js2 === 0 ? 7 : js2; } function computeOrdinal(year, month, day) { return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1]; } function uncomputeOrdinal(year, ordinal) { const table = isLeapYear(year) ? leapLadder : nonLeapLadder, month0 = table.findIndex((i) => i < ordinal), day = ordinal - table[month0]; return { month: month0 + 1, day }; } function isoWeekdayToLocal(isoWeekday, startOfWeek) { return (isoWeekday - startOfWeek + 7) % 7 + 1; } function gregorianToWeek(gregObj, minDaysInFirstWeek = 4, startOfWeek = 1) { const { year, month, day } = gregObj, ordinal = computeOrdinal(year, month, day), weekday = isoWeekdayToLocal(dayOfWeek(year, month, day), startOfWeek); let weekNumber = Math.floor((ordinal - weekday + 14 - minDaysInFirstWeek) / 7), weekYear; if (weekNumber < 1) { weekYear = year - 1; weekNumber = weeksInWeekYear(weekYear, minDaysInFirstWeek, startOfWeek); } else if (weekNumber > weeksInWeekYear(year, minDaysInFirstWeek, startOfWeek)) { weekYear = year + 1; weekNumber = 1; } else { weekYear = year; } return { weekYear, weekNumber, weekday, ...timeObject(gregObj) }; } function weekToGregorian(weekData, minDaysInFirstWeek = 4, startOfWeek = 1) { const { weekYear, weekNumber, weekday } = weekData, weekdayOfJan4 = isoWeekdayToLocal(dayOfWeek(weekYear, 1, minDaysInFirstWeek), startOfWeek), yearInDays = daysInYear(weekYear); let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 7 + minDaysInFirstWeek, 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 usesLocalWeekValues(obj, loc) { const hasLocaleWeekData = !isUndefined(obj.localWeekday) || !isUndefined(obj.localWeekNumber) || !isUndefined(obj.localWeekYear); if (hasLocaleWeekData) { const hasIsoWeekData = !isUndefined(obj.weekday) || !isUndefined(obj.weekNumber) || !isUndefined(obj.weekYear); if (hasIsoWeekData) { throw new ConflictingSpecificationError("Cannot mix locale-based week fields with ISO-based week fields"); } if (!isUndefined(obj.localWeekday)) obj.weekday = obj.localWeekday; if (!isUndefined(obj.localWeekNumber)) obj.weekNumber = obj.localWeekNumber; if (!isUndefined(obj.localWeekYear)) obj.weekYear = obj.localWeekYear; delete obj.localWeekday; delete obj.localWeekNumber; delete obj.localWeekYear; return { minDaysInFirstWeek: loc.getMinDaysInFirstWeek(), startOfWeek: loc.getStartOfWeek() }; } else { return { minDaysInFirstWeek: 4, startOfWeek: 1 }; } } function hasInvalidWeekData(obj, minDaysInFirstWeek = 4, startOfWeek = 1) { const validYear = isInteger(obj.weekYear), validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear, minDaysInFirstWeek, startOfWeek)), validWeekday = integerBetween(obj.weekday, 1, 7); if (!validYear) { return unitOutOfRange("weekYear", obj.weekYear); } else if (!validWeek) { return unitOutOfRange("week", obj.weekNumber); } else if (!validWeekday) { return unitOutOfRange("weekday", obj.weekday); } else return false; } function hasInvalidOrdinalData(obj) { const validYear = isInteger(obj.year), validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year)); if (!validYear) { return unitOutOfRange("year", obj.year); } else if (!validOrdinal) { return unitOutOfRange("ordinal", obj.ordinal); } else return false; } function hasInvalidGregorianData(obj) { const validYear = isInteger(obj.year), validMonth = integerBetween(obj.month, 1, 12), validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month)); if (!validYear) { return unitOutOfRange("year", obj.year); } else if (!validMonth) { return unitOutOfRange("month", obj.month); } else if (!validDay) { return unitOutOfRange("day", obj.day); } else return false; } function hasInvalidTimeData(obj) { const { hour, minute, second, millisecond } = obj; const validHour = integerBetween(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0, validMinute = integerBetween(minute, 0, 59), validSecond = integerBetween(second, 0, 59), validMillisecond = integerBetween(millisecond, 0, 999); if (!validHour) { return unitOutOfRange("hour", hour); } else if (!validMinute) { return unitOutOfRange("minute", minute); } else if (!validSecond) { return unitOutOfRange("second", second); } else if (!validMillisecond) { return unitOutOfRange("millisecond", millisecond); } else return false; } function isUndefined(o2) { return typeof o2 === "undefined"; } function isNumber(o2) { return typeof o2 === "number"; } function isInteger(o2) { return typeof o2 === "number" && o2 % 1 === 0; } function isString(o2) { return typeof o2 === "string"; } function isDate(o2) { return Object.prototype.toString.call(o2) === "[object Date]"; } function hasRelative() { try { return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat; } catch (e) { return false; } } function hasLocaleWeekInfo() { try { return typeof Intl !== "undefined" && !!Intl.Locale && ("weekInfo" in Intl.Locale.prototype || "getWeekInfo" in Intl.Locale.prototype); } catch (e) { return false; } } function maybeArray(thing) { return Array.isArray(thing) ? thing : [thing]; } function bestBy(arr, by, compare) { if (arr.length === 0) { return void 0; } return arr.reduce((best, next) => { const pair = [by(next), next]; if (!best) { return pair; } else if (compare(best[0], pair[0]) === best[0]) { return best; } else { return pair; } }, null)[1]; } function pick(obj, keys) { return keys.reduce((a, k) => { a[k] = obj[k]; return a; }, {}); } function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } function validateWeekSettings(settings) { if (settings == null) { return null; } else if (typeof settings !== "object") { throw new InvalidArgumentError("Week settings must be an object"); } else { if (!integerBetween(settings.firstDay, 1, 7) || !integerBetween(settings.minimalDays, 1, 7) || !Array.isArray(settings.weekend) || settings.weekend.some((v2) => !integerBetween(v2, 1, 7))) { throw new InvalidArgumentError("Invalid week settings"); } return { firstDay: settings.firstDay, minimalDays: settings.minimalDays, weekend: Array.from(settings.weekend) }; } } function integerBetween(thing, bottom, top) { return isInteger(thing) && thing >= bottom && thing <= top; } function floorMod(x, n2) { return x - n2 * Math.floor(x / n2); } function padStart(input, n2 = 2) { const isNeg = input < 0; let padded; if (isNeg) { padded = "-" + ("" + -input).padStart(n2, "0"); } else { padded = ("" + input).padStart(n2, "0"); } return padded; } function parseInteger(string) { if (isUndefined(string) || string === null || string === "") { return void 0; } else { return parseInt(string, 10); } } function parseFloating(string) { if (isUndefined(string) || string === null || string === "") { return void 0; } else { return parseFloat(string); } } function parseMillis(fraction) { if (isUndefined(fraction) || fraction === null || fraction === "") { return void 0; } else { const f = parseFloat("0." + fraction) * 1e3; return Math.floor(f); } } function roundTo(number, digits, rounding = "round") { const factor = 10 ** digits; switch (rounding) { case "expand": return number > 0 ? Math.ceil(number * factor) / factor : Math.floor(number * factor) / factor; case "trunc": return Math.trunc(number * factor) / factor; case "round": return Math.round(number * factor) / factor; case "floor": return Math.floor(number * factor) / factor; case "ceil": return Math.ceil(number * factor) / factor; default: throw new RangeError(`Value rounding ${rounding} is out of range`); } } function isLeapYear(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function daysInMonth(year, month) { const modMonth = floorMod(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12; if (modMonth === 2) { return isLeapYear(modYear) ? 29 : 28; } else { return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1]; } } function objToLocalTS(obj) { let d = Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond); if (obj.year < 100 && obj.year >= 0) { d = new Date(d); d.setUTCFullYear(obj.year, obj.month - 1, obj.day); } return +d; } function firstWeekOffset(year, minDaysInFirstWeek, startOfWeek) { const fwdlw = isoWeekdayToLocal(dayOfWeek(year, 1, minDaysInFirstWeek), startOfWeek); return -fwdlw + minDaysInFirstWeek - 1; } function weeksInWeekYear(weekYear, minDaysInFirstWeek = 4, startOfWeek = 1) { const weekOffset = firstWeekOffset(weekYear, minDaysInFirstWeek, startOfWeek); const weekOffsetNext = firstWeekOffset(weekYear + 1, minDaysInFirstWeek, startOfWeek); return (daysInYear(weekYear) - weekOffset + weekOffsetNext) / 7; } function untruncateYear(year) { if (year > 99) { return year; } else return year > Settings.twoDigitCutoffYear ? 1900 + year : 2e3 + year; } function parseZoneInfo(ts2, offsetFormat, locale, timeZone = null) { const date = new Date(ts2), intlOpts = { hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }; if (timeZone) { intlOpts.timeZone = timeZone; } const modified = { timeZoneName: offsetFormat, ...intlOpts }; const parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find((m) => m.type.toLowerCase() === "timezonename"); return parsed ? parsed.value : null; } function signedOffset(offHourStr, offMinuteStr) { let offHour = parseInt(offHourStr, 10); if (Number.isNaN(offHour)) { offHour = 0; } const offMin = parseInt(offMinuteStr, 10) || 0, offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin; return offHour * 60 + offMinSigned; } function asNumber(value) { const numericValue = Number(value); if (typeof value === "boolean" || value === "" || !Number.isFinite(numericValue)) throw new InvalidArgumentError(`Invalid unit value ${value}`); return numericValue; } function normalizeObject(obj, normalizer) { const normalized = {}; for (const u in obj) { if (hasOwnProperty(obj, u)) { const v2 = obj[u]; if (v2 === void 0 || v2 === null) continue; normalized[normalizer(u)] = asNumber(v2); } } return normalized; } function formatOffset(offset2, format) { const hours = Math.trunc(Math.abs(offset2 / 60)), minutes = Math.trunc(Math.abs(offset2 % 60)), sign = offset2 >= 0 ? "+" : "-"; switch (format) { case "short": return `${sign}${padStart(hours, 2)}:${padStart(minutes, 2)}`; case "narrow": return `${sign}${hours}${minutes > 0 ? `:${minutes}` : ""}`; case "techie": return `${sign}${padStart(hours, 2)}${padStart(minutes, 2)}`; default: throw new RangeError(`Value format ${format} is out of range for property format`); } } function timeObject(obj) { return pick(obj, ["hour", "minute", "second", "millisecond"]); } var monthsLong = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var monthsShort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]; function months(length) { switch (length) { case "narrow": return [...monthsNarrow]; case "short": return [...monthsShort]; case "long": return [...monthsLong]; case "numeric": return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]; case "2-digit": return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]; default: return null; } } var weekdaysLong = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; var weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; var weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"]; function weekdays(length) { switch (length) { case "narrow": return [...weekdaysNarrow]; case "short": return [...weekdaysShort]; case "long": return [...weekdaysLong]; case "numeric": return ["1", "2", "3", "4", "5", "6", "7"]; default: return null; } } var meridiems = ["AM", "PM"]; var erasLong = ["Before Christ", "Anno Domini"]; var erasShort = ["BC", "AD"]; var erasNarrow = ["B", "A"]; function eras(length) { switch (length) { case "narrow": return [...erasNarrow]; case "short": return [...erasShort]; case "long": return [...erasLong]; default: return null; } } function meridiemForDateTime(dt2) { return meridiems[dt2.hour < 12 ? 0 : 1]; } function weekdayForDateTime(dt2, length) { return weekdays(length)[dt2.weekday - 1]; } function monthForDateTime(dt2, length) { return months(length)[dt2.month - 1]; } function eraForDateTime(dt2, length) { return eras(length)[dt2.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 s16 = ""; for (const token of splits) { if (token.literal) { s16 += token.val; } else { s16 += tokenToString(token.val); } } return s16; } 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 _Formatter { static create(locale, opts = {}) { return new _Formatter(locale, opts); } static parseFormat(fmt) { let current = null, currentFull = "", bracketed = false; const splits = []; for (let i = 0; i < fmt.length; i++) { const c = fmt.charAt(i); if (c === "'") { if (currentFull.length > 0 || bracketed) { splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull === "" ? "'" : currentFull }); } current = null; currentFull = ""; bracketed = !bracketed; } else if (bracketed) { currentFull += c; } else if (c === current) { currentFull += c; } else { if (currentFull.length > 0) { splits.push({ literal: /^\s+$/.test(currentFull), val: currentFull }); } currentFull = c; current = c; } } if (currentFull.length > 0) { splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull }); } return splits; } static macroTokenToFormatOpts(token) { return macroTokenToFormatOpts[token]; } constructor(locale, formatOpts) { this.opts = formatOpts; this.loc = locale; this.systemLoc = null; } formatWithSystemDefault(dt2, opts) { if (this.systemLoc === null) { this.systemLoc = this.loc.redefaultToSystem(); } const df = this.systemLoc.dtFormatter(dt2, { ...this.opts, ...opts }); return df.format(); } dtFormatter(dt2, opts = {}) { return this.loc.dtFormatter(dt2, { ...this.opts, ...opts }); } formatDateTime(dt2, opts) { return this.dtFormatter(dt2, opts).format(); } formatDateTimeParts(dt2, opts) { return this.dtFormatter(dt2, opts).formatToParts(); } formatInterval(interval, opts) { const df = this.dtFormatter(interval.start, opts); return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate()); } resolvedOptions(dt2, opts) { return this.dtFormatter(dt2, opts).resolvedOptions(); } num(n2, p = 0, signDisplay = void 0) { if (this.opts.forceSimple) { return padStart(n2, p); } const opts = { ...this.opts }; if (p > 0) { opts.padTo = p; } if (signDisplay) { opts.signDisplay = signDisplay; } return this.loc.numberFormatter(opts).format(n2); } formatDateTimeFromString(dt2, fmt) { const knownEnglish = this.loc.listingMode() === "en", useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory", string = (opts, extract) => this.loc.extract(dt2, opts, extract), formatOffset2 = (opts) => { if (dt2.isOffsetFixed && dt2.offset === 0 && opts.allowZ) { return "Z"; } return dt2.isValid ? dt2.zone.formatOffset(dt2.ts, opts.format) : ""; }, meridiem = () => knownEnglish ? meridiemForDateTime(dt2) : string({ hour: "numeric", hourCycle: "h12" }, "dayperiod"), month = (length, standalone) => knownEnglish ? monthForDateTime(dt2, length) : string(standalone ? { month: length } : { month: length, day: "numeric" }, "month"), weekday = (length, standalone) => knownEnglish ? weekdayForDateTime(dt2, length) : string(standalone ? { weekday: length } : { weekday: length, month: "long", day: "numeric" }, "weekday"), maybeMacro = (token) => { const formatOpts = _Formatter.macroTokenToFormatOpts(token); if (formatOpts) { return this.formatWithSystemDefault(dt2, formatOpts); } else { return token; } }, era = (length) => knownEnglish ? eraForDateTime(dt2, length) : string({ era: length }, "era"), tokenToString = (token) => { switch (token) { // ms case "S": return this.num(dt2.millisecond); case "u": // falls through case "SSS": return this.num(dt2.millisecond, 3); // seconds case "s": return this.num(dt2.second); case "ss": return this.num(dt2.second, 2); // fractional seconds case "uu": return this.num(Math.floor(dt2.millisecond / 10), 2); case "uuu": return this.num(Math.floor(dt2.millisecond / 100)); // minutes case "m": return this.num(dt2.minute); case "mm": return this.num(dt2.minute, 2); // hours case "h": return this.num(dt2.hour % 12 === 0 ? 12 : dt2.hour % 12); case "hh": return this.num(dt2.hour % 12 === 0 ? 12 : dt2.hour % 12, 2); case "H": return this.num(dt2.hour); case "HH": return this.num(dt2.hour, 2); // offset 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 dt2.zone.offsetName(dt2.ts, { format: "short", locale: this.loc.locale }); case "ZZZZZ": return dt2.zone.offsetName(dt2.ts, { format: "long", locale: this.loc.locale }); // zone case "z": return dt2.zoneName; // meridiems case "a": return meridiem(); // dates case "d": return useDateTimeFormatter ? string({ day: "numeric" }, "day") : this.num(dt2.day); case "dd": return useDateTimeFormatter ? string({ day: "2-digit" }, "day") : this.num(dt2.day, 2); // weekdays - standalone case "c": return this.num(dt2.weekday); case "ccc": return weekday("short", true); case "cccc": return weekday("long", true); case "ccccc": return weekday("narrow", true); // weekdays - format case "E": return this.num(dt2.weekday); case "EEE": return weekday("short", false); case "EEEE": return weekday("long", false); case "EEEEE": return weekday("narrow", false); // months - standalone case "L": return useDateTimeFormatter ? string({ month: "numeric", day: "numeric" }, "month") : this.num(dt2.month); case "LL": return useDateTimeFormatter ? string({ month: "2-digit", day: "numeric" }, "month") : this.num(dt2.month, 2); case "LLL": return month("short", true); case "LLLL": return month("long", true); case "LLLLL": return month("narrow", true); // months - format case "M": return useDateTimeFormatter ? string({ month: "numeric" }, "month") : this.num(dt2.month); case "MM": return useDateTimeFormatter ? string({ month: "2-digit" }, "month") : this.num(dt2.month, 2); case "MMM": return month("short", false); case "MMMM": return month("long", false); case "MMMMM": return month("narrow", false); // years case "y": return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt2.year); case "yy": return useDateTimeFormatter ? string({ year: "2-digit" }, "year") : this.num(dt2.year.toString().slice(-2), 2); case "yyyy": return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt2.year, 4); case "yyyyyy": return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt2.year, 6); // eras case "G": return era("short"); case "GG": return era("long"); case "GGGGG": return era("narrow"); case "kk": return this.num(dt2.weekYear.toString().slice(-2), 2); case "kkkk": return this.num(dt2.weekYear, 4); case "W": return this.num(dt2.weekNumber); case "WW": return this.num(dt2.weekNumber, 2); case "n": return this.num(dt2.localWeekNumber); case "nn": return this.num(dt2.localWeekNumber, 2); case "ii": return this.num(dt2.localWeekYear.toString().slice(-2), 2); case "iiii": return this.num(dt2.localWeekYear, 4); case "o": return this.num(dt2.ordinal); case "ooo": return this.num(dt2.ordinal, 3); case "q": return this.num(dt2.quarter); case "qq": return this.num(dt2.quarter, 2); case "X": return this.num(Math.floor(dt2.ts / 1e3)); case "x": return this.num(dt2.ts); default: return maybeMacro(token); } }; return stringifyTokens(_Formatter.parseFormat(fmt), tokenToString); } formatDurationFromString(dur, fmt) { const invertLargest = this.opts.signMode === "negativeLargestOnly" ? -1 : 1; const tokenToField = (token) => { switch (token[0]) { case "S": return "milliseconds"; case "s": return "seconds"; case "m": return "minutes"; case "h": return "hours"; case "d": return "days"; case "w": return "weeks"; case "M": return "months"; case "y": return "years"; default: return null; } }, tokenToString = (lildur, info) => (token) => { const mapped = tokenToField(token); if (mapped) { const inversionFactor = info.isNegativeDuration && mapped !== info.largestUnit ? invertLargest : 1; let signDisplay; if (this.opts.signMode === "negativeLargestOnly" && mapped !== info.largestUnit) { signDisplay = "never"; } else if (this.opts.signMode === "all") { signDisplay = "always"; } else { signDisplay = "auto"; } return this.num(lildur.get(mapped) * inversionFactor, token.length, signDisplay); } else { return token; } }, tokens = _Formatter.parseFormat(fmt), realTokens = tokens.reduce((found, { literal, val }) => literal ? found : found.concat(val), []), collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t)), durationInfo = { isNegativeDuration: collapsed < 0, // this relies on "collapsed" being based on "shiftTo", which builds up the object // in order largestUnit: Object.keys(collapsed.values)[0] }; return stringifyTokens(tokens, tokenToString(collapsed, durationInfo)); } }; var ianaRegex = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/; function combineRegexes(...regexes) { const full = regexes.reduce((f, r) => f + r.source, ""); return RegExp(`^${full}$`); } function combineExtractors(...extractors) { return (m) => extractors.reduce(([mergedVals, mergedZone, cursor], ex) => { const [val, zone, next] = ex(m, cursor); return [{ ...mergedVals, ...val }, zone || mergedZone, next]; }, [{}, null, 1]).slice(0, 2); } function parse(s16, ...patterns) { if (s16 == null) { return [null, null]; } for (const [regex, extractor] of patterns) { const m = regex.exec(s16); if (m) { return extractor(m); } } return [null, null]; } function simpleParse(...keys) { return (match2, cursor) => { const ret = {}; let i; for (i = 0; i < keys.length; i++) { ret[keys[i]] = parseInteger(match2[cursor + i]); } return [ret, null, cursor + i]; }; } var offsetRegex = /(?:([Zz])|([+-]\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(`(?:[Tt]${isoTimeRegex.source})?`); var isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/; var isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/; var isoOrdinalRegex = /(\d{4})-?(\d{3})/; var extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay"); var extractISOOrdinalData = simpleParse("year", "ordinal"); var sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/; var sqlTimeRegex = RegExp(`${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`); var sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`); function int(match2, pos, fallback) { const m = match2[pos]; return isUndefined(m) ? fallback : parseInteger(m); } function extractISOYmd(match2, cursor) { const item = { year: int(match2, cursor), month: int(match2, cursor + 1, 1), day: int(match2, cursor + 2, 1) }; return [item, null, cursor + 3]; } function extractISOTime(match2, cursor) { const item = { hours: int(match2, cursor, 0), minutes: int(match2, cursor + 1, 0), seconds: int(match2, cursor + 2, 0), milliseconds: parseMillis(match2[cursor + 3]) }; return [item, null, cursor + 4]; } function extractISOOffset(match2, cursor) { const local = !match2[cursor] && !match2[cursor + 1], fullOffset = signedOffset(match2[cursor + 1], match2[cursor + 2]), zone = local ? null : FixedOffsetZone.instance(fullOffset); return [{}, zone, cursor + 3]; } function extractIANAZone(match2, cursor) { const zone = match2[cursor] ? IANAZone.create(match2[cursor]) : null; return [{}, zone, cursor + 1]; } var isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`); var isoDuration = /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/; function extractISODuration(match2) { const [s16, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = match2; const hasNegativePrefix = s16[0] === "-"; const negativeSeconds = secondStr && secondStr[0] === "-"; const maybeNegate = (num, force = false) => num !== void 0 && (force || num && hasNegativePrefix) ? -num : num; return [{ years: maybeNegate(parseFloating(yearStr)), months: maybeNegate(parseFloating(monthStr)), weeks: maybeNegate(parseFloating(weekStr)), days: maybeNegate(parseFloating(dayStr)), hours: maybeNegate(parseFloating(hourStr)), minutes: maybeNegate(parseFloating(minuteStr)), seconds: maybeNegate(parseFloating(secondStr), secondStr === "-0"), milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds) }]; } var obsOffsets = { GMT: 0, EDT: -4 * 60, EST: -5 * 60, CDT: -5 * 60, CST: -6 * 60, MDT: -6 * 60, MST: -7 * 60, PDT: -7 * 60, PST: -8 * 60 }; function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { const result = { year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr), month: monthsShort.indexOf(monthStr) + 1, day: parseInteger(dayStr), hour: parseInteger(hourStr), minute: parseInteger(minuteStr) }; if (secondStr) result.second = parseInteger(secondStr); if (weekdayStr) { result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1; } return result; } var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/; function extractRFC2822(match2) { const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr, obsOffset, milOffset, offHourStr, offMinuteStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); let offset2; if (obsOffset) { offset2 = obsOffsets[obsOffset]; } else if (milOffset) { offset2 = 0; } else { offset2 = signedOffset(offHourStr, offMinuteStr); } return [result, new FixedOffsetZone(offset2)]; } function preprocessRFC2822(s16) { return s16.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim(); } var rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/; var rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/; var ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/; function extractRFC1123Or850(match2) { const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); return [result, FixedOffsetZone.utcInstance]; } function extractASCII(match2) { const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); return [result, FixedOffsetZone.utcInstance]; } var isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex); var isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex); var isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex); var isoTimeCombinedRegex = combineRegexes(isoTimeRegex); var extractISOYmdTimeAndOffset = combineExtractors(extractISOYmd, extractISOTime, extractISOOffset, extractIANAZone); var extractISOWeekTimeAndOffset = combineExtractors(extractISOWeekData, extractISOTime, extractISOOffset, extractIANAZone); var extractISOOrdinalDateAndTime = combineExtractors(extractISOOrdinalData, extractISOTime, extractISOOffset, extractIANAZone); var extractISOTimeAndOffset = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone); function parseISODate(s16) { return parse(s16, [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], [isoTimeCombinedRegex, extractISOTimeAndOffset]); } function parseRFC2822Date(s16) { return parse(preprocessRFC2822(s16), [rfc2822, extractRFC2822]); } function parseHTTPDate(s16) { return parse(s16, [rfc1123, extractRFC1123Or850], [rfc850, extractRFC1123Or850], [ascii, extractASCII]); } function parseISODuration(s16) { return parse(s16, [isoDuration, extractISODuration]); } var extractISOTimeOnly = combineExtractors(extractISOTime); function parseISOTimeOnly(s16) { return parse(s16, [isoTimeOnly, extractISOTimeOnly]); } var sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex); var sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex); var extractISOTimeOffsetAndIANAZone = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone); function parseSQL(s16) { return parse(s16, [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 _vals$milliseconds; let sum = (_vals$milliseconds = vals.milliseconds) != null ? _vals$milliseconds : 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((previous, current) => { if (!isUndefined(vals[current])) { if (previous) { const previousVal = vals[previous] * factor; const conv = matrix[current][previous]; const rollUp = Math.floor(previousVal / conv); vals[current] += rollUp * factor; vals[previous] -= rollUp * conv * factor; } return current; } else { return previous; } }, null); orderedUnits$1.reduce((previous, current) => { if (!isUndefined(vals[current])) { if (previous) { const fraction = vals[previous] % 1; vals[previous] -= fraction; vals[current] += fraction * matrix[previous][current]; } return current; } else { return previous; } }, null); } function removeZeroes(vals) { const newVals = {}; for (const [key, value] of Object.entries(vals)) { if (value !== 0) { newVals[key] = value; } } return newVals; } var Duration = class _Duration { /** * @private */ constructor(config) { const accurate = config.conversionAccuracy === "longterm" || false; let matrix = accurate ? accurateMatrix : casualMatrix; if (config.matrix) { matrix = config.matrix; } this.values = config.values; this.loc = config.loc || Locale.create(); this.conversionAccuracy = accurate ? "longterm" : "casual"; this.invalid = config.invalid || null; this.matrix = matrix; this.isLuxonDuration = true; } /** * Create Duration from a number of milliseconds. * @param {number} count of milliseconds * @param {Object} opts - options for parsing * @param {string} [opts.locale='en-US'] - the locale to use * @param {string} opts.numberingSystem - the numbering system to use * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @return {Duration} */ static fromMillis(count, opts) { return _Duration.fromObject({ milliseconds: count }, opts); } /** * Create a Duration from a JavaScript object with keys like 'years' and 'hours'. * If this object is empty then a zero milliseconds duration is returned. * @param {Object} obj - the object to create the DateTime from * @param {number} obj.years * @param {number} obj.quarters * @param {number} obj.months * @param {number} obj.weeks * @param {number} obj.days * @param {number} obj.hours * @param {number} obj.minutes * @param {number} obj.seconds * @param {number} obj.milliseconds * @param {Object} [opts=[]] - options for creating this Duration * @param {string} [opts.locale='en-US'] - the locale to use * @param {string} opts.numberingSystem - the numbering system to use * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use * @param {string} [opts.matrix=Object] - the custom conversion system to use * @return {Duration} */ static fromObject(obj, opts = {}) { if (obj == null || typeof obj !== "object") { throw new InvalidArgumentError(`Duration.fromObject: argument expected to be an object, got ${obj === null ? "null" : typeof obj}`); } return new _Duration({ values: normalizeObject(obj, _Duration.normalizeUnit), loc: Locale.fromObject(opts), conversionAccuracy: opts.conversionAccuracy, matrix: opts.matrix }); } /** * Create a Duration from DurationLike. * * @param {Object | number | Duration} durationLike * One of: * - object with keys like 'years' and 'hours'. * - number representing milliseconds * - Duration instance * @return {Duration} */ static fromDurationLike(durationLike) { if (isNumber(durationLike)) { return _Duration.fromMillis(durationLike); } else if (_Duration.isDuration(durationLike)) { return durationLike; } else if (typeof durationLike === "object") { return _Duration.fromObject(durationLike); } else { throw new InvalidArgumentError(`Unknown duration argument ${durationLike} of type ${typeof durationLike}`); } } /** * Create a Duration from an ISO 8601 duration string. * @param {string} text - text to parse * @param {Object} opts - options for parsing * @param {string} [opts.locale='en-US'] - the locale to use * @param {string} opts.numberingSystem - the numbering system to use * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use * @param {string} [opts.matrix=Object] - the preset conversion system to use * @see https://en.wikipedia.org/wiki/ISO_8601#Durations * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 } * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 } * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 } * @return {Duration} */ static fromISO(text, opts) { const [parsed] = parseISODuration(text); if (parsed) { return _Duration.fromObject(parsed, opts); } else { return _Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`); } } /** * Create a Duration from an ISO 8601 time string. * @param {string} text - text to parse * @param {Object} opts - options for parsing * @param {string} [opts.locale='en-US'] - the locale to use * @param {string} opts.numberingSystem - the numbering system to use * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use * @param {string} [opts.matrix=Object] - the conversion system to use * @see https://en.wikipedia.org/wiki/ISO_8601#Times * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 } * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 } * @return {Duration} */ static fromISOTime(text, opts) { const [parsed] = parseISOTimeOnly(text); if (parsed) { return _Duration.fromObject(parsed, opts); } else { return _Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`); } } /** * Create an invalid Duration. * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information * @return {Duration} */ static invalid(reason, explanation = null) { if (!reason) { throw new InvalidArgumentError("need to specify a reason the Duration is invalid"); } const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); if (Settings.throwOnInvalid) { throw new InvalidDurationError(invalid); } else { return new _Duration({ invalid }); } } /** * @private */ static normalizeUnit(unit) { const normalized = { year: "years", years: "years", quarter: "quarters", quarters: "quarters", month: "months", months: "months", week: "weeks", weeks: "weeks", day: "days", days: "days", hour: "hours", hours: "hours", minute: "minutes", minutes: "minutes", second: "seconds", seconds: "seconds", millisecond: "milliseconds", milliseconds: "milliseconds" }[unit ? unit.toLowerCase() : unit]; if (!normalized) throw new InvalidUnitError(unit); return normalized; } /** * Check if an object is a Duration. Works across context boundaries * @param {object} o * @return {boolean} */ static isDuration(o2) { return o2 && o2.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 * @param {'negative'|'all'|'negativeLargestOnly'} [opts.signMode=negative] - How to handle signs * @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" * @example Duration.fromObject({ days: 6, seconds: 2 }).toFormat("d s", { signMode: "all" }) //=> "+6 +2" * @example Duration.fromObject({ days: -6, seconds: -2 }).toFormat("d s", { signMode: "all" }) //=> "-6 -2" * @example Duration.fromObject({ days: -6, seconds: -2 }).toFormat("d s", { signMode: "negativeLargestOnly" }) //=> "-6 2" * @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 `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/NumberFormat#options * @param {Object} opts - Formatting options. Accepts the same keys as the options parameter of the native `Intl.NumberFormat` constructor, as well as `listStyle`. * @param {string} [opts.listStyle='narrow'] - How to format the merged list. Corresponds to the `style` property of the options parameter of the native `Intl.ListFormat` constructor. * @param {boolean} [opts.showZeros=true] - Show all units previously used by the duration even if they are zero * @example * ```js * var dur = Duration.fromObject({ months: 1, weeks: 0, hours: 5, minutes: 6 }) * dur.toHuman() //=> '1 month, 0 weeks, 5 hours, 6 minutes' * dur.toHuman({ listStyle: "long" }) //=> '1 month, 0 weeks, 5 hours, and 6 minutes' * dur.toHuman({ unitDisplay: "short" }) //=> '1 mth, 0 wks, 5 hr, 6 min' * dur.toHuman({ showZeros: false }) //=> '1 month, 5 hours, 6 minutes' * ``` */ toHuman(opts = {}) { if (!this.isValid) return INVALID$2; const showZeros = opts.showZeros !== false; const l2 = orderedUnits$1.map((unit) => { const val = this.values[unit]; if (isUndefined(val) || val === 0 && !showZeros) { 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 s16 = "P"; if (this.years !== 0) s16 += this.years + "Y"; if (this.months !== 0 || this.quarters !== 0) s16 += this.months + this.quarters * 3 + "M"; if (this.weeks !== 0) s16 += this.weeks + "W"; if (this.days !== 0) s16 += this.days + "D"; if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) s16 += "T"; if (this.hours !== 0) s16 += this.hours + "H"; if (this.minutes !== 0) s16 += this.minutes + "M"; if (this.seconds !== 0 || this.milliseconds !== 0) s16 += roundTo(this.seconds + this.milliseconds / 1e3, 3) + "S"; if (s16 === "P") s16 += "T0S"; return s16; } /** * 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 a string representation of this Duration appropriate for the REPL. * @return {string} */ [Symbol.for("nodejs.util.inspect.custom")]() { if (this.isValid) { return `Duration { values: ${JSON.stringify(this.values)} }`; } else { return `Duration { Invalid, reason: ${this.invalidReason} }`; } } /** * 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 k of orderedUnits$1) { if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) { result[k] = dur.get(k) + this.get(k); } } return clone$1(this, { values: result }, true); } /** * Make this Duration shorter by the specified amount. Return a newly-constructed Duration. * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() * @return {Duration} */ minus(duration) { if (!this.isValid) return this; const dur = _Duration.fromDurationLike(duration); return this.plus(dur.negate()); } /** * Scale this Duration by the specified amount. Return a newly-constructed Duration. * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number. * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 } * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === "hours" ? x * 2 : x) //=> { hours: 2, minutes: 30 } * @return {Duration} */ mapUnits(fn2) { if (!this.isValid) return this; const result = {}; for (const k of Object.keys(this.values)) { result[k] = asNumber(fn2(this.values[k], k)); } return clone$1(this, { values: result }, true); } /** * Get the value of unit. * @param {string} unit - a unit such as 'minute' or 'day' * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2 * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0 * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3 * @return {number} */ get(unit) { return this[_Duration.normalizeUnit(unit)]; } /** * "Set" the values of specified units. Return a newly-constructed Duration. * @param {Object} values - a mapping of units to numbers * @example dur.set({ years: 2017 }) * @example dur.set({ hours: 8, minutes: 30 }) * @return {Duration} */ set(values) { if (!this.isValid) return this; const mixed = { ...this.values, ...normalizeObject(values, _Duration.normalizeUnit) }; return clone$1(this, { values: mixed }); } /** * "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration. * @example dur.reconfigure({ locale: 'en-GB' }) * @return {Duration} */ reconfigure({ locale, numberingSystem, conversionAccuracy, matrix } = {}) { const loc = this.loc.clone({ locale, numberingSystem }); const opts = { loc, matrix, conversionAccuracy }; return clone$1(this, opts); } /** * Return the length of the duration in the specified unit. * @param {string} unit - a unit such as 'minutes' or 'days' * @example Duration.fromObject({years: 1}).as('days') //=> 365 * @example Duration.fromObject({years: 1}).as('months') //=> 12 * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5 * @return {number} */ as(unit) { return this.isValid ? this.shiftTo(unit).get(unit) : NaN; } /** * Reduce this Duration to its canonical representation in its current units. * 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 third 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((u) => _Duration.normalizeUnit(u)); const built = {}, accumulated = {}, vals = this.toObject(); let lastUnit; for (const k of orderedUnits$1) { if (units.indexOf(k) >= 0) { lastUnit = k; let own = 0; for (const ak in accumulated) { own += this.matrix[ak][k] * accumulated[ak]; accumulated[ak] = 0; } if (isNumber(vals[k])) { own += vals[k]; } const i = Math.trunc(own); built[k] = i; accumulated[k] = (own * 1e3 - i * 1e3) / 1e3; } else if (isNumber(vals[k])) { accumulated[k] = vals[k]; } } for (const key in accumulated) { if (accumulated[key] !== 0) { built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key]; } } 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 k of Object.keys(this.values)) { negated[k] = this.values[k] === 0 ? 0 : -this.values[k]; } return clone$1(this, { values: negated }, true); } /** * Removes all units with values equal to 0 from this Duration. * @example Duration.fromObject({ years: 2, days: 0, hours: 0, minutes: 0 }).removeZeros().toObject() //=> { years: 2 } * @return {Duration} */ removeZeros() { if (!this.isValid) return this; const vals = removeZeroes(this.values); return clone$1(this, { values: vals }, true); } /** * Get the years. * @type {number} */ get years() { return this.isValid ? this.values.years || 0 : NaN; } /** * Get the quarters. * @type {number} */ get quarters() { return this.isValid ? this.values.quarters || 0 : NaN; } /** * Get the months. * @type {number} */ get months() { return this.isValid ? this.values.months || 0 : NaN; } /** * Get the weeks * @type {number} */ get weeks() { return this.isValid ? this.values.weeks || 0 : NaN; } /** * Get the days. * @type {number} */ get days() { return this.isValid ? this.values.days || 0 : NaN; } /** * Get the hours. * @type {number} */ get hours() { return this.isValid ? this.values.hours || 0 : NaN; } /** * Get the minutes. * @type {number} */ get minutes() { return this.isValid ? this.values.minutes || 0 : NaN; } /** * Get the seconds. * @return {number} */ get seconds() { return this.isValid ? this.values.seconds || 0 : NaN; } /** * Get the milliseconds. * @return {number} */ get milliseconds() { return this.isValid ? this.values.milliseconds || 0 : NaN; } /** * Returns whether the Duration is invalid. Invalid durations are returned by diff operations * on invalid DateTimes or Intervals. * @return {boolean} */ get isValid() { return this.invalid === null; } /** * Returns an error code if this Duration became invalid, or null if the Duration is valid * @return {string} */ get invalidReason() { return this.invalid ? this.invalid.reason : null; } /** * Returns an explanation of why this Duration became invalid, or null if the Duration is valid * @type {string} */ get invalidExplanation() { return this.invalid ? this.invalid.explanation : null; } /** * Equality check * Two Durations are equal iff they have the same units and the same values for each unit. * @param {Duration} other * @return {boolean} */ equals(other) { if (!this.isValid || !other.isValid) { return false; } if (!this.loc.equals(other.loc)) { return false; } function eq(v1, v2) { if (v1 === void 0 || v1 === 0) return v2 === void 0 || v2 === 0; return v1 === v2; } for (const u of orderedUnits$1) { if (!eq(this.values[u], other.values[u])) { return false; } } return true; } }; var INVALID$1 = "Invalid Interval"; function validateStartEnd(start, end) { if (!start || !start.isValid) { return Interval.invalid("missing or invalid start"); } else if (!end || !end.isValid) { return Interval.invalid("missing or invalid end"); } else if (end < start) { return Interval.invalid("end before start", `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}`); } else { return null; } } var Interval = class _Interval { /** * @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), dt2 = friendlyDateTime(start); return _Interval.fromDateTimes(dt2, dt2.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), dt2 = friendlyDateTime(end); return _Interval.fromDateTimes(dt2.minus(dur), dt2); } /** * 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(text, opts) { const [s16, e] = (text || "").split("/", 2); if (s16 && e) { let start, startIsValid; try { start = DateTime.fromISO(s16, opts); startIsValid = start.isValid; } catch (e2) { startIsValid = false; } let end, endIsValid; try { end = DateTime.fromISO(e, opts); endIsValid = end.isValid; } catch (e2) { endIsValid = false; } if (startIsValid && endIsValid) { return _Interval.fromDateTimes(start, end); } if (startIsValid) { const dur = Duration.fromISO(e, opts); if (dur.isValid) { return _Interval.after(start, dur); } } else if (endIsValid) { const dur = Duration.fromISO(s16, opts); if (dur.isValid) { return _Interval.before(end, dur); } } } return _Interval.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`); } /** * Check if an object is an Interval. Works across context boundaries * @param {object} o * @return {boolean} */ static isInterval(o2) { return o2 && o2.isLuxonInterval || false; } /** * Returns the start of the Interval * @type {DateTime} */ get start() { return this.isValid ? this.s : null; } /** * Returns the end of the Interval. This is the first instant which is not part of the interval * (Interval is half-open). * @type {DateTime} */ get end() { return this.isValid ? this.e : null; } /** * Returns the last DateTime included in the interval (since end is not part of the interval) * @type {DateTime} */ get lastDateTime() { return this.isValid ? this.e ? this.e.minus(1) : null : 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. * @param {Object} opts - options * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; this operation will always use the locale of the start DateTime * @return {number} */ count(unit = "milliseconds", opts) { if (!this.isValid) return NaN; const start = this.start.startOf(unit, opts); let end; if (opts != null && opts.useLocaleWeeks) { end = this.end.reconfigure({ locale: start.locale }); } else { end = this.end; } end = end.startOf(unit, opts); 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((d) => this.contains(d)).sort((a, b2) => a.toMillis() - b2.toMillis()), results = []; let { s: s16 } = this, i = 0; while (s16 < this.e) { const added = sorted[i] || this.e, next = +added > +this.e ? this.e : added; results.push(_Interval.fromDateTimes(s16, next)); s16 = next; i += 1; } return results; } /** * Split this Interval into smaller Intervals, each of the specified length. * Left over time is grouped into a smaller interval * @param {Duration|Object|number} duration - The length of each resulting interval. * @return {Array} */ splitBy(duration) { const dur = Duration.fromDurationLike(duration); if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) { return []; } let { s: s16 } = this, idx = 1, next; const results = []; while (s16 < this.e) { const added = this.start.plus(dur.mapUnits((x) => x * idx)); next = +added > +this.e ? this.e : added; results.push(_Interval.fromDateTimes(s16, next)); s16 = 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; } /** * Returns true if this Interval fully contains the specified Interval, specifically if the intersect (of this Interval and the other Interval) is equal to the other Interval; false otherwise. * @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 s16 = this.s > other.s ? this.s : other.s, e = this.e < other.e ? this.e : other.e; if (s16 >= e) { return null; } else { return _Interval.fromDateTimes(s16, e); } } /** * Return an Interval representing the union of this Interval and the specified Interval. * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals. * @param {Interval} other * @return {Interval} */ union(other) { if (!this.isValid) return this; const s16 = this.s < other.s ? this.s : other.s, e = this.e > other.e ? this.e : other.e; return _Interval.fromDateTimes(s16, e); } /** * Merge an array of Intervals into an equivalent minimal set of Intervals. * Combines overlapping and adjacent Intervals. * The resulting array will contain the Intervals in ascending order, that is, starting with the earliest Interval * and ending with the latest. * * @param {Array} intervals * @return {Array} */ static merge(intervals) { const [found, final] = intervals.sort((a, b2) => a.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((i) => [{ time: i.s, type: "s" }, { time: i.e, type: "e" }]), flattened = Array.prototype.concat(...ends), arr = flattened.sort((a, b2) => a.time - b2.time); for (const i of arr) { currentCount += i.type === "s" ? 1 : -1; if (currentCount === 1) { start = i.time; } else { if (start && +start !== +i.time) { results.push(_Interval.fromDateTimes(start, i.time)); } start = null; } } return _Interval.merge(results); } /** * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals. * @param {...Interval} intervals * @return {Array} */ difference(...intervals) { return _Interval.xor([this].concat(intervals)).map((i) => this.intersection(i)).filter((i) => i && !i.isEmpty()); } /** * Returns a string representation of this Interval appropriate for debugging. * @return {string} */ toString() { if (!this.isValid) return INVALID$1; return `[${this.s.toISO()} \u2013 ${this.e.toISO()})`; } /** * Returns a string representation of this Interval appropriate for the REPL. * @return {string} */ [Symbol.for("nodejs.util.inspect.custom")]() { if (this.isValid) { return `Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`; } else { return `Interval { Invalid, reason: ${this.invalidReason} }`; } } /** * 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); } /** * Get the weekday on which the week starts according to the given locale. * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.locObj=null] - an existing locale object to use * @returns {number} the start of the week, 1 for Monday through 7 for Sunday */ static getStartOfWeek({ locale = null, locObj = null } = {}) { return (locObj || Locale.create(locale)).getStartOfWeek(); } /** * Get the minimum number of days necessary in a week before it is considered part of the next year according * to the given locale. * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.locObj=null] - an existing locale object to use * @returns {number} */ static getMinimumDaysInFirstWeek({ locale = null, locObj = null } = {}) { return (locObj || Locale.create(locale)).getMinDaysInFirstWeek(); } /** * Get the weekdays, which are considered the weekend according to the given locale * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.locObj=null] - an existing locale object to use * @returns {number[]} an array of weekdays, 1 for Monday through 7 for Sunday */ static getWeekendWeekdays({ locale = null, locObj = null } = {}) { return (locObj || Locale.create(locale)).getWeekendDays().slice(); } /** * Return an array of standalone month names. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @param {string} [opts.locObj=null] - an existing locale object to use * @param {string} [opts.outputCalendar='gregory'] - the calendar * @example Info.months()[0] //=> 'January' * @example Info.months('short')[0] //=> 'Jan' * @example Info.months('numeric')[0] //=> '1' * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.' * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١' * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I' * @return {Array} */ static months(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) { return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length); } /** * Return an array of format month names. * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that * changes the string. * See {@link Info#months} * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @param {string} [opts.locObj=null] - an existing locale object to use * @param {string} [opts.outputCalendar='gregory'] - the calendar * @return {Array} */ static monthsFormat(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) { return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true); } /** * Return an array of standalone week names. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat * @param {string} [length='long'] - the length of the weekday representation, such as "narrow", "short", "long". * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @param {string} [opts.locObj=null] - an existing locale object to use * @example Info.weekdays()[0] //=> 'Monday' * @example Info.weekdays('short')[0] //=> 'Mon' * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.' * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين' * @return {Array} */ static weekdays(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) { return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length); } /** * Return an array of format week names. * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that * changes the string. * See {@link Info#weekdays} * @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long". * @param {Object} opts - options * @param {string} [opts.locale=null] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @param {string} [opts.locObj=null] - an existing locale object to use * @return {Array} */ static weekdaysFormat(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) { return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true); } /** * Return an array of meridiems. * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @example Info.meridiems() //=> [ 'AM', 'PM' ] * @example Info.meridiems({ locale: 'my' }) //=> [ 'နံနက်', 'ညနေ' ] * @return {Array} */ static meridiems({ locale = null } = {}) { return Locale.create(locale).meridiems(); } /** * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian. * @param {string} [length='short'] - the length of the era representation, such as "short" or "long". * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @example Info.eras() //=> [ 'BC', 'AD' ] * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ] * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ] * @return {Array} */ static eras(length = "short", { locale = null } = {}) { return Locale.create(locale, null, "gregory").eras(length); } /** * Return the set of available features in this environment. * Some features of Luxon are not available in all environments. For example, on older browsers, relative time formatting support is not available. Use this function to figure out if that's the case. * Keys: * * `relative`: whether this environment supports relative time formatting * * `localeWeek`: whether this environment supports different weekdays for the start of the week based on the locale * @example Info.features() //=> { relative: false, localeWeek: true } * @return {Object} */ static features() { return { relative: hasRelative(), localeWeek: hasLocaleWeekInfo() }; } }; function dayDiff(earlier, later) { const utcDayStart = (dt2) => dt2.toUTC(0, { keepLocalTime: true }).startOf("day").valueOf(), ms2 = utcDayStart(later) - utcDayStart(earlier); return Math.floor(Duration.fromMillis(ms2).as("days")); } function highOrderDiffs(cursor, later, units) { const differs = [["years", (a, b2) => b2.year - a.year], ["quarters", (a, b2) => b2.quarter - a.quarter + (b2.year - a.year) * 4], ["months", (a, b2) => b2.month - a.month + (b2.year - a.year) * 12], ["weeks", (a, b2) => { const days = dayDiff(a, 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((u) => ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0); if (lowerOrderUnits.length === 0) { if (highWater < later) { highWater = cursor.plus({ [lowestOrder]: 1 }); } if (highWater !== cursor) { results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor); } } const duration = Duration.fromObject(results, opts); if (lowerOrderUnits.length > 0) { return Duration.fromMillis(remainingMillis, opts).shiftTo(...lowerOrderUnits).plus(duration); } else { return duration; } } var MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support"; function intUnit(regex, post = (i) => i) { return { regex, deser: ([s16]) => post(parseDigits(s16)) }; } var NBSP = String.fromCharCode(160); var spaceOrNBSP = `[ ${NBSP}]`; var spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g"); function fixListRegex(s16) { return s16.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP); } function stripInsensitivities(s16) { return s16.replace(/\./g, "").replace(spaceOrNBSPRegExp, " ").toLowerCase(); } function oneOf(strings, startIndex) { if (strings === null) { return null; } else { return { regex: RegExp(strings.map(fixListRegex).join("|")), deser: ([s16]) => strings.findIndex((i) => stripInsensitivities(s16) === stripInsensitivities(i)) + startIndex }; } } function offset(regex, groups) { return { regex, deser: ([, h2, m]) => signedOffset(h2, m), groups }; } function simple(regex) { return { regex, deser: ([s16]) => s16 }; } function escapeToken(value) { return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); } function unitForToken(token, loc) { const one = digitRegex(loc), two = digitRegex(loc, "{2}"), three = digitRegex(loc, "{3}"), four = digitRegex(loc, "{4}"), six = digitRegex(loc, "{6}"), oneOrTwo = digitRegex(loc, "{1,2}"), oneToThree = digitRegex(loc, "{1,3}"), oneToSix = digitRegex(loc, "{1,6}"), oneToNine = digitRegex(loc, "{1,9}"), twoToFour = digitRegex(loc, "{2,4}"), fourToSix = digitRegex(loc, "{4,6}"), literal = (t) => ({ regex: RegExp(escapeToken(t.val)), deser: ([s16]) => s16, literal: true }), unitate = (t) => { if (token.literal) { return literal(t); } switch (t.val) { // era case "G": return oneOf(loc.eras("short"), 0); case "GG": return oneOf(loc.eras("long"), 0); // years case "y": return intUnit(oneToSix); case "yy": return intUnit(twoToFour, untruncateYear); case "yyyy": return intUnit(four); case "yyyyy": return intUnit(fourToSix); case "yyyyyy": return intUnit(six); // months case "M": return intUnit(oneOrTwo); case "MM": return intUnit(two); case "MMM": return oneOf(loc.months("short", true), 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); // dates case "d": return intUnit(oneOrTwo); case "dd": return intUnit(two); // ordinals case "o": return intUnit(oneToThree); case "ooo": return intUnit(three); // time case "HH": return intUnit(two); case "H": return intUnit(oneOrTwo); case "hh": return intUnit(two); case "h": return intUnit(oneOrTwo); case "mm": return intUnit(two); case "m": return intUnit(oneOrTwo); case "q": return intUnit(oneOrTwo); case "qq": return intUnit(two); case "s": return intUnit(oneOrTwo); case "ss": return intUnit(two); case "S": return intUnit(oneToThree); case "SSS": return intUnit(three); case "u": return simple(oneToNine); case "uu": return simple(oneOrTwo); case "uuu": return intUnit(one); // meridiem case "a": return oneOf(loc.meridiems(), 0); // weekYear (k) case "kkkk": return intUnit(four); case "kk": return intUnit(twoToFour, untruncateYear); // weekNumber (W) case "W": return intUnit(oneOrTwo); case "WW": return intUnit(two); // weekdays case "E": case "c": return intUnit(one); case "EEE": return oneOf(loc.weekdays("short", false), 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); // offset/zone case "Z": case "ZZ": return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2); case "ZZZ": return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2); // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing // because we don't have any way to figure out what they are case "z": return simple(/[a-z_+-/]{1,256}?/i); // this special-case "token" represents a place where a macro-token expanded into a white-space literal // in this case we accept any non-newline white-space case " ": return simple(/[^\S\n\r]/); default: return literal(t); } }; const unit = unitate(token) || { invalidReason: MISSING_FTP }; unit.token = token; return unit; } var partTypeStyleToTokenVal = { year: { "2-digit": "yy", numeric: "yyyyy" }, month: { numeric: "M", "2-digit": "MM", short: "MMM", long: "MMMM" }, day: { numeric: "d", "2-digit": "dd" }, weekday: { short: "EEE", long: "EEEE" }, dayperiod: "a", dayPeriod: "a", 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, value } = part; if (type === "literal") { const isSpace = /^\s+$/.test(value); return { literal: !isSpace, val: isSpace ? " " : value }; } const style = formatOpts[type]; let actualType = type; if (type === "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 re2 = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, ""); return [`^${re2}$`, units]; } function match(input, regex, handlers) { const matches = input.match(regex); if (matches) { const all = {}; let matchIndex = 1; for (const i in handlers) { if (hasOwnProperty(handlers, i)) { const h2 = handlers[i], groups = h2.groups ? h2.groups + 1 : 1; if (!h2.literal && h2.token) { all[h2.token.val[0]] = h2.deser(matches.slice(matchIndex, matchIndex + groups)); } matchIndex += groups; } } return [matches, all]; } else { return [matches, {}]; } } function dateTimeFromMatches(matches) { const toField = (token) => { switch (token) { case "S": return "millisecond"; case "s": return "second"; case "m": return "minute"; case "h": case "H": return "hour"; case "d": return "day"; case "o": return "ordinal"; case "L": case "M": return "month"; case "y": return "year"; case "E": case "c": return "weekday"; case "W": return "weekNumber"; case "k": return "weekYear"; case "q": return "quarter"; default: return null; } }; let zone = null; let specificOffset; if (!isUndefined(matches.z)) { zone = IANAZone.create(matches.z); } if (!isUndefined(matches.Z)) { if (!zone) { zone = new FixedOffsetZone(matches.Z); } specificOffset = matches.Z; } if (!isUndefined(matches.q)) { matches.M = (matches.q - 1) * 3 + 1; } if (!isUndefined(matches.h)) { if (matches.h < 12 && matches.a === 1) { matches.h += 12; } else if (matches.h === 12 && matches.a === 0) { matches.h = 0; } } if (matches.G === 0 && matches.y) { matches.y = -matches.y; } if (!isUndefined(matches.u)) { matches.S = parseMillis(matches.u); } const vals = Object.keys(matches).reduce((r, k) => { const f = toField(k); if (f) { r[f] = matches[k]; } return r; }, {}); return [vals, zone, specificOffset]; } var dummyDateTimeCache = null; function getDummyDateTime() { if (!dummyDateTimeCache) { dummyDateTimeCache = DateTime.fromMillis(1555555555555); } return dummyDateTimeCache; } function maybeExpandMacroToken(token, locale) { if (token.literal) { return token; } const formatOpts = Formatter.macroTokenToFormatOpts(token.val); const tokens = formatOptsToTokens(formatOpts, locale); if (tokens == null || tokens.includes(void 0)) { return token; } return tokens; } function expandMacroTokens(tokens, locale) { return Array.prototype.concat(...tokens.map((t) => maybeExpandMacroToken(t, locale))); } var TokenParser = class { constructor(locale, format) { this.locale = locale; this.format = format; this.tokens = expandMacroTokens(Formatter.parseFormat(format), locale); this.units = this.tokens.map((t) => unitForToken(t, locale)); this.disqualifyingUnit = this.units.find((t) => t.invalidReason); if (!this.disqualifyingUnit) { const [regexString, handlers] = buildRegex(this.units); this.regex = RegExp(regexString, "i"); this.handlers = handlers; } } explainFromTokens(input) { if (!this.isValid) { return { input, tokens: this.tokens, invalidReason: this.invalidReason }; } else { const [rawMatches, matches] = match(input, this.regex, this.handlers), [result, zone, specificOffset] = matches ? dateTimeFromMatches(matches) : [null, null, void 0]; if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) { throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format"); } return { input, tokens: this.tokens, regex: this.regex, rawMatches, matches, result, zone, specificOffset }; } } get isValid() { return !this.disqualifyingUnit; } get invalidReason() { return this.disqualifyingUnit ? this.disqualifyingUnit.invalidReason : null; } }; function explainFromTokens(locale, input, format) { const parser = new TokenParser(locale, format); return parser.explainFromTokens(input); } function parseFromTokens(locale, input, format) { const { result, zone, specificOffset, invalidReason } = explainFromTokens(locale, input, format); return [result, zone, specificOffset, invalidReason]; } function formatOptsToTokens(formatOpts, locale) { if (!formatOpts) { return null; } const formatter = Formatter.create(locale, formatOpts); const df = formatter.dtFormatter(getDummyDateTime()); const parts = df.formatToParts(); const resolvedOpts = df.resolvedOptions(); return parts.map((p) => tokenForPart(p, formatOpts, resolvedOpts)); } var INVALID = "Invalid DateTime"; var MAX_DATE = 864e13; function unsupportedZone(zone) { return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`); } function possiblyCachedWeekData(dt2) { if (dt2.weekData === null) { dt2.weekData = gregorianToWeek(dt2.c); } return dt2.weekData; } function possiblyCachedLocalWeekData(dt2) { if (dt2.localWeekData === null) { dt2.localWeekData = gregorianToWeek(dt2.c, dt2.loc.getMinDaysInFirstWeek(), dt2.loc.getStartOfWeek()); } return dt2.localWeekData; } 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, o2, tz) { let utcGuess = localTS - o2 * 60 * 1e3; const o22 = tz.offset(utcGuess); if (o2 === o22) { return [utcGuess, o2]; } utcGuess -= (o22 - o2) * 60 * 1e3; const o3 = tz.offset(utcGuess); if (o22 === o3) { return [utcGuess, o22]; } return [localTS - Math.min(o22, o3) * 60 * 1e3, Math.max(o22, o3)]; } function tsToObj(ts2, offset2) { ts2 += offset2 * 60 * 1e3; const d = new Date(ts2); return { year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, day: d.getUTCDate(), hour: d.getUTCHours(), minute: d.getUTCMinutes(), second: d.getUTCSeconds(), millisecond: d.getUTCMilliseconds() }; } function objToTS(obj, offset2, zone) { return fixOffset(objToLocalTS(obj), offset2, zone); } function adjustTime(inst, dur) { const oPre = inst.o, year = inst.c.year + Math.trunc(dur.years), month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, c = { ...inst.c, year, month, day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7 }, millisToAdd = Duration.fromObject({ years: dur.years - Math.trunc(dur.years), quarters: dur.quarters - Math.trunc(dur.quarters), months: dur.months - Math.trunc(dur.months), weeks: dur.weeks - Math.trunc(dur.weeks), days: dur.days - Math.trunc(dur.days), hours: dur.hours, minutes: dur.minutes, seconds: dur.seconds, milliseconds: dur.milliseconds }).as("milliseconds"), localTS = objToLocalTS(c); let [ts2, o2] = fixOffset(localTS, oPre, inst.zone); if (millisToAdd !== 0) { ts2 += millisToAdd; o2 = inst.zone.offset(ts2); } return { ts: ts2, o: o2 }; } function parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) { const { setZone, zone } = opts; if (parsed && Object.keys(parsed).length !== 0 || parsedZone) { const interpretationZone = parsedZone || zone, inst = DateTime.fromObject(parsed, { ...opts, zone: interpretationZone, specificOffset }); return setZone ? inst : inst.setZone(zone); } else { return DateTime.invalid(new Invalid("unparsable", `the input "${text}" can't be parsed as ${format}`)); } } function toTechFormat(dt2, format, allowZ = true) { return dt2.isValid ? Formatter.create(Locale.create("en-US"), { allowZ, forceSimple: true }).formatDateTimeFromString(dt2, format) : null; } function toISODate(o2, extended, precision) { const longFormat = o2.c.year > 9999 || o2.c.year < 0; let c = ""; if (longFormat && o2.c.year >= 0) c += "+"; c += padStart(o2.c.year, longFormat ? 6 : 4); if (precision === "year") return c; if (extended) { c += "-"; c += padStart(o2.c.month); if (precision === "month") return c; c += "-"; } else { c += padStart(o2.c.month); if (precision === "month") return c; } c += padStart(o2.c.day); return c; } function toISOTime(o2, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone, precision) { let showSeconds = !suppressSeconds || o2.c.millisecond !== 0 || o2.c.second !== 0, c = ""; switch (precision) { case "day": case "month": case "year": break; default: c += padStart(o2.c.hour); if (precision === "hour") break; if (extended) { c += ":"; c += padStart(o2.c.minute); if (precision === "minute") break; if (showSeconds) { c += ":"; c += padStart(o2.c.second); } } else { c += padStart(o2.c.minute); if (precision === "minute") break; if (showSeconds) { c += padStart(o2.c.second); } } if (precision === "second") break; if (showSeconds && (!suppressMilliseconds || o2.c.millisecond !== 0)) { c += "."; c += padStart(o2.c.millisecond, 3); } } if (includeOffset) { if (o2.isOffsetFixed && o2.offset === 0 && !extendedZone) { c += "Z"; } else if (o2.o < 0) { c += "-"; c += padStart(Math.trunc(-o2.o / 60)); c += ":"; c += padStart(Math.trunc(-o2.o % 60)); } else { c += "+"; c += padStart(Math.trunc(o2.o / 60)); c += ":"; c += padStart(Math.trunc(o2.o % 60)); } } if (extendedZone) { c += "[" + o2.zone.ianaName + "]"; } return c; } var defaultUnitValues = { month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }; var defaultWeekUnitValues = { weekNumber: 1, weekday: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }; var defaultOrdinalUnitValues = { ordinal: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }; var orderedUnits = ["year", "month", "day", "hour", "minute", "second", "millisecond"]; var orderedWeekUnits = ["weekYear", "weekNumber", "weekday", "hour", "minute", "second", "millisecond"]; var orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"]; function normalizeUnit(unit) { const normalized = { year: "year", years: "year", month: "month", months: "month", day: "day", days: "day", hour: "hour", hours: "hour", minute: "minute", minutes: "minute", quarter: "quarter", quarters: "quarter", second: "second", seconds: "second", millisecond: "millisecond", milliseconds: "millisecond", weekday: "weekday", weekdays: "weekday", weeknumber: "weekNumber", weeksnumber: "weekNumber", weeknumbers: "weekNumber", weekyear: "weekYear", weekyears: "weekYear", ordinal: "ordinal" }[unit.toLowerCase()]; if (!normalized) throw new InvalidUnitError(unit); return normalized; } function normalizeUnitWithLocalWeeks(unit) { switch (unit.toLowerCase()) { case "localweekday": case "localweekdays": return "localWeekday"; case "localweeknumber": case "localweeknumbers": return "localWeekNumber"; case "localweekyear": case "localweekyears": return "localWeekYear"; default: return normalizeUnit(unit); } } function guessOffsetForZone(zone) { if (zoneOffsetTs === void 0) { zoneOffsetTs = Settings.now(); } if (zone.type !== "iana") { return zone.offset(zoneOffsetTs); } const zoneName = zone.name; let offsetGuess = zoneOffsetGuessCache.get(zoneName); if (offsetGuess === void 0) { offsetGuess = zone.offset(zoneOffsetTs); zoneOffsetGuessCache.set(zoneName, offsetGuess); } return offsetGuess; } function quickDT(obj, opts) { const zone = normalizeZone(opts.zone, Settings.defaultZone); if (!zone.isValid) { return DateTime.invalid(unsupportedZone(zone)); } const loc = Locale.fromObject(opts); let ts2, o2; if (!isUndefined(obj.year)) { for (const u of orderedUnits) { if (isUndefined(obj[u])) { obj[u] = defaultUnitValues[u]; } } const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj); if (invalid) { return DateTime.invalid(invalid); } const offsetProvis = guessOffsetForZone(zone); [ts2, o2] = objToTS(obj, offsetProvis, zone); } else { ts2 = Settings.now(); } return new DateTime({ ts: ts2, zone, loc, o: o2 }); } function diffRelative(start, end, opts) { const round = isUndefined(opts.round) ? true : opts.round, rounding = isUndefined(opts.rounding) ? "trunc" : opts.rounding, format = (c, unit) => { c = roundTo(c, round || opts.calendary ? 0 : 2, opts.calendary ? "round" : rounding); const formatter = end.loc.clone(opts).relFormatter(opts); return formatter.format(c, unit); }, differ = (unit) => { if (opts.calendary) { if (!end.hasSame(start, unit)) { return end.startOf(unit).diff(start.startOf(unit), unit).get(unit); } else return 0; } else { return end.diff(start, unit).get(unit); } }; if (opts.unit) { return format(differ(opts.unit), opts.unit); } for (const unit of opts.units) { const count = differ(unit); if (Math.abs(count) >= 1) { return format(count, unit); } } return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]); } function lastOpts(argList) { let opts = {}, args; if (argList.length > 0 && typeof argList[argList.length - 1] === "object") { opts = argList[argList.length - 1]; args = Array.from(argList).slice(0, argList.length - 1); } else { args = Array.from(argList); } return [opts, args]; } var zoneOffsetTs; var zoneOffsetGuessCache = /* @__PURE__ */ new Map(); var DateTime = class _DateTime { /** * @access private */ constructor(config) { const zone = config.zone || Settings.defaultZone; let invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null); this.ts = isUndefined(config.ts) ? Settings.now() : config.ts; let c = null, o2 = null; if (!invalid) { const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); if (unchanged) { [c, o2] = [config.old.c, config.old.o]; } else { const ot2 = isNumber(config.o) && !config.old ? config.o : zone.offset(this.ts); c = tsToObj(this.ts, ot2); invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null; c = invalid ? null : c; o2 = invalid ? null : ot2; } } this._zone = zone; this.loc = config.loc || Locale.create(); this.invalid = invalid; this.weekData = null; this.localWeekData = null; this.c = c; this.o = o2; 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 * @param {string} [options.weekSettings] - the week settings 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 ts2 = isDate(date) ? date.valueOf() : NaN; if (Number.isNaN(ts2)) { return _DateTime.invalid("invalid input"); } const zoneToUse = normalizeZone(options.zone, Settings.defaultZone); if (!zoneToUse.isValid) { return _DateTime.invalid(unsupportedZone(zoneToUse)); } return new _DateTime({ ts: ts2, 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 * @param {string} options.weekSettings - the week settings 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 * @param {string} options.weekSettings - the week settings 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.localWeekYear - a week year, according to the locale * @param {number} obj.localWeekNumber - a week number, between 1 and 52 or 53, depending on the year, according to the locale * @param {number} obj.localWeekday - a weekday, 1-7, where 1 is the first and 7 is the last day of the week, according to the locale * @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 * @param {string} opts.weekSettings - the week settings 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' * @example DateTime.fromObject({ localWeekYear: 2022, localWeekNumber: 1, localWeekday: 1 }, { locale: "en-US" }).toISODate() //=> '2021-12-26' * @return {DateTime} */ static fromObject(obj, opts = {}) { obj = obj || {}; const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone); if (!zoneToUse.isValid) { return _DateTime.invalid(unsupportedZone(zoneToUse)); } const loc = Locale.fromObject(opts); const normalized = normalizeObject(obj, normalizeUnitWithLocalWeeks); const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, loc); const tsNow = Settings.now(), offsetProvis = !isUndefined(opts.specificOffset) ? opts.specificOffset : zoneToUse.offset(tsNow), 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"); } const useWeekData = definiteWeekDef || normalized.weekday && !containsGregor; let units, defaultValues, objNow = tsToObj(tsNow, offsetProvis); if (useWeekData) { units = orderedWeekUnits; defaultValues = defaultWeekUnitValues; objNow = gregorianToWeek(objNow, minDaysInFirstWeek, startOfWeek); } else if (containsOrdinal) { units = orderedOrdinalUnits; defaultValues = defaultOrdinalUnitValues; objNow = gregorianToOrdinal(objNow); } else { units = orderedUnits; defaultValues = defaultUnitValues; } let foundFirst = false; for (const u of units) { const v2 = normalized[u]; if (!isUndefined(v2)) { foundFirst = true; } else if (foundFirst) { normalized[u] = defaultValues[u]; } else { normalized[u] = objNow[u]; } } const higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid = higherOrderInvalid || hasInvalidTimeData(normalized); if (invalid) { return _DateTime.invalid(invalid); } const gregorian = useWeekData ? weekToGregorian(normalized, minDaysInFirstWeek, startOfWeek) : 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()}`); } if (!inst.isValid) { return _DateTime.invalid(inst.invalid); } 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 * @param {string} [opts.weekSettings] - the week settings to set on the resulting DateTime instance * @example DateTime.fromISO('2016-05-25T09:08:34.123') * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00') * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true}) * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'}) * @example DateTime.fromISO('2016-W05-4') * @return {DateTime} */ static fromISO(text, opts = {}) { const [vals, parsedZone] = parseISODate(text); return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text); } /** * Create a DateTime from an RFC 2822 string * @param {string} text - the RFC 2822 string * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT') * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600') * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z') * @return {DateTime} */ static fromRFC2822(text, opts = {}) { const [vals, parsedZone] = parseRFC2822Date(text); return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text); } /** * Create a DateTime from an HTTP header date * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 * @param {string} text - the HTTP header date * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods. * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT') * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT') * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994') * @return {DateTime} */ static fromHTTP(text, opts = {}) { const [vals, parsedZone] = parseHTTPDate(text); return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts); } /** * Create a DateTime from an input string and format string. * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens). * @param {string} text - the string to parse * @param {string} fmt - the format the string is expected to be in (see the link below for the formats) * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @return {DateTime} */ static fromFormat(text, fmt, opts = {}) { if (isUndefined(text) || isUndefined(fmt)) { throw new InvalidArgumentError("fromFormat requires an input string and a format"); } const { locale = null, numberingSystem = null } = opts, localeToUse = Locale.fromOpts({ locale, numberingSystem, defaultToEN: true }), [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt); if (invalid) { return _DateTime.invalid(invalid); } else { return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset); } } /** * @deprecated use fromFormat instead */ static fromString(text, fmt, opts = {}) { return _DateTime.fromFormat(text, fmt, opts); } /** * Create a DateTime from a SQL date, time, or datetime * Defaults to en-US if no locale has been specified, regardless of the system's locale * @param {string} text - the string to parse * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @example DateTime.fromSQL('2017-05-15') * @example DateTime.fromSQL('2017-05-15 09:12:34') * @example DateTime.fromSQL('2017-05-15 09:12:34.342') * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00') * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles') * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true }) * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' }) * @example DateTime.fromSQL('09:12:34.342') * @return {DateTime} */ static fromSQL(text, opts = {}) { const [vals, parsedZone] = parseSQL(text); return parseDataToDateTime(vals, parsedZone, opts, "SQL", text); } /** * Create an invalid DateTime. * @param {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(o2) { return o2 && o2.isLuxonDateTime || false; } /** * Produce the format string for a set of options * @param formatOpts * @param localeOpts * @returns {string} */ static parseFormatForOpts(formatOpts, localeOpts = {}) { const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts)); return !tokenList ? null : tokenList.map((t) => t ? t.val : null).join(""); } /** * Produce the the fully expanded format token for the locale * Does NOT quote characters, so quoted tokens will not round trip correctly * @param fmt * @param localeOpts * @returns {string} */ static expandFormat(fmt, localeOpts = {}) { const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts)); return expanded.map((t) => t.val).join(""); } static resetCache() { zoneOffsetTs = void 0; zoneOffsetGuessCache.clear(); } // 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; } /** * Returns true if this date is on a weekend according to the locale, false otherwise * @returns {boolean} */ get isWeekend() { return this.isValid && this.loc.getWeekendDays().includes(this.weekday); } /** * Get the day of the week according to the locale. * 1 is the first day of the week and 7 is the last day of the week. * If the locale assigns Sunday as the first day of the week, then a date which is a Sunday will return 1, * @returns {number} */ get localWeekday() { return this.isValid ? possiblyCachedLocalWeekData(this).weekday : NaN; } /** * Get the week number of the week year according to the locale. Different locales assign week numbers differently, * because the week can start on different days of the week (see localWeekday) and because a different number of days * is required for a week to count as the first week of a year. * @returns {number} */ get localWeekNumber() { return this.isValid ? possiblyCachedLocalWeekData(this).weekNumber : NaN; } /** * Get the week year according to the locale. Different locales assign week numbers (and therefor week years) * differently, see localWeekNumber. * @returns {number} */ get localWeekYear() { return this.isValid ? possiblyCachedLocalWeekData(this).weekYear : 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 number of weeks in this DateTime's local week year * @example DateTime.local(2020, 6, {locale: 'en-US'}).weeksInLocalWeekYear //=> 52 * @example DateTime.local(2020, 6, {locale: 'de-DE'}).weeksInLocalWeekYear //=> 53 * @type {number} */ get weeksInLocalWeekYear() { return this.isValid ? weeksInWeekYear(this.localWeekYear, this.loc.getMinDaysInFirstWeek(), this.loc.getStartOfWeek()) : NaN; } /** * Returns the resolved Intl options for this DateTime. * This is useful in understanding the behavior of formatting methods * @param {Object} opts - the same options as toLocaleString * @return {Object} */ resolvedLocaleOptions(opts = {}) { const { locale, numberingSystem, calendar } = Formatter.create(this.loc.clone(opts), opts).resolvedOptions(this); return { locale, numberingSystem, outputCalendar: calendar }; } // TRANSFORM /** * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime. * * Equivalent to {@link DateTime#setZone}('utc') * @param {number} [offset=0] - optionally, an offset from UTC in minutes * @param {Object} [opts={}] - options to pass to `setZone()` * @return {DateTime} */ toUTC(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, numberingSystem, outputCalendar } = {}) { const loc = this.loc.clone({ locale, numberingSystem, outputCalendar }); return clone(this, { loc }); } /** * "Set" the locale. Returns a newly-constructed DateTime. * Just a convenient alias for reconfigure({ locale }) * @example DateTime.local(2017, 5, 25).setLocale('en-GB') * @return {DateTime} */ setLocale(locale) { return this.reconfigure({ locale }); } /** * "Set" the values of specified units. Returns a newly-constructed DateTime. * You can only set units with this method; for "setting" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}. * * This method also supports setting locale-based week units, i.e. `localWeekday`, `localWeekNumber` and `localWeekYear`. * They cannot be mixed with ISO-week units like `weekday`. * @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, normalizeUnitWithLocalWeeks); const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, this.loc); const 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, minDaysInFirstWeek, startOfWeek), ...normalized }, minDaysInFirstWeek, startOfWeek); } 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 [ts2, o2] = objToTS(mixed, this.o, this.zone); return clone(this, { ts: ts2, o: o2 }); } /** * 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'. * @param {Object} opts - options * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week * @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, { useLocaleWeeks = false } = {}) { if (!this.isValid) return this; const o2 = {}, normalizedUnit = Duration.normalizeUnit(unit); switch (normalizedUnit) { case "years": o2.month = 1; // falls through case "quarters": case "months": o2.day = 1; // falls through case "weeks": case "days": o2.hour = 0; // falls through case "hours": o2.minute = 0; // falls through case "minutes": o2.second = 0; // falls through case "seconds": o2.millisecond = 0; break; } if (normalizedUnit === "weeks") { if (useLocaleWeeks) { const startOfWeek = this.loc.getStartOfWeek(); const { weekday } = this; if (weekday < startOfWeek) { o2.weekNumber = this.weekNumber - 1; } o2.weekday = startOfWeek; } else { o2.weekday = 1; } } if (normalizedUnit === "quarters") { const q2 = Math.ceil(this.month / 3); o2.month = (q2 - 1) * 3 + 1; } return this.set(o2); } /** * "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'. * @param {Object} opts - options * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week * @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, opts) { return this.isValid ? this.plus({ [unit]: 1 }).startOf(unit, opts).minus(1) : this; } // OUTPUT /** * Returns a string representation of this DateTime formatted according to the specified format string. * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens). * Defaults to en-US if no locale has been specified, regardless of the system's locale. * @param {string} fmt - the format string * @param {Object} opts - opts to override the configuration options on this DateTime * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22' * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22' * @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22' * @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes' * @return {string} */ toFormat(fmt, opts = {}) { return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID; } /** * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`. * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation * of the DateTime in the assigned locale. * Defaults to the system's locale if no locale has been specified * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options * @param {Object} opts - opts to override the configuration options on this DateTime * @example DateTime.now().toLocaleString(); //=> 4/20/2017 * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017' * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017' * @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022' * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM' * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM' * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20' * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM' * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32' * @return {string} */ toLocaleString(formatOpts = DATE_SHORT, opts = {}) { return this.isValid ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID; } /** * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output. * Defaults to the system's locale if no locale has been specified * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`. * @example DateTime.now().toLocaleParts(); //=> [ * //=> { type: 'day', value: '25' }, * //=> { type: 'literal', value: '/' }, * //=> { type: 'month', value: '05' }, * //=> { type: 'literal', value: '/' }, * //=> { type: 'year', value: '1982' } * //=> ] */ toLocaleParts(opts = {}) { return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : []; } /** * Returns an ISO 8601-compliant string representation of this DateTime * @param {Object} opts - options * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @param {boolean} [opts.extendedZone=false] - add the time zone format extension * @param {string} [opts.format='extended'] - choose between the basic and extended format * @param {string} [opts.precision='milliseconds'] - truncate output to desired presicion: 'years', 'months', 'days', 'hours', 'minutes', 'seconds' or 'milliseconds'. When precision and suppressSeconds or suppressMilliseconds are used together, precision sets the maximum unit shown in the output, however seconds or milliseconds will still be suppressed if they are 0. * @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' * @example DateTime.now().toISO({ precision: 'day' }) //=> '2017-04-22Z' * @example DateTime.now().toISO({ precision: 'minute' }) //=> '2017-04-22T20:47Z' * @return {string|null} */ toISO({ format = "extended", suppressSeconds = false, suppressMilliseconds = false, includeOffset = true, extendedZone = false, precision = "milliseconds" } = {}) { if (!this.isValid) { return null; } precision = normalizeUnit(precision); const ext = format === "extended"; let c = toISODate(this, ext, precision); if (orderedUnits.indexOf(precision) >= 3) c += "T"; c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone, precision); return c; } /** * Returns an ISO 8601-compliant string representation of this DateTime's date component * @param {Object} opts - options * @param {string} [opts.format='extended'] - choose between the basic and extended format * @param {string} [opts.precision='day'] - truncate output to desired precision: 'years', 'months', or 'days'. * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25' * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525' * @example DateTime.utc(1982, 5, 25).toISODate({ precision: 'month' }) //=> '1982-05' * @return {string|null} */ toISODate({ format = "extended", precision = "day" } = {}) { if (!this.isValid) { return null; } return toISODate(this, format === "extended", normalizeUnit(precision)); } /** * 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 * @param {string} [opts.precision='milliseconds'] - truncate output to desired presicion: 'hours', 'minutes', 'seconds' or 'milliseconds'. When precision and suppressSeconds or suppressMilliseconds are used together, precision sets the maximum unit shown in the output, however seconds or milliseconds will still be suppressed if they are 0. * @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' * @example DateTime.utc().set({ hour: 7, minute: 34, second: 56 }).toISOTime({ precision: 'minute' }) //=> '07:34Z' * @return {string} */ toISOTime({ suppressMilliseconds = false, suppressSeconds = false, includeOffset = true, includePrefix = false, extendedZone = false, format = "extended", precision = "milliseconds" } = {}) { if (!this.isValid) { return null; } precision = normalizeUnit(precision); let c = includePrefix && orderedUnits.indexOf(precision) >= 3 ? "T" : ""; return c + toISOTime(this, format === "extended", suppressSeconds, suppressMilliseconds, includeOffset, extendedZone, precision); } /** * 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|null} */ toSQLDate() { if (!this.isValid) { return null; } return toISODate(this, true); } /** * Returns a string representation of this DateTime appropriate for use in SQL Time * @param {Object} opts - options * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00' * @example DateTime.utc().toSQL() //=> '05:15:16.345' * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00' * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345' * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York' * @return {string} */ toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) { let fmt = "HH:mm:ss.SSS"; if (includeZone || includeOffset) { if (includeOffsetSpace) { fmt += " "; } if (includeZone) { fmt += "z"; } else if (includeOffset) { fmt += "ZZ"; } } return toTechFormat(this, fmt, true); } /** * Returns a string representation of this DateTime appropriate for use in SQL DateTime * @param {Object} opts - options * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00' * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z' * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00' * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000' * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York' * @return {string} */ toSQL(opts = {}) { if (!this.isValid) { return null; } return `${this.toSQLDate()} ${this.toSQLTime(opts)}`; } /** * Returns a string representation of this DateTime appropriate for debugging * @return {string} */ toString() { return this.isValid ? this.toISO() : INVALID; } /** * Returns a string representation of this DateTime appropriate for the REPL. * @return {string} */ [Symbol.for("nodejs.util.inspect.custom")]() { if (this.isValid) { return `DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`; } else { return `DateTime { Invalid, reason: ${this.invalidReason} }`; } } /** * 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 (including milliseconds in the fractional part) 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|DateTime} */ 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 * @param {Object} opts - options * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; only the locale of this DateTime is used * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day * @return {boolean} */ hasSame(otherDateTime, unit, opts) { if (!this.isValid) return false; const inputMs = otherDateTime.valueOf(); const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true }); return adjustedToZone.startOf(unit, opts) <= inputMs && inputMs <= adjustedToZone.endOf(unit, opts); } /** * 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 towards zero 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 {string} [options.rounding="trunc"] - rounding method to use when rounding the numbers in the output. Can be "trunc" (toward zero), "expand" (away from zero), "round", "floor", or "ceil". * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding. * @param {string} options.locale - override the locale of this DateTime * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this * @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day" * @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día" * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures" * @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago" * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago" * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago" */ toRelative(options = {}) { if (!this.isValid) return null; const base = options.base || _DateTime.fromObject({}, { zone: this.zone }), padding = options.padding ? this < base ? -options.padding : options.padding : 0; let units = ["years", "months", "days", "hours", "minutes", "seconds"]; let unit = options.unit; if (Array.isArray(options.unit)) { units = options.unit; unit = void 0; } return diffRelative(base, this.plus(padding), { ...options, numeric: "always", units, unit }); } /** * Returns a string representation of this date relative to today, such as "yesterday" or "next month". * Only internationalizes on platforms that supports Intl.RelativeTimeFormat. * @param {Object} options - options that affect the output * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now. * @param {string} options.locale - override the locale of this DateTime * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days" * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow" * @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana" * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain" * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago" */ toRelativeCalendar(options = {}) { if (!this.isValid) return null; return diffRelative(options.base || _DateTime.fromObject({}, { zone: this.zone }), this, { ...options, numeric: "auto", units: ["years", "months", "days"], calendary: true }); } /** * Return the min of several date times * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum * @return {DateTime} the min DateTime, or undefined if called with no argument */ static min(...dateTimes) { if (!dateTimes.every(_DateTime.isDateTime)) { throw new InvalidArgumentError("min requires all arguments be DateTimes"); } return bestBy(dateTimes, (i) => i.valueOf(), Math.min); } /** * Return the max of several date times * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum * @return {DateTime} the max DateTime, or undefined if called with no argument */ static max(...dateTimes) { if (!dateTimes.every(_DateTime.isDateTime)) { throw new InvalidArgumentError("max requires all arguments be DateTimes"); } return bestBy(dateTimes, (i) => i.valueOf(), Math.max); } // MISC /** * Explain how a string would be parsed by fromFormat() * @param {string} text - the string to parse * @param {string} fmt - the format the string is expected to be in (see description) * @param {Object} options - options taken by fromFormat() * @return {Object} */ static fromFormatExplain(text, fmt, options = {}) { const { locale = null, numberingSystem = null } = options, localeToUse = Locale.fromOpts({ locale, numberingSystem, defaultToEN: true }); return explainFromTokens(localeToUse, text, fmt); } /** * @deprecated use fromFormatExplain instead */ static fromStringExplain(text, fmt, options = {}) { return _DateTime.fromFormatExplain(text, fmt, options); } /** * Build a parser for `fmt` using the given locale. This parser can be passed * to {@link DateTime.fromFormatParser} to a parse a date in this format. This * can be used to optimize cases where many dates need to be parsed in a * specific format. * * @param {String} fmt - the format the string is expected to be in (see * description) * @param {Object} options - options used to set locale and numberingSystem * for parser * @returns {TokenParser} - opaque object to be used */ static buildFormatParser(fmt, options = {}) { const { locale = null, numberingSystem = null } = options, localeToUse = Locale.fromOpts({ locale, numberingSystem, defaultToEN: true }); return new TokenParser(localeToUse, fmt); } /** * Create a DateTime from an input string and format parser. * * The format parser must have been created with the same locale as this call. * * @param {String} text - the string to parse * @param {TokenParser} formatParser - parser from {@link DateTime.buildFormatParser} * @param {Object} opts - options taken by fromFormat() * @returns {DateTime} */ static fromFormatParser(text, formatParser, opts = {}) { if (isUndefined(text) || isUndefined(formatParser)) { throw new InvalidArgumentError("fromFormatParser requires an input string and a format parser"); } const { locale = null, numberingSystem = null } = opts, localeToUse = Locale.fromOpts({ locale, numberingSystem, defaultToEN: true }); if (!localeToUse.equals(formatParser.locale)) { throw new InvalidArgumentError(`fromFormatParser called with a locale of ${localeToUse}, but the format parser was created for ${formatParser.locale}`); } const { result, zone, specificOffset, invalidReason } = formatParser.explainFromTokens(text); if (invalidReason) { return _DateTime.invalid(invalidReason); } else { return parseDataToDateTime(result, zone, opts, `format ${formatParser.format}`, text, specificOffset); } } // FORMAT PRESETS /** * {@link DateTime#toLocaleString} format like 10/14/1983 * @type {Object} */ static get DATE_SHORT() { return DATE_SHORT; } /** * {@link DateTime#toLocaleString} format like 'Oct 14, 1983' * @type {Object} */ static get DATE_MED() { return DATE_MED; } /** * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983' * @type {Object} */ static get DATE_MED_WITH_WEEKDAY() { return DATE_MED_WITH_WEEKDAY; } /** * {@link DateTime#toLocaleString} format like 'October 14, 1983' * @type {Object} */ static get DATE_FULL() { return DATE_FULL; } /** * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983' * @type {Object} */ static get DATE_HUGE() { return DATE_HUGE; } /** * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is. * @type {Object} */ static get TIME_SIMPLE() { return TIME_SIMPLE; } /** * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is. * @type {Object} */ static get TIME_WITH_SECONDS() { return TIME_WITH_SECONDS; } /** * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is. * @type {Object} */ static get TIME_WITH_SHORT_OFFSET() { return TIME_WITH_SHORT_OFFSET; } /** * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is. * @type {Object} */ static get TIME_WITH_LONG_OFFSET() { return TIME_WITH_LONG_OFFSET; } /** * {@link DateTime#toLocaleString} format like '09:30', always 24-hour. * @type {Object} */ static get TIME_24_SIMPLE() { return TIME_24_SIMPLE; } /** * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour. * @type {Object} */ static get TIME_24_WITH_SECONDS() { return TIME_24_WITH_SECONDS; } /** * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour. * @type {Object} */ static get TIME_24_WITH_SHORT_OFFSET() { return TIME_24_WITH_SHORT_OFFSET; } /** * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour. * @type {Object} */ static get TIME_24_WITH_LONG_OFFSET() { return TIME_24_WITH_LONG_OFFSET; } /** * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_SHORT() { return DATETIME_SHORT; } /** * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_SHORT_WITH_SECONDS() { return DATETIME_SHORT_WITH_SECONDS; } /** * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_MED() { return DATETIME_MED; } /** * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_MED_WITH_SECONDS() { return DATETIME_MED_WITH_SECONDS; } /** * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_MED_WITH_WEEKDAY() { return DATETIME_MED_WITH_WEEKDAY; } /** * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_FULL() { return DATETIME_FULL; } /** * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_FULL_WITH_SECONDS() { return DATETIME_FULL_WITH_SECONDS; } /** * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_HUGE() { return DATETIME_HUGE; } /** * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is. * @type {Object} */ static get DATETIME_HUGE_WITH_SECONDS() { return DATETIME_HUGE_WITH_SECONDS; } }; function friendlyDateTime(dateTimeish) { if (DateTime.isDateTime(dateTimeish)) { return dateTimeish; } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) { return DateTime.fromJSDate(dateTimeish); } else if (dateTimeish && typeof dateTimeish === "object") { return DateTime.fromObject(dateTimeish); } else { throw new InvalidArgumentError(`Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`); } } var VERSION = "3.7.2"; exports.DateTime = DateTime; exports.Duration = Duration; exports.FixedOffsetZone = FixedOffsetZone; exports.IANAZone = IANAZone; exports.Info = Info; exports.Interval = Interval; exports.InvalidZone = InvalidZone; exports.Settings = Settings; exports.SystemZone = SystemZone; exports.VERSION = VERSION; exports.Zone = Zone; } }); // node_modules/cron-parser/dist/CronDate.js var require_CronDate = __commonJS({ "node_modules/cron-parser/dist/CronDate.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CronDate = exports.DAYS_IN_MONTH = exports.DateMathOp = exports.TimeUnit = void 0; var luxon_1 = require_luxon(); var TimeUnit; (function(TimeUnit2) { TimeUnit2["Second"] = "Second"; TimeUnit2["Minute"] = "Minute"; TimeUnit2["Hour"] = "Hour"; TimeUnit2["Day"] = "Day"; TimeUnit2["Month"] = "Month"; TimeUnit2["Year"] = "Year"; })(TimeUnit || (exports.TimeUnit = TimeUnit = {})); var DateMathOp; (function(DateMathOp2) { DateMathOp2["Add"] = "Add"; DateMathOp2["Subtract"] = "Subtract"; })(DateMathOp || (exports.DateMathOp = DateMathOp = {})); exports.DAYS_IN_MONTH = Object.freeze([31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]); var _date, _dstStart, _dstEnd, _verbMap, _CronDate_static, isLeapYear_fn, _CronDate_instances, getUTC_fn; var _CronDate = class _CronDate { /** * Constructs a new CronDate instance. * @param {CronDate | Date | number | string} [timestamp] - The timestamp to initialize the CronDate with. * @param {string} [tz] - The timezone to use for the CronDate. */ constructor(timestamp, tz) { __privateAdd(this, _CronDate_instances); __privateAdd(this, _date); __privateAdd(this, _dstStart, null); __privateAdd(this, _dstEnd, null); /** * Maps the verb to the appropriate method */ __privateAdd(this, _verbMap, { add: { [TimeUnit.Year]: this.addYear.bind(this), [TimeUnit.Month]: this.addMonth.bind(this), [TimeUnit.Day]: this.addDay.bind(this), [TimeUnit.Hour]: this.addHour.bind(this), [TimeUnit.Minute]: this.addMinute.bind(this), [TimeUnit.Second]: this.addSecond.bind(this) }, subtract: { [TimeUnit.Year]: this.subtractYear.bind(this), [TimeUnit.Month]: this.subtractMonth.bind(this), [TimeUnit.Day]: this.subtractDay.bind(this), [TimeUnit.Hour]: this.subtractHour.bind(this), [TimeUnit.Minute]: this.subtractMinute.bind(this), [TimeUnit.Second]: this.subtractSecond.bind(this) } }); const dateOpts = { zone: tz }; if (!timestamp) { __privateSet(this, _date, luxon_1.DateTime.local()); } else if (timestamp instanceof _CronDate) { __privateSet(this, _date, __privateGet(timestamp, _date)); __privateSet(this, _dstStart, __privateGet(timestamp, _dstStart)); __privateSet(this, _dstEnd, __privateGet(timestamp, _dstEnd)); } else if (timestamp instanceof Date) { __privateSet(this, _date, luxon_1.DateTime.fromJSDate(timestamp, dateOpts)); } else if (typeof timestamp === "number") { __privateSet(this, _date, luxon_1.DateTime.fromMillis(timestamp, dateOpts)); } else { __privateSet(this, _date, luxon_1.DateTime.fromISO(timestamp, dateOpts)); __privateGet(this, _date).isValid || __privateSet(this, _date, luxon_1.DateTime.fromRFC2822(timestamp, dateOpts)); __privateGet(this, _date).isValid || __privateSet(this, _date, luxon_1.DateTime.fromSQL(timestamp, dateOpts)); __privateGet(this, _date).isValid || __privateSet(this, _date, luxon_1.DateTime.fromFormat(timestamp, "EEE, d MMM yyyy HH:mm:ss", dateOpts)); } if (!__privateGet(this, _date).isValid) { throw new Error(`CronDate: unhandled timestamp: ${timestamp}`); } if (tz && tz !== __privateGet(this, _date).zoneName) { __privateSet(this, _date, __privateGet(this, _date).setZone(tz)); } } /** * Returns daylight savings start time. * @returns {number | null} */ get dstStart() { return __privateGet(this, _dstStart); } /** * Sets daylight savings start time. * @param {number | null} value */ set dstStart(value) { __privateSet(this, _dstStart, value); } /** * Returns daylight savings end time. * @returns {number | null} */ get dstEnd() { return __privateGet(this, _dstEnd); } /** * Sets daylight savings end time. * @param {number | null} value */ set dstEnd(value) { __privateSet(this, _dstEnd, value); } /** * Adds one year to the current CronDate. */ addYear() { __privateSet(this, _date, __privateGet(this, _date).plus({ years: 1 })); } /** * Adds one month to the current CronDate. */ addMonth() { __privateSet(this, _date, __privateGet(this, _date).plus({ months: 1 }).startOf("month")); } /** * Adds one day to the current CronDate. */ addDay() { __privateSet(this, _date, __privateGet(this, _date).plus({ days: 1 }).startOf("day")); } /** * Adds one hour to the current CronDate. */ addHour() { __privateSet(this, _date, __privateGet(this, _date).plus({ hours: 1 }).startOf("hour")); } /** * Adds one minute to the current CronDate. */ addMinute() { __privateSet(this, _date, __privateGet(this, _date).plus({ minutes: 1 }).startOf("minute")); } /** * Adds one second to the current CronDate. */ addSecond() { __privateSet(this, _date, __privateGet(this, _date).plus({ seconds: 1 })); } /** * Subtracts one year from the current CronDate. */ subtractYear() { __privateSet(this, _date, __privateGet(this, _date).minus({ years: 1 })); } /** * Subtracts one month from the current CronDate. * If the month is 1, it will subtract one year instead. */ subtractMonth() { __privateSet(this, _date, __privateGet(this, _date).minus({ months: 1 }).endOf("month").startOf("second")); } /** * Subtracts one day from the current CronDate. * If the day is 1, it will subtract one month instead. */ subtractDay() { __privateSet(this, _date, __privateGet(this, _date).minus({ days: 1 }).endOf("day").startOf("second")); } /** * Subtracts one hour from the current CronDate. * If the hour is 0, it will subtract one day instead. */ subtractHour() { __privateSet(this, _date, __privateGet(this, _date).minus({ hours: 1 }).endOf("hour").startOf("second")); } /** * Subtracts one minute from the current CronDate. * If the minute is 0, it will subtract one hour instead. */ subtractMinute() { __privateSet(this, _date, __privateGet(this, _date).minus({ minutes: 1 }).endOf("minute").startOf("second")); } /** * Subtracts one second from the current CronDate. * If the second is 0, it will subtract one minute instead. */ subtractSecond() { __privateSet(this, _date, __privateGet(this, _date).minus({ seconds: 1 })); } /** * Adds a unit of time to the current CronDate. * @param {TimeUnit} unit */ addUnit(unit) { __privateGet(this, _verbMap).add[unit](); } /** * Subtracts a unit of time from the current CronDate. * @param {TimeUnit} unit */ subtractUnit(unit) { __privateGet(this, _verbMap).subtract[unit](); } /** * Handles a math operation. * @param {DateMathOp} verb - {'add' | 'subtract'} * @param {TimeUnit} unit - {'year' | 'month' | 'day' | 'hour' | 'minute' | 'second'} */ invokeDateOperation(verb, unit) { if (verb === DateMathOp.Add) { this.addUnit(unit); return; } if (verb === DateMathOp.Subtract) { this.subtractUnit(unit); return; } throw new Error(`Invalid verb: ${verb}`); } /** * Returns the day. * @returns {number} */ getDate() { return __privateGet(this, _date).day; } /** * Returns the year. * @returns {number} */ getFullYear() { return __privateGet(this, _date).year; } /** * Returns the day of the week. * @returns {number} */ getDay() { const weekday = __privateGet(this, _date).weekday; return weekday === 7 ? 0 : weekday; } /** * Returns the month. * @returns {number} */ getMonth() { return __privateGet(this, _date).month - 1; } /** * Returns the hour. * @returns {number} */ getHours() { return __privateGet(this, _date).hour; } /** * Returns the minutes. * @returns {number} */ getMinutes() { return __privateGet(this, _date).minute; } /** * Returns the seconds. * @returns {number} */ getSeconds() { return __privateGet(this, _date).second; } /** * Returns the milliseconds. * @returns {number} */ getMilliseconds() { return __privateGet(this, _date).millisecond; } /** * Returns the timezone offset from UTC in minutes (e.g. UTC+2 => 120). * Useful for detecting DST transition days. * * @returns {number} UTC offset in minutes */ getUTCOffset() { return __privateGet(this, _date).offset; } /** * Sets the time to the start of the day (00:00:00.000) in the current timezone. */ setStartOfDay() { __privateSet(this, _date, __privateGet(this, _date).startOf("day")); } /** * Sets the time to the end of the day (23:59:59.999) in the current timezone. */ setEndOfDay() { __privateSet(this, _date, __privateGet(this, _date).endOf("day")); } /** * Returns the time. * @returns {number} */ getTime() { return __privateGet(this, _date).valueOf(); } /** * Returns the UTC day. * @returns {number} */ getUTCDate() { return __privateMethod(this, _CronDate_instances, getUTC_fn).call(this).day; } /** * Returns the UTC year. * @returns {number} */ getUTCFullYear() { return __privateMethod(this, _CronDate_instances, getUTC_fn).call(this).year; } /** * Returns the UTC day of the week. * @returns {number} */ getUTCDay() { const weekday = __privateMethod(this, _CronDate_instances, getUTC_fn).call(this).weekday; return weekday === 7 ? 0 : weekday; } /** * Returns the UTC month. * @returns {number} */ getUTCMonth() { return __privateMethod(this, _CronDate_instances, getUTC_fn).call(this).month - 1; } /** * Returns the UTC hour. * @returns {number} */ getUTCHours() { return __privateMethod(this, _CronDate_instances, getUTC_fn).call(this).hour; } /** * Returns the UTC minutes. * @returns {number} */ getUTCMinutes() { return __privateMethod(this, _CronDate_instances, getUTC_fn).call(this).minute; } /** * Returns the UTC seconds. * @returns {number} */ getUTCSeconds() { return __privateMethod(this, _CronDate_instances, getUTC_fn).call(this).second; } /** * Returns the UTC milliseconds. * @returns {string | null} */ toISOString() { return __privateGet(this, _date).toUTC().toISO(); } /** * Returns the date as a JSON string. * @returns {string | null} */ toJSON() { return __privateGet(this, _date).toJSON(); } /** * Sets the day. * @param d */ setDate(d) { __privateSet(this, _date, __privateGet(this, _date).set({ day: d })); } /** * Sets the year. * @param y */ setFullYear(y) { __privateSet(this, _date, __privateGet(this, _date).set({ year: y })); } /** * Sets the day of the week. * @param d */ setDay(d) { __privateSet(this, _date, __privateGet(this, _date).set({ weekday: d })); } /** * Sets the month. * @param m */ setMonth(m) { __privateSet(this, _date, __privateGet(this, _date).set({ month: m + 1 })); } /** * Sets the hour. * @param h */ setHours(h2) { __privateSet(this, _date, __privateGet(this, _date).set({ hour: h2 })); } /** * Sets the minutes. * @param m */ setMinutes(m) { __privateSet(this, _date, __privateGet(this, _date).set({ minute: m })); } /** * Sets the seconds. * @param s */ setSeconds(s15) { __privateSet(this, _date, __privateGet(this, _date).set({ second: s15 })); } /** * Sets the milliseconds. * @param s */ setMilliseconds(s15) { __privateSet(this, _date, __privateGet(this, _date).set({ millisecond: s15 })); } /** * Returns the date as a string. * @returns {string} */ toString() { return this.toDate().toString(); } /** * Returns the date as a Date object. * @returns {Date} */ toDate() { return __privateGet(this, _date).toJSDate(); } /** * Returns true if the day is the last day of the month. * @returns {boolean} */ isLastDayOfMonth() { var _a5; const { day, month } = __privateGet(this, _date); if (month === 2) { const isLeap = __privateMethod(_a5 = _CronDate, _CronDate_static, isLeapYear_fn).call(_a5, __privateGet(this, _date).year); return day === exports.DAYS_IN_MONTH[month - 1] - (isLeap ? 0 : 1); } return day === exports.DAYS_IN_MONTH[month - 1]; } /** * Returns true if the day is the last weekday of the month. * @returns {boolean} */ isLastWeekdayOfMonth() { var _a5; const { day, month } = __privateGet(this, _date); let lastDay; if (month === 2) { lastDay = exports.DAYS_IN_MONTH[month - 1] - (__privateMethod(_a5 = _CronDate, _CronDate_static, isLeapYear_fn).call(_a5, __privateGet(this, _date).year) ? 0 : 1); } else { lastDay = exports.DAYS_IN_MONTH[month - 1]; } return day > lastDay - 7; } /** * Primarily for internal use. * @param {DateMathOp} op - The operation to perform. * @param {TimeUnit} unit - The unit of time to use. * @param {number} [hoursLength] - The length of the hours. Required when unit is not month or day. */ applyDateOperation(op, unit, hoursLength) { if (unit === TimeUnit.Month || unit === TimeUnit.Day) { this.invokeDateOperation(op, unit); return; } const previousHour = this.getHours(); this.invokeDateOperation(op, unit); const currentHour = this.getHours(); const diff = currentHour - previousHour; if (diff === 2) { if (hoursLength !== 24) { this.dstStart = currentHour; } } else if (diff === 0 && this.getMinutes() === 0 && this.getSeconds() === 0) { if (hoursLength !== 24) { this.dstEnd = currentHour; } } } }; _date = new WeakMap(); _dstStart = new WeakMap(); _dstEnd = new WeakMap(); _verbMap = new WeakMap(); _CronDate_static = new WeakSet(); isLeapYear_fn = function(year) { return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0; }; _CronDate_instances = new WeakSet(); /** * Returns the UTC date. * @private * @returns {DateTime} */ getUTC_fn = function() { return __privateGet(this, _date).toUTC(); }; __privateAdd(_CronDate, _CronDate_static); var CronDate = _CronDate; exports.CronDate = CronDate; exports.default = CronDate; } }); // node_modules/cron-parser/dist/fields/CronMonth.js var require_CronMonth = __commonJS({ "node_modules/cron-parser/dist/fields/CronMonth.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CronMonth = void 0; var CronDate_1 = require_CronDate(); var CronField_1 = require_CronField(); var MIN_MONTH = 1; var MAX_MONTH = 12; var MONTH_CHARS = Object.freeze([]); var CronMonth = class extends CronField_1.CronField { static get min() { return MIN_MONTH; } static get max() { return MAX_MONTH; } static get chars() { return MONTH_CHARS; } static get daysInMonth() { return CronDate_1.DAYS_IN_MONTH; } /** * CronDayOfMonth constructor. Initializes the "day of the month" field with the provided values. * @param {MonthRange[]} values - Values for the "day of the month" field * @param {CronFieldOptions} [options] - Options provided by the parser */ constructor(values, options) { super(values, options); this.validate(); } /** * Returns an array of allowed values for the "day of the month" field. * @returns {MonthRange[]} */ get values() { return super.values; } }; exports.CronMonth = CronMonth; } }); // node_modules/cron-parser/dist/fields/CronSecond.js var require_CronSecond = __commonJS({ "node_modules/cron-parser/dist/fields/CronSecond.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CronSecond = void 0; var CronField_1 = require_CronField(); var MIN_SECOND = 0; var MAX_SECOND = 59; var SECOND_CHARS = Object.freeze([]); var CronSecond = class extends CronField_1.CronField { static get min() { return MIN_SECOND; } static get max() { return MAX_SECOND; } static get chars() { return SECOND_CHARS; } /** * CronSecond constructor. Initializes the "second" field with the provided values. * @param {SixtyRange[]} values - Values for the "second" field * @param {CronFieldOptions} [options] - Options provided by the parser */ constructor(values, options) { super(values, options); this.validate(); } /** * Returns an array of allowed values for the "second" field. * @returns {SixtyRange[]} */ get values() { return super.values; } }; exports.CronSecond = CronSecond; } }); // node_modules/cron-parser/dist/fields/index.js var require_fields = __commonJS({ "node_modules/cron-parser/dist/fields/index.js"(exports) { "use strict"; var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o2, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o2, k2, desc); }) : (function(o2, m, k, k2) { if (k2 === void 0) k2 = k; o2[k2] = m[k]; })); var __exportStar = exports && exports.__exportStar || function(m, exports2) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); __exportStar(require_types(), exports); __exportStar(require_CronDayOfMonth(), exports); __exportStar(require_CronDayOfWeek(), exports); __exportStar(require_CronField(), exports); __exportStar(require_CronHour(), exports); __exportStar(require_CronMinute(), exports); __exportStar(require_CronMonth(), exports); __exportStar(require_CronSecond(), exports); } }); // node_modules/cron-parser/dist/CronFieldCollection.js var require_CronFieldCollection = __commonJS({ "node_modules/cron-parser/dist/CronFieldCollection.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CronFieldCollection = void 0; var fields_1 = require_fields(); var _second, _minute, _hour, _dayOfMonth, _month, _dayOfWeek, _CronFieldCollection_static, handleSingleRange_fn, handleMultipleRanges_fn; var _CronFieldCollection = class _CronFieldCollection { /** * CronFieldCollection constructor. Initializes the cron fields with the provided values. * @param {CronFields} param0 - The cron fields values * @throws {Error} if validation fails * @example * const cronFields = new CronFieldCollection({ * second: new CronSecond([0]), * minute: new CronMinute([0, 30]), * hour: new CronHour([9]), * dayOfMonth: new CronDayOfMonth([15]), * month: new CronMonth([1]), * dayOfWeek: new CronDayOfTheWeek([1, 2, 3, 4, 5]), * }) * * console.log(cronFields.second.values); // [0] * console.log(cronFields.minute.values); // [0, 30] * console.log(cronFields.hour.values); // [9] * console.log(cronFields.dayOfMonth.values); // [15] * console.log(cronFields.month.values); // [1] * console.log(cronFields.dayOfWeek.values); // [1, 2, 3, 4, 5] */ constructor({ second, minute, hour, dayOfMonth, month, dayOfWeek }) { __privateAdd(this, _second); __privateAdd(this, _minute); __privateAdd(this, _hour); __privateAdd(this, _dayOfMonth); __privateAdd(this, _month); __privateAdd(this, _dayOfWeek); if (!second) { throw new Error("Validation error, Field second is missing"); } if (!minute) { throw new Error("Validation error, Field minute is missing"); } if (!hour) { throw new Error("Validation error, Field hour is missing"); } if (!dayOfMonth) { throw new Error("Validation error, Field dayOfMonth is missing"); } if (!month) { throw new Error("Validation error, Field month is missing"); } if (!dayOfWeek) { throw new Error("Validation error, Field dayOfWeek is missing"); } if (month.values.length === 1 && !dayOfMonth.hasLastChar) { if (!(parseInt(dayOfMonth.values[0], 10) <= fields_1.CronMonth.daysInMonth[month.values[0] - 1])) { throw new Error("Invalid explicit day of month definition"); } } __privateSet(this, _second, second); __privateSet(this, _minute, minute); __privateSet(this, _hour, hour); __privateSet(this, _month, month); __privateSet(this, _dayOfWeek, dayOfWeek); __privateSet(this, _dayOfMonth, dayOfMonth); } /** * Creates a new CronFieldCollection instance by partially overriding fields from an existing one. * @param {CronFieldCollection} base - The base CronFieldCollection to copy fields from * @param {CronFieldOverride} fields - The fields to override, can be CronField instances or raw values * @returns {CronFieldCollection} A new CronFieldCollection instance * @example * const base = new CronFieldCollection({ * second: new CronSecond([0]), * minute: new CronMinute([0]), * hour: new CronHour([12]), * dayOfMonth: new CronDayOfMonth([1]), * month: new CronMonth([1]), * dayOfWeek: new CronDayOfWeek([1]) * }); * * // Using CronField instances * const modified1 = CronFieldCollection.from(base, { * hour: new CronHour([15]), * minute: new CronMinute([30]) * }); * * // Using raw values * const modified2 = CronFieldCollection.from(base, { * hour: [15], // Will create new CronHour * minute: [30] // Will create new CronMinute * }); */ static from(base, fields) { return new _CronFieldCollection({ second: this.resolveField(fields_1.CronSecond, base.second, fields.second), minute: this.resolveField(fields_1.CronMinute, base.minute, fields.minute), hour: this.resolveField(fields_1.CronHour, base.hour, fields.hour), dayOfMonth: this.resolveField(fields_1.CronDayOfMonth, base.dayOfMonth, fields.dayOfMonth), month: this.resolveField(fields_1.CronMonth, base.month, fields.month), dayOfWeek: this.resolveField(fields_1.CronDayOfWeek, base.dayOfWeek, fields.dayOfWeek) }); } /** * Resolves a field value, either using the provided CronField instance or creating a new one from raw values. * @param constructor - The constructor for creating new field instances * @param baseField - The base field to use if no override is provided * @param fieldValue - The override value, either a CronField instance or raw values * @returns The resolved CronField instance * @private */ static resolveField(constructor, baseField, fieldValue) { if (!fieldValue) { return baseField; } if (fieldValue instanceof fields_1.CronField) { return fieldValue; } return new constructor(fieldValue); } /** * Returns the second field. * @returns {CronSecond} */ get second() { return __privateGet(this, _second); } /** * Returns the minute field. * @returns {CronMinute} */ get minute() { return __privateGet(this, _minute); } /** * Returns the hour field. * @returns {CronHour} */ get hour() { return __privateGet(this, _hour); } /** * Returns the day of the month field. * @returns {CronDayOfMonth} */ get dayOfMonth() { return __privateGet(this, _dayOfMonth); } /** * Returns the month field. * @returns {CronMonth} */ get month() { return __privateGet(this, _month); } /** * Returns the day of the week field. * @returns {CronDayOfWeek} */ get dayOfWeek() { return __privateGet(this, _dayOfWeek); } /** * Returns a string representation of the cron fields. * @param {(number | CronChars)[]} input - The cron fields values * @static * @returns {FieldRange[]} - The compacted cron fields */ static compactField(input) { if (input.length === 0) { return []; } const output = []; let current = void 0; input.forEach((item, i, arr) => { var _a5, _b; if (current === void 0) { current = { start: item, count: 1 }; return; } const prevItem = arr[i - 1] || current.start; const nextItem = arr[i + 1]; if (item === "L" || item === "W") { output.push(current); output.push({ start: item, count: 1 }); current = void 0; return; } if (current.step === void 0 && nextItem !== void 0) { const step = item - prevItem; const nextStep = nextItem - item; if (step <= nextStep) { current = { ...current, count: 2, end: item, step }; return; } current.step = 1; } if (item - ((_a5 = current.end) != null ? _a5 : 0) === current.step) { current.count++; current.end = item; } else { if (current.count === 1) { output.push({ start: current.start, count: 1 }); } else if (current.count === 2) { output.push({ start: current.start, count: 1 }); output.push({ start: (_b = current.end) != null ? _b : ( /* istanbul ignore next - see above */ prevItem ), count: 1 }); } else { output.push(current); } current = { start: item, count: 1 }; } }); if (current) { output.push(current); } return output; } /** * Returns a string representation of the cron fields. * @param {CronField} field - The cron field to stringify * @static * @returns {string} - The stringified cron field */ stringifyField(field) { var _a5; let max = field.max; let values = field.values; if (field instanceof fields_1.CronDayOfWeek) { max = 6; const dayOfWeek = __privateGet(this, _dayOfWeek).values; values = dayOfWeek[dayOfWeek.length - 1] === 7 ? dayOfWeek.slice(0, -1) : dayOfWeek; } if (field instanceof fields_1.CronDayOfMonth) { max = __privateGet(this, _month).values.length === 1 ? fields_1.CronMonth.daysInMonth[__privateGet(this, _month).values[0] - 1] : field.max; } const ranges = _CronFieldCollection.compactField(values); if (ranges.length === 1) { const singleRangeResult = __privateMethod(_a5 = _CronFieldCollection, _CronFieldCollection_static, handleSingleRange_fn).call(_a5, field, ranges[0], max); if (singleRangeResult) { return singleRangeResult; } } return ranges.map((range) => { var _a6; const value = range.count === 1 ? range.start.toString() : __privateMethod(_a6 = _CronFieldCollection, _CronFieldCollection_static, handleMultipleRanges_fn).call(_a6, range, max); if (field instanceof fields_1.CronDayOfWeek && field.nthDay > 0) { return `${value}#${field.nthDay}`; } return value; }).join(","); } /** * Returns a string representation of the cron field values. * @param {boolean} includeSeconds - Whether to include seconds in the output * @returns {string} The formatted cron string */ stringify(includeSeconds = false) { const arr = []; if (includeSeconds) { arr.push(this.stringifyField(__privateGet(this, _second))); } arr.push( this.stringifyField(__privateGet(this, _minute)), // minute this.stringifyField(__privateGet(this, _hour)), // hour this.stringifyField(__privateGet(this, _dayOfMonth)), // dayOfMonth this.stringifyField(__privateGet(this, _month)), // month this.stringifyField(__privateGet(this, _dayOfWeek)) ); return arr.join(" "); } /** * Returns a serialized representation of the cron fields values. * @returns {SerializedCronFields} An object containing the cron field values */ serialize() { return { second: __privateGet(this, _second).serialize(), minute: __privateGet(this, _minute).serialize(), hour: __privateGet(this, _hour).serialize(), dayOfMonth: __privateGet(this, _dayOfMonth).serialize(), month: __privateGet(this, _month).serialize(), dayOfWeek: __privateGet(this, _dayOfWeek).serialize() }; } }; _second = new WeakMap(); _minute = new WeakMap(); _hour = new WeakMap(); _dayOfMonth = new WeakMap(); _month = new WeakMap(); _dayOfWeek = new WeakMap(); _CronFieldCollection_static = new WeakSet(); handleSingleRange_fn = function(field, range, max) { const step = range.step; if (!step) { return null; } if (step === 1 && range.start === field.min && range.end && range.end >= max) { return field.hasQuestionMarkChar ? "?" : "*"; } if (step !== 1 && range.start === field.min && range.end && range.end >= max - step + 1) { return `*/${step}`; } return null; }; handleMultipleRanges_fn = function(range, max) { const step = range.step; if (step === 1) { return `${range.start}-${range.end}`; } const multiplier = range.start === 0 ? range.count - 1 : range.count; if (!step) { throw new Error("Unexpected range step"); } if (!range.end) { throw new Error("Unexpected range end"); } if (step * multiplier > range.end) { const mapFn = (_2, index) => { if (typeof range.start !== "number") { throw new Error("Unexpected range start"); } return index % step === 0 ? range.start + index : null; }; if (typeof range.start !== "number") { throw new Error("Unexpected range start"); } const seed = { length: range.end - range.start + 1 }; return Array.from(seed, mapFn).filter((value) => value !== null).join(","); } return range.end === max - step + 1 ? `${range.start}/${step}` : `${range.start}-${range.end}/${step}`; }; __privateAdd(_CronFieldCollection, _CronFieldCollection_static); var CronFieldCollection = _CronFieldCollection; exports.CronFieldCollection = CronFieldCollection; } }); // node_modules/cron-parser/dist/CronExpression.js var require_CronExpression = __commonJS({ "node_modules/cron-parser/dist/CronExpression.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CronExpression = exports.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE = exports.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE = void 0; var CronDate_1 = require_CronDate(); exports.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE = "Out of the time span range"; exports.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE = "Invalid expression, loop limit exceeded"; var LOOP_LIMIT = 1e4; var _options, _tz, _currentDate, _startDate, _endDate, _fields, _dstTransitionDayKey, _isDstTransitionDay, _CronExpression_static, matchSchedule_fn, _CronExpression_instances, getMinOrMax_fn, checkDstTransition_fn, moveToNextSecond_fn, moveToNextMinute_fn, isLastWeekdayOfMonthMatch_fn, matchDayOfMonth_fn, matchHour_fn, validateTimeSpan_fn, findSchedule_fn; var _CronExpression = class _CronExpression { /** * Creates a new CronExpression instance. * * @param {CronFieldCollection} fields - Cron fields. * @param {CronExpressionOptions} options - Parser options. */ constructor(fields, options) { __privateAdd(this, _CronExpression_instances); __privateAdd(this, _options); __privateAdd(this, _tz); __privateAdd(this, _currentDate); __privateAdd(this, _startDate); __privateAdd(this, _endDate); __privateAdd(this, _fields); __privateAdd(this, _dstTransitionDayKey, null); __privateAdd(this, _isDstTransitionDay, false); var _a5; __privateSet(this, _options, options); __privateSet(this, _tz, options.tz); __privateSet(this, _startDate, options.startDate ? new CronDate_1.CronDate(options.startDate, __privateGet(this, _tz)) : null); __privateSet(this, _endDate, options.endDate ? new CronDate_1.CronDate(options.endDate, __privateGet(this, _tz)) : null); let currentDateValue = (_a5 = options.currentDate) != null ? _a5 : options.startDate; if (currentDateValue) { const tempCurrentDate = new CronDate_1.CronDate(currentDateValue, __privateGet(this, _tz)); if (__privateGet(this, _startDate) && tempCurrentDate.getTime() < __privateGet(this, _startDate).getTime()) { currentDateValue = __privateGet(this, _startDate); } else if (__privateGet(this, _endDate) && tempCurrentDate.getTime() > __privateGet(this, _endDate).getTime()) { currentDateValue = __privateGet(this, _endDate); } } __privateSet(this, _currentDate, new CronDate_1.CronDate(currentDateValue, __privateGet(this, _tz))); __privateSet(this, _fields, fields); } /** * Getter for the cron fields. * * @returns {CronFieldCollection} Cron fields. */ get fields() { return __privateGet(this, _fields); } /** * Converts cron fields back to a CronExpression instance. * * @public * @param {Record} fields - The input cron fields object. * @param {CronExpressionOptions} [options] - Optional parsing options. * @returns {CronExpression} - A new CronExpression instance. */ static fieldsToExpression(fields, options) { return new _CronExpression(fields, options || {}); } /** * Find the next scheduled date based on the cron expression. * @returns {CronDate} - The next scheduled date or an ES6 compatible iterator object. * @memberof CronExpression * @public */ next() { return __privateMethod(this, _CronExpression_instances, findSchedule_fn).call(this); } /** * Find the previous scheduled date based on the cron expression. * @returns {CronDate} - The previous scheduled date or an ES6 compatible iterator object. * @memberof CronExpression * @public */ prev() { return __privateMethod(this, _CronExpression_instances, findSchedule_fn).call(this, true); } /** * Check if there is a next scheduled date based on the current date and cron expression. * @returns {boolean} - Returns true if there is a next scheduled date, false otherwise. * @memberof CronExpression * @public */ hasNext() { const current = __privateGet(this, _currentDate); try { __privateMethod(this, _CronExpression_instances, findSchedule_fn).call(this); return true; } catch (e) { return false; } finally { __privateSet(this, _currentDate, current); } } /** * Check if there is a previous scheduled date based on the current date and cron expression. * @returns {boolean} - Returns true if there is a previous scheduled date, false otherwise. * @memberof CronExpression * @public */ hasPrev() { const current = __privateGet(this, _currentDate); try { __privateMethod(this, _CronExpression_instances, findSchedule_fn).call(this, true); return true; } catch (e) { return false; } finally { __privateSet(this, _currentDate, current); } } /** * Iterate over a specified number of steps and optionally execute a callback function for each step. * @param {number} steps - The number of steps to iterate. Positive value iterates forward, negative value iterates backward. * @returns {CronDate[]} - An array of iterator fields or CronDate objects. * @memberof CronExpression * @public */ take(limit) { const items = []; if (limit >= 0) { for (let i = 0; i < limit; i++) { try { items.push(this.next()); } catch (e) { return items; } } } else { for (let i = 0; i > limit; i--) { try { items.push(this.prev()); } catch (e) { return items; } } } return items; } /** * Reset the iterators current date to a new date or the initial date. * @param {Date | CronDate} [newDate] - Optional new date to reset to. If not provided, it will reset to the initial date. * @memberof CronExpression * @public */ reset(newDate) { __privateSet(this, _currentDate, new CronDate_1.CronDate(newDate || __privateGet(this, _options).currentDate)); } /** * Generate a string representation of the cron expression. * @param {boolean} [includeSeconds=false] - Whether to include the seconds field in the string representation. * @returns {string} - The string representation of the cron expression. * @memberof CronExpression * @public */ stringify(includeSeconds = false) { return __privateGet(this, _fields).stringify(includeSeconds); } /** * Check if the cron expression includes the given date * @param {Date|CronDate} date * @returns {boolean} */ includesDate(date) { const { second, minute, hour, month } = __privateGet(this, _fields); const dt2 = new CronDate_1.CronDate(date, __privateGet(this, _tz)); if (!second.values.includes(dt2.getSeconds()) || !minute.values.includes(dt2.getMinutes()) || !hour.values.includes(dt2.getHours()) || !month.values.includes(dt2.getMonth() + 1)) { return false; } if (!__privateMethod(this, _CronExpression_instances, matchDayOfMonth_fn).call(this, dt2)) { return false; } if (__privateGet(this, _fields).dayOfWeek.nthDay > 0) { const weekInMonth = Math.ceil(dt2.getDate() / 7); if (weekInMonth !== __privateGet(this, _fields).dayOfWeek.nthDay) { return false; } } return true; } /** * Returns the string representation of the cron expression. * @returns {CronDate} - The next schedule date. */ toString() { return __privateGet(this, _options).expression || this.stringify(true); } /** * Returns an iterator for iterating through future CronDate instances * * @name Symbol.iterator * @memberof CronExpression * @returns {Iterator} An iterator object for CronExpression that returns CronDate values. */ [Symbol.iterator]() { return { next: () => { const schedule = __privateMethod(this, _CronExpression_instances, findSchedule_fn).call(this); return { value: schedule, done: !this.hasNext() }; } }; } }; _options = new WeakMap(); _tz = new WeakMap(); _currentDate = new WeakMap(); _startDate = new WeakMap(); _endDate = new WeakMap(); _fields = new WeakMap(); _dstTransitionDayKey = new WeakMap(); _isDstTransitionDay = new WeakMap(); _CronExpression_static = new WeakSet(); matchSchedule_fn = function(value, sequence) { return sequence.some((element) => element === value); }; _CronExpression_instances = new WeakSet(); /** * Returns the minimum or maximum value from the given array of numbers. * * @param {number[]} values - An array of numbers. * @param {boolean} reverse - If true, returns the maximum value; otherwise, returns the minimum value. * @returns {number} - The minimum or maximum value. */ getMinOrMax_fn = function(values, reverse) { return values[reverse ? values.length - 1 : 0]; }; /** * Checks whether the given date falls on a DST transition day in its timezone. * * This is used to disable certain “direct set” fast paths on DST days, because setting the hour * directly may land on a non-existent or repeated local time. We cache the result per calendar day * to keep iteration overhead low. * * @param {CronDate} currentDate - Date to check (in the cron timezone) * @returns {boolean} True when the day has a DST transition * @private */ checkDstTransition_fn = function(currentDate) { const key = `${currentDate.getFullYear()}-${currentDate.getMonth() + 1}-${currentDate.getDate()}`; if (__privateGet(this, _dstTransitionDayKey) === key) { return __privateGet(this, _isDstTransitionDay); } const startOfDay = new CronDate_1.CronDate(currentDate); startOfDay.setStartOfDay(); const endOfDay = new CronDate_1.CronDate(currentDate); endOfDay.setEndOfDay(); __privateSet(this, _dstTransitionDayKey, key); __privateSet(this, _isDstTransitionDay, startOfDay.getUTCOffset() !== endOfDay.getUTCOffset()); return __privateGet(this, _isDstTransitionDay); }; /** * Moves the date to the next/previous allowed second value. If there is no remaining allowed second * within the current minute, rolls to the next/previous minute and resets seconds to the min/max allowed. * * @param {CronDate} currentDate - Mutable date being iterated * @param {DateMathOp} dateMathVerb - Add/Subtract depending on direction * @param {boolean} reverse - When true, iterating backwards * @private */ moveToNextSecond_fn = function(currentDate, dateMathVerb, reverse) { const seconds = __privateGet(this, _fields).second.values; const currentSecond = currentDate.getSeconds(); const nextSecond = __privateGet(this, _fields).second.findNearestValue(currentSecond, reverse); if (nextSecond !== null) { currentDate.setSeconds(nextSecond); return; } currentDate.applyDateOperation(dateMathVerb, CronDate_1.TimeUnit.Minute, __privateGet(this, _fields).hour.values.length); currentDate.setSeconds(__privateMethod(this, _CronExpression_instances, getMinOrMax_fn).call(this, seconds, reverse)); }; /** * Moves the date to the next/previous allowed minute value and resets seconds to the min/max allowed. * If there is no remaining allowed minute within the current hour, rolls to the next/previous hour and * resets minutes/seconds to their extrema. * * @param {CronDate} currentDate - Mutable date being iterated * @param {DateMathOp} dateMathVerb - Add/Subtract depending on direction * @param {boolean} reverse - When true, iterating backwards * @private */ moveToNextMinute_fn = function(currentDate, dateMathVerb, reverse) { const minutes = __privateGet(this, _fields).minute.values; const seconds = __privateGet(this, _fields).second.values; const currentMinute = currentDate.getMinutes(); const nextMinute = __privateGet(this, _fields).minute.findNearestValue(currentMinute, reverse); if (nextMinute !== null) { currentDate.setMinutes(nextMinute); currentDate.setSeconds(__privateMethod(this, _CronExpression_instances, getMinOrMax_fn).call(this, seconds, reverse)); return; } currentDate.applyDateOperation(dateMathVerb, CronDate_1.TimeUnit.Hour, __privateGet(this, _fields).hour.values.length); currentDate.setMinutes(__privateMethod(this, _CronExpression_instances, getMinOrMax_fn).call(this, minutes, reverse)); currentDate.setSeconds(__privateMethod(this, _CronExpression_instances, getMinOrMax_fn).call(this, seconds, reverse)); }; isLastWeekdayOfMonthMatch_fn = function(expressions, currentDate) { const isLastWeekdayOfMonth = currentDate.isLastWeekdayOfMonth(); return expressions.some((expression) => { const weekday = parseInt(expression.toString().charAt(0), 10) % 7; if (Number.isNaN(weekday)) { throw new Error(`Invalid last weekday of the month expression: ${expression}`); } return currentDate.getDay() === weekday && isLastWeekdayOfMonth; }); }; /** * Determines if the given date matches the cron expression's day of month and day of week fields. * * The function checks the following rules: * Rule 1: If both "day of month" and "day of week" are restricted (not wildcard), then one or both must match the current day. * Rule 2: If "day of month" is restricted and "day of week" is not restricted, then "day of month" must match the current day. * Rule 3: If "day of month" is a wildcard, "day of week" is not a wildcard, and "day of week" matches the current day, then the match is accepted. * If none of the rules match, the match is rejected. * * @param {CronDate} currentDate - The current date to be evaluated against the cron expression. * @returns {boolean} Returns true if the current date matches the cron expression's day of month and day of week fields, otherwise false. * @memberof CronExpression * @private */ matchDayOfMonth_fn = function(currentDate) { var _a5, _b, _c2; const isDayOfMonthWildcardMatch = __privateGet(this, _fields).dayOfMonth.isWildcard; const isRestrictedDayOfMonth = !isDayOfMonthWildcardMatch; const isDayOfWeekWildcardMatch = __privateGet(this, _fields).dayOfWeek.isWildcard; const isRestrictedDayOfWeek = !isDayOfWeekWildcardMatch; const matchedDOM = __privateMethod(_a5 = _CronExpression, _CronExpression_static, matchSchedule_fn).call(_a5, currentDate.getDate(), __privateGet(this, _fields).dayOfMonth.values) || __privateGet(this, _fields).dayOfMonth.hasLastChar && currentDate.isLastDayOfMonth(); const matchedDOW = __privateMethod(_b = _CronExpression, _CronExpression_static, matchSchedule_fn).call(_b, currentDate.getDay(), __privateGet(this, _fields).dayOfWeek.values) || __privateGet(this, _fields).dayOfWeek.hasLastChar && __privateMethod(_c2 = _CronExpression, _CronExpression_static, isLastWeekdayOfMonthMatch_fn).call(_c2, __privateGet(this, _fields).dayOfWeek.values, currentDate); if (isRestrictedDayOfMonth && isRestrictedDayOfWeek && (matchedDOM || matchedDOW)) { return true; } if (matchedDOM && !isRestrictedDayOfWeek) { return true; } if (isDayOfMonthWildcardMatch && !isDayOfWeekWildcardMatch && matchedDOW) { return true; } return false; }; /** * Determines if the current hour matches the cron expression. * * @param {CronDate} currentDate - The current date object. * @param {DateMathOp} dateMathVerb - The date math operation enumeration value. * @param {boolean} reverse - A flag indicating whether the matching should be done in reverse order. * @returns {boolean} - True if the current hour matches the cron expression; otherwise, false. */ matchHour_fn = function(currentDate, dateMathVerb, reverse) { var _a5, _b; const hourValues = __privateGet(this, _fields).hour.values; const hours = hourValues; const currentHour = currentDate.getHours(); const isMatch = __privateMethod(_a5 = _CronExpression, _CronExpression_static, matchSchedule_fn).call(_a5, currentHour, hourValues); const isDstStart = currentDate.dstStart === currentHour; const isDstEnd = currentDate.dstEnd === currentHour; if (isDstStart) { if (__privateMethod(_b = _CronExpression, _CronExpression_static, matchSchedule_fn).call(_b, currentHour - 1, hourValues)) { return true; } currentDate.invokeDateOperation(dateMathVerb, CronDate_1.TimeUnit.Hour); return false; } if (isDstEnd && !reverse) { currentDate.dstEnd = null; currentDate.applyDateOperation(CronDate_1.DateMathOp.Add, CronDate_1.TimeUnit.Hour, hours.length); return false; } if (isMatch) { return true; } currentDate.dstStart = null; const nextHour = __privateGet(this, _fields).hour.findNearestValue(currentHour, reverse); if (nextHour === null) { currentDate.applyDateOperation(dateMathVerb, CronDate_1.TimeUnit.Day, hours.length); return false; } if (__privateMethod(this, _CronExpression_instances, checkDstTransition_fn).call(this, currentDate)) { const steps = reverse ? currentHour - nextHour : nextHour - currentHour; for (let i = 0; i < steps; i++) { currentDate.applyDateOperation(dateMathVerb, CronDate_1.TimeUnit.Hour, hours.length); } } else { currentDate.setHours(nextHour); } currentDate.setMinutes(__privateMethod(this, _CronExpression_instances, getMinOrMax_fn).call(this, __privateGet(this, _fields).minute.values, reverse)); currentDate.setSeconds(__privateMethod(this, _CronExpression_instances, getMinOrMax_fn).call(this, __privateGet(this, _fields).second.values, reverse)); return false; }; /** * Validates the current date against the start and end dates of the cron expression. * If the current date is outside the specified time span, an error is thrown. * * @param currentDate {CronDate} - The current date to validate. * @throws {Error} If the current date is outside the specified time span. * @private */ validateTimeSpan_fn = function(currentDate) { if (!__privateGet(this, _startDate) && !__privateGet(this, _endDate)) { return; } const currentTime = currentDate.getTime(); if (__privateGet(this, _startDate) && currentTime < __privateGet(this, _startDate).getTime()) { throw new Error(exports.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE); } if (__privateGet(this, _endDate) && currentTime > __privateGet(this, _endDate).getTime()) { throw new Error(exports.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE); } }; /** * Finds the next or previous schedule based on the cron expression. * * @param {boolean} [reverse=false] - If true, finds the previous schedule; otherwise, finds the next schedule. * @returns {CronDate} - The next or previous schedule date. * @private */ findSchedule_fn = function(reverse = false) { var _a5, _b, _c2; const dateMathVerb = reverse ? CronDate_1.DateMathOp.Subtract : CronDate_1.DateMathOp.Add; const currentDate = new CronDate_1.CronDate(__privateGet(this, _currentDate)); const startTimestamp = currentDate.getTime(); let stepCount = 0; while (++stepCount < LOOP_LIMIT) { __privateMethod(this, _CronExpression_instances, validateTimeSpan_fn).call(this, currentDate); if (!__privateMethod(this, _CronExpression_instances, matchDayOfMonth_fn).call(this, currentDate)) { currentDate.applyDateOperation(dateMathVerb, CronDate_1.TimeUnit.Day, __privateGet(this, _fields).hour.values.length); continue; } if (!(__privateGet(this, _fields).dayOfWeek.nthDay <= 0 || Math.ceil(currentDate.getDate() / 7) === __privateGet(this, _fields).dayOfWeek.nthDay)) { currentDate.applyDateOperation(dateMathVerb, CronDate_1.TimeUnit.Day, __privateGet(this, _fields).hour.values.length); continue; } if (!__privateMethod(_a5 = _CronExpression, _CronExpression_static, matchSchedule_fn).call(_a5, currentDate.getMonth() + 1, __privateGet(this, _fields).month.values)) { currentDate.applyDateOperation(dateMathVerb, CronDate_1.TimeUnit.Month, __privateGet(this, _fields).hour.values.length); continue; } if (!__privateMethod(this, _CronExpression_instances, matchHour_fn).call(this, currentDate, dateMathVerb, reverse)) { continue; } if (!__privateMethod(_b = _CronExpression, _CronExpression_static, matchSchedule_fn).call(_b, currentDate.getMinutes(), __privateGet(this, _fields).minute.values)) { __privateMethod(this, _CronExpression_instances, moveToNextMinute_fn).call(this, currentDate, dateMathVerb, reverse); continue; } if (!__privateMethod(_c2 = _CronExpression, _CronExpression_static, matchSchedule_fn).call(_c2, currentDate.getSeconds(), __privateGet(this, _fields).second.values)) { __privateMethod(this, _CronExpression_instances, moveToNextSecond_fn).call(this, currentDate, dateMathVerb, reverse); continue; } if (startTimestamp === currentDate.getTime()) { if (dateMathVerb === "Add" || currentDate.getMilliseconds() === 0) { currentDate.applyDateOperation(dateMathVerb, CronDate_1.TimeUnit.Second, __privateGet(this, _fields).hour.values.length); } continue; } break; } if (stepCount > LOOP_LIMIT) { throw new Error(exports.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE); } if (currentDate.getMilliseconds() !== 0) { currentDate.setMilliseconds(0); } __privateSet(this, _currentDate, currentDate); return currentDate; }; __privateAdd(_CronExpression, _CronExpression_static); var CronExpression = _CronExpression; exports.CronExpression = CronExpression; exports.default = CronExpression; } }); // node_modules/cron-parser/dist/utils/random.js var require_random = __commonJS({ "node_modules/cron-parser/dist/utils/random.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.seededRandom = seededRandom; function xfnv1a(str) { let h2 = 2166136261 >>> 0; for (let i = 0; i < str.length; i++) { h2 ^= str.charCodeAt(i); h2 = Math.imul(h2, 16777619); } return () => h2 >>> 0; } function mulberry32(seed) { return () => { let t = seed += 1831565813; t = Math.imul(t ^ t >>> 15, t | 1); t ^= t + Math.imul(t ^ t >>> 7, t | 61); return ((t ^ t >>> 14) >>> 0) / 4294967296; }; } function seededRandom(str) { const seed = str ? xfnv1a(str)() : Math.floor(Math.random() * 1e10); return mulberry32(seed); } } }); // node_modules/cron-parser/dist/CronExpressionParser.js var require_CronExpressionParser = __commonJS({ "node_modules/cron-parser/dist/CronExpressionParser.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CronExpressionParser = exports.DayOfWeek = exports.Months = exports.CronUnit = exports.PredefinedExpressions = void 0; var CronFieldCollection_1 = require_CronFieldCollection(); var CronExpression_1 = require_CronExpression(); var random_1 = require_random(); var fields_1 = require_fields(); var PredefinedExpressions; (function(PredefinedExpressions2) { PredefinedExpressions2["@yearly"] = "0 0 0 1 1 *"; PredefinedExpressions2["@annually"] = "0 0 0 1 1 *"; PredefinedExpressions2["@monthly"] = "0 0 0 1 * *"; PredefinedExpressions2["@weekly"] = "0 0 0 * * 0"; PredefinedExpressions2["@daily"] = "0 0 0 * * *"; PredefinedExpressions2["@hourly"] = "0 0 * * * *"; PredefinedExpressions2["@minutely"] = "0 * * * * *"; PredefinedExpressions2["@secondly"] = "* * * * * *"; PredefinedExpressions2["@weekdays"] = "0 0 0 * * 1-5"; PredefinedExpressions2["@weekends"] = "0 0 0 * * 0,6"; })(PredefinedExpressions || (exports.PredefinedExpressions = PredefinedExpressions = {})); var CronUnit; (function(CronUnit2) { CronUnit2["Second"] = "Second"; CronUnit2["Minute"] = "Minute"; CronUnit2["Hour"] = "Hour"; CronUnit2["DayOfMonth"] = "DayOfMonth"; CronUnit2["Month"] = "Month"; CronUnit2["DayOfWeek"] = "DayOfWeek"; })(CronUnit || (exports.CronUnit = CronUnit = {})); var Months; (function(Months2) { Months2[Months2["jan"] = 1] = "jan"; Months2[Months2["feb"] = 2] = "feb"; Months2[Months2["mar"] = 3] = "mar"; Months2[Months2["apr"] = 4] = "apr"; Months2[Months2["may"] = 5] = "may"; Months2[Months2["jun"] = 6] = "jun"; Months2[Months2["jul"] = 7] = "jul"; Months2[Months2["aug"] = 8] = "aug"; Months2[Months2["sep"] = 9] = "sep"; Months2[Months2["oct"] = 10] = "oct"; Months2[Months2["nov"] = 11] = "nov"; Months2[Months2["dec"] = 12] = "dec"; })(Months || (exports.Months = Months = {})); var DayOfWeek; (function(DayOfWeek2) { DayOfWeek2[DayOfWeek2["sun"] = 0] = "sun"; DayOfWeek2[DayOfWeek2["mon"] = 1] = "mon"; DayOfWeek2[DayOfWeek2["tue"] = 2] = "tue"; DayOfWeek2[DayOfWeek2["wed"] = 3] = "wed"; DayOfWeek2[DayOfWeek2["thu"] = 4] = "thu"; DayOfWeek2[DayOfWeek2["fri"] = 5] = "fri"; DayOfWeek2[DayOfWeek2["sat"] = 6] = "sat"; })(DayOfWeek || (exports.DayOfWeek = DayOfWeek = {})); var _CronExpressionParser_static, getRawFields_fn, parseField_fn, parseWildcard_fn, parseHashed_fn, parseSequence_fn, parseRepeat_fn, validateRange_fn, validateRepeatInterval_fn, createRange_fn, parseRange_fn, parseNthDay_fn, isValidConstraintChar_fn; var _CronExpressionParser = class _CronExpressionParser { /** * Parses a cron expression and returns a CronExpression object. * @param {string} expression - The cron expression to parse. * @param {CronExpressionOptions} [options={}] - The options to use when parsing the expression. * @param {boolean} [options.strict=false] - If true, will throw an error if the expression contains both dayOfMonth and dayOfWeek. * @param {CronDate} [options.currentDate=new CronDate(undefined, 'UTC')] - The date to use when calculating the next/previous occurrence. * * @returns {CronExpression} A CronExpression object. */ static parse(expression, options = {}) { var _a5, _b, _c2, _d, _e3, _f, _g, _h; const { strict = false, hashSeed } = options; const rand = (0, random_1.seededRandom)(hashSeed); expression = PredefinedExpressions[expression] || expression; const rawFields = __privateMethod(_a5 = _CronExpressionParser, _CronExpressionParser_static, getRawFields_fn).call(_a5, expression, strict); if (!(rawFields.dayOfMonth === "*" || rawFields.dayOfWeek === "*" || !strict)) { throw new Error("Cannot use both dayOfMonth and dayOfWeek together in strict mode!"); } const second = __privateMethod(_b = _CronExpressionParser, _CronExpressionParser_static, parseField_fn).call(_b, CronUnit.Second, rawFields.second, fields_1.CronSecond.constraints, rand); const minute = __privateMethod(_c2 = _CronExpressionParser, _CronExpressionParser_static, parseField_fn).call(_c2, CronUnit.Minute, rawFields.minute, fields_1.CronMinute.constraints, rand); const hour = __privateMethod(_d = _CronExpressionParser, _CronExpressionParser_static, parseField_fn).call(_d, CronUnit.Hour, rawFields.hour, fields_1.CronHour.constraints, rand); const month = __privateMethod(_e3 = _CronExpressionParser, _CronExpressionParser_static, parseField_fn).call(_e3, CronUnit.Month, rawFields.month, fields_1.CronMonth.constraints, rand); const dayOfMonth = __privateMethod(_f = _CronExpressionParser, _CronExpressionParser_static, parseField_fn).call(_f, CronUnit.DayOfMonth, rawFields.dayOfMonth, fields_1.CronDayOfMonth.constraints, rand); const { dayOfWeek: _dayOfWeek, nthDayOfWeek } = __privateMethod(_g = _CronExpressionParser, _CronExpressionParser_static, parseNthDay_fn).call(_g, rawFields.dayOfWeek); const dayOfWeek = __privateMethod(_h = _CronExpressionParser, _CronExpressionParser_static, parseField_fn).call(_h, CronUnit.DayOfWeek, _dayOfWeek, fields_1.CronDayOfWeek.constraints, rand); const fields = new CronFieldCollection_1.CronFieldCollection({ second: new fields_1.CronSecond(second, { rawValue: rawFields.second }), minute: new fields_1.CronMinute(minute, { rawValue: rawFields.minute }), hour: new fields_1.CronHour(hour, { rawValue: rawFields.hour }), dayOfMonth: new fields_1.CronDayOfMonth(dayOfMonth, { rawValue: rawFields.dayOfMonth }), month: new fields_1.CronMonth(month, { rawValue: rawFields.month }), dayOfWeek: new fields_1.CronDayOfWeek(dayOfWeek, { rawValue: rawFields.dayOfWeek, nthDayOfWeek }) }); return new CronExpression_1.CronExpression(fields, { ...options, expression }); } }; _CronExpressionParser_static = new WeakSet(); getRawFields_fn = function(expression, strict) { if (strict && !expression.length) { throw new Error("Invalid cron expression"); } expression = expression || "0 * * * * *"; const atoms = expression.trim().split(/\s+/); if (strict && atoms.length < 6) { throw new Error("Invalid cron expression, expected 6 fields"); } if (atoms.length > 6) { throw new Error("Invalid cron expression, too many fields"); } const defaults = ["*", "*", "*", "*", "*", "0"]; if (atoms.length < defaults.length) { atoms.unshift(...defaults.slice(atoms.length)); } const [second, minute, hour, dayOfMonth, month, dayOfWeek] = atoms; return { second, minute, hour, dayOfMonth, month, dayOfWeek }; }; parseField_fn = function(field, value, constraints, rand) { if (field === CronUnit.Month || field === CronUnit.DayOfWeek) { value = value.replace(/[a-z]{3}/gi, (match) => { match = match.toLowerCase(); const replacer = Months[match] || DayOfWeek[match]; if (replacer === void 0) { throw new Error(`Validation error, cannot resolve alias "${match}"`); } return replacer.toString(); }); } if (!constraints.validChars.test(value)) { throw new Error(`Invalid characters, got value: ${value}`); } value = __privateMethod(this, _CronExpressionParser_static, parseWildcard_fn).call(this, value, constraints); value = __privateMethod(this, _CronExpressionParser_static, parseHashed_fn).call(this, value, constraints, rand); return __privateMethod(this, _CronExpressionParser_static, parseSequence_fn).call(this, field, value, constraints); }; parseWildcard_fn = function(value, constraints) { return value.replace(/[*?]/g, constraints.min + "-" + constraints.max); }; parseHashed_fn = function(value, constraints, rand) { const randomValue = rand(); return value.replace(/H(?:\((\d+)-(\d+)\))?(?:\/(\d+))?/g, (_2, min, max, step) => { if (min && max && step) { const minNum = parseInt(min, 10); const maxNum = parseInt(max, 10); const stepNum = parseInt(step, 10); if (minNum > maxNum) { throw new Error(`Invalid range: ${minNum}-${maxNum}, min > max`); } if (stepNum <= 0) { throw new Error(`Invalid step: ${stepNum}, must be positive`); } const minStart = Math.max(minNum, constraints.min); const offset = Math.floor(randomValue * stepNum); const values = []; for (let i = Math.floor(minStart / stepNum) * stepNum + offset; i <= maxNum; i += stepNum) { if (i >= minStart) { values.push(i); } } return values.join(","); } else if (min && max) { const minNum = parseInt(min, 10); const maxNum = parseInt(max, 10); if (minNum > maxNum) { throw new Error(`Invalid range: ${minNum}-${maxNum}, min > max`); } return String(Math.floor(randomValue * (maxNum - minNum + 1)) + minNum); } else if (step) { const stepNum = parseInt(step, 10); if (stepNum <= 0) { throw new Error(`Invalid step: ${stepNum}, must be positive`); } const offset = Math.floor(randomValue * stepNum); const values = []; for (let i = Math.floor(constraints.min / stepNum) * stepNum + offset; i <= constraints.max; i += stepNum) { if (i >= constraints.min) { values.push(i); } } return values.join(","); } else { return String(Math.floor(randomValue * (constraints.max - constraints.min + 1) + constraints.min)); } }); }; parseSequence_fn = function(field, val, constraints) { const stack = []; function handleResult(result, constraints2) { var _a5; if (Array.isArray(result)) { stack.push(...result); } else { if (__privateMethod(_a5 = _CronExpressionParser, _CronExpressionParser_static, isValidConstraintChar_fn).call(_a5, constraints2, result)) { stack.push(result); } else { const v2 = parseInt(result.toString(), 10); const isValid = v2 >= constraints2.min && v2 <= constraints2.max; if (!isValid) { throw new Error(`Constraint error, got value ${result} expected range ${constraints2.min}-${constraints2.max}`); } stack.push(field === CronUnit.DayOfWeek ? v2 % 7 : result); } } } const atoms = val.split(","); atoms.forEach((atom) => { var _a5; if (!(atom.length > 0)) { throw new Error("Invalid list value format"); } handleResult(__privateMethod(_a5 = _CronExpressionParser, _CronExpressionParser_static, parseRepeat_fn).call(_a5, field, atom, constraints), constraints); }); return stack; }; parseRepeat_fn = function(field, val, constraints) { var _a5, _b; const atoms = val.split("/"); if (atoms.length > 2) { throw new Error(`Invalid repeat: ${val}`); } if (atoms.length === 2) { if (!isNaN(parseInt(atoms[0], 10))) { atoms[0] = `${atoms[0]}-${constraints.max}`; } return __privateMethod(_a5 = _CronExpressionParser, _CronExpressionParser_static, parseRange_fn).call(_a5, field, atoms[0], parseInt(atoms[1], 10), constraints); } return __privateMethod(_b = _CronExpressionParser, _CronExpressionParser_static, parseRange_fn).call(_b, field, val, 1, constraints); }; validateRange_fn = function(min, max, constraints) { const isValid = !isNaN(min) && !isNaN(max) && min >= constraints.min && max <= constraints.max; if (!isValid) { throw new Error(`Constraint error, got range ${min}-${max} expected range ${constraints.min}-${constraints.max}`); } if (min > max) { throw new Error(`Invalid range: ${min}-${max}, min(${min}) > max(${max})`); } }; validateRepeatInterval_fn = function(repeatInterval) { if (!(!isNaN(repeatInterval) && repeatInterval > 0)) { throw new Error(`Constraint error, cannot repeat at every ${repeatInterval} time.`); } }; createRange_fn = function(field, min, max, repeatInterval) { const stack = []; if (field === CronUnit.DayOfWeek && max % 7 === 0) { stack.push(0); } for (let index = min; index <= max; index += repeatInterval) { if (stack.indexOf(index) === -1) { stack.push(index); } } return stack; }; parseRange_fn = function(field, val, repeatInterval, constraints) { const atoms = val.split("-"); if (atoms.length <= 1) { return isNaN(+val) ? val : +val; } const [min, max] = atoms.map((num) => parseInt(num, 10)); __privateMethod(this, _CronExpressionParser_static, validateRange_fn).call(this, min, max, constraints); __privateMethod(this, _CronExpressionParser_static, validateRepeatInterval_fn).call(this, repeatInterval); return __privateMethod(this, _CronExpressionParser_static, createRange_fn).call(this, field, min, max, repeatInterval); }; parseNthDay_fn = function(val) { const atoms = val.split("#"); if (atoms.length <= 1) { return { dayOfWeek: atoms[0] }; } const nthValue = +atoms[atoms.length - 1]; const matches = val.match(/([,-/])/); if (matches !== null) { throw new Error(`Constraint error, invalid dayOfWeek \`#\` and \`${matches == null ? void 0 : matches[0]}\` special characters are incompatible`); } if (!(atoms.length <= 2 && !isNaN(nthValue) && nthValue >= 1 && nthValue <= 5)) { throw new Error("Constraint error, invalid dayOfWeek occurrence number (#)"); } return { dayOfWeek: atoms[0], nthDayOfWeek: nthValue }; }; isValidConstraintChar_fn = function(constraints, value) { return constraints.chars.some((char) => value.toString().includes(char)); }; __privateAdd(_CronExpressionParser, _CronExpressionParser_static); var CronExpressionParser2 = _CronExpressionParser; exports.CronExpressionParser = CronExpressionParser2; } }); // node_modules/cron-parser/dist/CronFileParser.js var require_CronFileParser = __commonJS({ "node_modules/cron-parser/dist/CronFileParser.js"(exports) { "use strict"; var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o2, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o2, k2, desc); }) : (function(o2, m, k, k2) { if (k2 === void 0) k2 = k; o2[k2] = m[k]; })); var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o2, v2) { Object.defineProperty(o2, "default", { enumerable: true, value: v2 }); }) : function(o2, v2) { o2["default"] = v2; }); var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { var ownKeys = function(o2) { ownKeys = Object.getOwnPropertyNames || function(o3) { var ar2 = []; for (var k in o3) if (Object.prototype.hasOwnProperty.call(o3, k)) ar2[ar2.length] = k; return ar2; }; return ownKeys(o2); }; return function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); } __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.CronFileParser = void 0; var CronExpressionParser_1 = require_CronExpressionParser(); var _CronFileParser_static, parseContent_fn, parseEntry_fn; var _CronFileParser = class _CronFileParser { /** * Parse a crontab file asynchronously * @param filePath Path to crontab file * @returns Promise resolving to parse results * @throws If file cannot be read */ static async parseFile(filePath) { var _a5; const { readFile } = await Promise.resolve().then(() => __importStar(require("fs/promises"))); const data = await readFile(filePath, "utf8"); return __privateMethod(_a5 = _CronFileParser, _CronFileParser_static, parseContent_fn).call(_a5, data); } /** * Parse a crontab file synchronously * @param filePath Path to crontab file * @returns Parse results * @throws If file cannot be read */ static parseFileSync(filePath) { var _a5; const { readFileSync: readFileSync2 } = require("fs"); const data = readFileSync2(filePath, "utf8"); return __privateMethod(_a5 = _CronFileParser, _CronFileParser_static, parseContent_fn).call(_a5, data); } }; _CronFileParser_static = new WeakSet(); parseContent_fn = function(data) { var _a5; const blocks = data.split("\n"); const result = { variables: {}, expressions: [], errors: {} }; for (const block of blocks) { const entry = block.trim(); if (entry.length === 0 || entry.startsWith("#")) { continue; } const variableMatch = entry.match(/^(.*)=(.*)$/); if (variableMatch) { const [, key, value] = variableMatch; result.variables[key] = value.replace(/["']/g, ""); continue; } try { const parsedEntry = __privateMethod(_a5 = _CronFileParser, _CronFileParser_static, parseEntry_fn).call(_a5, entry); result.expressions.push(parsedEntry.interval); } catch (err) { result.errors[entry] = err; } } return result; }; parseEntry_fn = function(entry) { const atoms = entry.split(" "); return { interval: CronExpressionParser_1.CronExpressionParser.parse(atoms.slice(0, 5).join(" ")), command: atoms.slice(5, atoms.length) }; }; __privateAdd(_CronFileParser, _CronFileParser_static); var CronFileParser = _CronFileParser; exports.CronFileParser = CronFileParser; } }); // node_modules/cron-parser/dist/index.js var require_dist = __commonJS({ "node_modules/cron-parser/dist/index.js"(exports) { "use strict"; var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o2, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o2, k2, desc); }) : (function(o2, m, k, k2) { if (k2 === void 0) k2 = k; o2[k2] = m[k]; })); var __exportStar = exports && exports.__exportStar || function(m, exports2) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.CronFileParser = exports.CronExpressionParser = exports.CronExpression = exports.CronFieldCollection = exports.CronDate = void 0; var CronExpressionParser_1 = require_CronExpressionParser(); var CronDate_1 = require_CronDate(); Object.defineProperty(exports, "CronDate", { enumerable: true, get: function() { return CronDate_1.CronDate; } }); var CronFieldCollection_1 = require_CronFieldCollection(); Object.defineProperty(exports, "CronFieldCollection", { enumerable: true, get: function() { return CronFieldCollection_1.CronFieldCollection; } }); var CronExpression_1 = require_CronExpression(); Object.defineProperty(exports, "CronExpression", { enumerable: true, get: function() { return CronExpression_1.CronExpression; } }); var CronExpressionParser_2 = require_CronExpressionParser(); Object.defineProperty(exports, "CronExpressionParser", { enumerable: true, get: function() { return CronExpressionParser_2.CronExpressionParser; } }); var CronFileParser_1 = require_CronFileParser(); Object.defineProperty(exports, "CronFileParser", { enumerable: true, get: function() { return CronFileParser_1.CronFileParser; } }); __exportStar(require_fields(), exports); exports.default = CronExpressionParser_1.CronExpressionParser; } }); // main.ts var main_exports = {}; __export(main_exports, { default: () => ClaudeCliPlugin }); module.exports = __toCommonJS(main_exports); var import_obsidian2 = require("obsidian"); var import_child_process = require("child_process"); var import_node_crypto2 = require("node:crypto"); var fs2 = __toESM(require("fs")); var os2 = __toESM(require("os")); var path = __toESM(require("path")); // node_modules/@xterm/xterm/lib/xterm.mjs var zs = Object.defineProperty; var Rl = Object.getOwnPropertyDescriptor; var Ll = (s15, t) => { for (var e in t) zs(s15, e, { get: t[e], enumerable: true }); }; var M = (s15, t, e, i) => { for (var r = i > 1 ? void 0 : i ? Rl(t, e) : t, n = s15.length - 1, o2; n >= 0; n--) (o2 = s15[n]) && (r = (i ? o2(t, e, r) : o2(r)) || r); return i && r && zs(t, e, r), r; }; var S = (s15, t) => (e, i) => t(e, i, s15); var Gs = "Terminal input"; var mi = { get: () => Gs, set: (s15) => Gs = s15 }; var $s = "Too much output to announce, navigate to rows manually to read"; var _i = { get: () => $s, set: (s15) => $s = s15 }; function Al(s15) { return s15.replace(/\r?\n/g, "\r"); } function kl(s15, t) { return t ? "\x1B[200~" + s15 + "\x1B[201~" : s15; } function Vs(s15, t) { s15.clipboardData && s15.clipboardData.setData("text/plain", t.selectionText), s15.preventDefault(); } function qs(s15, t, e, i) { if (s15.stopPropagation(), s15.clipboardData) { let r = s15.clipboardData.getData("text/plain"); Cn(r, t, e, i); } } function Cn(s15, t, e, i) { s15 = Al(s15), s15 = kl(s15, e.decPrivateModes.bracketedPasteMode && i.rawOptions.ignoreBracketedPasteMode !== true), e.triggerDataEvent(s15, true), t.value = ""; } function Mn(s15, t, e) { let i = e.getBoundingClientRect(), r = s15.clientX - i.left - 10, n = s15.clientY - i.top - 10; t.style.width = "20px", t.style.height = "20px", t.style.left = `${r}px`, t.style.top = `${n}px`, t.style.zIndex = "1000", t.focus(); } function Pn(s15, t, e, i, r) { Mn(s15, t, e), r && i.rightClickSelect(s15), t.value = i.selectionText, t.select(); } function Ce(s15) { return s15 > 65535 ? (s15 -= 65536, String.fromCharCode((s15 >> 10) + 55296) + String.fromCharCode(s15 % 1024 + 56320)) : String.fromCharCode(s15); } function It(s15, t = 0, e = s15.length) { let i = ""; for (let r = t; r < e; ++r) { let n = s15[r]; n > 65535 ? (n -= 65536, i += String.fromCharCode((n >> 10) + 55296) + String.fromCharCode(n % 1024 + 56320)) : i += String.fromCharCode(n); } return i; } var er = class { constructor() { this._interim = 0; } clear() { this._interim = 0; } decode(t, e) { let i = t.length; if (!i) return 0; let r = 0, n = 0; if (this._interim) { let o2 = t.charCodeAt(n++); 56320 <= o2 && o2 <= 57343 ? e[r++] = (this._interim - 55296) * 1024 + o2 - 56320 + 65536 : (e[r++] = this._interim, e[r++] = o2), this._interim = 0; } for (let o2 = n; o2 < i; ++o2) { let l = t.charCodeAt(o2); if (55296 <= l && l <= 56319) { if (++o2 >= i) return this._interim = l, r; let a = t.charCodeAt(o2); 56320 <= a && a <= 57343 ? e[r++] = (l - 55296) * 1024 + a - 56320 + 65536 : (e[r++] = l, e[r++] = a); continue; } l !== 65279 && (e[r++] = l); } return r; } }; var tr = class { constructor() { this.interim = new Uint8Array(3); } clear() { this.interim.fill(0); } decode(t, e) { let i = t.length; if (!i) return 0; let r = 0, n, o2, l, a, u = 0, h2 = 0; if (this.interim[0]) { let _2 = false, p = this.interim[0]; p &= (p & 224) === 192 ? 31 : (p & 240) === 224 ? 15 : 7; let m = 0, f; for (; (f = this.interim[++m] & 63) && m < 4; ) p <<= 6, p |= f; let A = (this.interim[0] & 224) === 192 ? 2 : (this.interim[0] & 240) === 224 ? 3 : 4, R = A - m; for (; h2 < R; ) { if (h2 >= i) return 0; if (f = t[h2++], (f & 192) !== 128) { h2--, _2 = true; break; } else this.interim[m++] = f, p <<= 6, p |= f & 63; } _2 || (A === 2 ? p < 128 ? h2-- : e[r++] = p : A === 3 ? p < 2048 || p >= 55296 && p <= 57343 || p === 65279 || (e[r++] = p) : p < 65536 || p > 1114111 || (e[r++] = p)), this.interim.fill(0); } let c = i - 4, d = h2; for (; d < i; ) { for (; d < c && !((n = t[d]) & 128) && !((o2 = t[d + 1]) & 128) && !((l = t[d + 2]) & 128) && !((a = t[d + 3]) & 128); ) e[r++] = n, e[r++] = o2, e[r++] = l, e[r++] = a, d += 4; if (n = t[d++], n < 128) e[r++] = n; else if ((n & 224) === 192) { if (d >= i) return this.interim[0] = n, r; if (o2 = t[d++], (o2 & 192) !== 128) { d--; continue; } if (u = (n & 31) << 6 | o2 & 63, u < 128) { d--; continue; } e[r++] = u; } else if ((n & 240) === 224) { if (d >= i) return this.interim[0] = n, r; if (o2 = t[d++], (o2 & 192) !== 128) { d--; continue; } if (d >= i) return this.interim[0] = n, this.interim[1] = o2, r; if (l = t[d++], (l & 192) !== 128) { d--; continue; } if (u = (n & 15) << 12 | (o2 & 63) << 6 | l & 63, u < 2048 || u >= 55296 && u <= 57343 || u === 65279) continue; e[r++] = u; } else if ((n & 248) === 240) { if (d >= i) return this.interim[0] = n, r; if (o2 = t[d++], (o2 & 192) !== 128) { d--; continue; } if (d >= i) return this.interim[0] = n, this.interim[1] = o2, r; if (l = t[d++], (l & 192) !== 128) { d--; continue; } if (d >= i) return this.interim[0] = n, this.interim[1] = o2, this.interim[2] = l, r; if (a = t[d++], (a & 192) !== 128) { d--; continue; } if (u = (n & 7) << 18 | (o2 & 63) << 12 | (l & 63) << 6 | a & 63, u < 65536 || u > 1114111) continue; e[r++] = u; } } return r; } }; var ir = ""; var we = " "; var De = class s { constructor() { this.fg = 0; this.bg = 0; this.extended = new rt(); } static toColorRGB(t) { return [t >>> 16 & 255, t >>> 8 & 255, t & 255]; } static fromColorRGB(t) { return (t[0] & 255) << 16 | (t[1] & 255) << 8 | t[2] & 255; } clone() { let t = new s(); return t.fg = this.fg, t.bg = this.bg, t.extended = this.extended.clone(), t; } isInverse() { return this.fg & 67108864; } isBold() { return this.fg & 134217728; } isUnderline() { return this.hasExtendedAttrs() && this.extended.underlineStyle !== 0 ? 1 : this.fg & 268435456; } isBlink() { return this.fg & 536870912; } isInvisible() { return this.fg & 1073741824; } isItalic() { return this.bg & 67108864; } isDim() { return this.bg & 134217728; } isStrikethrough() { return this.fg & 2147483648; } isProtected() { return this.bg & 536870912; } isOverline() { return this.bg & 1073741824; } getFgColorMode() { return this.fg & 50331648; } getBgColorMode() { return this.bg & 50331648; } isFgRGB() { return (this.fg & 50331648) === 50331648; } isBgRGB() { return (this.bg & 50331648) === 50331648; } isFgPalette() { return (this.fg & 50331648) === 16777216 || (this.fg & 50331648) === 33554432; } isBgPalette() { return (this.bg & 50331648) === 16777216 || (this.bg & 50331648) === 33554432; } isFgDefault() { return (this.fg & 50331648) === 0; } isBgDefault() { return (this.bg & 50331648) === 0; } isAttributeDefault() { return this.fg === 0 && this.bg === 0; } getFgColor() { switch (this.fg & 50331648) { case 16777216: case 33554432: return this.fg & 255; case 50331648: return this.fg & 16777215; default: return -1; } } getBgColor() { switch (this.bg & 50331648) { case 16777216: case 33554432: return this.bg & 255; case 50331648: return this.bg & 16777215; default: return -1; } } hasExtendedAttrs() { return this.bg & 268435456; } updateExtended() { this.extended.isEmpty() ? this.bg &= -268435457 : this.bg |= 268435456; } getUnderlineColor() { if (this.bg & 268435456 && ~this.extended.underlineColor) switch (this.extended.underlineColor & 50331648) { case 16777216: case 33554432: return this.extended.underlineColor & 255; case 50331648: return this.extended.underlineColor & 16777215; default: return this.getFgColor(); } return this.getFgColor(); } getUnderlineColorMode() { return this.bg & 268435456 && ~this.extended.underlineColor ? this.extended.underlineColor & 50331648 : this.getFgColorMode(); } isUnderlineColorRGB() { return this.bg & 268435456 && ~this.extended.underlineColor ? (this.extended.underlineColor & 50331648) === 50331648 : this.isFgRGB(); } isUnderlineColorPalette() { return this.bg & 268435456 && ~this.extended.underlineColor ? (this.extended.underlineColor & 50331648) === 16777216 || (this.extended.underlineColor & 50331648) === 33554432 : this.isFgPalette(); } isUnderlineColorDefault() { return this.bg & 268435456 && ~this.extended.underlineColor ? (this.extended.underlineColor & 50331648) === 0 : this.isFgDefault(); } getUnderlineStyle() { return this.fg & 268435456 ? this.bg & 268435456 ? this.extended.underlineStyle : 1 : 0; } getUnderlineVariantOffset() { return this.extended.underlineVariantOffset; } }; var rt = class s2 { constructor(t = 0, e = 0) { this._ext = 0; this._urlId = 0; this._ext = t, this._urlId = e; } get ext() { return this._urlId ? this._ext & -469762049 | this.underlineStyle << 26 : this._ext; } set ext(t) { this._ext = t; } get underlineStyle() { return this._urlId ? 5 : (this._ext & 469762048) >> 26; } set underlineStyle(t) { this._ext &= -469762049, this._ext |= t << 26 & 469762048; } get underlineColor() { return this._ext & 67108863; } set underlineColor(t) { this._ext &= -67108864, this._ext |= t & 67108863; } get urlId() { return this._urlId; } set urlId(t) { this._urlId = t; } get underlineVariantOffset() { let t = (this._ext & 3758096384) >> 29; return t < 0 ? t ^ 4294967288 : t; } set underlineVariantOffset(t) { this._ext &= 536870911, this._ext |= t << 29 & 3758096384; } clone() { return new s2(this._ext, this._urlId); } isEmpty() { return this.underlineStyle === 0 && this._urlId === 0; } }; var q = class s3 extends De { constructor() { super(...arguments); this.content = 0; this.fg = 0; this.bg = 0; this.extended = new rt(); this.combinedData = ""; } static fromCharData(e) { let i = new s3(); return i.setFromCharData(e), i; } isCombined() { return this.content & 2097152; } getWidth() { return this.content >> 22; } getChars() { return this.content & 2097152 ? this.combinedData : this.content & 2097151 ? Ce(this.content & 2097151) : ""; } getCode() { return this.isCombined() ? this.combinedData.charCodeAt(this.combinedData.length - 1) : this.content & 2097151; } setFromCharData(e) { this.fg = e[0], this.bg = 0; let i = false; if (e[1].length > 2) i = true; else if (e[1].length === 2) { let r = e[1].charCodeAt(0); if (55296 <= r && r <= 56319) { let n = e[1].charCodeAt(1); 56320 <= n && n <= 57343 ? this.content = (r - 55296) * 1024 + n - 56320 + 65536 | e[2] << 22 : i = true; } else i = true; } else this.content = e[1].charCodeAt(0) | e[2] << 22; i && (this.combinedData = e[1], this.content = 2097152 | e[2] << 22); } getAsCharData() { return [this.fg, this.getChars(), this.getWidth(), this.getCode()]; } }; var js = "di$target"; var Hn = "di$dependencies"; var Fn = /* @__PURE__ */ new Map(); function Xs(s15) { return s15[Hn] || []; } function ie(s15) { if (Fn.has(s15)) return Fn.get(s15); let t = function(e, i, r) { if (arguments.length !== 3) throw new Error("@IServiceName-decorator can only be used to decorate a parameter"); Pl(t, e, r); }; return t._id = s15, Fn.set(s15, t), t; } function Pl(s15, t, e) { t[js] === t ? t[Hn].push({ id: s15, index: e }) : (t[Hn] = [{ id: s15, index: e }], t[js] = t); } var F = ie("BufferService"); var rr = ie("CoreMouseService"); var ge = ie("CoreService"); var Zs = ie("CharsetService"); var xt = ie("InstantiationService"); var nr = ie("LogService"); var H = ie("OptionsService"); var sr = ie("OscLinkService"); var Js = ie("UnicodeService"); var Be = ie("DecorationService"); var wt = class { constructor(t, e, i) { this._bufferService = t; this._optionsService = e; this._oscLinkService = i; } provideLinks(t, e) { var _a5; let i = this._bufferService.buffer.lines.get(t - 1); if (!i) { e(void 0); return; } let r = [], n = this._optionsService.rawOptions.linkHandler, o2 = new q(), l = i.getTrimmedLength(), a = -1, u = -1, h2 = false; for (let c = 0; c < l; c++) if (!(u === -1 && !i.hasContent(c))) { if (i.loadCell(c, o2), o2.hasExtendedAttrs() && o2.extended.urlId) if (u === -1) { u = c, a = o2.extended.urlId; continue; } else h2 = o2.extended.urlId !== a; else u !== -1 && (h2 = true); if (h2 || u !== -1 && c === l - 1) { let d = (_a5 = this._oscLinkService.getLinkData(a)) == null ? void 0 : _a5.uri; if (d) { let _2 = { start: { x: u + 1, y: t }, end: { x: c + (!h2 && c === l - 1 ? 1 : 0), y: t } }, p = false; if (!(n == null ? void 0 : n.allowNonHttpProtocols)) try { let m = new URL(d); ["http:", "https:"].includes(m.protocol) || (p = true); } catch (e2) { p = true; } p || r.push({ text: d, range: _2, activate: (m, f) => n ? n.activate(m, f, _2) : Ol(m, f), hover: (m, f) => { var _a6; return (_a6 = n == null ? void 0 : n.hover) == null ? void 0 : _a6.call(n, m, f, _2); }, leave: (m, f) => { var _a6; return (_a6 = n == null ? void 0 : n.leave) == null ? void 0 : _a6.call(n, m, f, _2); } }); } h2 = false, o2.hasExtendedAttrs() && o2.extended.urlId ? (u = c, a = o2.extended.urlId) : (u = -1, a = -1); } } e(r); } }; wt = M([S(0, F), S(1, H), S(2, sr)], wt); function Ol(s15, t) { if (confirm(`Do you want to navigate to ${t}? WARNING: This link could potentially be dangerous`)) { let i = window.open(); if (i) { try { i.opener = null; } catch (e) { } i.location.href = t; } else console.warn("Opening link blocked as opener could not be cleared"); } } var nt = ie("CharSizeService"); var ae = ie("CoreBrowserService"); var Dt = ie("MouseService"); var ce = ie("RenderService"); var Qs = ie("SelectionService"); var or = ie("CharacterJoinerService"); var Re = ie("ThemeService"); var lr = ie("LinkProviderService"); var Wn = class { constructor() { this.listeners = [], this.unexpectedErrorHandler = function(t) { setTimeout(() => { throw t.stack ? ar.isErrorNoTelemetry(t) ? new ar(t.message + ` ` + t.stack) : new Error(t.message + ` ` + t.stack) : t; }, 0); }; } addListener(t) { return this.listeners.push(t), () => { this._removeListener(t); }; } emit(t) { this.listeners.forEach((e) => { e(t); }); } _removeListener(t) { this.listeners.splice(this.listeners.indexOf(t), 1); } setUnexpectedErrorHandler(t) { this.unexpectedErrorHandler = t; } getUnexpectedErrorHandler() { return this.unexpectedErrorHandler; } onUnexpectedError(t) { this.unexpectedErrorHandler(t), this.emit(t); } onUnexpectedExternalError(t) { this.unexpectedErrorHandler(t); } }; var Bl = new Wn(); function Lt(s15) { Nl(s15) || Bl.onUnexpectedError(s15); } var Un = "Canceled"; function Nl(s15) { return s15 instanceof bi ? true : s15 instanceof Error && s15.name === Un && s15.message === Un; } var bi = class extends Error { constructor() { super(Un), this.name = this.message; } }; function eo(s15) { return s15 ? new Error(`Illegal argument: ${s15}`) : new Error("Illegal argument"); } var ar = class s4 extends Error { constructor(t) { super(t), this.name = "CodeExpectedError"; } static fromError(t) { if (t instanceof s4) return t; let e = new s4(); return e.message = t.message, e.stack = t.stack, e; } static isErrorNoTelemetry(t) { return t.name === "CodeExpectedError"; } }; var Rt = class s5 extends Error { constructor(t) { super(t || "An unexpected bug occurred."), Object.setPrototypeOf(this, s5.prototype); } }; function Fl(s15, t, e = 0, i = s15.length) { let r = e, n = i; for (; r < n; ) { let o2 = Math.floor((r + n) / 2); t(s15[o2]) ? r = o2 + 1 : n = o2; } return r - 1; } var cr = class cr2 { constructor(t) { this._array = t; this._findLastMonotonousLastIdx = 0; } findLastMonotonous(t) { if (cr2.assertInvariants) { if (this._prevFindLastPredicate) { for (let i of this._array) if (this._prevFindLastPredicate(i) && !t(i)) throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate."); } this._prevFindLastPredicate = t; } let e = Fl(this._array, t, this._findLastMonotonousLastIdx); return this._findLastMonotonousLastIdx = e + 1, e === -1 ? void 0 : this._array[e]; } }; cr.assertInvariants = false; function Se(s15, t = 0) { return s15[s15.length - (1 + t)]; } var ro; ((l) => { function s15(a) { return a < 0; } l.isLessThan = s15; function t(a) { return a <= 0; } l.isLessThanOrEqual = t; function e(a) { return a > 0; } l.isGreaterThan = e; function i(a) { return a === 0; } l.isNeitherLessOrGreaterThan = i, l.greaterThan = 1, l.lessThan = -1, l.neitherLessOrGreaterThan = 0; })(ro || (ro = {})); function no(s15, t) { return (e, i) => t(s15(e), s15(i)); } var so = (s15, t) => s15 - t; var At = class At2 { constructor(t) { this.iterate = t; } forEach(t) { this.iterate((e) => (t(e), true)); } toArray() { let t = []; return this.iterate((e) => (t.push(e), true)), t; } filter(t) { return new At2((e) => this.iterate((i) => t(i) ? e(i) : true)); } map(t) { return new At2((e) => this.iterate((i) => e(t(i)))); } some(t) { let e = false; return this.iterate((i) => (e = t(i), !e)), e; } findFirst(t) { let e; return this.iterate((i) => t(i) ? (e = i, false) : true), e; } findLast(t) { let e; return this.iterate((i) => (t(i) && (e = i), true)), e; } findLastMaxBy(t) { let e, i = true; return this.iterate((r) => ((i || ro.isGreaterThan(t(r, e))) && (i = false, e = r), true)), e; } }; At.empty = new At((t) => { }); function co(s15, t) { let e = /* @__PURE__ */ Object.create(null); for (let i of s15) { let r = t(i), n = e[r]; n || (n = e[r] = []), n.push(i); } return e; } var lo; var ao; var oo = class { constructor(t, e) { this.toKey = e; this._map = /* @__PURE__ */ new Map(); this[lo] = "SetWithKey"; for (let i of t) this.add(i); } get size() { return this._map.size; } add(t) { let e = this.toKey(t); return this._map.set(e, t), this; } delete(t) { return this._map.delete(this.toKey(t)); } has(t) { return this._map.has(this.toKey(t)); } *entries() { for (let t of this._map.values()) yield [t, t]; } keys() { return this.values(); } *values() { for (let t of this._map.values()) yield t; } clear() { this._map.clear(); } forEach(t, e) { this._map.forEach((i) => t.call(e, i, i, this)); } [(ao = Symbol.iterator, lo = Symbol.toStringTag, ao)]() { return this.values(); } }; var ur = class { constructor() { this.map = /* @__PURE__ */ new Map(); } add(t, e) { let i = this.map.get(t); i || (i = /* @__PURE__ */ new Set(), this.map.set(t, i)), i.add(e); } delete(t, e) { let i = this.map.get(t); i && (i.delete(e), i.size === 0 && this.map.delete(t)); } forEach(t, e) { let i = this.map.get(t); i && i.forEach(e); } get(t) { let e = this.map.get(t); return e || /* @__PURE__ */ new Set(); } }; function Kn(s15, t) { let e = this, i = false, r; return function() { if (i) return r; if (i = true, t) try { r = s15.apply(e, arguments); } finally { t(); } else r = s15.apply(e, arguments); return r; }; } var zn; ((O) => { function s15(I) { return I && typeof I == "object" && typeof I[Symbol.iterator] == "function"; } O.is = s15; let t = Object.freeze([]); function e() { return t; } O.empty = e; function* i(I) { yield I; } O.single = i; function r(I) { return s15(I) ? I : i(I); } O.wrap = r; function n(I) { return I || t; } O.from = n; function* o2(I) { for (let k = I.length - 1; k >= 0; k--) yield I[k]; } O.reverse = o2; function l(I) { return !I || I[Symbol.iterator]().next().done === true; } O.isEmpty = l; function a(I) { return I[Symbol.iterator]().next().value; } O.first = a; function u(I, k) { let P = 0; for (let oe of I) if (k(oe, P++)) return true; return false; } O.some = u; function h2(I, k) { for (let P of I) if (k(P)) return P; } O.find = h2; function* c(I, k) { for (let P of I) k(P) && (yield P); } O.filter = c; function* d(I, k) { let P = 0; for (let oe of I) yield k(oe, P++); } O.map = d; function* _2(I, k) { let P = 0; for (let oe of I) yield* k(oe, P++); } O.flatMap = _2; function* p(...I) { for (let k of I) yield* k; } O.concat = p; function m(I, k, P) { let oe = P; for (let Me of I) oe = k(oe, Me); return oe; } O.reduce = m; function* f(I, k, P = I.length) { for (k < 0 && (k += I.length), P < 0 ? P += I.length : P > I.length && (P = I.length); k < P; k++) yield I[k]; } O.slice = f; function A(I, k = Number.POSITIVE_INFINITY) { let P = []; if (k === 0) return [P, I]; let oe = I[Symbol.iterator](); for (let Me = 0; Me < k; Me++) { let Pe = oe.next(); if (Pe.done) return [P, O.empty()]; P.push(Pe.value); } return [P, { [Symbol.iterator]() { return oe; } }]; } O.consume = A; async function R(I) { let k = []; for await (let P of I) k.push(P); return Promise.resolve(k); } O.asyncToArray = R; })(zn || (zn = {})); var Wl = false; var dt = null; var hr = class hr2 { constructor() { this.livingDisposables = /* @__PURE__ */ new Map(); } getDisposableData(t) { let e = this.livingDisposables.get(t); return e || (e = { parent: null, source: null, isSingleton: false, value: t, idx: hr2.idx++ }, this.livingDisposables.set(t, e)), e; } trackDisposable(t) { let e = this.getDisposableData(t); e.source || (e.source = new Error().stack); } setParent(t, e) { let i = this.getDisposableData(t); i.parent = e; } markAsDisposed(t) { this.livingDisposables.delete(t); } markAsSingleton(t) { this.getDisposableData(t).isSingleton = true; } getRootParent(t, e) { let i = e.get(t); if (i) return i; let r = t.parent ? this.getRootParent(this.getDisposableData(t.parent), e) : t; return e.set(t, r), r; } getTrackedDisposables() { let t = /* @__PURE__ */ new Map(); return [...this.livingDisposables.entries()].filter(([, i]) => i.source !== null && !this.getRootParent(i, t).isSingleton).flatMap(([i]) => i); } computeLeakingDisposables(t = 10, e) { let i; if (e) i = e; else { let a = /* @__PURE__ */ new Map(), u = [...this.livingDisposables.values()].filter((c) => c.source !== null && !this.getRootParent(c, a).isSingleton); if (u.length === 0) return; let h2 = new Set(u.map((c) => c.value)); if (i = u.filter((c) => !(c.parent && h2.has(c.parent))), i.length === 0) throw new Error("There are cyclic diposable chains!"); } if (!i) return; function r(a) { function u(c, d) { for (; c.length > 0 && d.some((_2) => typeof _2 == "string" ? _2 === c[0] : c[0].match(_2)); ) c.shift(); } let h2 = a.source.split(` `).map((c) => c.trim().replace("at ", "")).filter((c) => c !== ""); return u(h2, ["Error", /^trackDisposable \(.*\)$/, /^DisposableTracker.trackDisposable \(.*\)$/]), h2.reverse(); } let n = new ur(); for (let a of i) { let u = r(a); for (let h2 = 0; h2 <= u.length; h2++) n.add(u.slice(0, h2).join(` `), a); } i.sort(no((a) => a.idx, so)); let o2 = "", l = 0; for (let a of i.slice(0, t)) { l++; let u = r(a), h2 = []; for (let c = 0; c < u.length; c++) { let d = u[c]; d = `(shared with ${n.get(u.slice(0, c + 1).join(` `)).size}/${i.length} leaks) at ${d}`; let p = n.get(u.slice(0, c).join(` `)), m = co([...p].map((f) => r(f)[c]), (f) => f); delete m[u[c]]; for (let [f, A] of Object.entries(m)) h2.unshift(` - stacktraces of ${A.length} other leaks continue with ${f}`); h2.unshift(d); } o2 += ` ==================== Leaking disposable ${l}/${i.length}: ${a.value.constructor.name} ==================== ${h2.join(` `)} ============================================================ `; } return i.length > t && (o2 += ` ... and ${i.length - t} more leaking disposables `), { leaks: i, details: o2 }; } }; hr.idx = 0; function Ul(s15) { dt = s15; } if (Wl) { let s15 = "__is_disposable_tracked__"; Ul(new class { trackDisposable(t) { let e = new Error("Potentially leaked disposable").stack; setTimeout(() => { t[s15] || console.log(e); }, 3e3); } setParent(t, e) { if (t && t !== D.None) try { t[s15] = true; } catch (e2) { } } markAsDisposed(t) { if (t && t !== D.None) try { t[s15] = true; } catch (e) { } } markAsSingleton(t) { } }()); } function fr(s15) { return dt == null ? void 0 : dt.trackDisposable(s15), s15; } function pr(s15) { dt == null ? void 0 : dt.markAsDisposed(s15); } function vi(s15, t) { dt == null ? void 0 : dt.setParent(s15, t); } function Kl(s15, t) { if (dt) for (let e of s15) dt.setParent(e, t); } function Gn(s15) { return dt == null ? void 0 : dt.markAsSingleton(s15), s15; } function Ne(s15) { if (zn.is(s15)) { let t = []; for (let e of s15) if (e) try { e.dispose(); } catch (i) { t.push(i); } if (t.length === 1) throw t[0]; if (t.length > 1) throw new AggregateError(t, "Encountered errors while disposing of store"); return Array.isArray(s15) ? [] : s15; } else if (s15) return s15.dispose(), s15; } function ho(...s15) { let t = C(() => Ne(s15)); return Kl(s15, t), t; } function C(s15) { let t = fr({ dispose: Kn(() => { pr(t), s15(); }) }); return t; } var dr = class dr2 { constructor() { this._toDispose = /* @__PURE__ */ new Set(); this._isDisposed = false; fr(this); } dispose() { this._isDisposed || (pr(this), this._isDisposed = true, this.clear()); } get isDisposed() { return this._isDisposed; } clear() { if (this._toDispose.size !== 0) try { Ne(this._toDispose); } finally { this._toDispose.clear(); } } add(t) { if (!t) return t; if (t === this) throw new Error("Cannot register a disposable on itself!"); return vi(t, this), this._isDisposed ? dr2.DISABLE_DISPOSED_WARNING || console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack) : this._toDispose.add(t), t; } delete(t) { if (t) { if (t === this) throw new Error("Cannot dispose a disposable on itself!"); this._toDispose.delete(t), t.dispose(); } } deleteAndLeak(t) { t && this._toDispose.has(t) && (this._toDispose.delete(t), vi(t, null)); } }; dr.DISABLE_DISPOSED_WARNING = false; var Ee = dr; var D = class { constructor() { this._store = new Ee(); fr(this), vi(this._store, this); } dispose() { pr(this), this._store.dispose(); } _register(t) { if (t === this) throw new Error("Cannot register a disposable on itself!"); return this._store.add(t); } }; D.None = Object.freeze({ dispose() { } }); var ye = class { constructor() { this._isDisposed = false; fr(this); } get value() { return this._isDisposed ? void 0 : this._value; } set value(t) { var _a5; this._isDisposed || t === this._value || ((_a5 = this._value) == null ? void 0 : _a5.dispose(), t && vi(t, this), this._value = t); } clear() { this.value = void 0; } dispose() { var _a5; this._isDisposed = true, pr(this), (_a5 = this._value) == null ? void 0 : _a5.dispose(), this._value = void 0; } clearAndLeak() { let t = this._value; return this._value = void 0, t && vi(t, null), t; } }; var fe = typeof window == "object" ? window : globalThis; var kt = class kt2 { constructor(t) { this.element = t, this.next = kt2.Undefined, this.prev = kt2.Undefined; } }; kt.Undefined = new kt(void 0); var G = kt; var Ct = class { constructor() { this._first = G.Undefined; this._last = G.Undefined; this._size = 0; } get size() { return this._size; } isEmpty() { return this._first === G.Undefined; } clear() { let t = this._first; for (; t !== G.Undefined; ) { let e = t.next; t.prev = G.Undefined, t.next = G.Undefined, t = e; } this._first = G.Undefined, this._last = G.Undefined, this._size = 0; } unshift(t) { return this._insert(t, false); } push(t) { return this._insert(t, true); } _insert(t, e) { let i = new G(t); if (this._first === G.Undefined) this._first = i, this._last = i; else if (e) { let n = this._last; this._last = i, i.prev = n, n.next = i; } else { let n = this._first; this._first = i, i.next = n, n.prev = i; } this._size += 1; let r = false; return () => { r || (r = true, this._remove(i)); }; } shift() { if (this._first !== G.Undefined) { let t = this._first.element; return this._remove(this._first), t; } } pop() { if (this._last !== G.Undefined) { let t = this._last.element; return this._remove(this._last), t; } } _remove(t) { if (t.prev !== G.Undefined && t.next !== G.Undefined) { let e = t.prev; e.next = t.next, t.next.prev = e; } else t.prev === G.Undefined && t.next === G.Undefined ? (this._first = G.Undefined, this._last = G.Undefined) : t.next === G.Undefined ? (this._last = this._last.prev, this._last.next = G.Undefined) : t.prev === G.Undefined && (this._first = this._first.next, this._first.prev = G.Undefined); this._size -= 1; } *[Symbol.iterator]() { let t = this._first; for (; t !== G.Undefined; ) yield t.element, t = t.next; } }; var zl = globalThis.performance && typeof globalThis.performance.now == "function"; var mr = class s6 { static create(t) { return new s6(t); } constructor(t) { this._now = zl && t === false ? Date.now : globalThis.performance.now.bind(globalThis.performance), this._startTime = this._now(), this._stopTime = -1; } stop() { this._stopTime = this._now(); } reset() { this._startTime = this._now(), this._stopTime = -1; } elapsed() { return this._stopTime !== -1 ? this._stopTime - this._startTime : this._now() - this._startTime; } }; var Gl = false; var fo = false; var $l = false; var $; ((Qe) => { Qe.None = () => D.None; function t(y) { if ($l) { let { onDidAddListener: T } = y, g = gi.create(), w = 0; y.onDidAddListener = () => { ++w === 2 && (console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here"), g.print()), T == null ? void 0 : T(); }; } } function e(y, T) { return d(y, () => { }, 0, void 0, true, void 0, T); } Qe.defer = e; function i(y) { return (T, g = null, w) => { let E = false, x; return x = y((N) => { if (!E) return x ? x.dispose() : E = true, T.call(g, N); }, null, w), E && x.dispose(), x; }; } Qe.once = i; function r(y, T, g) { return h2((w, E = null, x) => y((N) => w.call(E, T(N)), null, x), g); } Qe.map = r; function n(y, T, g) { return h2((w, E = null, x) => y((N) => { T(N), w.call(E, N); }, null, x), g); } Qe.forEach = n; function o2(y, T, g) { return h2((w, E = null, x) => y((N) => T(N) && w.call(E, N), null, x), g); } Qe.filter = o2; function l(y) { return y; } Qe.signal = l; function a(...y) { return (T, g = null, w) => { let E = ho(...y.map((x) => x((N) => T.call(g, N)))); return c(E, w); }; } Qe.any = a; function u(y, T, g, w) { let E = g; return r(y, (x) => (E = T(E, x), E), w); } Qe.reduce = u; function h2(y, T) { let g, w = { onWillAddFirstListener() { g = y(E.fire, E); }, onDidRemoveLastListener() { g == null ? void 0 : g.dispose(); } }; T || t(w); let E = new v(w); return T == null ? void 0 : T.add(E), E.event; } function c(y, T) { return T instanceof Array ? T.push(y) : T && T.add(y), y; } function d(y, T, g = 100, w = false, E = false, x, N) { let Z, te, Oe, ze = 0, le, et = { leakWarningThreshold: x, onWillAddFirstListener() { Z = y((ht) => { ze++, te = T(te, ht), w && !Oe && (me.fire(te), te = void 0), le = () => { let fi = te; te = void 0, Oe = void 0, (!w || ze > 1) && me.fire(fi), ze = 0; }, typeof g == "number" ? (clearTimeout(Oe), Oe = setTimeout(le, g)) : Oe === void 0 && (Oe = 0, queueMicrotask(le)); }); }, onWillRemoveListener() { E && ze > 0 && (le == null ? void 0 : le()); }, onDidRemoveLastListener() { le = void 0, Z.dispose(); } }; N || t(et); let me = new v(et); return N == null ? void 0 : N.add(me), me.event; } Qe.debounce = d; function _2(y, T = 0, g) { return Qe.debounce(y, (w, E) => w ? (w.push(E), w) : [E], T, void 0, true, void 0, g); } Qe.accumulate = _2; function p(y, T = (w, E) => w === E, g) { let w = true, E; return o2(y, (x) => { let N = w || !T(x, E); return w = false, E = x, N; }, g); } Qe.latch = p; function m(y, T, g) { return [Qe.filter(y, T, g), Qe.filter(y, (w) => !T(w), g)]; } Qe.split = m; function f(y, T = false, g = [], w) { let E = g.slice(), x = y((te) => { E ? E.push(te) : Z.fire(te); }); w && w.add(x); let N = () => { E == null ? void 0 : E.forEach((te) => Z.fire(te)), E = null; }, Z = new v({ onWillAddFirstListener() { x || (x = y((te) => Z.fire(te)), w && w.add(x)); }, onDidAddFirstListener() { E && (T ? setTimeout(N) : N()); }, onDidRemoveLastListener() { x && x.dispose(), x = null; } }); return w && w.add(Z), Z.event; } Qe.buffer = f; function A(y, T) { return (w, E, x) => { let N = T(new O()); return y(function(Z) { let te = N.evaluate(Z); te !== R && w.call(E, te); }, void 0, x); }; } Qe.chain = A; let R = Symbol("HaltChainable"); class O { constructor() { this.steps = []; } map(T) { return this.steps.push(T), this; } forEach(T) { return this.steps.push((g) => (T(g), g)), this; } filter(T) { return this.steps.push((g) => T(g) ? g : R), this; } reduce(T, g) { let w = g; return this.steps.push((E) => (w = T(w, E), w)), this; } latch(T = (g, w) => g === w) { let g = true, w; return this.steps.push((E) => { let x = g || !T(E, w); return g = false, w = E, x ? E : R; }), this; } evaluate(T) { for (let g of this.steps) if (T = g(T), T === R) break; return T; } } function I(y, T, g = (w) => w) { let w = (...Z) => N.fire(g(...Z)), E = () => y.on(T, w), x = () => y.removeListener(T, w), N = new v({ onWillAddFirstListener: E, onDidRemoveLastListener: x }); return N.event; } Qe.fromNodeEventEmitter = I; function k(y, T, g = (w) => w) { let w = (...Z) => N.fire(g(...Z)), E = () => y.addEventListener(T, w), x = () => y.removeEventListener(T, w), N = new v({ onWillAddFirstListener: E, onDidRemoveLastListener: x }); return N.event; } Qe.fromDOMEventEmitter = k; function P(y) { return new Promise((T) => i(y)(T)); } Qe.toPromise = P; function oe(y) { let T = new v(); return y.then((g) => { T.fire(g); }, () => { T.fire(void 0); }).finally(() => { T.dispose(); }), T.event; } Qe.fromPromise = oe; function Me(y, T) { return y((g) => T.fire(g)); } Qe.forward = Me; function Pe(y, T, g) { return T(g), y((w) => T(w)); } Qe.runAndSubscribe = Pe; class Ke { constructor(T, g) { this._observable = T; this._counter = 0; this._hasChanged = false; let w = { onWillAddFirstListener: () => { T.addObserver(this); }, onDidRemoveLastListener: () => { T.removeObserver(this); } }; g || t(w), this.emitter = new v(w), g && g.add(this.emitter); } beginUpdate(T) { this._counter++; } handlePossibleChange(T) { } handleChange(T, g) { this._hasChanged = true; } endUpdate(T) { this._counter--, this._counter === 0 && (this._observable.reportChanges(), this._hasChanged && (this._hasChanged = false, this.emitter.fire(this._observable.get()))); } } function di(y, T) { return new Ke(y, T).emitter.event; } Qe.fromObservable = di; function V(y) { return (T, g, w) => { let E = 0, x = false, N = { beginUpdate() { E++; }, endUpdate() { E--, E === 0 && (y.reportChanges(), x && (x = false, T.call(g))); }, handlePossibleChange() { }, handleChange() { x = true; } }; y.addObserver(N), y.reportChanges(); let Z = { dispose() { y.removeObserver(N); } }; return w instanceof Ee ? w.add(Z) : Array.isArray(w) && w.push(Z), Z; }; } Qe.fromObservableLight = V; })($ || ($ = {})); var Mt = class Mt2 { constructor(t) { this.listenerCount = 0; this.invocationCount = 0; this.elapsedOverall = 0; this.durations = []; this.name = `${t}_${Mt2._idPool++}`, Mt2.all.add(this); } start(t) { this._stopWatch = new mr(), this.listenerCount = t; } stop() { if (this._stopWatch) { let t = this._stopWatch.elapsed(); this.durations.push(t), this.elapsedOverall += t, this.invocationCount += 1, this._stopWatch = void 0; } } }; Mt.all = /* @__PURE__ */ new Set(), Mt._idPool = 0; var $n = Mt; var po = -1; var br = class br2 { constructor(t, e, i = (br2._idPool++).toString(16).padStart(3, "0")) { this._errorHandler = t; this.threshold = e; this.name = i; this._warnCountdown = 0; } dispose() { var _a5; (_a5 = this._stacks) == null ? void 0 : _a5.clear(); } check(t, e) { let i = this.threshold; if (i <= 0 || e < i) return; this._stacks || (this._stacks = /* @__PURE__ */ new Map()); let r = this._stacks.get(t.value) || 0; if (this._stacks.set(t.value, r + 1), this._warnCountdown -= 1, this._warnCountdown <= 0) { this._warnCountdown = i * 0.5; let [n, o2] = this.getMostFrequentStack(), l = `[${this.name}] potential listener LEAK detected, having ${e} listeners already. MOST frequent listener (${o2}):`; console.warn(l), console.warn(n); let a = new qn(l, n); this._errorHandler(a); } return () => { let n = this._stacks.get(t.value) || 0; this._stacks.set(t.value, n - 1); }; } getMostFrequentStack() { if (!this._stacks) return; let t, e = 0; for (let [i, r] of this._stacks) (!t || e < r) && (t = [i, r], e = r); return t; } }; br._idPool = 1; var Vn = br; var gi = class s7 { constructor(t) { this.value = t; } static create() { var _a5; let t = new Error(); return new s7((_a5 = t.stack) != null ? _a5 : ""); } print() { console.warn(this.value.split(` `).slice(2).join(` `)); } }; var qn = class extends Error { constructor(t, e) { super(t), this.name = "ListenerLeakError", this.stack = e; } }; var Yn = class extends Error { constructor(t, e) { super(t), this.name = "ListenerRefusalError", this.stack = e; } }; var Vl = 0; var Pt = class { constructor(t) { this.value = t; this.id = Vl++; } }; var ql = 2; var Yl = (s15, t) => { if (s15 instanceof Pt) t(s15); else for (let e = 0; e < s15.length; e++) { let i = s15[e]; i && t(i); } }; var _r; if (Gl) { let s15 = []; setInterval(() => { s15.length !== 0 && (console.warn("[LEAKING LISTENERS] GC'ed these listeners that were NOT yet disposed:"), console.warn(s15.join(` `)), s15.length = 0); }, 3e3), _r = new FinalizationRegistry((t) => { typeof t == "string" && s15.push(t); }); } var v = class { constructor(t) { var _a5, _b, _c2, _d, _e3, _f; this._size = 0; this._options = t, this._leakageMon = po > 0 || ((_a5 = this._options) == null ? void 0 : _a5.leakWarningThreshold) ? new Vn((_b = t == null ? void 0 : t.onListenerError) != null ? _b : Lt, (_d = (_c2 = this._options) == null ? void 0 : _c2.leakWarningThreshold) != null ? _d : po) : void 0, this._perfMon = ((_e3 = this._options) == null ? void 0 : _e3._profName) ? new $n(this._options._profName) : void 0, this._deliveryQueue = (_f = this._options) == null ? void 0 : _f.deliveryQueue; } dispose() { var _a5, _b, _c2, _d; if (!this._disposed) { if (this._disposed = true, ((_a5 = this._deliveryQueue) == null ? void 0 : _a5.current) === this && this._deliveryQueue.reset(), this._listeners) { if (fo) { let t = this._listeners; queueMicrotask(() => { Yl(t, (e) => { var _a6; return (_a6 = e.stack) == null ? void 0 : _a6.print(); }); }); } this._listeners = void 0, this._size = 0; } (_c2 = (_b = this._options) == null ? void 0 : _b.onDidRemoveLastListener) == null ? void 0 : _c2.call(_b), (_d = this._leakageMon) == null ? void 0 : _d.dispose(); } } get event() { var _a5; return (_a5 = this._event) != null ? _a5 : this._event = (t, e, i) => { var _a6, _b, _c2, _d, _e3, _f, _g, _h; if (this._leakageMon && this._size > this._leakageMon.threshold ** 2) { let a = `[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`; console.warn(a); let u = (_a6 = this._leakageMon.getMostFrequentStack()) != null ? _a6 : ["UNKNOWN stack", -1], h2 = new Yn(`${a}. HINT: Stack shows most frequent listener (${u[1]}-times)`, u[0]); return (((_b = this._options) == null ? void 0 : _b.onListenerError) || Lt)(h2), D.None; } if (this._disposed) return D.None; e && (t = t.bind(e)); let r = new Pt(t), n, o2; this._leakageMon && this._size >= Math.ceil(this._leakageMon.threshold * 0.2) && (r.stack = gi.create(), n = this._leakageMon.check(r.stack, this._size + 1)), fo && (r.stack = o2 != null ? o2 : gi.create()), this._listeners ? this._listeners instanceof Pt ? ((_c2 = this._deliveryQueue) != null ? _c2 : this._deliveryQueue = new jn(), this._listeners = [this._listeners, r]) : this._listeners.push(r) : ((_e3 = (_d = this._options) == null ? void 0 : _d.onWillAddFirstListener) == null ? void 0 : _e3.call(_d, this), this._listeners = r, (_g = (_f = this._options) == null ? void 0 : _f.onDidAddFirstListener) == null ? void 0 : _g.call(_f, this)), this._size++; let l = C(() => { _r == null ? void 0 : _r.unregister(l), n == null ? void 0 : n(), this._removeListener(r); }); if (i instanceof Ee ? i.add(l) : Array.isArray(i) && i.push(l), _r) { let a = new Error().stack.split(` `).slice(2, 3).join(` `).trim(), u = /(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(a); _r.register(l, (_h = u == null ? void 0 : u[2]) != null ? _h : a, l); } return l; }, this._event; } _removeListener(t) { var _a5, _b, _c2, _d; if ((_b = (_a5 = this._options) == null ? void 0 : _a5.onWillRemoveListener) == null ? void 0 : _b.call(_a5, this), !this._listeners) return; if (this._size === 1) { this._listeners = void 0, (_d = (_c2 = this._options) == null ? void 0 : _c2.onDidRemoveLastListener) == null ? void 0 : _d.call(_c2, this), this._size = 0; return; } let e = this._listeners, i = e.indexOf(t); if (i === -1) throw console.log("disposed?", this._disposed), console.log("size?", this._size), console.log("arr?", JSON.stringify(this._listeners)), new Error("Attempted to dispose unknown listener"); this._size--, e[i] = void 0; let r = this._deliveryQueue.current === this; if (this._size * ql <= e.length) { let n = 0; for (let o2 = 0; o2 < e.length; o2++) e[o2] ? e[n++] = e[o2] : r && (this._deliveryQueue.end--, n < this._deliveryQueue.i && this._deliveryQueue.i--); e.length = n; } } _deliver(t, e) { var _a5; if (!t) return; let i = ((_a5 = this._options) == null ? void 0 : _a5.onListenerError) || Lt; if (!i) { t.value(e); return; } try { t.value(e); } catch (r) { i(r); } } _deliverQueue(t) { let e = t.current._listeners; for (; t.i < t.end; ) this._deliver(e[t.i++], t.value); t.reset(); } fire(t) { var _a5, _b, _c2, _d; if (((_a5 = this._deliveryQueue) == null ? void 0 : _a5.current) && (this._deliverQueue(this._deliveryQueue), (_b = this._perfMon) == null ? void 0 : _b.stop()), (_c2 = this._perfMon) == null ? void 0 : _c2.start(this._size), this._listeners) if (this._listeners instanceof Pt) this._deliver(this._listeners, t); else { let e = this._deliveryQueue; e.enqueue(this, t, this._listeners.length), this._deliverQueue(e); } (_d = this._perfMon) == null ? void 0 : _d.stop(); } hasListeners() { return this._size > 0; } }; var jn = class { constructor() { this.i = -1; this.end = 0; } enqueue(t, e, i) { this.i = 0, this.end = i, this.current = t, this.value = e; } reset() { this.i = this.end, this.current = void 0, this.value = void 0; } }; var gr = class gr2 { constructor() { this.mapWindowIdToZoomLevel = /* @__PURE__ */ new Map(); this._onDidChangeZoomLevel = new v(); this.onDidChangeZoomLevel = this._onDidChangeZoomLevel.event; this.mapWindowIdToZoomFactor = /* @__PURE__ */ new Map(); this._onDidChangeFullscreen = new v(); this.onDidChangeFullscreen = this._onDidChangeFullscreen.event; this.mapWindowIdToFullScreen = /* @__PURE__ */ new Map(); } getZoomLevel(t) { var _a5; return (_a5 = this.mapWindowIdToZoomLevel.get(this.getWindowId(t))) != null ? _a5 : 0; } setZoomLevel(t, e) { if (this.getZoomLevel(e) === t) return; let i = this.getWindowId(e); this.mapWindowIdToZoomLevel.set(i, t), this._onDidChangeZoomLevel.fire(i); } getZoomFactor(t) { var _a5; return (_a5 = this.mapWindowIdToZoomFactor.get(this.getWindowId(t))) != null ? _a5 : 1; } setZoomFactor(t, e) { this.mapWindowIdToZoomFactor.set(this.getWindowId(e), t); } setFullscreen(t, e) { if (this.isFullscreen(e) === t) return; let i = this.getWindowId(e); this.mapWindowIdToFullScreen.set(i, t), this._onDidChangeFullscreen.fire(i); } isFullscreen(t) { return !!this.mapWindowIdToFullScreen.get(this.getWindowId(t)); } getWindowId(t) { return t.vscodeWindowId; } }; gr.INSTANCE = new gr(); var Si = gr; function Xl(s15, t, e) { typeof t == "string" && (t = s15.matchMedia(t)), t.addEventListener("change", e); } var Eu = Si.INSTANCE.onDidChangeZoomLevel; function mo(s15) { return Si.INSTANCE.getZoomFactor(s15); } var Tu = Si.INSTANCE.onDidChangeFullscreen; var Ot = typeof navigator == "object" ? navigator.userAgent : ""; var Ei = Ot.indexOf("Firefox") >= 0; var Bt = Ot.indexOf("AppleWebKit") >= 0; var Ti = Ot.indexOf("Chrome") >= 0; var Sr = !Ti && Ot.indexOf("Safari") >= 0; var Iu = Ot.indexOf("Electron/") >= 0; var yu = Ot.indexOf("Android") >= 0; var vr = false; if (typeof fe.matchMedia == "function") { let s15 = fe.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"), t = fe.matchMedia("(display-mode: fullscreen)"); vr = s15.matches, Xl(fe, s15, ({ matches: e }) => { vr && t.matches || (vr = e); }); } function _o() { return vr; } var Nt = "en"; var yr = false; var xr = false; var Ii = false; var Zl = false; var vo = false; var go = false; var Jl = false; var Ql = false; var ea = false; var ta = false; var Tr; var Ir = Nt; var bo = Nt; var ia; var $e; var Ve = globalThis; var xe; var _a; typeof Ve.vscode < "u" && typeof Ve.vscode.process < "u" ? xe = Ve.vscode.process : typeof process < "u" && typeof ((_a = process == null ? void 0 : process.versions) == null ? void 0 : _a.node) == "string" && (xe = process); var _a2; var So = typeof ((_a2 = xe == null ? void 0 : xe.versions) == null ? void 0 : _a2.electron) == "string"; var ra = So && (xe == null ? void 0 : xe.type) === "renderer"; var _a3; if (typeof xe == "object") { yr = xe.platform === "win32", xr = xe.platform === "darwin", Ii = xe.platform === "linux", Zl = Ii && !!xe.env.SNAP && !!xe.env.SNAP_REVISION, Jl = So, ea = !!xe.env.CI || !!xe.env.BUILD_ARTIFACTSTAGINGDIRECTORY, Tr = Nt, Ir = Nt; let s15 = xe.env.VSCODE_NLS_CONFIG; if (s15) try { let t = JSON.parse(s15); Tr = t.userLocale, bo = t.osLocale, Ir = t.resolvedLanguage || Nt, ia = (_a3 = t.languagePack) == null ? void 0 : _a3.translationsConfigFile; } catch (e) { } vo = true; } else typeof navigator == "object" && !ra ? ($e = navigator.userAgent, yr = $e.indexOf("Windows") >= 0, xr = $e.indexOf("Macintosh") >= 0, Ql = ($e.indexOf("Macintosh") >= 0 || $e.indexOf("iPad") >= 0 || $e.indexOf("iPhone") >= 0) && !!navigator.maxTouchPoints && navigator.maxTouchPoints > 0, Ii = $e.indexOf("Linux") >= 0, ta = ($e == null ? void 0 : $e.indexOf("Mobi")) >= 0, go = true, Ir = globalThis._VSCODE_NLS_LANGUAGE || Nt, Tr = navigator.language.toLowerCase(), bo = Tr) : console.error("Unable to resolve platform."); var Xn = 0; xr ? Xn = 1 : yr ? Xn = 3 : Ii && (Xn = 2); var wr = yr; var Te = xr; var Zn = Ii; var Dr = vo; var na = go && typeof Ve.importScripts == "function"; var xu = na ? Ve.origin : void 0; var Fe = $e; var st = Ir; var sa; ((i) => { function s15() { return st; } i.value = s15; function t() { return st.length === 2 ? st === "en" : st.length >= 3 ? st[0] === "e" && st[1] === "n" && st[2] === "-" : false; } i.isDefaultVariant = t; function e() { return st === "en"; } i.isDefault = e; })(sa || (sa = {})); var oa = typeof Ve.postMessage == "function" && !Ve.importScripts; var Eo = (() => { if (oa) { let s15 = []; Ve.addEventListener("message", (e) => { if (e.data && e.data.vscodeScheduleAsyncWork) for (let i = 0, r = s15.length; i < r; i++) { let n = s15[i]; if (n.id === e.data.vscodeScheduleAsyncWork) { s15.splice(i, 1), n.callback(); return; } } }); let t = 0; return (e) => { let i = ++t; s15.push({ id: i, callback: e }), Ve.postMessage({ vscodeScheduleAsyncWork: i }, "*"); }; } return (s15) => setTimeout(s15); })(); var la = !!(Fe && Fe.indexOf("Chrome") >= 0); var wu = !!(Fe && Fe.indexOf("Firefox") >= 0); var Du = !!(!la && Fe && Fe.indexOf("Safari") >= 0); var Ru = !!(Fe && Fe.indexOf("Edg/") >= 0); var Lu = !!(Fe && Fe.indexOf("Android") >= 0); var ot = typeof navigator == "object" ? navigator : {}; var aa = { clipboard: { writeText: Dr || document.queryCommandSupported && document.queryCommandSupported("copy") || !!(ot && ot.clipboard && ot.clipboard.writeText), readText: Dr || !!(ot && ot.clipboard && ot.clipboard.readText) }, keyboard: Dr || _o() ? 0 : ot.keyboard || Sr ? 1 : 2, touch: "ontouchstart" in fe || ot.maxTouchPoints > 0, pointerEvents: fe.PointerEvent && ("ontouchstart" in fe || navigator.maxTouchPoints > 0) }; var yi = class { constructor() { this._keyCodeToStr = [], this._strToKeyCode = /* @__PURE__ */ Object.create(null); } define(t, e) { this._keyCodeToStr[t] = e, this._strToKeyCode[e.toLowerCase()] = t; } keyCodeToStr(t) { return this._keyCodeToStr[t]; } strToKeyCode(t) { return this._strToKeyCode[t.toLowerCase()] || 0; } }; var Jn = new yi(); var To = new yi(); var Io = new yi(); var yo = new Array(230); var Qn; ((o2) => { function s15(l) { return Jn.keyCodeToStr(l); } o2.toString = s15; function t(l) { return Jn.strToKeyCode(l); } o2.fromString = t; function e(l) { return To.keyCodeToStr(l); } o2.toUserSettingsUS = e; function i(l) { return Io.keyCodeToStr(l); } o2.toUserSettingsGeneral = i; function r(l) { return To.strToKeyCode(l) || Io.strToKeyCode(l); } o2.fromUserSettings = r; function n(l) { if (l >= 98 && l <= 113) return null; switch (l) { case 16: return "Up"; case 18: return "Down"; case 15: return "Left"; case 17: return "Right"; } return Jn.keyCodeToStr(l); } o2.toElectronAccelerator = n; })(Qn || (Qn = {})); var Rr = class s8 { constructor(t, e, i, r, n) { this.ctrlKey = t; this.shiftKey = e; this.altKey = i; this.metaKey = r; this.keyCode = n; } equals(t) { return t instanceof s8 && this.ctrlKey === t.ctrlKey && this.shiftKey === t.shiftKey && this.altKey === t.altKey && this.metaKey === t.metaKey && this.keyCode === t.keyCode; } getHashCode() { let t = this.ctrlKey ? "1" : "0", e = this.shiftKey ? "1" : "0", i = this.altKey ? "1" : "0", r = this.metaKey ? "1" : "0"; return `K${t}${e}${i}${r}${this.keyCode}`; } isModifierKey() { return this.keyCode === 0 || this.keyCode === 5 || this.keyCode === 57 || this.keyCode === 6 || this.keyCode === 4; } toKeybinding() { return new es([this]); } isDuplicateModifierCase() { return this.ctrlKey && this.keyCode === 5 || this.shiftKey && this.keyCode === 4 || this.altKey && this.keyCode === 6 || this.metaKey && this.keyCode === 57; } }; var es = class { constructor(t) { if (t.length === 0) throw eo("chords"); this.chords = t; } getHashCode() { let t = ""; for (let e = 0, i = this.chords.length; e < i; e++) e !== 0 && (t += ";"), t += this.chords[e].getHashCode(); return t; } equals(t) { if (t === null || this.chords.length !== t.chords.length) return false; for (let e = 0; e < this.chords.length; e++) if (!this.chords[e].equals(t.chords[e])) return false; return true; } }; function ca(s15) { if (s15.charCode) { let e = String.fromCharCode(s15.charCode).toUpperCase(); return Qn.fromString(e); } let t = s15.keyCode; if (t === 3) return 7; if (Ei) switch (t) { case 59: return 85; case 60: if (Zn) return 97; break; case 61: return 86; case 107: return 109; case 109: return 111; case 173: return 88; case 224: if (Te) return 57; break; } else if (Bt) { if (Te && t === 93) return 57; if (!Te && t === 92) return 57; } return yo[t] || 0; } var ua = Te ? 256 : 2048; var ha = 512; var da = 1024; var fa = Te ? 2048 : 256; var ft = class { constructor(t) { var _a5; this._standardKeyboardEventBrand = true; let e = t; this.browserEvent = e, this.target = e.target, this.ctrlKey = e.ctrlKey, this.shiftKey = e.shiftKey, this.altKey = e.altKey, this.metaKey = e.metaKey, this.altGraphKey = (_a5 = e.getModifierState) == null ? void 0 : _a5.call(e, "AltGraph"), this.keyCode = ca(e), this.code = e.code, this.ctrlKey = this.ctrlKey || this.keyCode === 5, this.altKey = this.altKey || this.keyCode === 6, this.shiftKey = this.shiftKey || this.keyCode === 4, this.metaKey = this.metaKey || this.keyCode === 57, this._asKeybinding = this._computeKeybinding(), this._asKeyCodeChord = this._computeKeyCodeChord(); } preventDefault() { this.browserEvent && this.browserEvent.preventDefault && this.browserEvent.preventDefault(); } stopPropagation() { this.browserEvent && this.browserEvent.stopPropagation && this.browserEvent.stopPropagation(); } toKeyCodeChord() { return this._asKeyCodeChord; } equals(t) { return this._asKeybinding === t; } _computeKeybinding() { let t = 0; this.keyCode !== 5 && this.keyCode !== 4 && this.keyCode !== 6 && this.keyCode !== 57 && (t = this.keyCode); let e = 0; return this.ctrlKey && (e |= ua), this.altKey && (e |= ha), this.shiftKey && (e |= da), this.metaKey && (e |= fa), e |= t, e; } _computeKeyCodeChord() { let t = 0; return this.keyCode !== 5 && this.keyCode !== 4 && this.keyCode !== 6 && this.keyCode !== 57 && (t = this.keyCode), new Rr(this.ctrlKey, this.shiftKey, this.altKey, this.metaKey, t); } }; var wo = /* @__PURE__ */ new WeakMap(); function pa(s15) { if (!s15.parent || s15.parent === s15) return null; try { let t = s15.location, e = s15.parent.location; if (t.origin !== "null" && e.origin !== "null" && t.origin !== e.origin) return null; } catch (e) { return null; } return s15.parent; } var Lr = class { static getSameOriginWindowChain(t) { let e = wo.get(t); if (!e) { e = [], wo.set(t, e); let i = t, r; do r = pa(i), r ? e.push({ window: new WeakRef(i), iframeElement: i.frameElement || null }) : e.push({ window: new WeakRef(i), iframeElement: null }), i = r; while (i); } return e.slice(0); } static getPositionOfChildWindowRelativeToAncestorWindow(t, e) { var _a5, _b; if (!e || t === e) return { top: 0, left: 0 }; let i = 0, r = 0, n = this.getSameOriginWindowChain(t); for (let o2 of n) { let l = o2.window.deref(); if (i += (_a5 = l == null ? void 0 : l.scrollY) != null ? _a5 : 0, r += (_b = l == null ? void 0 : l.scrollX) != null ? _b : 0, l === e || !o2.iframeElement) break; let a = o2.iframeElement.getBoundingClientRect(); i += a.top, r += a.left; } return { top: i, left: r }; } }; var qe = class { constructor(t, e) { this.timestamp = Date.now(), this.browserEvent = e, this.leftButton = e.button === 0, this.middleButton = e.button === 1, this.rightButton = e.button === 2, this.buttons = e.buttons, this.target = e.target, this.detail = e.detail || 1, e.type === "dblclick" && (this.detail = 2), this.ctrlKey = e.ctrlKey, this.shiftKey = e.shiftKey, this.altKey = e.altKey, this.metaKey = e.metaKey, typeof e.pageX == "number" ? (this.posx = e.pageX, this.posy = e.pageY) : (this.posx = e.clientX + this.target.ownerDocument.body.scrollLeft + this.target.ownerDocument.documentElement.scrollLeft, this.posy = e.clientY + this.target.ownerDocument.body.scrollTop + this.target.ownerDocument.documentElement.scrollTop); let i = Lr.getPositionOfChildWindowRelativeToAncestorWindow(t, e.view); this.posx -= i.left, this.posy -= i.top; } preventDefault() { this.browserEvent.preventDefault(); } stopPropagation() { this.browserEvent.stopPropagation(); } }; var xi = class { constructor(t, e = 0, i = 0) { var _a5; this.browserEvent = t || null, this.target = t ? t.target || t.targetNode || t.srcElement : null, this.deltaY = i, this.deltaX = e; let r = false; if (Ti) { let n = navigator.userAgent.match(/Chrome\/(\d+)/); r = (n ? parseInt(n[1]) : 123) <= 122; } if (t) { let n = t, o2 = t, l = ((_a5 = t.view) == null ? void 0 : _a5.devicePixelRatio) || 1; if (typeof n.wheelDeltaY < "u") r ? this.deltaY = n.wheelDeltaY / (120 * l) : this.deltaY = n.wheelDeltaY / 120; else if (typeof o2.VERTICAL_AXIS < "u" && o2.axis === o2.VERTICAL_AXIS) this.deltaY = -o2.detail / 3; else if (t.type === "wheel") { let a = t; a.deltaMode === a.DOM_DELTA_LINE ? Ei && !Te ? this.deltaY = -t.deltaY / 3 : this.deltaY = -t.deltaY : this.deltaY = -t.deltaY / 40; } if (typeof n.wheelDeltaX < "u") Sr && wr ? this.deltaX = -(n.wheelDeltaX / 120) : r ? this.deltaX = n.wheelDeltaX / (120 * l) : this.deltaX = n.wheelDeltaX / 120; else if (typeof o2.HORIZONTAL_AXIS < "u" && o2.axis === o2.HORIZONTAL_AXIS) this.deltaX = -t.detail / 3; else if (t.type === "wheel") { let a = t; a.deltaMode === a.DOM_DELTA_LINE ? Ei && !Te ? this.deltaX = -t.deltaX / 3 : this.deltaX = -t.deltaX : this.deltaX = -t.deltaX / 40; } this.deltaY === 0 && this.deltaX === 0 && t.wheelDelta && (r ? this.deltaY = t.wheelDelta / (120 * l) : this.deltaY = t.wheelDelta / 120); } } preventDefault() { var _a5; (_a5 = this.browserEvent) == null ? void 0 : _a5.preventDefault(); } stopPropagation() { var _a5; (_a5 = this.browserEvent) == null ? void 0 : _a5.stopPropagation(); } }; var Do = Object.freeze(function(s15, t) { let e = setTimeout(s15.bind(t), 0); return { dispose() { clearTimeout(e); } }; }); var ma; ((i) => { function s15(r) { return r === i.None || r === i.Cancelled || r instanceof ts ? true : !r || typeof r != "object" ? false : typeof r.isCancellationRequested == "boolean" && typeof r.onCancellationRequested == "function"; } i.isCancellationToken = s15, i.None = Object.freeze({ isCancellationRequested: false, onCancellationRequested: $.None }), i.Cancelled = Object.freeze({ isCancellationRequested: true, onCancellationRequested: Do }); })(ma || (ma = {})); var ts = class { constructor() { this._isCancelled = false; this._emitter = null; } cancel() { this._isCancelled || (this._isCancelled = true, this._emitter && (this._emitter.fire(void 0), this.dispose())); } get isCancellationRequested() { return this._isCancelled; } get onCancellationRequested() { return this._isCancelled ? Do : (this._emitter || (this._emitter = new v()), this._emitter.event); } dispose() { this._emitter && (this._emitter.dispose(), this._emitter = null); } }; var _a4 = Symbol("MicrotaskDelay"); var Ye = class { constructor(t, e) { this._isDisposed = false; this._token = -1, typeof t == "function" && typeof e == "number" && this.setIfNotSet(t, e); } dispose() { this.cancel(), this._isDisposed = true; } cancel() { this._token !== -1 && (clearTimeout(this._token), this._token = -1); } cancelAndSet(t, e) { if (this._isDisposed) throw new Rt("Calling 'cancelAndSet' on a disposed TimeoutTimer"); this.cancel(), this._token = setTimeout(() => { this._token = -1, t(); }, e); } setIfNotSet(t, e) { if (this._isDisposed) throw new Rt("Calling 'setIfNotSet' on a disposed TimeoutTimer"); this._token === -1 && (this._token = setTimeout(() => { this._token = -1, t(); }, e)); } }; var kr = class { constructor() { this.disposable = void 0; this.isDisposed = false; } cancel() { var _a5; (_a5 = this.disposable) == null ? void 0 : _a5.dispose(), this.disposable = void 0; } cancelAndSet(t, e, i = globalThis) { if (this.isDisposed) throw new Rt("Calling 'cancelAndSet' on a disposed IntervalTimer"); this.cancel(); let r = i.setInterval(() => { t(); }, e); this.disposable = C(() => { i.clearInterval(r), this.disposable = void 0; }); } dispose() { this.cancel(), this.isDisposed = true; } }; var ba; var Ar; (function() { typeof globalThis.requestIdleCallback != "function" || typeof globalThis.cancelIdleCallback != "function" ? Ar = (s15, t) => { Eo(() => { if (e) return; let i = Date.now() + 15; t(Object.freeze({ didTimeout: true, timeRemaining() { return Math.max(0, i - Date.now()); } })); }); let e = false; return { dispose() { e || (e = true); } }; } : Ar = (s15, t, e) => { let i = s15.requestIdleCallback(t, typeof e == "number" ? { timeout: e } : void 0), r = false; return { dispose() { r || (r = true, s15.cancelIdleCallback(i)); } }; }, ba = (s15) => Ar(globalThis, s15); })(); var va; ((e) => { async function s15(i) { let r, n = await Promise.all(i.map((o2) => o2.then((l) => l, (l) => { r || (r = l); }))); if (typeof r < "u") throw r; return n; } e.settled = s15; function t(i) { return new Promise(async (r, n) => { try { await i(r, n); } catch (o2) { n(o2); } }); } e.withAsyncBody = t; })(va || (va = {})); var _e = class _e2 { static fromArray(t) { return new _e2((e) => { e.emitMany(t); }); } static fromPromise(t) { return new _e2(async (e) => { e.emitMany(await t); }); } static fromPromises(t) { return new _e2(async (e) => { await Promise.all(t.map(async (i) => e.emitOne(await i))); }); } static merge(t) { return new _e2(async (e) => { await Promise.all(t.map(async (i) => { for await (let r of i) e.emitOne(r); })); }); } constructor(t, e) { this._state = 0, this._results = [], this._error = null, this._onReturn = e, this._onStateChanged = new v(), queueMicrotask(async () => { let i = { emitOne: (r) => this.emitOne(r), emitMany: (r) => this.emitMany(r), reject: (r) => this.reject(r) }; try { await Promise.resolve(t(i)), this.resolve(); } catch (r) { this.reject(r); } finally { i.emitOne = void 0, i.emitMany = void 0, i.reject = void 0; } }); } [Symbol.asyncIterator]() { let t = 0; return { next: async () => { do { if (this._state === 2) throw this._error; if (t < this._results.length) return { done: false, value: this._results[t++] }; if (this._state === 1) return { done: true, value: void 0 }; await $.toPromise(this._onStateChanged.event); } while (true); }, return: async () => { var _a5; return (_a5 = this._onReturn) == null ? void 0 : _a5.call(this), { done: true, value: void 0 }; } }; } static map(t, e) { return new _e2(async (i) => { for await (let r of t) i.emitOne(e(r)); }); } map(t) { return _e2.map(this, t); } static filter(t, e) { return new _e2(async (i) => { for await (let r of t) e(r) && i.emitOne(r); }); } filter(t) { return _e2.filter(this, t); } static coalesce(t) { return _e2.filter(t, (e) => !!e); } coalesce() { return _e2.coalesce(this); } static async toPromise(t) { let e = []; for await (let i of t) e.push(i); return e; } toPromise() { return _e2.toPromise(this); } emitOne(t) { this._state === 0 && (this._results.push(t), this._onStateChanged.fire()); } emitMany(t) { this._state === 0 && (this._results = this._results.concat(t), this._onStateChanged.fire()); } resolve() { this._state === 0 && (this._state = 1, this._onStateChanged.fire()); } reject(t) { this._state === 0 && (this._state = 2, this._error = t, this._onStateChanged.fire()); } }; _e.EMPTY = _e.fromArray([]); function Lo(s15) { return 55296 <= s15 && s15 <= 56319; } function is(s15) { return 56320 <= s15 && s15 <= 57343; } function Ao(s15, t) { return (s15 - 55296 << 10) + (t - 56320) + 65536; } function Mo(s15) { return ns(s15, 0); } function ns(s15, t) { switch (typeof s15) { case "object": return s15 === null ? je(349, t) : Array.isArray(s15) ? Ea(s15, t) : Ta(s15, t); case "string": return Po(s15, t); case "boolean": return Sa(s15, t); case "number": return je(s15, t); case "undefined": return je(937, t); default: return je(617, t); } } function je(s15, t) { return (t << 5) - t + s15 | 0; } function Sa(s15, t) { return je(s15 ? 433 : 863, t); } function Po(s15, t) { t = je(149417, t); for (let e = 0, i = s15.length; e < i; e++) t = je(s15.charCodeAt(e), t); return t; } function Ea(s15, t) { return t = je(104579, t), s15.reduce((e, i) => ns(i, e), t); } function Ta(s15, t) { return t = je(181387, t), Object.keys(s15).sort().reduce((e, i) => (e = Po(i, e), ns(s15[i], e)), t); } function rs(s15, t, e = 32) { let i = e - t, r = ~((1 << i) - 1); return (s15 << t | (r & s15) >>> i) >>> 0; } function ko(s15, t = 0, e = s15.byteLength, i = 0) { for (let r = 0; r < e; r++) s15[t + r] = i; } function Ia(s15, t, e = "0") { for (; s15.length < t; ) s15 = e + s15; return s15; } function wi(s15, t = 32) { return s15 instanceof ArrayBuffer ? Array.from(new Uint8Array(s15)).map((e) => e.toString(16).padStart(2, "0")).join("") : Ia((s15 >>> 0).toString(16), t / 4); } var Cr = class Cr2 { constructor() { this._h0 = 1732584193; this._h1 = 4023233417; this._h2 = 2562383102; this._h3 = 271733878; this._h4 = 3285377520; this._buff = new Uint8Array(67), this._buffDV = new DataView(this._buff.buffer), this._buffLen = 0, this._totalLen = 0, this._leftoverHighSurrogate = 0, this._finished = false; } update(t) { let e = t.length; if (e === 0) return; let i = this._buff, r = this._buffLen, n = this._leftoverHighSurrogate, o2, l; for (n !== 0 ? (o2 = n, l = -1, n = 0) : (o2 = t.charCodeAt(0), l = 0); ; ) { let a = o2; if (Lo(o2)) if (l + 1 < e) { let u = t.charCodeAt(l + 1); is(u) ? (l++, a = Ao(o2, u)) : a = 65533; } else { n = o2; break; } else is(o2) && (a = 65533); if (r = this._push(i, r, a), l++, l < e) o2 = t.charCodeAt(l); else break; } this._buffLen = r, this._leftoverHighSurrogate = n; } _push(t, e, i) { return i < 128 ? t[e++] = i : i < 2048 ? (t[e++] = 192 | (i & 1984) >>> 6, t[e++] = 128 | (i & 63) >>> 0) : i < 65536 ? (t[e++] = 224 | (i & 61440) >>> 12, t[e++] = 128 | (i & 4032) >>> 6, t[e++] = 128 | (i & 63) >>> 0) : (t[e++] = 240 | (i & 1835008) >>> 18, t[e++] = 128 | (i & 258048) >>> 12, t[e++] = 128 | (i & 4032) >>> 6, t[e++] = 128 | (i & 63) >>> 0), e >= 64 && (this._step(), e -= 64, this._totalLen += 64, t[0] = t[64], t[1] = t[65], t[2] = t[66]), e; } digest() { return this._finished || (this._finished = true, this._leftoverHighSurrogate && (this._leftoverHighSurrogate = 0, this._buffLen = this._push(this._buff, this._buffLen, 65533)), this._totalLen += this._buffLen, this._wrapUp()), wi(this._h0) + wi(this._h1) + wi(this._h2) + wi(this._h3) + wi(this._h4); } _wrapUp() { this._buff[this._buffLen++] = 128, ko(this._buff, this._buffLen), this._buffLen > 56 && (this._step(), ko(this._buff)); let t = 8 * this._totalLen; this._buffDV.setUint32(56, Math.floor(t / 4294967296), false), this._buffDV.setUint32(60, t % 4294967296, false), this._step(); } _step() { let t = Cr2._bigBlock32, e = this._buffDV; for (let c = 0; c < 64; c += 4) t.setUint32(c, e.getUint32(c, false), false); for (let c = 64; c < 320; c += 4) t.setUint32(c, rs(t.getUint32(c - 12, false) ^ t.getUint32(c - 32, false) ^ t.getUint32(c - 56, false) ^ t.getUint32(c - 64, false), 1), false); let i = this._h0, r = this._h1, n = this._h2, o2 = this._h3, l = this._h4, a, u, h2; for (let c = 0; c < 80; c++) c < 20 ? (a = r & n | ~r & o2, u = 1518500249) : c < 40 ? (a = r ^ n ^ o2, u = 1859775393) : c < 60 ? (a = r & n | r & o2 | n & o2, u = 2400959708) : (a = r ^ n ^ o2, u = 3395469782), h2 = rs(i, 5) + a + l + u + t.getUint32(c * 4, false) & 4294967295, l = o2, o2 = n, n = rs(r, 30), r = i, i = h2; this._h0 = this._h0 + i & 4294967295, this._h1 = this._h1 + r & 4294967295, this._h2 = this._h2 + n & 4294967295, this._h3 = this._h3 + o2 & 4294967295, this._h4 = this._h4 + l & 4294967295; } }; Cr._bigBlock32 = new DataView(new ArrayBuffer(320)); var { registerWindow: Bh, getWindow: be, getDocument: Nh, getWindows: Fh, getWindowsCount: Hh, getWindowId: Oo, getWindowById: Wh, hasWindow: Uh, onDidRegisterWindow: No, onWillUnregisterWindow: Kh, onDidUnregisterWindow: zh } = (function() { let s15 = /* @__PURE__ */ new Map(); fe; let t = { window: fe, disposables: new Ee() }; s15.set(fe.vscodeWindowId, t); let e = new v(), i = new v(), r = new v(); function n(o2, l) { var _a5; return (_a5 = typeof o2 == "number" ? s15.get(o2) : void 0) != null ? _a5 : l ? t : void 0; } return { onDidRegisterWindow: e.event, onWillUnregisterWindow: r.event, onDidUnregisterWindow: i.event, registerWindow(o2) { if (s15.has(o2.vscodeWindowId)) return D.None; let l = new Ee(), a = { window: o2, disposables: l.add(new Ee()) }; return s15.set(o2.vscodeWindowId, a), l.add(C(() => { s15.delete(o2.vscodeWindowId), i.fire(o2); })), l.add(L(o2, Y.BEFORE_UNLOAD, () => { r.fire(o2); })), e.fire(a), l; }, getWindows() { return s15.values(); }, getWindowsCount() { return s15.size; }, getWindowId(o2) { return o2.vscodeWindowId; }, hasWindow(o2) { return s15.has(o2); }, getWindowById: n, getWindow(o2) { var _a5; let l = o2; if ((_a5 = l == null ? void 0 : l.ownerDocument) == null ? void 0 : _a5.defaultView) return l.ownerDocument.defaultView.window; let a = o2; return (a == null ? void 0 : a.view) ? a.view.window : fe; }, getDocument(o2) { return be(o2).document; } }; })(); var ss = class { constructor(t, e, i, r) { this._node = t, this._type = e, this._handler = i, this._options = r || false, this._node.addEventListener(this._type, this._handler, this._options); } dispose() { this._handler && (this._node.removeEventListener(this._type, this._handler, this._options), this._node = null, this._handler = null); } }; function L(s15, t, e, i) { return new ss(s15, t, e, i); } function ya(s15, t) { return function(e) { return t(new qe(s15, e)); }; } function xa(s15) { return function(t) { return s15(new ft(t)); }; } var os = function(t, e, i, r) { let n = i; return e === "click" || e === "mousedown" || e === "contextmenu" ? n = ya(be(t), i) : (e === "keydown" || e === "keypress" || e === "keyup") && (n = xa(i)), L(t, e, n, r); }; var wa; var mt; var Mr = class extends kr { constructor(t) { super(), this.defaultTarget = t && be(t); } cancelAndSet(t, e, i) { return super.cancelAndSet(t, e, i != null ? i : this.defaultTarget); } }; var Di = class { constructor(t, e = 0) { this._runner = t, this.priority = e, this._canceled = false; } dispose() { this._canceled = true; } execute() { if (!this._canceled) try { this._runner(); } catch (t) { Lt(t); } } static sort(t, e) { return e.priority - t.priority; } }; (function() { let s15 = /* @__PURE__ */ new Map(), t = /* @__PURE__ */ new Map(), e = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map(), r = (n) => { var _a5; e.set(n, false); let o2 = (_a5 = s15.get(n)) != null ? _a5 : []; for (t.set(n, o2), s15.set(n, []), i.set(n, true); o2.length > 0; ) o2.sort(Di.sort), o2.shift().execute(); i.set(n, false); }; mt = (n, o2, l = 0) => { let a = Oo(n), u = new Di(o2, l), h2 = s15.get(a); return h2 || (h2 = [], s15.set(a, h2)), h2.push(u), e.get(a) || (e.set(a, true), n.requestAnimationFrame(() => r(a))), u; }, wa = (n, o2, l) => { let a = Oo(n); if (i.get(a)) { let u = new Di(o2, l), h2 = t.get(a); return h2 || (h2 = [], t.set(a, h2)), h2.push(u), u; } else return mt(n, o2, l); }; })(); var pt = class pt2 { constructor(t, e) { this.width = t; this.height = e; } with(t = this.width, e = this.height) { return t !== this.width || e !== this.height ? new pt2(t, e) : this; } static is(t) { return typeof t == "object" && typeof t.height == "number" && typeof t.width == "number"; } static lift(t) { return t instanceof pt2 ? t : new pt2(t.width, t.height); } static equals(t, e) { return t === e ? true : !t || !e ? false : t.width === e.width && t.height === e.height; } }; pt.None = new pt(0, 0); function Fo(s15) { let t = s15.getBoundingClientRect(), e = be(s15); return { left: t.left + e.scrollX, top: t.top + e.scrollY, width: t.width, height: t.height }; } var Gh = new class { constructor() { this.mutationObservers = /* @__PURE__ */ new Map(); } observe(s15, t, e) { let i = this.mutationObservers.get(s15); i || (i = /* @__PURE__ */ new Map(), this.mutationObservers.set(s15, i)); let r = Mo(e), n = i.get(r); if (n) n.users += 1; else { let o2 = new v(), l = new MutationObserver((u) => o2.fire(u)); l.observe(s15, e); let a = n = { users: 1, observer: l, onDidMutate: o2.event }; t.add(C(() => { a.users -= 1, a.users === 0 && (o2.dispose(), l.disconnect(), i == null ? void 0 : i.delete(r), (i == null ? void 0 : i.size) === 0 && this.mutationObservers.delete(s15)); })), i.set(r, n); } return n.onDidMutate; } }(); var Y = { CLICK: "click", AUXCLICK: "auxclick", DBLCLICK: "dblclick", MOUSE_UP: "mouseup", MOUSE_DOWN: "mousedown", MOUSE_OVER: "mouseover", MOUSE_MOVE: "mousemove", MOUSE_OUT: "mouseout", MOUSE_ENTER: "mouseenter", MOUSE_LEAVE: "mouseleave", MOUSE_WHEEL: "wheel", POINTER_UP: "pointerup", POINTER_DOWN: "pointerdown", POINTER_MOVE: "pointermove", POINTER_LEAVE: "pointerleave", CONTEXT_MENU: "contextmenu", WHEEL: "wheel", KEY_DOWN: "keydown", KEY_PRESS: "keypress", KEY_UP: "keyup", LOAD: "load", BEFORE_UNLOAD: "beforeunload", UNLOAD: "unload", PAGE_SHOW: "pageshow", PAGE_HIDE: "pagehide", PASTE: "paste", ABORT: "abort", ERROR: "error", RESIZE: "resize", SCROLL: "scroll", FULLSCREEN_CHANGE: "fullscreenchange", WK_FULLSCREEN_CHANGE: "webkitfullscreenchange", SELECT: "select", CHANGE: "change", SUBMIT: "submit", RESET: "reset", FOCUS: "focus", FOCUS_IN: "focusin", FOCUS_OUT: "focusout", BLUR: "blur", INPUT: "input", STORAGE: "storage", DRAG_START: "dragstart", DRAG: "drag", DRAG_ENTER: "dragenter", DRAG_LEAVE: "dragleave", DRAG_OVER: "dragover", DROP: "drop", DRAG_END: "dragend", ANIMATION_START: Bt ? "webkitAnimationStart" : "animationstart", ANIMATION_END: Bt ? "webkitAnimationEnd" : "animationend", ANIMATION_ITERATION: Bt ? "webkitAnimationIteration" : "animationiteration" }; var Da = /([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/; function Ho(s15, t, e, ...i) { let r = Da.exec(t); if (!r) throw new Error("Bad use of emmet"); let n = r[1] || "div", o2; return s15 !== "http://www.w3.org/1999/xhtml" ? o2 = document.createElementNS(s15, n) : o2 = document.createElement(n), r[3] && (o2.id = r[3]), r[4] && (o2.className = r[4].replace(/\./g, " ").trim()), e && Object.entries(e).forEach(([l, a]) => { typeof a > "u" || (/^on\w+$/.test(l) ? o2[l] = a : l === "selected" ? a && o2.setAttribute(l, "true") : o2.setAttribute(l, a)); }), o2.append(...i), o2; } function Ra(s15, t, ...e) { return Ho("http://www.w3.org/1999/xhtml", s15, t, ...e); } Ra.SVG = function(s15, t, ...e) { return Ho("http://www.w3.org/2000/svg", s15, t, ...e); }; var ls = class { constructor(t) { this.domNode = t; this._maxWidth = ""; this._width = ""; this._height = ""; this._top = ""; this._left = ""; this._bottom = ""; this._right = ""; this._paddingTop = ""; this._paddingLeft = ""; this._paddingBottom = ""; this._paddingRight = ""; this._fontFamily = ""; this._fontWeight = ""; this._fontSize = ""; this._fontStyle = ""; this._fontFeatureSettings = ""; this._fontVariationSettings = ""; this._textDecoration = ""; this._lineHeight = ""; this._letterSpacing = ""; this._className = ""; this._display = ""; this._position = ""; this._visibility = ""; this._color = ""; this._backgroundColor = ""; this._layerHint = false; this._contain = "none"; this._boxShadow = ""; } setMaxWidth(t) { let e = Ie(t); this._maxWidth !== e && (this._maxWidth = e, this.domNode.style.maxWidth = this._maxWidth); } setWidth(t) { let e = Ie(t); this._width !== e && (this._width = e, this.domNode.style.width = this._width); } setHeight(t) { let e = Ie(t); this._height !== e && (this._height = e, this.domNode.style.height = this._height); } setTop(t) { let e = Ie(t); this._top !== e && (this._top = e, this.domNode.style.top = this._top); } setLeft(t) { let e = Ie(t); this._left !== e && (this._left = e, this.domNode.style.left = this._left); } setBottom(t) { let e = Ie(t); this._bottom !== e && (this._bottom = e, this.domNode.style.bottom = this._bottom); } setRight(t) { let e = Ie(t); this._right !== e && (this._right = e, this.domNode.style.right = this._right); } setPaddingTop(t) { let e = Ie(t); this._paddingTop !== e && (this._paddingTop = e, this.domNode.style.paddingTop = this._paddingTop); } setPaddingLeft(t) { let e = Ie(t); this._paddingLeft !== e && (this._paddingLeft = e, this.domNode.style.paddingLeft = this._paddingLeft); } setPaddingBottom(t) { let e = Ie(t); this._paddingBottom !== e && (this._paddingBottom = e, this.domNode.style.paddingBottom = this._paddingBottom); } setPaddingRight(t) { let e = Ie(t); this._paddingRight !== e && (this._paddingRight = e, this.domNode.style.paddingRight = this._paddingRight); } setFontFamily(t) { this._fontFamily !== t && (this._fontFamily = t, this.domNode.style.fontFamily = this._fontFamily); } setFontWeight(t) { this._fontWeight !== t && (this._fontWeight = t, this.domNode.style.fontWeight = this._fontWeight); } setFontSize(t) { let e = Ie(t); this._fontSize !== e && (this._fontSize = e, this.domNode.style.fontSize = this._fontSize); } setFontStyle(t) { this._fontStyle !== t && (this._fontStyle = t, this.domNode.style.fontStyle = this._fontStyle); } setFontFeatureSettings(t) { this._fontFeatureSettings !== t && (this._fontFeatureSettings = t, this.domNode.style.fontFeatureSettings = this._fontFeatureSettings); } setFontVariationSettings(t) { this._fontVariationSettings !== t && (this._fontVariationSettings = t, this.domNode.style.fontVariationSettings = this._fontVariationSettings); } setTextDecoration(t) { this._textDecoration !== t && (this._textDecoration = t, this.domNode.style.textDecoration = this._textDecoration); } setLineHeight(t) { let e = Ie(t); this._lineHeight !== e && (this._lineHeight = e, this.domNode.style.lineHeight = this._lineHeight); } setLetterSpacing(t) { let e = Ie(t); this._letterSpacing !== e && (this._letterSpacing = e, this.domNode.style.letterSpacing = this._letterSpacing); } setClassName(t) { this._className !== t && (this._className = t, this.domNode.className = this._className); } toggleClassName(t, e) { this.domNode.classList.toggle(t, e), this._className = this.domNode.className; } setDisplay(t) { this._display !== t && (this._display = t, this.domNode.style.display = this._display); } setPosition(t) { this._position !== t && (this._position = t, this.domNode.style.position = this._position); } setVisibility(t) { this._visibility !== t && (this._visibility = t, this.domNode.style.visibility = this._visibility); } setColor(t) { this._color !== t && (this._color = t, this.domNode.style.color = this._color); } setBackgroundColor(t) { this._backgroundColor !== t && (this._backgroundColor = t, this.domNode.style.backgroundColor = this._backgroundColor); } setLayerHinting(t) { this._layerHint !== t && (this._layerHint = t, this.domNode.style.transform = this._layerHint ? "translate3d(0px, 0px, 0px)" : ""); } setBoxShadow(t) { this._boxShadow !== t && (this._boxShadow = t, this.domNode.style.boxShadow = t); } setContain(t) { this._contain !== t && (this._contain = t, this.domNode.style.contain = this._contain); } setAttribute(t, e) { this.domNode.setAttribute(t, e); } removeAttribute(t) { this.domNode.removeAttribute(t); } appendChild(t) { this.domNode.appendChild(t.domNode); } removeChild(t) { this.domNode.removeChild(t.domNode); } }; function Ie(s15) { return typeof s15 == "number" ? `${s15}px` : s15; } function _t(s15) { return new ls(s15); } var Wt = class { constructor() { this._hooks = new Ee(); this._pointerMoveCallback = null; this._onStopCallback = null; } dispose() { this.stopMonitoring(false), this._hooks.dispose(); } stopMonitoring(t, e) { if (!this.isMonitoring()) return; this._hooks.clear(), this._pointerMoveCallback = null; let i = this._onStopCallback; this._onStopCallback = null, t && i && i(e); } isMonitoring() { return !!this._pointerMoveCallback; } startMonitoring(t, e, i, r, n) { this.isMonitoring() && this.stopMonitoring(false), this._pointerMoveCallback = r, this._onStopCallback = n; let o2 = t; try { t.setPointerCapture(e), this._hooks.add(C(() => { try { t.releasePointerCapture(e); } catch (e2) { } })); } catch (e2) { o2 = be(t); } this._hooks.add(L(o2, Y.POINTER_MOVE, (l) => { if (l.buttons !== i) { this.stopMonitoring(true); return; } l.preventDefault(), this._pointerMoveCallback(l); })), this._hooks.add(L(o2, Y.POINTER_UP, (l) => this.stopMonitoring(true))); } }; function Wo(s15, t, e) { let i = null, r = null; if (typeof e.value == "function" ? (i = "value", r = e.value, r.length !== 0 && console.warn("Memoize should only be used in functions with zero parameters")) : typeof e.get == "function" && (i = "get", r = e.get), !r) throw new Error("not supported"); let n = `$memoize$${t}`; e[i] = function(...o2) { return this.hasOwnProperty(n) || Object.defineProperty(this, n, { configurable: false, enumerable: false, writable: false, value: r.apply(this, o2) }), this[n]; }; } var He; ((n) => (n.Tap = "-xterm-gesturetap", n.Change = "-xterm-gesturechange", n.Start = "-xterm-gesturestart", n.End = "-xterm-gesturesend", n.Contextmenu = "-xterm-gesturecontextmenu"))(He || (He = {})); var Q = class Q2 extends D { constructor() { super(); this.dispatched = false; this.targets = new Ct(); this.ignoreTargets = new Ct(); this.activeTouches = {}, this.handle = null, this._lastSetTapCountTime = 0, this._register($.runAndSubscribe(No, ({ window: e, disposables: i }) => { i.add(L(e.document, "touchstart", (r) => this.onTouchStart(r), { passive: false })), i.add(L(e.document, "touchend", (r) => this.onTouchEnd(e, r))), i.add(L(e.document, "touchmove", (r) => this.onTouchMove(r), { passive: false })); }, { window: fe, disposables: this._store })); } static addTarget(e) { if (!Q2.isTouchDevice()) return D.None; Q2.INSTANCE || (Q2.INSTANCE = Gn(new Q2())); let i = Q2.INSTANCE.targets.push(e); return C(i); } static ignoreTarget(e) { if (!Q2.isTouchDevice()) return D.None; Q2.INSTANCE || (Q2.INSTANCE = Gn(new Q2())); let i = Q2.INSTANCE.ignoreTargets.push(e); return C(i); } static isTouchDevice() { return "ontouchstart" in fe || navigator.maxTouchPoints > 0; } dispose() { this.handle && (this.handle.dispose(), this.handle = null), super.dispose(); } onTouchStart(e) { let i = Date.now(); this.handle && (this.handle.dispose(), this.handle = null); for (let r = 0, n = e.targetTouches.length; r < n; r++) { let o2 = e.targetTouches.item(r); this.activeTouches[o2.identifier] = { id: o2.identifier, initialTarget: o2.target, initialTimeStamp: i, initialPageX: o2.pageX, initialPageY: o2.pageY, rollingTimestamps: [i], rollingPageX: [o2.pageX], rollingPageY: [o2.pageY] }; let l = this.newGestureEvent(He.Start, o2.target); l.pageX = o2.pageX, l.pageY = o2.pageY, this.dispatchEvent(l); } this.dispatched && (e.preventDefault(), e.stopPropagation(), this.dispatched = false); } onTouchEnd(e, i) { let r = Date.now(), n = Object.keys(this.activeTouches).length; for (let o2 = 0, l = i.changedTouches.length; o2 < l; o2++) { let a = i.changedTouches.item(o2); if (!this.activeTouches.hasOwnProperty(String(a.identifier))) { console.warn("move of an UNKNOWN touch", a); continue; } let u = this.activeTouches[a.identifier], h2 = Date.now() - u.initialTimeStamp; if (h2 < Q2.HOLD_DELAY && Math.abs(u.initialPageX - Se(u.rollingPageX)) < 30 && Math.abs(u.initialPageY - Se(u.rollingPageY)) < 30) { let c = this.newGestureEvent(He.Tap, u.initialTarget); c.pageX = Se(u.rollingPageX), c.pageY = Se(u.rollingPageY), this.dispatchEvent(c); } else if (h2 >= Q2.HOLD_DELAY && Math.abs(u.initialPageX - Se(u.rollingPageX)) < 30 && Math.abs(u.initialPageY - Se(u.rollingPageY)) < 30) { let c = this.newGestureEvent(He.Contextmenu, u.initialTarget); c.pageX = Se(u.rollingPageX), c.pageY = Se(u.rollingPageY), this.dispatchEvent(c); } else if (n === 1) { let c = Se(u.rollingPageX), d = Se(u.rollingPageY), _2 = Se(u.rollingTimestamps) - u.rollingTimestamps[0], p = c - u.rollingPageX[0], m = d - u.rollingPageY[0], f = [...this.targets].filter((A) => u.initialTarget instanceof Node && A.contains(u.initialTarget)); this.inertia(e, f, r, Math.abs(p) / _2, p > 0 ? 1 : -1, c, Math.abs(m) / _2, m > 0 ? 1 : -1, d); } this.dispatchEvent(this.newGestureEvent(He.End, u.initialTarget)), delete this.activeTouches[a.identifier]; } this.dispatched && (i.preventDefault(), i.stopPropagation(), this.dispatched = false); } newGestureEvent(e, i) { let r = document.createEvent("CustomEvent"); return r.initEvent(e, false, true), r.initialTarget = i, r.tapCount = 0, r; } dispatchEvent(e) { if (e.type === He.Tap) { let i = (/* @__PURE__ */ new Date()).getTime(), r = 0; i - this._lastSetTapCountTime > Q2.CLEAR_TAP_COUNT_TIME ? r = 1 : r = 2, this._lastSetTapCountTime = i, e.tapCount = r; } else (e.type === He.Change || e.type === He.Contextmenu) && (this._lastSetTapCountTime = 0); if (e.initialTarget instanceof Node) { for (let r of this.ignoreTargets) if (r.contains(e.initialTarget)) return; let i = []; for (let r of this.targets) if (r.contains(e.initialTarget)) { let n = 0, o2 = e.initialTarget; for (; o2 && o2 !== r; ) n++, o2 = o2.parentElement; i.push([n, r]); } i.sort((r, n) => r[0] - n[0]); for (let [r, n] of i) n.dispatchEvent(e), this.dispatched = true; } } inertia(e, i, r, n, o2, l, a, u, h2) { this.handle = mt(e, () => { let c = Date.now(), d = c - r, _2 = 0, p = 0, m = true; n += Q2.SCROLL_FRICTION * d, a += Q2.SCROLL_FRICTION * d, n > 0 && (m = false, _2 = o2 * n * d), a > 0 && (m = false, p = u * a * d); let f = this.newGestureEvent(He.Change); f.translationX = _2, f.translationY = p, i.forEach((A) => A.dispatchEvent(f)), m || this.inertia(e, i, c, n, o2, l + _2, a, u, h2 + p); }); } onTouchMove(e) { let i = Date.now(); for (let r = 0, n = e.changedTouches.length; r < n; r++) { let o2 = e.changedTouches.item(r); if (!this.activeTouches.hasOwnProperty(String(o2.identifier))) { console.warn("end of an UNKNOWN touch", o2); continue; } let l = this.activeTouches[o2.identifier], a = this.newGestureEvent(He.Change, l.initialTarget); a.translationX = o2.pageX - Se(l.rollingPageX), a.translationY = o2.pageY - Se(l.rollingPageY), a.pageX = o2.pageX, a.pageY = o2.pageY, this.dispatchEvent(a), l.rollingPageX.length > 3 && (l.rollingPageX.shift(), l.rollingPageY.shift(), l.rollingTimestamps.shift()), l.rollingPageX.push(o2.pageX), l.rollingPageY.push(o2.pageY), l.rollingTimestamps.push(i); } this.dispatched && (e.preventDefault(), e.stopPropagation(), this.dispatched = false); } }; Q.SCROLL_FRICTION = -5e-3, Q.HOLD_DELAY = 700, Q.CLEAR_TAP_COUNT_TIME = 400, M([Wo], Q, "isTouchDevice", 1); var Pr = Q; var lt = class extends D { onclick(t, e) { this._register(L(t, Y.CLICK, (i) => e(new qe(be(t), i)))); } onmousedown(t, e) { this._register(L(t, Y.MOUSE_DOWN, (i) => e(new qe(be(t), i)))); } onmouseover(t, e) { this._register(L(t, Y.MOUSE_OVER, (i) => e(new qe(be(t), i)))); } onmouseleave(t, e) { this._register(L(t, Y.MOUSE_LEAVE, (i) => e(new qe(be(t), i)))); } onkeydown(t, e) { this._register(L(t, Y.KEY_DOWN, (i) => e(new ft(i)))); } onkeyup(t, e) { this._register(L(t, Y.KEY_UP, (i) => e(new ft(i)))); } oninput(t, e) { this._register(L(t, Y.INPUT, e)); } onblur(t, e) { this._register(L(t, Y.BLUR, e)); } onfocus(t, e) { this._register(L(t, Y.FOCUS, e)); } onchange(t, e) { this._register(L(t, Y.CHANGE, e)); } ignoreGesture(t) { return Pr.ignoreTarget(t); } }; var Uo = 11; var Or = class extends lt { constructor(t) { super(), this._onActivate = t.onActivate, this.bgDomNode = document.createElement("div"), this.bgDomNode.className = "arrow-background", this.bgDomNode.style.position = "absolute", this.bgDomNode.style.width = t.bgWidth + "px", this.bgDomNode.style.height = t.bgHeight + "px", typeof t.top < "u" && (this.bgDomNode.style.top = "0px"), typeof t.left < "u" && (this.bgDomNode.style.left = "0px"), typeof t.bottom < "u" && (this.bgDomNode.style.bottom = "0px"), typeof t.right < "u" && (this.bgDomNode.style.right = "0px"), this.domNode = document.createElement("div"), this.domNode.className = t.className, this.domNode.style.position = "absolute", this.domNode.style.width = Uo + "px", this.domNode.style.height = Uo + "px", typeof t.top < "u" && (this.domNode.style.top = t.top + "px"), typeof t.left < "u" && (this.domNode.style.left = t.left + "px"), typeof t.bottom < "u" && (this.domNode.style.bottom = t.bottom + "px"), typeof t.right < "u" && (this.domNode.style.right = t.right + "px"), this._pointerMoveMonitor = this._register(new Wt()), this._register(os(this.bgDomNode, Y.POINTER_DOWN, (e) => this._arrowPointerDown(e))), this._register(os(this.domNode, Y.POINTER_DOWN, (e) => this._arrowPointerDown(e))), this._pointerdownRepeatTimer = this._register(new Mr()), this._pointerdownScheduleRepeatTimer = this._register(new Ye()); } _arrowPointerDown(t) { if (!t.target || !(t.target instanceof Element)) return; let e = () => { this._pointerdownRepeatTimer.cancelAndSet(() => this._onActivate(), 1e3 / 24, be(t)); }; this._onActivate(), this._pointerdownRepeatTimer.cancel(), this._pointerdownScheduleRepeatTimer.cancelAndSet(e, 200), this._pointerMoveMonitor.startMonitoring(t.target, t.pointerId, t.buttons, (i) => { }, () => { this._pointerdownRepeatTimer.cancel(), this._pointerdownScheduleRepeatTimer.cancel(); }), t.preventDefault(); } }; var cs = class s9 { constructor(t, e, i, r, n, o2, l) { this._forceIntegerValues = t; this._scrollStateBrand = void 0; this._forceIntegerValues && (e = e | 0, i = i | 0, r = r | 0, n = n | 0, o2 = o2 | 0, l = l | 0), this.rawScrollLeft = r, this.rawScrollTop = l, e < 0 && (e = 0), r + e > i && (r = i - e), r < 0 && (r = 0), n < 0 && (n = 0), l + n > o2 && (l = o2 - n), l < 0 && (l = 0), this.width = e, this.scrollWidth = i, this.scrollLeft = r, this.height = n, this.scrollHeight = o2, this.scrollTop = l; } equals(t) { return this.rawScrollLeft === t.rawScrollLeft && this.rawScrollTop === t.rawScrollTop && this.width === t.width && this.scrollWidth === t.scrollWidth && this.scrollLeft === t.scrollLeft && this.height === t.height && this.scrollHeight === t.scrollHeight && this.scrollTop === t.scrollTop; } withScrollDimensions(t, e) { return new s9(this._forceIntegerValues, typeof t.width < "u" ? t.width : this.width, typeof t.scrollWidth < "u" ? t.scrollWidth : this.scrollWidth, e ? this.rawScrollLeft : this.scrollLeft, typeof t.height < "u" ? t.height : this.height, typeof t.scrollHeight < "u" ? t.scrollHeight : this.scrollHeight, e ? this.rawScrollTop : this.scrollTop); } withScrollPosition(t) { return new s9(this._forceIntegerValues, this.width, this.scrollWidth, typeof t.scrollLeft < "u" ? t.scrollLeft : this.rawScrollLeft, this.height, this.scrollHeight, typeof t.scrollTop < "u" ? t.scrollTop : this.rawScrollTop); } createScrollEvent(t, e) { let i = this.width !== t.width, r = this.scrollWidth !== t.scrollWidth, n = this.scrollLeft !== t.scrollLeft, o2 = this.height !== t.height, l = this.scrollHeight !== t.scrollHeight, a = this.scrollTop !== t.scrollTop; return { inSmoothScrolling: e, oldWidth: t.width, oldScrollWidth: t.scrollWidth, oldScrollLeft: t.scrollLeft, width: this.width, scrollWidth: this.scrollWidth, scrollLeft: this.scrollLeft, oldHeight: t.height, oldScrollHeight: t.scrollHeight, oldScrollTop: t.scrollTop, height: this.height, scrollHeight: this.scrollHeight, scrollTop: this.scrollTop, widthChanged: i, scrollWidthChanged: r, scrollLeftChanged: n, heightChanged: o2, scrollHeightChanged: l, scrollTopChanged: a }; } }; var Ri = class extends D { constructor(e) { super(); this._scrollableBrand = void 0; this._onScroll = this._register(new v()); this.onScroll = this._onScroll.event; this._smoothScrollDuration = e.smoothScrollDuration, this._scheduleAtNextAnimationFrame = e.scheduleAtNextAnimationFrame, this._state = new cs(e.forceIntegerValues, 0, 0, 0, 0, 0, 0), this._smoothScrolling = null; } dispose() { this._smoothScrolling && (this._smoothScrolling.dispose(), this._smoothScrolling = null), super.dispose(); } setSmoothScrollDuration(e) { this._smoothScrollDuration = e; } validateScrollPosition(e) { return this._state.withScrollPosition(e); } getScrollDimensions() { return this._state; } setScrollDimensions(e, i) { var _a5; let r = this._state.withScrollDimensions(e, i); this._setState(r, !!this._smoothScrolling), (_a5 = this._smoothScrolling) == null ? void 0 : _a5.acceptScrollDimensions(this._state); } getFutureScrollPosition() { return this._smoothScrolling ? this._smoothScrolling.to : this._state; } getCurrentScrollPosition() { return this._state; } setScrollPositionNow(e) { let i = this._state.withScrollPosition(e); this._smoothScrolling && (this._smoothScrolling.dispose(), this._smoothScrolling = null), this._setState(i, false); } setScrollPositionSmooth(e, i) { if (this._smoothScrollDuration === 0) return this.setScrollPositionNow(e); if (this._smoothScrolling) { e = { scrollLeft: typeof e.scrollLeft > "u" ? this._smoothScrolling.to.scrollLeft : e.scrollLeft, scrollTop: typeof e.scrollTop > "u" ? this._smoothScrolling.to.scrollTop : e.scrollTop }; let r = this._state.withScrollPosition(e); if (this._smoothScrolling.to.scrollLeft === r.scrollLeft && this._smoothScrolling.to.scrollTop === r.scrollTop) return; let n; i ? n = new Nr(this._smoothScrolling.from, r, this._smoothScrolling.startTime, this._smoothScrolling.duration) : n = this._smoothScrolling.combine(this._state, r, this._smoothScrollDuration), this._smoothScrolling.dispose(), this._smoothScrolling = n; } else { let r = this._state.withScrollPosition(e); this._smoothScrolling = Nr.start(this._state, r, this._smoothScrollDuration); } this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => { this._smoothScrolling && (this._smoothScrolling.animationFrameDisposable = null, this._performSmoothScrolling()); }); } hasPendingScrollAnimation() { return !!this._smoothScrolling; } _performSmoothScrolling() { if (!this._smoothScrolling) return; let e = this._smoothScrolling.tick(), i = this._state.withScrollPosition(e); if (this._setState(i, true), !!this._smoothScrolling) { if (e.isDone) { this._smoothScrolling.dispose(), this._smoothScrolling = null; return; } this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => { this._smoothScrolling && (this._smoothScrolling.animationFrameDisposable = null, this._performSmoothScrolling()); }); } } _setState(e, i) { let r = this._state; r.equals(e) || (this._state = e, this._onScroll.fire(this._state.createScrollEvent(r, i))); } }; var Br = class { constructor(t, e, i) { this.scrollLeft = t, this.scrollTop = e, this.isDone = i; } }; function as(s15, t) { let e = t - s15; return function(i) { return s15 + e * ka(i); }; } function La(s15, t, e) { return function(i) { return i < e ? s15(i / e) : t((i - e) / (1 - e)); }; } var Nr = class s10 { constructor(t, e, i, r) { this.from = t, this.to = e, this.duration = r, this.startTime = i, this.animationFrameDisposable = null, this._initAnimations(); } _initAnimations() { this.scrollLeft = this._initAnimation(this.from.scrollLeft, this.to.scrollLeft, this.to.width), this.scrollTop = this._initAnimation(this.from.scrollTop, this.to.scrollTop, this.to.height); } _initAnimation(t, e, i) { if (Math.abs(t - e) > 2.5 * i) { let n, o2; return t < e ? (n = t + 0.75 * i, o2 = e - 0.75 * i) : (n = t - 0.75 * i, o2 = e + 0.75 * i), La(as(t, n), as(o2, e), 0.33); } return as(t, e); } dispose() { this.animationFrameDisposable !== null && (this.animationFrameDisposable.dispose(), this.animationFrameDisposable = null); } acceptScrollDimensions(t) { this.to = t.withScrollPosition(this.to), this._initAnimations(); } tick() { return this._tick(Date.now()); } _tick(t) { let e = (t - this.startTime) / this.duration; if (e < 1) { let i = this.scrollLeft(e), r = this.scrollTop(e); return new Br(i, r, false); } return new Br(this.to.scrollLeft, this.to.scrollTop, true); } combine(t, e, i) { return s10.start(t, e, i); } static start(t, e, i) { i = i + 10; let r = Date.now() - 10; return new s10(t, e, r, i); } }; function Aa(s15) { return Math.pow(s15, 3); } function ka(s15) { return 1 - Aa(1 - s15); } var Fr = class extends D { constructor(t, e, i) { super(), this._visibility = t, this._visibleClassName = e, this._invisibleClassName = i, this._domNode = null, this._isVisible = false, this._isNeeded = false, this._rawShouldBeVisible = false, this._shouldBeVisible = false, this._revealTimer = this._register(new Ye()); } setVisibility(t) { this._visibility !== t && (this._visibility = t, this._updateShouldBeVisible()); } setShouldBeVisible(t) { this._rawShouldBeVisible = t, this._updateShouldBeVisible(); } _applyVisibilitySetting() { return this._visibility === 2 ? false : this._visibility === 3 ? true : this._rawShouldBeVisible; } _updateShouldBeVisible() { let t = this._applyVisibilitySetting(); this._shouldBeVisible !== t && (this._shouldBeVisible = t, this.ensureVisibility()); } setIsNeeded(t) { this._isNeeded !== t && (this._isNeeded = t, this.ensureVisibility()); } setDomNode(t) { this._domNode = t, this._domNode.setClassName(this._invisibleClassName), this.setShouldBeVisible(false); } ensureVisibility() { if (!this._isNeeded) { this._hide(false); return; } this._shouldBeVisible ? this._reveal() : this._hide(true); } _reveal() { this._isVisible || (this._isVisible = true, this._revealTimer.setIfNotSet(() => { var _a5; (_a5 = this._domNode) == null ? void 0 : _a5.setClassName(this._visibleClassName); }, 0)); } _hide(t) { var _a5; this._revealTimer.cancel(), this._isVisible && (this._isVisible = false, (_a5 = this._domNode) == null ? void 0 : _a5.setClassName(this._invisibleClassName + (t ? " fade" : ""))); } }; var Ca = 140; var Ut = class extends lt { constructor(t) { super(), this._lazyRender = t.lazyRender, this._host = t.host, this._scrollable = t.scrollable, this._scrollByPage = t.scrollByPage, this._scrollbarState = t.scrollbarState, this._visibilityController = this._register(new Fr(t.visibility, "visible scrollbar " + t.extraScrollbarClassName, "invisible scrollbar " + t.extraScrollbarClassName)), this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()), this._pointerMoveMonitor = this._register(new Wt()), this._shouldRender = true, this.domNode = _t(document.createElement("div")), this.domNode.setAttribute("role", "presentation"), this.domNode.setAttribute("aria-hidden", "true"), this._visibilityController.setDomNode(this.domNode), this.domNode.setPosition("absolute"), this._register(L(this.domNode.domNode, Y.POINTER_DOWN, (e) => this._domNodePointerDown(e))); } _createArrow(t) { let e = this._register(new Or(t)); this.domNode.domNode.appendChild(e.bgDomNode), this.domNode.domNode.appendChild(e.domNode); } _createSlider(t, e, i, r) { this.slider = _t(document.createElement("div")), this.slider.setClassName("slider"), this.slider.setPosition("absolute"), this.slider.setTop(t), this.slider.setLeft(e), typeof i == "number" && this.slider.setWidth(i), typeof r == "number" && this.slider.setHeight(r), this.slider.setLayerHinting(true), this.slider.setContain("strict"), this.domNode.domNode.appendChild(this.slider.domNode), this._register(L(this.slider.domNode, Y.POINTER_DOWN, (n) => { n.button === 0 && (n.preventDefault(), this._sliderPointerDown(n)); })), this.onclick(this.slider.domNode, (n) => { n.leftButton && n.stopPropagation(); }); } _onElementSize(t) { return this._scrollbarState.setVisibleSize(t) && (this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()), this._shouldRender = true, this._lazyRender || this.render()), this._shouldRender; } _onElementScrollSize(t) { return this._scrollbarState.setScrollSize(t) && (this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()), this._shouldRender = true, this._lazyRender || this.render()), this._shouldRender; } _onElementScrollPosition(t) { return this._scrollbarState.setScrollPosition(t) && (this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()), this._shouldRender = true, this._lazyRender || this.render()), this._shouldRender; } beginReveal() { this._visibilityController.setShouldBeVisible(true); } beginHide() { this._visibilityController.setShouldBeVisible(false); } render() { this._shouldRender && (this._shouldRender = false, this._renderDomNode(this._scrollbarState.getRectangleLargeSize(), this._scrollbarState.getRectangleSmallSize()), this._updateSlider(this._scrollbarState.getSliderSize(), this._scrollbarState.getArrowSize() + this._scrollbarState.getSliderPosition())); } _domNodePointerDown(t) { t.target === this.domNode.domNode && this._onPointerDown(t); } delegatePointerDown(t) { let e = this.domNode.domNode.getClientRects()[0].top, i = e + this._scrollbarState.getSliderPosition(), r = e + this._scrollbarState.getSliderPosition() + this._scrollbarState.getSliderSize(), n = this._sliderPointerPosition(t); i <= n && n <= r ? t.button === 0 && (t.preventDefault(), this._sliderPointerDown(t)) : this._onPointerDown(t); } _onPointerDown(t) { let e, i; if (t.target === this.domNode.domNode && typeof t.offsetX == "number" && typeof t.offsetY == "number") e = t.offsetX, i = t.offsetY; else { let n = Fo(this.domNode.domNode); e = t.pageX - n.left, i = t.pageY - n.top; } let r = this._pointerDownRelativePosition(e, i); this._setDesiredScrollPositionNow(this._scrollByPage ? this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r) : this._scrollbarState.getDesiredScrollPositionFromOffset(r)), t.button === 0 && (t.preventDefault(), this._sliderPointerDown(t)); } _sliderPointerDown(t) { if (!t.target || !(t.target instanceof Element)) return; let e = this._sliderPointerPosition(t), i = this._sliderOrthogonalPointerPosition(t), r = this._scrollbarState.clone(); this.slider.toggleClassName("active", true), this._pointerMoveMonitor.startMonitoring(t.target, t.pointerId, t.buttons, (n) => { let o2 = this._sliderOrthogonalPointerPosition(n), l = Math.abs(o2 - i); if (wr && l > Ca) { this._setDesiredScrollPositionNow(r.getScrollPosition()); return; } let u = this._sliderPointerPosition(n) - e; this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(u)); }, () => { this.slider.toggleClassName("active", false), this._host.onDragEnd(); }), this._host.onDragStart(); } _setDesiredScrollPositionNow(t) { let e = {}; this.writeScrollPosition(e, t), this._scrollable.setScrollPositionNow(e); } updateScrollbarSize(t) { this._updateScrollbarSize(t), this._scrollbarState.setScrollbarSize(t), this._shouldRender = true, this._lazyRender || this.render(); } isNeeded() { return this._scrollbarState.isNeeded(); } }; var Kt = class s11 { constructor(t, e, i, r, n, o2) { this._scrollbarSize = Math.round(e), this._oppositeScrollbarSize = Math.round(i), this._arrowSize = Math.round(t), this._visibleSize = r, this._scrollSize = n, this._scrollPosition = o2, this._computedAvailableSize = 0, this._computedIsNeeded = false, this._computedSliderSize = 0, this._computedSliderRatio = 0, this._computedSliderPosition = 0, this._refreshComputedValues(); } clone() { return new s11(this._arrowSize, this._scrollbarSize, this._oppositeScrollbarSize, this._visibleSize, this._scrollSize, this._scrollPosition); } setVisibleSize(t) { let e = Math.round(t); return this._visibleSize !== e ? (this._visibleSize = e, this._refreshComputedValues(), true) : false; } setScrollSize(t) { let e = Math.round(t); return this._scrollSize !== e ? (this._scrollSize = e, this._refreshComputedValues(), true) : false; } setScrollPosition(t) { let e = Math.round(t); return this._scrollPosition !== e ? (this._scrollPosition = e, this._refreshComputedValues(), true) : false; } setScrollbarSize(t) { this._scrollbarSize = Math.round(t); } setOppositeScrollbarSize(t) { this._oppositeScrollbarSize = Math.round(t); } static _computeValues(t, e, i, r, n) { let o2 = Math.max(0, i - t), l = Math.max(0, o2 - 2 * e), a = r > 0 && r > i; if (!a) return { computedAvailableSize: Math.round(o2), computedIsNeeded: a, computedSliderSize: Math.round(l), computedSliderRatio: 0, computedSliderPosition: 0 }; let u = Math.round(Math.max(20, Math.floor(i * l / r))), h2 = (l - u) / (r - i), c = n * h2; return { computedAvailableSize: Math.round(o2), computedIsNeeded: a, computedSliderSize: Math.round(u), computedSliderRatio: h2, computedSliderPosition: Math.round(c) }; } _refreshComputedValues() { let t = s11._computeValues(this._oppositeScrollbarSize, this._arrowSize, this._visibleSize, this._scrollSize, this._scrollPosition); this._computedAvailableSize = t.computedAvailableSize, this._computedIsNeeded = t.computedIsNeeded, this._computedSliderSize = t.computedSliderSize, this._computedSliderRatio = t.computedSliderRatio, this._computedSliderPosition = t.computedSliderPosition; } getArrowSize() { return this._arrowSize; } getScrollPosition() { return this._scrollPosition; } getRectangleLargeSize() { return this._computedAvailableSize; } getRectangleSmallSize() { return this._scrollbarSize; } isNeeded() { return this._computedIsNeeded; } getSliderSize() { return this._computedSliderSize; } getSliderPosition() { return this._computedSliderPosition; } getDesiredScrollPositionFromOffset(t) { if (!this._computedIsNeeded) return 0; let e = t - this._arrowSize - this._computedSliderSize / 2; return Math.round(e / this._computedSliderRatio); } getDesiredScrollPositionFromOffsetPaged(t) { if (!this._computedIsNeeded) return 0; let e = t - this._arrowSize, i = this._scrollPosition; return e < this._computedSliderPosition ? i -= this._visibleSize : i += this._visibleSize, i; } getDesiredScrollPositionFromDelta(t) { if (!this._computedIsNeeded) return 0; let e = this._computedSliderPosition + t; return Math.round(e / this._computedSliderRatio); } }; var Wr = class extends Ut { constructor(t, e, i) { let r = t.getScrollDimensions(), n = t.getCurrentScrollPosition(); if (super({ lazyRender: e.lazyRender, host: i, scrollbarState: new Kt(e.horizontalHasArrows ? e.arrowSize : 0, e.horizontal === 2 ? 0 : e.horizontalScrollbarSize, e.vertical === 2 ? 0 : e.verticalScrollbarSize, r.width, r.scrollWidth, n.scrollLeft), visibility: e.horizontal, extraScrollbarClassName: "horizontal", scrollable: t, scrollByPage: e.scrollByPage }), e.horizontalHasArrows) throw new Error("horizontalHasArrows is not supported in xterm.js"); this._createSlider(Math.floor((e.horizontalScrollbarSize - e.horizontalSliderSize) / 2), 0, void 0, e.horizontalSliderSize); } _updateSlider(t, e) { this.slider.setWidth(t), this.slider.setLeft(e); } _renderDomNode(t, e) { this.domNode.setWidth(t), this.domNode.setHeight(e), this.domNode.setLeft(0), this.domNode.setBottom(0); } onDidScroll(t) { return this._shouldRender = this._onElementScrollSize(t.scrollWidth) || this._shouldRender, this._shouldRender = this._onElementScrollPosition(t.scrollLeft) || this._shouldRender, this._shouldRender = this._onElementSize(t.width) || this._shouldRender, this._shouldRender; } _pointerDownRelativePosition(t, e) { return t; } _sliderPointerPosition(t) { return t.pageX; } _sliderOrthogonalPointerPosition(t) { return t.pageY; } _updateScrollbarSize(t) { this.slider.setHeight(t); } writeScrollPosition(t, e) { t.scrollLeft = e; } updateOptions(t) { this.updateScrollbarSize(t.horizontal === 2 ? 0 : t.horizontalScrollbarSize), this._scrollbarState.setOppositeScrollbarSize(t.vertical === 2 ? 0 : t.verticalScrollbarSize), this._visibilityController.setVisibility(t.horizontal), this._scrollByPage = t.scrollByPage; } }; var Ur = class extends Ut { constructor(t, e, i) { let r = t.getScrollDimensions(), n = t.getCurrentScrollPosition(); if (super({ lazyRender: e.lazyRender, host: i, scrollbarState: new Kt(e.verticalHasArrows ? e.arrowSize : 0, e.vertical === 2 ? 0 : e.verticalScrollbarSize, 0, r.height, r.scrollHeight, n.scrollTop), visibility: e.vertical, extraScrollbarClassName: "vertical", scrollable: t, scrollByPage: e.scrollByPage }), e.verticalHasArrows) throw new Error("horizontalHasArrows is not supported in xterm.js"); this._createSlider(0, Math.floor((e.verticalScrollbarSize - e.verticalSliderSize) / 2), e.verticalSliderSize, void 0); } _updateSlider(t, e) { this.slider.setHeight(t), this.slider.setTop(e); } _renderDomNode(t, e) { this.domNode.setWidth(e), this.domNode.setHeight(t), this.domNode.setRight(0), this.domNode.setTop(0); } onDidScroll(t) { return this._shouldRender = this._onElementScrollSize(t.scrollHeight) || this._shouldRender, this._shouldRender = this._onElementScrollPosition(t.scrollTop) || this._shouldRender, this._shouldRender = this._onElementSize(t.height) || this._shouldRender, this._shouldRender; } _pointerDownRelativePosition(t, e) { return e; } _sliderPointerPosition(t) { return t.pageY; } _sliderOrthogonalPointerPosition(t) { return t.pageX; } _updateScrollbarSize(t) { this.slider.setWidth(t); } writeScrollPosition(t, e) { t.scrollTop = e; } updateOptions(t) { this.updateScrollbarSize(t.vertical === 2 ? 0 : t.verticalScrollbarSize), this._scrollbarState.setOppositeScrollbarSize(0), this._visibilityController.setVisibility(t.vertical), this._scrollByPage = t.scrollByPage; } }; var Ma = 500; var Ko = 50; var zo = true; var us = class { constructor(t, e, i) { this.timestamp = t, this.deltaX = e, this.deltaY = i, this.score = 0; } }; var zr = class zr2 { constructor() { this._capacity = 5, this._memory = [], this._front = -1, this._rear = -1; } isPhysicalMouseWheel() { if (this._front === -1 && this._rear === -1) return false; let t = 1, e = 0, i = 1, r = this._rear; do { let n = r === this._front ? t : Math.pow(2, -i); if (t -= n, e += this._memory[r].score * n, r === this._front) break; r = (this._capacity + r - 1) % this._capacity, i++; } while (true); return e <= 0.5; } acceptStandardWheelEvent(t) { if (Ti) { let e = be(t.browserEvent), i = mo(e); this.accept(Date.now(), t.deltaX * i, t.deltaY * i); } else this.accept(Date.now(), t.deltaX, t.deltaY); } accept(t, e, i) { let r = null, n = new us(t, e, i); this._front === -1 && this._rear === -1 ? (this._memory[0] = n, this._front = 0, this._rear = 0) : (r = this._memory[this._rear], this._rear = (this._rear + 1) % this._capacity, this._rear === this._front && (this._front = (this._front + 1) % this._capacity), this._memory[this._rear] = n), n.score = this._computeScore(n, r); } _computeScore(t, e) { if (Math.abs(t.deltaX) > 0 && Math.abs(t.deltaY) > 0) return 1; let i = 0.5; if ((!this._isAlmostInt(t.deltaX) || !this._isAlmostInt(t.deltaY)) && (i += 0.25), e) { let r = Math.abs(t.deltaX), n = Math.abs(t.deltaY), o2 = Math.abs(e.deltaX), l = Math.abs(e.deltaY), a = Math.max(Math.min(r, o2), 1), u = Math.max(Math.min(n, l), 1), h2 = Math.max(r, o2), c = Math.max(n, l); h2 % a === 0 && c % u === 0 && (i -= 0.5); } return Math.min(Math.max(i, 0), 1); } _isAlmostInt(t) { return Math.abs(Math.round(t) - t) < 0.01; } }; zr.INSTANCE = new zr(); var hs = zr; var ds = class extends lt { constructor(e, i, r) { super(); this._onScroll = this._register(new v()); this.onScroll = this._onScroll.event; this._onWillScroll = this._register(new v()); this.onWillScroll = this._onWillScroll.event; this._options = Pa(i), this._scrollable = r, this._register(this._scrollable.onScroll((o2) => { this._onWillScroll.fire(o2), this._onDidScroll(o2), this._onScroll.fire(o2); })); let n = { onMouseWheel: (o2) => this._onMouseWheel(o2), onDragStart: () => this._onDragStart(), onDragEnd: () => this._onDragEnd() }; this._verticalScrollbar = this._register(new Ur(this._scrollable, this._options, n)), this._horizontalScrollbar = this._register(new Wr(this._scrollable, this._options, n)), this._domNode = document.createElement("div"), this._domNode.className = "xterm-scrollable-element " + this._options.className, this._domNode.setAttribute("role", "presentation"), this._domNode.style.position = "relative", this._domNode.appendChild(e), this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode), this._domNode.appendChild(this._verticalScrollbar.domNode.domNode), this._options.useShadows ? (this._leftShadowDomNode = _t(document.createElement("div")), this._leftShadowDomNode.setClassName("shadow"), this._domNode.appendChild(this._leftShadowDomNode.domNode), this._topShadowDomNode = _t(document.createElement("div")), this._topShadowDomNode.setClassName("shadow"), this._domNode.appendChild(this._topShadowDomNode.domNode), this._topLeftShadowDomNode = _t(document.createElement("div")), this._topLeftShadowDomNode.setClassName("shadow"), this._domNode.appendChild(this._topLeftShadowDomNode.domNode)) : (this._leftShadowDomNode = null, this._topShadowDomNode = null, this._topLeftShadowDomNode = null), this._listenOnDomNode = this._options.listenOnDomNode || this._domNode, this._mouseWheelToDispose = [], this._setListeningToMouseWheel(this._options.handleMouseWheel), this.onmouseover(this._listenOnDomNode, (o2) => this._onMouseOver(o2)), this.onmouseleave(this._listenOnDomNode, (o2) => this._onMouseLeave(o2)), this._hideTimeout = this._register(new Ye()), this._isDragging = false, this._mouseIsOver = false, this._shouldRender = true, this._revealOnScroll = true; } get options() { return this._options; } dispose() { this._mouseWheelToDispose = Ne(this._mouseWheelToDispose), super.dispose(); } getDomNode() { return this._domNode; } getOverviewRulerLayoutInfo() { return { parent: this._domNode, insertBefore: this._verticalScrollbar.domNode.domNode }; } delegateVerticalScrollbarPointerDown(e) { this._verticalScrollbar.delegatePointerDown(e); } getScrollDimensions() { return this._scrollable.getScrollDimensions(); } setScrollDimensions(e) { this._scrollable.setScrollDimensions(e, false); } updateClassName(e) { this._options.className = e, Te && (this._options.className += " mac"), this._domNode.className = "xterm-scrollable-element " + this._options.className; } updateOptions(e) { typeof e.handleMouseWheel < "u" && (this._options.handleMouseWheel = e.handleMouseWheel, this._setListeningToMouseWheel(this._options.handleMouseWheel)), typeof e.mouseWheelScrollSensitivity < "u" && (this._options.mouseWheelScrollSensitivity = e.mouseWheelScrollSensitivity), typeof e.fastScrollSensitivity < "u" && (this._options.fastScrollSensitivity = e.fastScrollSensitivity), typeof e.scrollPredominantAxis < "u" && (this._options.scrollPredominantAxis = e.scrollPredominantAxis), typeof e.horizontal < "u" && (this._options.horizontal = e.horizontal), typeof e.vertical < "u" && (this._options.vertical = e.vertical), typeof e.horizontalScrollbarSize < "u" && (this._options.horizontalScrollbarSize = e.horizontalScrollbarSize), typeof e.verticalScrollbarSize < "u" && (this._options.verticalScrollbarSize = e.verticalScrollbarSize), typeof e.scrollByPage < "u" && (this._options.scrollByPage = e.scrollByPage), this._horizontalScrollbar.updateOptions(this._options), this._verticalScrollbar.updateOptions(this._options), this._options.lazyRender || this._render(); } setRevealOnScroll(e) { this._revealOnScroll = e; } delegateScrollFromMouseWheelEvent(e) { this._onMouseWheel(new xi(e)); } _setListeningToMouseWheel(e) { if (this._mouseWheelToDispose.length > 0 !== e && (this._mouseWheelToDispose = Ne(this._mouseWheelToDispose), e)) { let r = (n) => { this._onMouseWheel(new xi(n)); }; this._mouseWheelToDispose.push(L(this._listenOnDomNode, Y.MOUSE_WHEEL, r, { passive: false })); } } _onMouseWheel(e) { var _a5; if ((_a5 = e.browserEvent) == null ? void 0 : _a5.defaultPrevented) return; let i = hs.INSTANCE; zo && i.acceptStandardWheelEvent(e); let r = false; if (e.deltaY || e.deltaX) { let o2 = e.deltaY * this._options.mouseWheelScrollSensitivity, l = e.deltaX * this._options.mouseWheelScrollSensitivity; this._options.scrollPredominantAxis && (this._options.scrollYToX && l + o2 === 0 ? l = o2 = 0 : Math.abs(o2) >= Math.abs(l) ? l = 0 : o2 = 0), this._options.flipAxes && ([o2, l] = [l, o2]); let a = !Te && e.browserEvent && e.browserEvent.shiftKey; (this._options.scrollYToX || a) && !l && (l = o2, o2 = 0), e.browserEvent && e.browserEvent.altKey && (l = l * this._options.fastScrollSensitivity, o2 = o2 * this._options.fastScrollSensitivity); let u = this._scrollable.getFutureScrollPosition(), h2 = {}; if (o2) { let c = Ko * o2, d = u.scrollTop - (c < 0 ? Math.floor(c) : Math.ceil(c)); this._verticalScrollbar.writeScrollPosition(h2, d); } if (l) { let c = Ko * l, d = u.scrollLeft - (c < 0 ? Math.floor(c) : Math.ceil(c)); this._horizontalScrollbar.writeScrollPosition(h2, d); } h2 = this._scrollable.validateScrollPosition(h2), (u.scrollLeft !== h2.scrollLeft || u.scrollTop !== h2.scrollTop) && (zo && this._options.mouseWheelSmoothScroll && i.isPhysicalMouseWheel() ? this._scrollable.setScrollPositionSmooth(h2) : this._scrollable.setScrollPositionNow(h2), r = true); } let n = r; !n && this._options.alwaysConsumeMouseWheel && (n = true), !n && this._options.consumeMouseWheelIfScrollbarIsNeeded && (this._verticalScrollbar.isNeeded() || this._horizontalScrollbar.isNeeded()) && (n = true), n && (e.preventDefault(), e.stopPropagation()); } _onDidScroll(e) { this._shouldRender = this._horizontalScrollbar.onDidScroll(e) || this._shouldRender, this._shouldRender = this._verticalScrollbar.onDidScroll(e) || this._shouldRender, this._options.useShadows && (this._shouldRender = true), this._revealOnScroll && this._reveal(), this._options.lazyRender || this._render(); } renderNow() { if (!this._options.lazyRender) throw new Error("Please use `lazyRender` together with `renderNow`!"); this._render(); } _render() { if (this._shouldRender && (this._shouldRender = false, this._horizontalScrollbar.render(), this._verticalScrollbar.render(), this._options.useShadows)) { let e = this._scrollable.getCurrentScrollPosition(), i = e.scrollTop > 0, r = e.scrollLeft > 0, n = r ? " left" : "", o2 = i ? " top" : "", l = r || i ? " top-left-corner" : ""; this._leftShadowDomNode.setClassName(`shadow${n}`), this._topShadowDomNode.setClassName(`shadow${o2}`), this._topLeftShadowDomNode.setClassName(`shadow${l}${o2}${n}`); } } _onDragStart() { this._isDragging = true, this._reveal(); } _onDragEnd() { this._isDragging = false, this._hide(); } _onMouseLeave(e) { this._mouseIsOver = false, this._hide(); } _onMouseOver(e) { this._mouseIsOver = true, this._reveal(); } _reveal() { this._verticalScrollbar.beginReveal(), this._horizontalScrollbar.beginReveal(), this._scheduleHide(); } _hide() { !this._mouseIsOver && !this._isDragging && (this._verticalScrollbar.beginHide(), this._horizontalScrollbar.beginHide()); } _scheduleHide() { !this._mouseIsOver && !this._isDragging && this._hideTimeout.cancelAndSet(() => this._hide(), Ma); } }; var Kr = class extends ds { constructor(t, e, i) { super(t, e, i); } setScrollPosition(t) { t.reuseAnimation ? this._scrollable.setScrollPositionSmooth(t, t.reuseAnimation) : this._scrollable.setScrollPositionNow(t); } getScrollPosition() { return this._scrollable.getCurrentScrollPosition(); } }; function Pa(s15) { let t = { lazyRender: typeof s15.lazyRender < "u" ? s15.lazyRender : false, className: typeof s15.className < "u" ? s15.className : "", useShadows: typeof s15.useShadows < "u" ? s15.useShadows : true, handleMouseWheel: typeof s15.handleMouseWheel < "u" ? s15.handleMouseWheel : true, flipAxes: typeof s15.flipAxes < "u" ? s15.flipAxes : false, consumeMouseWheelIfScrollbarIsNeeded: typeof s15.consumeMouseWheelIfScrollbarIsNeeded < "u" ? s15.consumeMouseWheelIfScrollbarIsNeeded : false, alwaysConsumeMouseWheel: typeof s15.alwaysConsumeMouseWheel < "u" ? s15.alwaysConsumeMouseWheel : false, scrollYToX: typeof s15.scrollYToX < "u" ? s15.scrollYToX : false, mouseWheelScrollSensitivity: typeof s15.mouseWheelScrollSensitivity < "u" ? s15.mouseWheelScrollSensitivity : 1, fastScrollSensitivity: typeof s15.fastScrollSensitivity < "u" ? s15.fastScrollSensitivity : 5, scrollPredominantAxis: typeof s15.scrollPredominantAxis < "u" ? s15.scrollPredominantAxis : true, mouseWheelSmoothScroll: typeof s15.mouseWheelSmoothScroll < "u" ? s15.mouseWheelSmoothScroll : true, arrowSize: typeof s15.arrowSize < "u" ? s15.arrowSize : 11, listenOnDomNode: typeof s15.listenOnDomNode < "u" ? s15.listenOnDomNode : null, horizontal: typeof s15.horizontal < "u" ? s15.horizontal : 1, horizontalScrollbarSize: typeof s15.horizontalScrollbarSize < "u" ? s15.horizontalScrollbarSize : 10, horizontalSliderSize: typeof s15.horizontalSliderSize < "u" ? s15.horizontalSliderSize : 0, horizontalHasArrows: typeof s15.horizontalHasArrows < "u" ? s15.horizontalHasArrows : false, vertical: typeof s15.vertical < "u" ? s15.vertical : 1, verticalScrollbarSize: typeof s15.verticalScrollbarSize < "u" ? s15.verticalScrollbarSize : 10, verticalHasArrows: typeof s15.verticalHasArrows < "u" ? s15.verticalHasArrows : false, verticalSliderSize: typeof s15.verticalSliderSize < "u" ? s15.verticalSliderSize : 0, scrollByPage: typeof s15.scrollByPage < "u" ? s15.scrollByPage : false }; return t.horizontalSliderSize = typeof s15.horizontalSliderSize < "u" ? s15.horizontalSliderSize : t.horizontalScrollbarSize, t.verticalSliderSize = typeof s15.verticalSliderSize < "u" ? s15.verticalSliderSize : t.verticalScrollbarSize, Te && (t.className += " mac"), t; } var zt = class extends D { constructor(e, i, r, n, o2, l, a, u) { super(); this._bufferService = r; this._optionsService = a; this._renderService = u; this._onRequestScrollLines = this._register(new v()); this.onRequestScrollLines = this._onRequestScrollLines.event; this._isSyncing = false; this._isHandlingScroll = false; this._suppressOnScrollHandler = false; let h2 = this._register(new Ri({ forceIntegerValues: false, smoothScrollDuration: this._optionsService.rawOptions.smoothScrollDuration, scheduleAtNextAnimationFrame: (c) => mt(n.window, c) })); this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration", () => { h2.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration); })), this._scrollableElement = this._register(new Kr(i, { vertical: 1, horizontal: 2, useShadows: false, mouseWheelSmoothScroll: true, ...this._getChangeOptions() }, h2)), this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity", "fastScrollSensitivity", "overviewRuler"], () => this._scrollableElement.updateOptions(this._getChangeOptions()))), this._register(o2.onProtocolChange((c) => { this._scrollableElement.updateOptions({ handleMouseWheel: !(c & 16) }); })), this._scrollableElement.setScrollDimensions({ height: 0, scrollHeight: 0 }), this._register($.runAndSubscribe(l.onChangeColors, () => { this._scrollableElement.getDomNode().style.backgroundColor = l.colors.background.css; })), e.appendChild(this._scrollableElement.getDomNode()), this._register(C(() => this._scrollableElement.getDomNode().remove())), this._styleElement = n.mainDocument.createElement("style"), i.appendChild(this._styleElement), this._register(C(() => this._styleElement.remove())), this._register($.runAndSubscribe(l.onChangeColors, () => { this._styleElement.textContent = [".xterm .xterm-scrollable-element > .scrollbar > .slider {", ` background: ${l.colors.scrollbarSliderBackground.css};`, "}", ".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {", ` background: ${l.colors.scrollbarSliderHoverBackground.css};`, "}", ".xterm .xterm-scrollable-element > .scrollbar > .slider.active {", ` background: ${l.colors.scrollbarSliderActiveBackground.css};`, "}"].join(` `); })), this._register(this._bufferService.onResize(() => this.queueSync())), this._register(this._bufferService.buffers.onBufferActivate(() => { this._latestYDisp = void 0, this.queueSync(); })), this._register(this._bufferService.onScroll(() => this._sync())), this._register(this._scrollableElement.onScroll((c) => this._handleScroll(c))); } scrollLines(e) { let i = this._scrollableElement.getScrollPosition(); this._scrollableElement.setScrollPosition({ reuseAnimation: true, scrollTop: i.scrollTop + e * this._renderService.dimensions.css.cell.height }); } scrollToLine(e, i) { i && (this._latestYDisp = e), this._scrollableElement.setScrollPosition({ reuseAnimation: !i, scrollTop: e * this._renderService.dimensions.css.cell.height }); } _getChangeOptions() { var _a5; return { mouseWheelScrollSensitivity: this._optionsService.rawOptions.scrollSensitivity, fastScrollSensitivity: this._optionsService.rawOptions.fastScrollSensitivity, verticalScrollbarSize: ((_a5 = this._optionsService.rawOptions.overviewRuler) == null ? void 0 : _a5.width) || 14 }; } queueSync(e) { e !== void 0 && (this._latestYDisp = e), this._queuedAnimationFrame === void 0 && (this._queuedAnimationFrame = this._renderService.addRefreshCallback(() => { this._queuedAnimationFrame = void 0, this._sync(this._latestYDisp); })); } _sync(e = this._bufferService.buffer.ydisp) { !this._renderService || this._isSyncing || (this._isSyncing = true, this._suppressOnScrollHandler = true, this._scrollableElement.setScrollDimensions({ height: this._renderService.dimensions.css.canvas.height, scrollHeight: this._renderService.dimensions.css.cell.height * this._bufferService.buffer.lines.length }), this._suppressOnScrollHandler = false, e !== this._latestYDisp && this._scrollableElement.setScrollPosition({ scrollTop: e * this._renderService.dimensions.css.cell.height }), this._isSyncing = false); } _handleScroll(e) { if (!this._renderService || this._isHandlingScroll || this._suppressOnScrollHandler) return; this._isHandlingScroll = true; let i = Math.round(e.scrollTop / this._renderService.dimensions.css.cell.height), r = i - this._bufferService.buffer.ydisp; r !== 0 && (this._latestYDisp = i, this._onRequestScrollLines.fire(r)), this._isHandlingScroll = false; } }; zt = M([S(2, F), S(3, ae), S(4, rr), S(5, Re), S(6, H), S(7, ce)], zt); var Gt = class extends D { constructor(e, i, r, n, o2) { super(); this._screenElement = e; this._bufferService = i; this._coreBrowserService = r; this._decorationService = n; this._renderService = o2; this._decorationElements = /* @__PURE__ */ new Map(); this._altBufferIsActive = false; this._dimensionsChanged = false; this._container = document.createElement("div"), this._container.classList.add("xterm-decoration-container"), this._screenElement.appendChild(this._container), this._register(this._renderService.onRenderedViewportChange(() => this._doRefreshDecorations())), this._register(this._renderService.onDimensionsChange(() => { this._dimensionsChanged = true, this._queueRefresh(); })), this._register(this._coreBrowserService.onDprChange(() => this._queueRefresh())), this._register(this._bufferService.buffers.onBufferActivate(() => { this._altBufferIsActive = this._bufferService.buffer === this._bufferService.buffers.alt; })), this._register(this._decorationService.onDecorationRegistered(() => this._queueRefresh())), this._register(this._decorationService.onDecorationRemoved((l) => this._removeDecoration(l))), this._register(C(() => { this._container.remove(), this._decorationElements.clear(); })); } _queueRefresh() { this._animationFrame === void 0 && (this._animationFrame = this._renderService.addRefreshCallback(() => { this._doRefreshDecorations(), this._animationFrame = void 0; })); } _doRefreshDecorations() { for (let e of this._decorationService.decorations) this._renderDecoration(e); this._dimensionsChanged = false; } _renderDecoration(e) { this._refreshStyle(e), this._dimensionsChanged && this._refreshXPosition(e); } _createElement(e) { var _a5, _b; let i = this._coreBrowserService.mainDocument.createElement("div"); i.classList.add("xterm-decoration"), i.classList.toggle("xterm-decoration-top-layer", ((_a5 = e == null ? void 0 : e.options) == null ? void 0 : _a5.layer) === "top"), i.style.width = `${Math.round((e.options.width || 1) * this._renderService.dimensions.css.cell.width)}px`, i.style.height = `${(e.options.height || 1) * this._renderService.dimensions.css.cell.height}px`, i.style.top = `${(e.marker.line - this._bufferService.buffers.active.ydisp) * this._renderService.dimensions.css.cell.height}px`, i.style.lineHeight = `${this._renderService.dimensions.css.cell.height}px`; let r = (_b = e.options.x) != null ? _b : 0; return r && r > this._bufferService.cols && (i.style.display = "none"), this._refreshXPosition(e, i), i; } _refreshStyle(e) { let i = e.marker.line - this._bufferService.buffers.active.ydisp; if (i < 0 || i >= this._bufferService.rows) e.element && (e.element.style.display = "none", e.onRenderEmitter.fire(e.element)); else { let r = this._decorationElements.get(e); r || (r = this._createElement(e), e.element = r, this._decorationElements.set(e, r), this._container.appendChild(r), e.onDispose(() => { this._decorationElements.delete(e), r.remove(); })), r.style.display = this._altBufferIsActive ? "none" : "block", this._altBufferIsActive || (r.style.width = `${Math.round((e.options.width || 1) * this._renderService.dimensions.css.cell.width)}px`, r.style.height = `${(e.options.height || 1) * this._renderService.dimensions.css.cell.height}px`, r.style.top = `${i * this._renderService.dimensions.css.cell.height}px`, r.style.lineHeight = `${this._renderService.dimensions.css.cell.height}px`), e.onRenderEmitter.fire(r); } } _refreshXPosition(e, i = e.element) { var _a5; if (!i) return; let r = (_a5 = e.options.x) != null ? _a5 : 0; (e.options.anchor || "left") === "right" ? i.style.right = r ? `${r * this._renderService.dimensions.css.cell.width}px` : "" : i.style.left = r ? `${r * this._renderService.dimensions.css.cell.width}px` : ""; } _removeDecoration(e) { var _a5; (_a5 = this._decorationElements.get(e)) == null ? void 0 : _a5.remove(), this._decorationElements.delete(e), e.dispose(); } }; Gt = M([S(1, F), S(2, ae), S(3, Be), S(4, ce)], Gt); var Gr = class { constructor() { this._zones = []; this._zonePool = []; this._zonePoolIndex = 0; this._linePadding = { full: 0, left: 0, center: 0, right: 0 }; } get zones() { return this._zonePool.length = Math.min(this._zonePool.length, this._zones.length), this._zones; } clear() { this._zones.length = 0, this._zonePoolIndex = 0; } addDecoration(t) { if (t.options.overviewRulerOptions) { for (let e of this._zones) if (e.color === t.options.overviewRulerOptions.color && e.position === t.options.overviewRulerOptions.position) { if (this._lineIntersectsZone(e, t.marker.line)) return; if (this._lineAdjacentToZone(e, t.marker.line, t.options.overviewRulerOptions.position)) { this._addLineToZone(e, t.marker.line); return; } } if (this._zonePoolIndex < this._zonePool.length) { this._zonePool[this._zonePoolIndex].color = t.options.overviewRulerOptions.color, this._zonePool[this._zonePoolIndex].position = t.options.overviewRulerOptions.position, this._zonePool[this._zonePoolIndex].startBufferLine = t.marker.line, this._zonePool[this._zonePoolIndex].endBufferLine = t.marker.line, this._zones.push(this._zonePool[this._zonePoolIndex++]); return; } this._zones.push({ color: t.options.overviewRulerOptions.color, position: t.options.overviewRulerOptions.position, startBufferLine: t.marker.line, endBufferLine: t.marker.line }), this._zonePool.push(this._zones[this._zones.length - 1]), this._zonePoolIndex++; } } setPadding(t) { this._linePadding = t; } _lineIntersectsZone(t, e) { return e >= t.startBufferLine && e <= t.endBufferLine; } _lineAdjacentToZone(t, e, i) { return e >= t.startBufferLine - this._linePadding[i || "full"] && e <= t.endBufferLine + this._linePadding[i || "full"]; } _addLineToZone(t, e) { t.startBufferLine = Math.min(t.startBufferLine, e), t.endBufferLine = Math.max(t.endBufferLine, e); } }; var We = { full: 0, left: 0, center: 0, right: 0 }; var at = { full: 0, left: 0, center: 0, right: 0 }; var Li = { full: 0, left: 0, center: 0, right: 0 }; var bt = class extends D { constructor(e, i, r, n, o2, l, a, u) { var _a5; super(); this._viewportElement = e; this._screenElement = i; this._bufferService = r; this._decorationService = n; this._renderService = o2; this._optionsService = l; this._themeService = a; this._coreBrowserService = u; this._colorZoneStore = new Gr(); this._shouldUpdateDimensions = true; this._shouldUpdateAnchor = true; this._lastKnownBufferLength = 0; this._canvas = this._coreBrowserService.mainDocument.createElement("canvas"), this._canvas.classList.add("xterm-decoration-overview-ruler"), this._refreshCanvasDimensions(), (_a5 = this._viewportElement.parentElement) == null ? void 0 : _a5.insertBefore(this._canvas, this._viewportElement), this._register(C(() => { var _a6; return (_a6 = this._canvas) == null ? void 0 : _a6.remove(); })); let h2 = this._canvas.getContext("2d"); if (h2) this._ctx = h2; else throw new Error("Ctx cannot be null"); this._register(this._decorationService.onDecorationRegistered(() => this._queueRefresh(void 0, true))), this._register(this._decorationService.onDecorationRemoved(() => this._queueRefresh(void 0, true))), this._register(this._renderService.onRenderedViewportChange(() => this._queueRefresh())), this._register(this._bufferService.buffers.onBufferActivate(() => { this._canvas.style.display = this._bufferService.buffer === this._bufferService.buffers.alt ? "none" : "block"; })), this._register(this._bufferService.onScroll(() => { this._lastKnownBufferLength !== this._bufferService.buffers.normal.lines.length && (this._refreshDrawHeightConstants(), this._refreshColorZonePadding()); })), this._register(this._renderService.onRender(() => { (!this._containerHeight || this._containerHeight !== this._screenElement.clientHeight) && (this._queueRefresh(true), this._containerHeight = this._screenElement.clientHeight); })), this._register(this._coreBrowserService.onDprChange(() => this._queueRefresh(true))), this._register(this._optionsService.onSpecificOptionChange("overviewRuler", () => this._queueRefresh(true))), this._register(this._themeService.onChangeColors(() => this._queueRefresh())), this._queueRefresh(true); } get _width() { var _a5; return ((_a5 = this._optionsService.options.overviewRuler) == null ? void 0 : _a5.width) || 0; } _refreshDrawConstants() { let e = Math.floor((this._canvas.width - 1) / 3), i = Math.ceil((this._canvas.width - 1) / 3); at.full = this._canvas.width, at.left = e, at.center = i, at.right = e, this._refreshDrawHeightConstants(), Li.full = 1, Li.left = 1, Li.center = 1 + at.left, Li.right = 1 + at.left + at.center; } _refreshDrawHeightConstants() { We.full = Math.round(2 * this._coreBrowserService.dpr); let e = this._canvas.height / this._bufferService.buffer.lines.length, i = Math.round(Math.max(Math.min(e, 12), 6) * this._coreBrowserService.dpr); We.left = i, We.center = i, We.right = i; } _refreshColorZonePadding() { this._colorZoneStore.setPadding({ full: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * We.full), left: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * We.left), center: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * We.center), right: Math.floor(this._bufferService.buffers.active.lines.length / (this._canvas.height - 1) * We.right) }), this._lastKnownBufferLength = this._bufferService.buffers.normal.lines.length; } _refreshCanvasDimensions() { this._canvas.style.width = `${this._width}px`, this._canvas.width = Math.round(this._width * this._coreBrowserService.dpr), this._canvas.style.height = `${this._screenElement.clientHeight}px`, this._canvas.height = Math.round(this._screenElement.clientHeight * this._coreBrowserService.dpr), this._refreshDrawConstants(), this._refreshColorZonePadding(); } _refreshDecorations() { this._shouldUpdateDimensions && this._refreshCanvasDimensions(), this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height), this._colorZoneStore.clear(); for (let i of this._decorationService.decorations) this._colorZoneStore.addDecoration(i); this._ctx.lineWidth = 1, this._renderRulerOutline(); let e = this._colorZoneStore.zones; for (let i of e) i.position !== "full" && this._renderColorZone(i); for (let i of e) i.position === "full" && this._renderColorZone(i); this._shouldUpdateDimensions = false, this._shouldUpdateAnchor = false; } _renderRulerOutline() { this._ctx.fillStyle = this._themeService.colors.overviewRulerBorder.css, this._ctx.fillRect(0, 0, 1, this._canvas.height), this._optionsService.rawOptions.overviewRuler.showTopBorder && this._ctx.fillRect(1, 0, this._canvas.width - 1, 1), this._optionsService.rawOptions.overviewRuler.showBottomBorder && this._ctx.fillRect(1, this._canvas.height - 1, this._canvas.width - 1, this._canvas.height); } _renderColorZone(e) { this._ctx.fillStyle = e.color, this._ctx.fillRect(Li[e.position || "full"], Math.round((this._canvas.height - 1) * (e.startBufferLine / this._bufferService.buffers.active.lines.length) - We[e.position || "full"] / 2), at[e.position || "full"], Math.round((this._canvas.height - 1) * ((e.endBufferLine - e.startBufferLine) / this._bufferService.buffers.active.lines.length) + We[e.position || "full"])); } _queueRefresh(e, i) { this._shouldUpdateDimensions = e || this._shouldUpdateDimensions, this._shouldUpdateAnchor = i || this._shouldUpdateAnchor, this._animationFrame === void 0 && (this._animationFrame = this._coreBrowserService.window.requestAnimationFrame(() => { this._refreshDecorations(), this._animationFrame = void 0; })); } }; bt = M([S(2, F), S(3, Be), S(4, ce), S(5, H), S(6, Re), S(7, ae)], bt); var b; ((E) => (E.NUL = "\0", E.SOH = "", E.STX = "", E.ETX = "", E.EOT = "", E.ENQ = "", E.ACK = "", E.BEL = "\x07", E.BS = "\b", E.HT = " ", E.LF = ` `, E.VT = "\v", E.FF = "\f", E.CR = "\r", E.SO = "", E.SI = "", E.DLE = "", E.DC1 = "", E.DC2 = "", E.DC3 = "", E.DC4 = "", E.NAK = "", E.SYN = "", E.ETB = "", E.CAN = "", E.EM = "", E.SUB = "", E.ESC = "\x1B", E.FS = "", E.GS = "", E.RS = "", E.US = "", E.SP = " ", E.DEL = "\x7F"))(b || (b = {})); var Ai; ((g) => (g.PAD = "\x80", g.HOP = "\x81", g.BPH = "\x82", g.NBH = "\x83", g.IND = "\x84", g.NEL = "\x85", g.SSA = "\x86", g.ESA = "\x87", g.HTS = "\x88", g.HTJ = "\x89", g.VTS = "\x8A", g.PLD = "\x8B", g.PLU = "\x8C", g.RI = "\x8D", g.SS2 = "\x8E", g.SS3 = "\x8F", g.DCS = "\x90", g.PU1 = "\x91", g.PU2 = "\x92", g.STS = "\x93", g.CCH = "\x94", g.MW = "\x95", g.SPA = "\x96", g.EPA = "\x97", g.SOS = "\x98", g.SGCI = "\x99", g.SCI = "\x9A", g.CSI = "\x9B", g.ST = "\x9C", g.OSC = "\x9D", g.PM = "\x9E", g.APC = "\x9F"))(Ai || (Ai = {})); var fs; ((t) => t.ST = `${b.ESC}\\`)(fs || (fs = {})); var $t = class { constructor(t, e, i, r, n, o2) { this._textarea = t; this._compositionView = e; this._bufferService = i; this._optionsService = r; this._coreService = n; this._renderService = o2; this._isComposing = false, this._isSendingComposition = false, this._compositionPosition = { start: 0, end: 0 }, this._dataAlreadySent = ""; } get isComposing() { return this._isComposing; } compositionstart() { this._isComposing = true, this._compositionPosition.start = this._textarea.value.length, this._compositionView.textContent = "", this._dataAlreadySent = "", this._compositionView.classList.add("active"); } compositionupdate(t) { this._compositionView.textContent = t.data, this.updateCompositionElements(), setTimeout(() => { this._compositionPosition.end = this._textarea.value.length; }, 0); } compositionend() { this._finalizeComposition(true); } keydown(t) { if (this._isComposing || this._isSendingComposition) { if (t.keyCode === 20 || t.keyCode === 229 || t.keyCode === 16 || t.keyCode === 17 || t.keyCode === 18) return false; this._finalizeComposition(false); } return t.keyCode === 229 ? (this._handleAnyTextareaChanges(), false) : true; } _finalizeComposition(t) { if (this._compositionView.classList.remove("active"), this._isComposing = false, t) { let e = { start: this._compositionPosition.start, end: this._compositionPosition.end }; this._isSendingComposition = true, setTimeout(() => { if (this._isSendingComposition) { this._isSendingComposition = false; let i; e.start += this._dataAlreadySent.length, this._isComposing ? i = this._textarea.value.substring(e.start, this._compositionPosition.start) : i = this._textarea.value.substring(e.start), i.length > 0 && this._coreService.triggerDataEvent(i, true); } }, 0); } else { this._isSendingComposition = false; let e = this._textarea.value.substring(this._compositionPosition.start, this._compositionPosition.end); this._coreService.triggerDataEvent(e, true); } } _handleAnyTextareaChanges() { let t = this._textarea.value; setTimeout(() => { if (!this._isComposing) { let e = this._textarea.value, i = e.replace(t, ""); this._dataAlreadySent = i, e.length > t.length ? this._coreService.triggerDataEvent(i, true) : e.length < t.length ? this._coreService.triggerDataEvent(`${b.DEL}`, true) : e.length === t.length && e !== t && this._coreService.triggerDataEvent(e, true); } }, 0); } updateCompositionElements(t) { if (this._isComposing) { if (this._bufferService.buffer.isCursorInViewport) { let e = Math.min(this._bufferService.buffer.x, this._bufferService.cols - 1), i = this._renderService.dimensions.css.cell.height, r = this._bufferService.buffer.y * this._renderService.dimensions.css.cell.height, n = e * this._renderService.dimensions.css.cell.width; this._compositionView.style.left = n + "px", this._compositionView.style.top = r + "px", this._compositionView.style.height = i + "px", this._compositionView.style.lineHeight = i + "px", this._compositionView.style.fontFamily = this._optionsService.rawOptions.fontFamily, this._compositionView.style.fontSize = this._optionsService.rawOptions.fontSize + "px"; let o2 = this._compositionView.getBoundingClientRect(); this._textarea.style.left = n + "px", this._textarea.style.top = r + "px", this._textarea.style.width = Math.max(o2.width, 1) + "px", this._textarea.style.height = Math.max(o2.height, 1) + "px", this._textarea.style.lineHeight = o2.height + "px"; } t || setTimeout(() => this.updateCompositionElements(true), 0); } } }; $t = M([S(2, F), S(3, H), S(4, ge), S(5, ce)], $t); var ue = 0; var he = 0; var de = 0; var J = 0; var ps = { css: "#00000000", rgba: 0 }; var j; ((i) => { function s15(r, n, o2, l) { return l !== void 0 ? `#${vt(r)}${vt(n)}${vt(o2)}${vt(l)}` : `#${vt(r)}${vt(n)}${vt(o2)}`; } i.toCss = s15; function t(r, n, o2, l = 255) { return (r << 24 | n << 16 | o2 << 8 | l) >>> 0; } i.toRgba = t; function e(r, n, o2, l) { return { css: i.toCss(r, n, o2, l), rgba: i.toRgba(r, n, o2, l) }; } i.toColor = e; })(j || (j = {})); var U; ((l) => { function s15(a, u) { if (J = (u.rgba & 255) / 255, J === 1) return { css: u.css, rgba: u.rgba }; let h2 = u.rgba >> 24 & 255, c = u.rgba >> 16 & 255, d = u.rgba >> 8 & 255, _2 = a.rgba >> 24 & 255, p = a.rgba >> 16 & 255, m = a.rgba >> 8 & 255; ue = _2 + Math.round((h2 - _2) * J), he = p + Math.round((c - p) * J), de = m + Math.round((d - m) * J); let f = j.toCss(ue, he, de), A = j.toRgba(ue, he, de); return { css: f, rgba: A }; } l.blend = s15; function t(a) { return (a.rgba & 255) === 255; } l.isOpaque = t; function e(a, u, h2) { let c = $r.ensureContrastRatio(a.rgba, u.rgba, h2); if (c) return j.toColor(c >> 24 & 255, c >> 16 & 255, c >> 8 & 255); } l.ensureContrastRatio = e; function i(a) { let u = (a.rgba | 255) >>> 0; return [ue, he, de] = $r.toChannels(u), { css: j.toCss(ue, he, de), rgba: u }; } l.opaque = i; function r(a, u) { return J = Math.round(u * 255), [ue, he, de] = $r.toChannels(a.rgba), { css: j.toCss(ue, he, de, J), rgba: j.toRgba(ue, he, de, J) }; } l.opacity = r; function n(a, u) { return J = a.rgba & 255, r(a, J * u / 255); } l.multiplyOpacity = n; function o2(a) { return [a.rgba >> 24 & 255, a.rgba >> 16 & 255, a.rgba >> 8 & 255]; } l.toColorRGB = o2; })(U || (U = {})); var z; ((i) => { let s15, t; try { let r = document.createElement("canvas"); r.width = 1, r.height = 1; let n = r.getContext("2d", { willReadFrequently: true }); n && (s15 = n, s15.globalCompositeOperation = "copy", t = s15.createLinearGradient(0, 0, 1, 1)); } catch (e2) { } function e(r) { if (r.match(/#[\da-f]{3,8}/i)) switch (r.length) { case 4: return ue = parseInt(r.slice(1, 2).repeat(2), 16), he = parseInt(r.slice(2, 3).repeat(2), 16), de = parseInt(r.slice(3, 4).repeat(2), 16), j.toColor(ue, he, de); case 5: return ue = parseInt(r.slice(1, 2).repeat(2), 16), he = parseInt(r.slice(2, 3).repeat(2), 16), de = parseInt(r.slice(3, 4).repeat(2), 16), J = parseInt(r.slice(4, 5).repeat(2), 16), j.toColor(ue, he, de, J); case 7: return { css: r, rgba: (parseInt(r.slice(1), 16) << 8 | 255) >>> 0 }; case 9: return { css: r, rgba: parseInt(r.slice(1), 16) >>> 0 }; } let n = r.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/); if (n) return ue = parseInt(n[1]), he = parseInt(n[2]), de = parseInt(n[3]), J = Math.round((n[5] === void 0 ? 1 : parseFloat(n[5])) * 255), j.toColor(ue, he, de, J); if (!s15 || !t) throw new Error("css.toColor: Unsupported css format"); if (s15.fillStyle = t, s15.fillStyle = r, typeof s15.fillStyle != "string") throw new Error("css.toColor: Unsupported css format"); if (s15.fillRect(0, 0, 1, 1), [ue, he, de, J] = s15.getImageData(0, 0, 1, 1).data, J !== 255) throw new Error("css.toColor: Unsupported css format"); return { rgba: j.toRgba(ue, he, de, J), css: r }; } i.toColor = e; })(z || (z = {})); var ve; ((e) => { function s15(i) { return t(i >> 16 & 255, i >> 8 & 255, i & 255); } e.relativeLuminance = s15; function t(i, r, n) { let o2 = i / 255, l = r / 255, a = n / 255, u = o2 <= 0.03928 ? o2 / 12.92 : Math.pow((o2 + 0.055) / 1.055, 2.4), h2 = l <= 0.03928 ? l / 12.92 : Math.pow((l + 0.055) / 1.055, 2.4), c = a <= 0.03928 ? a / 12.92 : Math.pow((a + 0.055) / 1.055, 2.4); return u * 0.2126 + h2 * 0.7152 + c * 0.0722; } e.relativeLuminance2 = t; })(ve || (ve = {})); var $r; ((n) => { function s15(o2, l) { if (J = (l & 255) / 255, J === 1) return l; let a = l >> 24 & 255, u = l >> 16 & 255, h2 = l >> 8 & 255, c = o2 >> 24 & 255, d = o2 >> 16 & 255, _2 = o2 >> 8 & 255; return ue = c + Math.round((a - c) * J), he = d + Math.round((u - d) * J), de = _2 + Math.round((h2 - _2) * J), j.toRgba(ue, he, de); } n.blend = s15; function t(o2, l, a) { let u = ve.relativeLuminance(o2 >> 8), h2 = ve.relativeLuminance(l >> 8); if (Xe(u, h2) < a) { if (h2 < u) { let p = e(o2, l, a), m = Xe(u, ve.relativeLuminance(p >> 8)); if (m < a) { let f = i(o2, l, a), A = Xe(u, ve.relativeLuminance(f >> 8)); return m > A ? p : f; } return p; } let d = i(o2, l, a), _2 = Xe(u, ve.relativeLuminance(d >> 8)); if (_2 < a) { let p = e(o2, l, a), m = Xe(u, ve.relativeLuminance(p >> 8)); return _2 > m ? d : p; } return d; } } n.ensureContrastRatio = t; function e(o2, l, a) { let u = o2 >> 24 & 255, h2 = o2 >> 16 & 255, c = o2 >> 8 & 255, d = l >> 24 & 255, _2 = l >> 16 & 255, p = l >> 8 & 255, m = Xe(ve.relativeLuminance2(d, _2, p), ve.relativeLuminance2(u, h2, c)); for (; m < a && (d > 0 || _2 > 0 || p > 0); ) d -= Math.max(0, Math.ceil(d * 0.1)), _2 -= Math.max(0, Math.ceil(_2 * 0.1)), p -= Math.max(0, Math.ceil(p * 0.1)), m = Xe(ve.relativeLuminance2(d, _2, p), ve.relativeLuminance2(u, h2, c)); return (d << 24 | _2 << 16 | p << 8 | 255) >>> 0; } n.reduceLuminance = e; function i(o2, l, a) { let u = o2 >> 24 & 255, h2 = o2 >> 16 & 255, c = o2 >> 8 & 255, d = l >> 24 & 255, _2 = l >> 16 & 255, p = l >> 8 & 255, m = Xe(ve.relativeLuminance2(d, _2, p), ve.relativeLuminance2(u, h2, c)); for (; m < a && (d < 255 || _2 < 255 || p < 255); ) d = Math.min(255, d + Math.ceil((255 - d) * 0.1)), _2 = Math.min(255, _2 + Math.ceil((255 - _2) * 0.1)), p = Math.min(255, p + Math.ceil((255 - p) * 0.1)), m = Xe(ve.relativeLuminance2(d, _2, p), ve.relativeLuminance2(u, h2, c)); return (d << 24 | _2 << 16 | p << 8 | 255) >>> 0; } n.increaseLuminance = i; function r(o2) { return [o2 >> 24 & 255, o2 >> 16 & 255, o2 >> 8 & 255, o2 & 255]; } n.toChannels = r; })($r || ($r = {})); function vt(s15) { let t = s15.toString(16); return t.length < 2 ? "0" + t : t; } function Xe(s15, t) { return s15 < t ? (t + 0.05) / (s15 + 0.05) : (s15 + 0.05) / (t + 0.05); } var Vr = class extends De { constructor(e, i, r) { super(); this.content = 0; this.combinedData = ""; this.fg = e.fg, this.bg = e.bg, this.combinedData = i, this._width = r; } isCombined() { return 2097152; } getWidth() { return this._width; } getChars() { return this.combinedData; } getCode() { return 2097151; } setFromCharData(e) { throw new Error("not implemented"); } getAsCharData() { return [this.fg, this.getChars(), this.getWidth(), this.getCode()]; } }; var ct = class { constructor(t) { this._bufferService = t; this._characterJoiners = []; this._nextCharacterJoinerId = 0; this._workCell = new q(); } register(t) { let e = { id: this._nextCharacterJoinerId++, handler: t }; return this._characterJoiners.push(e), e.id; } deregister(t) { for (let e = 0; e < this._characterJoiners.length; e++) if (this._characterJoiners[e].id === t) return this._characterJoiners.splice(e, 1), true; return false; } getJoinedCharacters(t) { if (this._characterJoiners.length === 0) return []; let e = this._bufferService.buffer.lines.get(t); if (!e || e.length === 0) return []; let i = [], r = e.translateToString(true), n = 0, o2 = 0, l = 0, a = e.getFg(0), u = e.getBg(0); for (let h2 = 0; h2 < e.getTrimmedLength(); h2++) if (e.loadCell(h2, this._workCell), this._workCell.getWidth() !== 0) { if (this._workCell.fg !== a || this._workCell.bg !== u) { if (h2 - n > 1) { let c = this._getJoinedRanges(r, l, o2, e, n); for (let d = 0; d < c.length; d++) i.push(c[d]); } n = h2, l = o2, a = this._workCell.fg, u = this._workCell.bg; } o2 += this._workCell.getChars().length || we.length; } if (this._bufferService.cols - n > 1) { let h2 = this._getJoinedRanges(r, l, o2, e, n); for (let c = 0; c < h2.length; c++) i.push(h2[c]); } return i; } _getJoinedRanges(t, e, i, r, n) { let o2 = t.substring(e, i), l = []; try { l = this._characterJoiners[0].handler(o2); } catch (a) { console.error(a); } for (let a = 1; a < this._characterJoiners.length; a++) try { let u = this._characterJoiners[a].handler(o2); for (let h2 = 0; h2 < u.length; h2++) ct._mergeRanges(l, u[h2]); } catch (u) { console.error(u); } return this._stringRangesToCellRanges(l, r, n), l; } _stringRangesToCellRanges(t, e, i) { let r = 0, n = false, o2 = 0, l = t[r]; if (l) { for (let a = i; a < this._bufferService.cols; a++) { let u = e.getWidth(a), h2 = e.getString(a).length || we.length; if (u !== 0) { if (!n && l[0] <= o2 && (l[0] = a, n = true), l[1] <= o2) { if (l[1] = a, l = t[++r], !l) break; l[0] <= o2 ? (l[0] = a, n = true) : n = false; } o2 += h2; } } l && (l[1] = this._bufferService.cols); } } static _mergeRanges(t, e) { let i = false; for (let r = 0; r < t.length; r++) { let n = t[r]; if (i) { if (e[1] <= n[0]) return t[r - 1][1] = e[1], t; if (e[1] <= n[1]) return t[r - 1][1] = Math.max(e[1], n[1]), t.splice(r, 1), t; t.splice(r, 1), r--; } else { if (e[1] <= n[0]) return t.splice(r, 0, e), t; if (e[1] <= n[1]) return n[0] = Math.min(e[0], n[0]), t; e[0] < n[1] && (n[0] = Math.min(e[0], n[0]), i = true); continue; } } return i ? t[t.length - 1][1] = e[1] : t.push(e), t; } }; ct = M([S(0, F)], ct); function Oa(s15) { return 57508 <= s15 && s15 <= 57558; } function Ba(s15) { return 9472 <= s15 && s15 <= 9631; } function $o(s15) { return Oa(s15) || Ba(s15); } function Vo() { return { css: { canvas: qr(), cell: qr() }, device: { canvas: qr(), cell: qr(), char: { width: 0, height: 0, left: 0, top: 0 } } }; } function qr() { return { width: 0, height: 0 }; } var Vt = class { constructor(t, e, i, r, n, o2, l) { this._document = t; this._characterJoinerService = e; this._optionsService = i; this._coreBrowserService = r; this._coreService = n; this._decorationService = o2; this._themeService = l; this._workCell = new q(); this._columnSelectMode = false; this.defaultSpacing = 0; } handleSelectionChanged(t, e, i) { this._selectionStart = t, this._selectionEnd = e, this._columnSelectMode = i; } createRow(t, e, i, r, n, o2, l, a, u, h2, c) { let d = [], _2 = this._characterJoinerService.getJoinedCharacters(e), p = this._themeService.colors, m = t.getNoBgTrimmedLength(); i && m < o2 + 1 && (m = o2 + 1); let f, A = 0, R = "", O = 0, I = 0, k = 0, P = 0, oe = false, Me = 0, Pe = false, Ke = 0, di = 0, V = [], Qe = h2 !== -1 && c !== -1; for (let y = 0; y < m; y++) { t.loadCell(y, this._workCell); let T = this._workCell.getWidth(); if (T === 0) continue; let g = false, w = y >= di, E = y, x = this._workCell; if (_2.length > 0 && y === _2[0][0] && w) { let W = _2.shift(), An = this._isCellInSelection(W[0], e); for (O = W[0] + 1; O < W[1]; O++) w && (w = An === this._isCellInSelection(O, e)); w && (w = !i || o2 < W[0] || o2 >= W[1]), w ? (g = true, x = new Vr(this._workCell, t.translateToString(true, W[0], W[1]), W[1] - W[0]), E = W[1] - 1, T = x.getWidth()) : di = W[1]; } let N = this._isCellInSelection(y, e), Z = i && y === o2, te = Qe && y >= h2 && y <= c, Oe = false; this._decorationService.forEachDecorationAtCell(y, e, void 0, (W) => { Oe = true; }); let ze = x.getChars() || we; if (ze === " " && (x.isUnderline() || x.isOverline()) && (ze = "\xA0"), Ke = T * a - u.get(ze, x.isBold(), x.isItalic()), !f) f = this._document.createElement("span"); else if (A && (N && Pe || !N && !Pe && x.bg === I) && (N && Pe && p.selectionForeground || x.fg === k) && x.extended.ext === P && te === oe && Ke === Me && !Z && !g && !Oe && w) { x.isInvisible() ? R += we : R += ze, A++; continue; } else A && (f.textContent = R), f = this._document.createElement("span"), A = 0, R = ""; if (I = x.bg, k = x.fg, P = x.extended.ext, oe = te, Me = Ke, Pe = N, g && o2 >= y && o2 <= E && (o2 = y), !this._coreService.isCursorHidden && Z && this._coreService.isCursorInitialized) { if (V.push("xterm-cursor"), this._coreBrowserService.isFocused) l && V.push("xterm-cursor-blink"), V.push(r === "bar" ? "xterm-cursor-bar" : r === "underline" ? "xterm-cursor-underline" : "xterm-cursor-block"); else if (n) switch (n) { case "outline": V.push("xterm-cursor-outline"); break; case "block": V.push("xterm-cursor-block"); break; case "bar": V.push("xterm-cursor-bar"); break; case "underline": V.push("xterm-cursor-underline"); break; default: break; } } if (x.isBold() && V.push("xterm-bold"), x.isItalic() && V.push("xterm-italic"), x.isDim() && V.push("xterm-dim"), x.isInvisible() ? R = we : R = x.getChars() || we, x.isUnderline() && (V.push(`xterm-underline-${x.extended.underlineStyle}`), R === " " && (R = "\xA0"), !x.isUnderlineColorDefault())) if (x.isUnderlineColorRGB()) f.style.textDecorationColor = `rgb(${De.toColorRGB(x.getUnderlineColor()).join(",")})`; else { let W = x.getUnderlineColor(); this._optionsService.rawOptions.drawBoldTextInBrightColors && x.isBold() && W < 8 && (W += 8), f.style.textDecorationColor = p.ansi[W].css; } x.isOverline() && (V.push("xterm-overline"), R === " " && (R = "\xA0")), x.isStrikethrough() && V.push("xterm-strikethrough"), te && (f.style.textDecoration = "underline"); let le = x.getFgColor(), et = x.getFgColorMode(), me = x.getBgColor(), ht = x.getBgColorMode(), fi = !!x.isInverse(); if (fi) { let W = le; le = me, me = W; let An = et; et = ht, ht = An; } let tt, Qi, pi = false; this._decorationService.forEachDecorationAtCell(y, e, void 0, (W) => { W.options.layer !== "top" && pi || (W.backgroundColorRGB && (ht = 50331648, me = W.backgroundColorRGB.rgba >> 8 & 16777215, tt = W.backgroundColorRGB), W.foregroundColorRGB && (et = 50331648, le = W.foregroundColorRGB.rgba >> 8 & 16777215, Qi = W.foregroundColorRGB), pi = W.options.layer === "top"); }), !pi && N && (tt = this._coreBrowserService.isFocused ? p.selectionBackgroundOpaque : p.selectionInactiveBackgroundOpaque, me = tt.rgba >> 8 & 16777215, ht = 50331648, pi = true, p.selectionForeground && (et = 50331648, le = p.selectionForeground.rgba >> 8 & 16777215, Qi = p.selectionForeground)), pi && V.push("xterm-decoration-top"); let it; switch (ht) { case 16777216: case 33554432: it = p.ansi[me], V.push(`xterm-bg-${me}`); break; case 50331648: it = j.toColor(me >> 16, me >> 8 & 255, me & 255), this._addStyle(f, `background-color:#${qo((me >>> 0).toString(16), "0", 6)}`); break; case 0: default: fi ? (it = p.foreground, V.push(`xterm-bg-${257}`)) : it = p.background; } switch (tt || x.isDim() && (tt = U.multiplyOpacity(it, 0.5)), et) { case 16777216: case 33554432: x.isBold() && le < 8 && this._optionsService.rawOptions.drawBoldTextInBrightColors && (le += 8), this._applyMinimumContrast(f, it, p.ansi[le], x, tt, void 0) || V.push(`xterm-fg-${le}`); break; case 50331648: let W = j.toColor(le >> 16 & 255, le >> 8 & 255, le & 255); this._applyMinimumContrast(f, it, W, x, tt, Qi) || this._addStyle(f, `color:#${qo(le.toString(16), "0", 6)}`); break; case 0: default: this._applyMinimumContrast(f, it, p.foreground, x, tt, Qi) || fi && V.push(`xterm-fg-${257}`); } V.length && (f.className = V.join(" "), V.length = 0), !Z && !g && !Oe && w ? A++ : f.textContent = R, Ke !== this.defaultSpacing && (f.style.letterSpacing = `${Ke}px`), d.push(f), y = E; } return f && A && (f.textContent = R), d; } _applyMinimumContrast(t, e, i, r, n, o2) { if (this._optionsService.rawOptions.minimumContrastRatio === 1 || $o(r.getCode())) return false; let l = this._getContrastCache(r), a; if (!n && !o2 && (a = l.getColor(e.rgba, i.rgba)), a === void 0) { let u = this._optionsService.rawOptions.minimumContrastRatio / (r.isDim() ? 2 : 1); a = U.ensureContrastRatio(n || e, o2 || i, u), l.setColor((n || e).rgba, (o2 || i).rgba, a != null ? a : null); } return a ? (this._addStyle(t, `color:${a.css}`), true) : false; } _getContrastCache(t) { return t.isDim() ? this._themeService.colors.halfContrastCache : this._themeService.colors.contrastCache; } _addStyle(t, e) { t.setAttribute("style", `${t.getAttribute("style") || ""}${e};`); } _isCellInSelection(t, e) { let i = this._selectionStart, r = this._selectionEnd; return !i || !r ? false : this._columnSelectMode ? i[0] <= r[0] ? t >= i[0] && e >= i[1] && t < r[0] && e <= r[1] : t < i[0] && e >= i[1] && t >= r[0] && e <= r[1] : e > i[1] && e < r[1] || i[1] === r[1] && e === i[1] && t >= i[0] && t < r[0] || i[1] < r[1] && e === r[1] && t < r[0] || i[1] < r[1] && e === i[1] && t >= i[0]; } }; Vt = M([S(1, or), S(2, H), S(3, ae), S(4, ge), S(5, Be), S(6, Re)], Vt); function qo(s15, t, e) { for (; s15.length < e; ) s15 = t + s15; return s15; } var Yr = class { constructor(t, e) { this._flat = new Float32Array(256); this._font = ""; this._fontSize = 0; this._weight = "normal"; this._weightBold = "bold"; this._measureElements = []; this._container = t.createElement("div"), this._container.classList.add("xterm-width-cache-measure-container"), this._container.setAttribute("aria-hidden", "true"), this._container.style.whiteSpace = "pre", this._container.style.fontKerning = "none"; let i = t.createElement("span"); i.classList.add("xterm-char-measure-element"); let r = t.createElement("span"); r.classList.add("xterm-char-measure-element"), r.style.fontWeight = "bold"; let n = t.createElement("span"); n.classList.add("xterm-char-measure-element"), n.style.fontStyle = "italic"; let o2 = t.createElement("span"); o2.classList.add("xterm-char-measure-element"), o2.style.fontWeight = "bold", o2.style.fontStyle = "italic", this._measureElements = [i, r, n, o2], this._container.appendChild(i), this._container.appendChild(r), this._container.appendChild(n), this._container.appendChild(o2), e.appendChild(this._container), this.clear(); } dispose() { this._container.remove(), this._measureElements.length = 0, this._holey = void 0; } clear() { this._flat.fill(-9999), this._holey = /* @__PURE__ */ new Map(); } setFont(t, e, i, r) { t === this._font && e === this._fontSize && i === this._weight && r === this._weightBold || (this._font = t, this._fontSize = e, this._weight = i, this._weightBold = r, this._container.style.fontFamily = this._font, this._container.style.fontSize = `${this._fontSize}px`, this._measureElements[0].style.fontWeight = `${i}`, this._measureElements[1].style.fontWeight = `${r}`, this._measureElements[2].style.fontWeight = `${i}`, this._measureElements[3].style.fontWeight = `${r}`, this.clear()); } get(t, e, i) { let r = 0; if (!e && !i && t.length === 1 && (r = t.charCodeAt(0)) < 256) { if (this._flat[r] !== -9999) return this._flat[r]; let l = this._measure(t, 0); return l > 0 && (this._flat[r] = l), l; } let n = t; e && (n += "B"), i && (n += "I"); let o2 = this._holey.get(n); if (o2 === void 0) { let l = 0; e && (l |= 1), i && (l |= 2), o2 = this._measure(t, l), o2 > 0 && this._holey.set(n, o2); } return o2; } _measure(t, e) { let i = this._measureElements[e]; return i.textContent = t.repeat(32), i.offsetWidth / 32; } }; var ms = class { constructor() { this.clear(); } clear() { this.hasSelection = false, this.columnSelectMode = false, this.viewportStartRow = 0, this.viewportEndRow = 0, this.viewportCappedStartRow = 0, this.viewportCappedEndRow = 0, this.startCol = 0, this.endCol = 0, this.selectionStart = void 0, this.selectionEnd = void 0; } update(t, e, i, r = false) { if (this.selectionStart = e, this.selectionEnd = i, !e || !i || e[0] === i[0] && e[1] === i[1]) { this.clear(); return; } let n = t.buffers.active.ydisp, o2 = e[1] - n, l = i[1] - n, a = Math.max(o2, 0), u = Math.min(l, t.rows - 1); if (a >= t.rows || u < 0) { this.clear(); return; } this.hasSelection = true, this.columnSelectMode = r, this.viewportStartRow = o2, this.viewportEndRow = l, this.viewportCappedStartRow = a, this.viewportCappedEndRow = u, this.startCol = e[0], this.endCol = i[0]; } isCellSelected(t, e, i) { return this.hasSelection ? (i -= t.buffer.active.viewportY, this.columnSelectMode ? this.startCol <= this.endCol ? e >= this.startCol && i >= this.viewportCappedStartRow && e < this.endCol && i <= this.viewportCappedEndRow : e < this.startCol && i >= this.viewportCappedStartRow && e >= this.endCol && i <= this.viewportCappedEndRow : i > this.viewportStartRow && i < this.viewportEndRow || this.viewportStartRow === this.viewportEndRow && i === this.viewportStartRow && e >= this.startCol && e < this.endCol || this.viewportStartRow < this.viewportEndRow && i === this.viewportEndRow && e < this.endCol || this.viewportStartRow < this.viewportEndRow && i === this.viewportStartRow && e >= this.startCol) : false; } }; function Yo() { return new ms(); } var _s = "xterm-dom-renderer-owner-"; var Le = "xterm-rows"; var jr = "xterm-fg-"; var jo = "xterm-bg-"; var ki = "xterm-focus"; var Xr = "xterm-selection"; var Na = 1; var Yt = class extends D { constructor(e, i, r, n, o2, l, a, u, h2, c, d, _2, p, m) { super(); this._terminal = e; this._document = i; this._element = r; this._screenElement = n; this._viewportElement = o2; this._helperContainer = l; this._linkifier2 = a; this._charSizeService = h2; this._optionsService = c; this._bufferService = d; this._coreService = _2; this._coreBrowserService = p; this._themeService = m; this._terminalClass = Na++; this._rowElements = []; this._selectionRenderModel = Yo(); this.onRequestRedraw = this._register(new v()).event; this._rowContainer = this._document.createElement("div"), this._rowContainer.classList.add(Le), this._rowContainer.style.lineHeight = "normal", this._rowContainer.setAttribute("aria-hidden", "true"), this._refreshRowElements(this._bufferService.cols, this._bufferService.rows), this._selectionContainer = this._document.createElement("div"), this._selectionContainer.classList.add(Xr), this._selectionContainer.setAttribute("aria-hidden", "true"), this.dimensions = Vo(), this._updateDimensions(), this._register(this._optionsService.onOptionChange(() => this._handleOptionsChanged())), this._register(this._themeService.onChangeColors((f) => this._injectCss(f))), this._injectCss(this._themeService.colors), this._rowFactory = u.createInstance(Vt, document), this._element.classList.add(_s + this._terminalClass), this._screenElement.appendChild(this._rowContainer), this._screenElement.appendChild(this._selectionContainer), this._register(this._linkifier2.onShowLinkUnderline((f) => this._handleLinkHover(f))), this._register(this._linkifier2.onHideLinkUnderline((f) => this._handleLinkLeave(f))), this._register(C(() => { this._element.classList.remove(_s + this._terminalClass), this._rowContainer.remove(), this._selectionContainer.remove(), this._widthCache.dispose(), this._themeStyleElement.remove(), this._dimensionsStyleElement.remove(); })), this._widthCache = new Yr(this._document, this._helperContainer), this._widthCache.setFont(this._optionsService.rawOptions.fontFamily, this._optionsService.rawOptions.fontSize, this._optionsService.rawOptions.fontWeight, this._optionsService.rawOptions.fontWeightBold), this._setDefaultSpacing(); } _updateDimensions() { let e = this._coreBrowserService.dpr; this.dimensions.device.char.width = this._charSizeService.width * e, this.dimensions.device.char.height = Math.ceil(this._charSizeService.height * e), this.dimensions.device.cell.width = this.dimensions.device.char.width + Math.round(this._optionsService.rawOptions.letterSpacing), this.dimensions.device.cell.height = Math.floor(this.dimensions.device.char.height * this._optionsService.rawOptions.lineHeight), this.dimensions.device.char.left = 0, this.dimensions.device.char.top = 0, this.dimensions.device.canvas.width = this.dimensions.device.cell.width * this._bufferService.cols, this.dimensions.device.canvas.height = this.dimensions.device.cell.height * this._bufferService.rows, this.dimensions.css.canvas.width = Math.round(this.dimensions.device.canvas.width / e), this.dimensions.css.canvas.height = Math.round(this.dimensions.device.canvas.height / e), this.dimensions.css.cell.width = this.dimensions.css.canvas.width / this._bufferService.cols, this.dimensions.css.cell.height = this.dimensions.css.canvas.height / this._bufferService.rows; for (let r of this._rowElements) r.style.width = `${this.dimensions.css.canvas.width}px`, r.style.height = `${this.dimensions.css.cell.height}px`, r.style.lineHeight = `${this.dimensions.css.cell.height}px`, r.style.overflow = "hidden"; this._dimensionsStyleElement || (this._dimensionsStyleElement = this._document.createElement("style"), this._screenElement.appendChild(this._dimensionsStyleElement)); let i = `${this._terminalSelector} .${Le} span { display: inline-block; height: 100%; vertical-align: top;}`; this._dimensionsStyleElement.textContent = i, this._selectionContainer.style.height = this._viewportElement.style.height, this._screenElement.style.width = `${this.dimensions.css.canvas.width}px`, this._screenElement.style.height = `${this.dimensions.css.canvas.height}px`; } _injectCss(e) { this._themeStyleElement || (this._themeStyleElement = this._document.createElement("style"), this._screenElement.appendChild(this._themeStyleElement)); let i = `${this._terminalSelector} .${Le} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`; i += `${this._terminalSelector} .${Le} .xterm-dim { color: ${U.multiplyOpacity(e.foreground, 0.5).css};}`, i += `${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`; let r = `blink_underline_${this._terminalClass}`, n = `blink_bar_${this._terminalClass}`, o2 = `blink_block_${this._terminalClass}`; i += `@keyframes ${r} { 50% { border-bottom-style: hidden; }}`, i += `@keyframes ${n} { 50% { box-shadow: none; }}`, i += `@keyframes ${o2} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`, i += `${this._terminalSelector} .${Le}.${ki} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${Le}.${ki} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${Le}.${ki} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${o2} 1s step-end infinite;}${this._terminalSelector} .${Le} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${Le} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${Le} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${Le} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${Le} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`, i += `${this._terminalSelector} .${Xr} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Xr} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Xr} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`; for (let [l, a] of e.ansi.entries()) i += `${this._terminalSelector} .${jr}${l} { color: ${a.css}; }${this._terminalSelector} .${jr}${l}.xterm-dim { color: ${U.multiplyOpacity(a, 0.5).css}; }${this._terminalSelector} .${jo}${l} { background-color: ${a.css}; }`; i += `${this._terminalSelector} .${jr}${257} { color: ${U.opaque(e.background).css}; }${this._terminalSelector} .${jr}${257}.xterm-dim { color: ${U.multiplyOpacity(U.opaque(e.background), 0.5).css}; }${this._terminalSelector} .${jo}${257} { background-color: ${e.foreground.css}; }`, this._themeStyleElement.textContent = i; } _setDefaultSpacing() { let e = this.dimensions.css.cell.width - this._widthCache.get("W", false, false); this._rowContainer.style.letterSpacing = `${e}px`, this._rowFactory.defaultSpacing = e; } handleDevicePixelRatioChange() { this._updateDimensions(), this._widthCache.clear(), this._setDefaultSpacing(); } _refreshRowElements(e, i) { for (let r = this._rowElements.length; r <= i; r++) { let n = this._document.createElement("div"); this._rowContainer.appendChild(n), this._rowElements.push(n); } for (; this._rowElements.length > i; ) this._rowContainer.removeChild(this._rowElements.pop()); } handleResize(e, i) { this._refreshRowElements(e, i), this._updateDimensions(), this.handleSelectionChanged(this._selectionRenderModel.selectionStart, this._selectionRenderModel.selectionEnd, this._selectionRenderModel.columnSelectMode); } handleCharSizeChanged() { this._updateDimensions(), this._widthCache.clear(), this._setDefaultSpacing(); } handleBlur() { this._rowContainer.classList.remove(ki), this.renderRows(0, this._bufferService.rows - 1); } handleFocus() { this._rowContainer.classList.add(ki), this.renderRows(this._bufferService.buffer.y, this._bufferService.buffer.y); } handleSelectionChanged(e, i, r) { if (this._selectionContainer.replaceChildren(), this._rowFactory.handleSelectionChanged(e, i, r), this.renderRows(0, this._bufferService.rows - 1), !e || !i || (this._selectionRenderModel.update(this._terminal, e, i, r), !this._selectionRenderModel.hasSelection)) return; let n = this._selectionRenderModel.viewportStartRow, o2 = this._selectionRenderModel.viewportEndRow, l = this._selectionRenderModel.viewportCappedStartRow, a = this._selectionRenderModel.viewportCappedEndRow, u = this._document.createDocumentFragment(); if (r) { let h2 = e[0] > i[0]; u.appendChild(this._createSelectionElement(l, h2 ? i[0] : e[0], h2 ? e[0] : i[0], a - l + 1)); } else { let h2 = n === l ? e[0] : 0, c = l === o2 ? i[0] : this._bufferService.cols; u.appendChild(this._createSelectionElement(l, h2, c)); let d = a - l - 1; if (u.appendChild(this._createSelectionElement(l + 1, 0, this._bufferService.cols, d)), l !== a) { let _2 = o2 === a ? i[0] : this._bufferService.cols; u.appendChild(this._createSelectionElement(a, 0, _2)); } } this._selectionContainer.appendChild(u); } _createSelectionElement(e, i, r, n = 1) { let o2 = this._document.createElement("div"), l = i * this.dimensions.css.cell.width, a = this.dimensions.css.cell.width * (r - i); return l + a > this.dimensions.css.canvas.width && (a = this.dimensions.css.canvas.width - l), o2.style.height = `${n * this.dimensions.css.cell.height}px`, o2.style.top = `${e * this.dimensions.css.cell.height}px`, o2.style.left = `${l}px`, o2.style.width = `${a}px`, o2; } handleCursorMove() { } _handleOptionsChanged() { this._updateDimensions(), this._injectCss(this._themeService.colors), this._widthCache.setFont(this._optionsService.rawOptions.fontFamily, this._optionsService.rawOptions.fontSize, this._optionsService.rawOptions.fontWeight, this._optionsService.rawOptions.fontWeightBold), this._setDefaultSpacing(); } clear() { for (let e of this._rowElements) e.replaceChildren(); } renderRows(e, i) { var _a5, _b; let r = this._bufferService.buffer, n = r.ybase + r.y, o2 = Math.min(r.x, this._bufferService.cols - 1), l = (_a5 = this._coreService.decPrivateModes.cursorBlink) != null ? _a5 : this._optionsService.rawOptions.cursorBlink, a = (_b = this._coreService.decPrivateModes.cursorStyle) != null ? _b : this._optionsService.rawOptions.cursorStyle, u = this._optionsService.rawOptions.cursorInactiveStyle; for (let h2 = e; h2 <= i; h2++) { let c = h2 + r.ydisp, d = this._rowElements[h2], _2 = r.lines.get(c); if (!d || !_2) break; d.replaceChildren(...this._rowFactory.createRow(_2, c, c === n, a, u, o2, l, this.dimensions.css.cell.width, this._widthCache, -1, -1)); } } get _terminalSelector() { return `.${_s}${this._terminalClass}`; } _handleLinkHover(e) { this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, true); } _handleLinkLeave(e) { this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, false); } _setCellUnderline(e, i, r, n, o2, l) { r < 0 && (e = 0), n < 0 && (i = 0); let a = this._bufferService.rows - 1; r = Math.max(Math.min(r, a), 0), n = Math.max(Math.min(n, a), 0), o2 = Math.min(o2, this._bufferService.cols); let u = this._bufferService.buffer, h2 = u.ybase + u.y, c = Math.min(u.x, o2 - 1), d = this._optionsService.rawOptions.cursorBlink, _2 = this._optionsService.rawOptions.cursorStyle, p = this._optionsService.rawOptions.cursorInactiveStyle; for (let m = r; m <= n; ++m) { let f = m + u.ydisp, A = this._rowElements[m], R = u.lines.get(f); if (!A || !R) break; A.replaceChildren(...this._rowFactory.createRow(R, f, f === h2, _2, p, c, d, this.dimensions.css.cell.width, this._widthCache, l ? m === r ? e : 0 : -1, l ? (m === n ? i : o2) - 1 : -1)); } } }; Yt = M([S(7, xt), S(8, nt), S(9, H), S(10, F), S(11, ge), S(12, ae), S(13, Re)], Yt); var jt = class extends D { constructor(e, i, r) { super(); this._optionsService = r; this.width = 0; this.height = 0; this._onCharSizeChange = this._register(new v()); this.onCharSizeChange = this._onCharSizeChange.event; try { this._measureStrategy = this._register(new vs(this._optionsService)); } catch (e2) { this._measureStrategy = this._register(new bs(e, i, this._optionsService)); } this._register(this._optionsService.onMultipleOptionChange(["fontFamily", "fontSize"], () => this.measure())); } get hasValidSize() { return this.width > 0 && this.height > 0; } measure() { let e = this._measureStrategy.measure(); (e.width !== this.width || e.height !== this.height) && (this.width = e.width, this.height = e.height, this._onCharSizeChange.fire()); } }; jt = M([S(2, H)], jt); var Zr = class extends D { constructor() { super(...arguments); this._result = { width: 0, height: 0 }; } _validateAndSet(e, i) { e !== void 0 && e > 0 && i !== void 0 && i > 0 && (this._result.width = e, this._result.height = i); } }; var bs = class extends Zr { constructor(e, i, r) { super(); this._document = e; this._parentElement = i; this._optionsService = r; this._measureElement = this._document.createElement("span"), this._measureElement.classList.add("xterm-char-measure-element"), this._measureElement.textContent = "W".repeat(32), this._measureElement.setAttribute("aria-hidden", "true"), this._measureElement.style.whiteSpace = "pre", this._measureElement.style.fontKerning = "none", this._parentElement.appendChild(this._measureElement); } measure() { return this._measureElement.style.fontFamily = this._optionsService.rawOptions.fontFamily, this._measureElement.style.fontSize = `${this._optionsService.rawOptions.fontSize}px`, this._validateAndSet(Number(this._measureElement.offsetWidth) / 32, Number(this._measureElement.offsetHeight)), this._result; } }; var vs = class extends Zr { constructor(e) { super(); this._optionsService = e; this._canvas = new OffscreenCanvas(100, 100), this._ctx = this._canvas.getContext("2d"); let i = this._ctx.measureText("W"); if (!("width" in i && "fontBoundingBoxAscent" in i && "fontBoundingBoxDescent" in i)) throw new Error("Required font metrics not supported"); } measure() { this._ctx.font = `${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`; let e = this._ctx.measureText("W"); return this._validateAndSet(e.width, e.fontBoundingBoxAscent + e.fontBoundingBoxDescent), this._result; } }; var Jr = class extends D { constructor(e, i, r) { super(); this._textarea = e; this._window = i; this.mainDocument = r; this._isFocused = false; this._cachedIsFocused = void 0; this._screenDprMonitor = this._register(new gs(this._window)); this._onDprChange = this._register(new v()); this.onDprChange = this._onDprChange.event; this._onWindowChange = this._register(new v()); this.onWindowChange = this._onWindowChange.event; this._register(this.onWindowChange((n) => this._screenDprMonitor.setWindow(n))), this._register($.forward(this._screenDprMonitor.onDprChange, this._onDprChange)), this._register(L(this._textarea, "focus", () => this._isFocused = true)), this._register(L(this._textarea, "blur", () => this._isFocused = false)); } get window() { return this._window; } set window(e) { this._window !== e && (this._window = e, this._onWindowChange.fire(this._window)); } get dpr() { return this.window.devicePixelRatio; } get isFocused() { return this._cachedIsFocused === void 0 && (this._cachedIsFocused = this._isFocused && this._textarea.ownerDocument.hasFocus(), queueMicrotask(() => this._cachedIsFocused = void 0)), this._cachedIsFocused; } }; var gs = class extends D { constructor(e) { super(); this._parentWindow = e; this._windowResizeListener = this._register(new ye()); this._onDprChange = this._register(new v()); this.onDprChange = this._onDprChange.event; this._outerListener = () => this._setDprAndFireIfDiffers(), this._currentDevicePixelRatio = this._parentWindow.devicePixelRatio, this._updateDpr(), this._setWindowResizeListener(), this._register(C(() => this.clearListener())); } setWindow(e) { this._parentWindow = e, this._setWindowResizeListener(), this._setDprAndFireIfDiffers(); } _setWindowResizeListener() { this._windowResizeListener.value = L(this._parentWindow, "resize", () => this._setDprAndFireIfDiffers()); } _setDprAndFireIfDiffers() { this._parentWindow.devicePixelRatio !== this._currentDevicePixelRatio && this._onDprChange.fire(this._parentWindow.devicePixelRatio), this._updateDpr(); } _updateDpr() { var _a5; this._outerListener && ((_a5 = this._resolutionMediaMatchList) == null ? void 0 : _a5.removeListener(this._outerListener), this._currentDevicePixelRatio = this._parentWindow.devicePixelRatio, this._resolutionMediaMatchList = this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`), this._resolutionMediaMatchList.addListener(this._outerListener)); } clearListener() { !this._resolutionMediaMatchList || !this._outerListener || (this._resolutionMediaMatchList.removeListener(this._outerListener), this._resolutionMediaMatchList = void 0, this._outerListener = void 0); } }; var Qr = class extends D { constructor() { super(); this.linkProviders = []; this._register(C(() => this.linkProviders.length = 0)); } registerLinkProvider(e) { return this.linkProviders.push(e), { dispose: () => { let i = this.linkProviders.indexOf(e); i !== -1 && this.linkProviders.splice(i, 1); } }; } }; function Ci(s15, t, e) { let i = e.getBoundingClientRect(), r = s15.getComputedStyle(e), n = parseInt(r.getPropertyValue("padding-left")), o2 = parseInt(r.getPropertyValue("padding-top")); return [t.clientX - i.left - n, t.clientY - i.top - o2]; } function Xo(s15, t, e, i, r, n, o2, l, a) { if (!n) return; let u = Ci(s15, t, e); if (u) return u[0] = Math.ceil((u[0] + (a ? o2 / 2 : 0)) / o2), u[1] = Math.ceil(u[1] / l), u[0] = Math.min(Math.max(u[0], 1), i + (a ? 1 : 0)), u[1] = Math.min(Math.max(u[1], 1), r), u; } var Xt = class { constructor(t, e) { this._renderService = t; this._charSizeService = e; } getCoords(t, e, i, r, n) { return Xo(window, t, e, i, r, this._charSizeService.hasValidSize, this._renderService.dimensions.css.cell.width, this._renderService.dimensions.css.cell.height, n); } getMouseReportCoords(t, e) { let i = Ci(window, t, e); if (this._charSizeService.hasValidSize) return i[0] = Math.min(Math.max(i[0], 0), this._renderService.dimensions.css.canvas.width - 1), i[1] = Math.min(Math.max(i[1], 0), this._renderService.dimensions.css.canvas.height - 1), { col: Math.floor(i[0] / this._renderService.dimensions.css.cell.width), row: Math.floor(i[1] / this._renderService.dimensions.css.cell.height), x: Math.floor(i[0]), y: Math.floor(i[1]) }; } }; Xt = M([S(0, ce), S(1, nt)], Xt); var en = class { constructor(t, e) { this._renderCallback = t; this._coreBrowserService = e; this._refreshCallbacks = []; } dispose() { this._animationFrame && (this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame), this._animationFrame = void 0); } addRefreshCallback(t) { return this._refreshCallbacks.push(t), this._animationFrame || (this._animationFrame = this._coreBrowserService.window.requestAnimationFrame(() => this._innerRefresh())), this._animationFrame; } refresh(t, e, i) { this._rowCount = i, t = t !== void 0 ? t : 0, e = e !== void 0 ? e : this._rowCount - 1, this._rowStart = this._rowStart !== void 0 ? Math.min(this._rowStart, t) : t, this._rowEnd = this._rowEnd !== void 0 ? Math.max(this._rowEnd, e) : e, !this._animationFrame && (this._animationFrame = this._coreBrowserService.window.requestAnimationFrame(() => this._innerRefresh())); } _innerRefresh() { if (this._animationFrame = void 0, this._rowStart === void 0 || this._rowEnd === void 0 || this._rowCount === void 0) { this._runRefreshCallbacks(); return; } let t = Math.max(this._rowStart, 0), e = Math.min(this._rowEnd, this._rowCount - 1); this._rowStart = void 0, this._rowEnd = void 0, this._renderCallback(t, e), this._runRefreshCallbacks(); } _runRefreshCallbacks() { for (let t of this._refreshCallbacks) t(0); this._refreshCallbacks = []; } }; var tn = {}; Ll(tn, { getSafariVersion: () => Ha, isChromeOS: () => Ts, isFirefox: () => Ss, isIpad: () => Wa, isIphone: () => Ua, isLegacyEdge: () => Fa, isLinux: () => Bi, isMac: () => Zt, isNode: () => Mi, isSafari: () => Zo, isWindows: () => Es }); var Mi = typeof process < "u" && "title" in process; var Pi = Mi ? "node" : navigator.userAgent; var Oi = Mi ? "node" : navigator.platform; var Ss = Pi.includes("Firefox"); var Fa = Pi.includes("Edge"); var Zo = /^((?!chrome|android).)*safari/i.test(Pi); function Ha() { if (!Zo) return 0; let s15 = Pi.match(/Version\/(\d+)/); return s15 === null || s15.length < 2 ? 0 : parseInt(s15[1]); } var Zt = ["Macintosh", "MacIntel", "MacPPC", "Mac68K"].includes(Oi); var Wa = Oi === "iPad"; var Ua = Oi === "iPhone"; var Es = ["Windows", "Win16", "Win32", "WinCE"].includes(Oi); var Bi = Oi.indexOf("Linux") >= 0; var Ts = /\bCrOS\b/.test(Pi); var rn = class { constructor() { this._tasks = []; this._i = 0; } enqueue(t) { this._tasks.push(t), this._start(); } flush() { for (; this._i < this._tasks.length; ) this._tasks[this._i]() || this._i++; this.clear(); } clear() { this._idleCallback && (this._cancelCallback(this._idleCallback), this._idleCallback = void 0), this._i = 0, this._tasks.length = 0; } _start() { this._idleCallback || (this._idleCallback = this._requestCallback(this._process.bind(this))); } _process(t) { this._idleCallback = void 0; let e = 0, i = 0, r = t.timeRemaining(), n = 0; for (; this._i < this._tasks.length; ) { if (e = performance.now(), this._tasks[this._i]() || this._i++, e = Math.max(1, performance.now() - e), i = Math.max(e, i), n = t.timeRemaining(), i * 1.5 > n) { r - e < -20 && console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r - e))}ms`), this._start(); return; } r = n; } this.clear(); } }; var Is = class extends rn { _requestCallback(t) { return setTimeout(() => t(this._createDeadline(16))); } _cancelCallback(t) { clearTimeout(t); } _createDeadline(t) { let e = performance.now() + t; return { timeRemaining: () => Math.max(0, e - performance.now()) }; } }; var ys = class extends rn { _requestCallback(t) { return requestIdleCallback(t); } _cancelCallback(t) { cancelIdleCallback(t); } }; var Jt = !Mi && "requestIdleCallback" in window ? ys : Is; var nn = class { constructor() { this._queue = new Jt(); } set(t) { this._queue.clear(), this._queue.enqueue(t); } flush() { this._queue.flush(); } }; var Qt = class extends D { constructor(e, i, r, n, o2, l, a, u, h2) { super(); this._rowCount = e; this._optionsService = r; this._charSizeService = n; this._coreService = o2; this._coreBrowserService = u; this._renderer = this._register(new ye()); this._pausedResizeTask = new nn(); this._observerDisposable = this._register(new ye()); this._isPaused = false; this._needsFullRefresh = false; this._isNextRenderRedrawOnly = true; this._needsSelectionRefresh = false; this._canvasWidth = 0; this._canvasHeight = 0; this._selectionState = { start: void 0, end: void 0, columnSelectMode: false }; this._onDimensionsChange = this._register(new v()); this.onDimensionsChange = this._onDimensionsChange.event; this._onRenderedViewportChange = this._register(new v()); this.onRenderedViewportChange = this._onRenderedViewportChange.event; this._onRender = this._register(new v()); this.onRender = this._onRender.event; this._onRefreshRequest = this._register(new v()); this.onRefreshRequest = this._onRefreshRequest.event; this._renderDebouncer = new en((c, d) => this._renderRows(c, d), this._coreBrowserService), this._register(this._renderDebouncer), this._syncOutputHandler = new xs(this._coreBrowserService, this._coreService, () => this._fullRefresh()), this._register(C(() => this._syncOutputHandler.dispose())), this._register(this._coreBrowserService.onDprChange(() => this.handleDevicePixelRatioChange())), this._register(a.onResize(() => this._fullRefresh())), this._register(a.buffers.onBufferActivate(() => { var _a5; return (_a5 = this._renderer.value) == null ? void 0 : _a5.clear(); })), this._register(this._optionsService.onOptionChange(() => this._handleOptionsChanged())), this._register(this._charSizeService.onCharSizeChange(() => this.handleCharSizeChanged())), this._register(l.onDecorationRegistered(() => this._fullRefresh())), this._register(l.onDecorationRemoved(() => this._fullRefresh())), this._register(this._optionsService.onMultipleOptionChange(["customGlyphs", "drawBoldTextInBrightColors", "letterSpacing", "lineHeight", "fontFamily", "fontSize", "fontWeight", "fontWeightBold", "minimumContrastRatio", "rescaleOverlappingGlyphs"], () => { this.clear(), this.handleResize(a.cols, a.rows), this._fullRefresh(); })), this._register(this._optionsService.onMultipleOptionChange(["cursorBlink", "cursorStyle"], () => this.refreshRows(a.buffer.y, a.buffer.y, true))), this._register(h2.onChangeColors(() => this._fullRefresh())), this._registerIntersectionObserver(this._coreBrowserService.window, i), this._register(this._coreBrowserService.onWindowChange((c) => this._registerIntersectionObserver(c, i))); } get dimensions() { return this._renderer.value.dimensions; } _registerIntersectionObserver(e, i) { if ("IntersectionObserver" in e) { let r = new e.IntersectionObserver((n) => this._handleIntersectionChange(n[n.length - 1]), { threshold: 0 }); r.observe(i), this._observerDisposable.value = C(() => r.disconnect()); } } _handleIntersectionChange(e) { this._isPaused = e.isIntersecting === void 0 ? e.intersectionRatio === 0 : !e.isIntersecting, !this._isPaused && !this._charSizeService.hasValidSize && this._charSizeService.measure(), !this._isPaused && this._needsFullRefresh && (this._pausedResizeTask.flush(), this.refreshRows(0, this._rowCount - 1), this._needsFullRefresh = false); } refreshRows(e, i, r = false) { if (this._isPaused) { this._needsFullRefresh = true; return; } if (this._coreService.decPrivateModes.synchronizedOutput) { this._syncOutputHandler.bufferRows(e, i); return; } let n = this._syncOutputHandler.flush(); n && (e = Math.min(e, n.start), i = Math.max(i, n.end)), r || (this._isNextRenderRedrawOnly = false), this._renderDebouncer.refresh(e, i, this._rowCount); } _renderRows(e, i) { if (this._renderer.value) { if (this._coreService.decPrivateModes.synchronizedOutput) { this._syncOutputHandler.bufferRows(e, i); return; } e = Math.min(e, this._rowCount - 1), i = Math.min(i, this._rowCount - 1), this._renderer.value.renderRows(e, i), this._needsSelectionRefresh && (this._renderer.value.handleSelectionChanged(this._selectionState.start, this._selectionState.end, this._selectionState.columnSelectMode), this._needsSelectionRefresh = false), this._isNextRenderRedrawOnly || this._onRenderedViewportChange.fire({ start: e, end: i }), this._onRender.fire({ start: e, end: i }), this._isNextRenderRedrawOnly = true; } } resize(e, i) { this._rowCount = i, this._fireOnCanvasResize(); } _handleOptionsChanged() { this._renderer.value && (this.refreshRows(0, this._rowCount - 1), this._fireOnCanvasResize()); } _fireOnCanvasResize() { this._renderer.value && (this._renderer.value.dimensions.css.canvas.width === this._canvasWidth && this._renderer.value.dimensions.css.canvas.height === this._canvasHeight || this._onDimensionsChange.fire(this._renderer.value.dimensions)); } hasRenderer() { return !!this._renderer.value; } setRenderer(e) { this._renderer.value = e, this._renderer.value && (this._renderer.value.onRequestRedraw((i) => this.refreshRows(i.start, i.end, true)), this._needsSelectionRefresh = true, this._fullRefresh()); } addRefreshCallback(e) { return this._renderDebouncer.addRefreshCallback(e); } _fullRefresh() { this._isPaused ? this._needsFullRefresh = true : this.refreshRows(0, this._rowCount - 1); } clearTextureAtlas() { var _a5, _b; this._renderer.value && ((_b = (_a5 = this._renderer.value).clearTextureAtlas) == null ? void 0 : _b.call(_a5), this._fullRefresh()); } handleDevicePixelRatioChange() { this._charSizeService.measure(), this._renderer.value && (this._renderer.value.handleDevicePixelRatioChange(), this.refreshRows(0, this._rowCount - 1)); } handleResize(e, i) { this._renderer.value && (this._isPaused ? this._pausedResizeTask.set(() => { var _a5; return (_a5 = this._renderer.value) == null ? void 0 : _a5.handleResize(e, i); }) : this._renderer.value.handleResize(e, i), this._fullRefresh()); } handleCharSizeChanged() { var _a5; (_a5 = this._renderer.value) == null ? void 0 : _a5.handleCharSizeChanged(); } handleBlur() { var _a5; (_a5 = this._renderer.value) == null ? void 0 : _a5.handleBlur(); } handleFocus() { var _a5; (_a5 = this._renderer.value) == null ? void 0 : _a5.handleFocus(); } handleSelectionChanged(e, i, r) { var _a5; this._selectionState.start = e, this._selectionState.end = i, this._selectionState.columnSelectMode = r, (_a5 = this._renderer.value) == null ? void 0 : _a5.handleSelectionChanged(e, i, r); } handleCursorMove() { var _a5; (_a5 = this._renderer.value) == null ? void 0 : _a5.handleCursorMove(); } clear() { var _a5; (_a5 = this._renderer.value) == null ? void 0 : _a5.clear(); } }; Qt = M([S(2, H), S(3, nt), S(4, ge), S(5, Be), S(6, F), S(7, ae), S(8, Re)], Qt); var xs = class { constructor(t, e, i) { this._coreBrowserService = t; this._coreService = e; this._onTimeout = i; this._start = 0; this._end = 0; this._isBuffering = false; } bufferRows(t, e) { this._isBuffering ? (this._start = Math.min(this._start, t), this._end = Math.max(this._end, e)) : (this._start = t, this._end = e, this._isBuffering = true), this._timeout === void 0 && (this._timeout = this._coreBrowserService.window.setTimeout(() => { this._timeout = void 0, this._coreService.decPrivateModes.synchronizedOutput = false, this._onTimeout(); }, 1e3)); } flush() { if (this._timeout !== void 0 && (this._coreBrowserService.window.clearTimeout(this._timeout), this._timeout = void 0), !this._isBuffering) return; let t = { start: this._start, end: this._end }; return this._isBuffering = false, t; } dispose() { this._timeout !== void 0 && (this._coreBrowserService.window.clearTimeout(this._timeout), this._timeout = void 0); } }; function Jo(s15, t, e, i) { let r = e.buffer.x, n = e.buffer.y; if (!e.buffer.hasScrollback) return Ga(r, n, s15, t, e, i) + sn(n, t, e, i) + $a(r, n, s15, t, e, i); let o2; if (n === t) return o2 = r > s15 ? "D" : "C", Fi(Math.abs(r - s15), Ni(o2, i)); o2 = n > t ? "D" : "C"; let l = Math.abs(n - t), a = za(n > t ? s15 : r, e) + (l - 1) * e.cols + 1 + Ka(n > t ? r : s15, e); return Fi(a, Ni(o2, i)); } function Ka(s15, t) { return s15 - 1; } function za(s15, t) { return t.cols - s15; } function Ga(s15, t, e, i, r, n) { return sn(t, i, r, n).length === 0 ? "" : Fi(el(s15, t, s15, t - gt(t, r), false, r).length, Ni("D", n)); } function sn(s15, t, e, i) { let r = s15 - gt(s15, e), n = t - gt(t, e), o2 = Math.abs(r - n) - Va(s15, t, e); return Fi(o2, Ni(Qo(s15, t), i)); } function $a(s15, t, e, i, r, n) { let o2; sn(t, i, r, n).length > 0 ? o2 = i - gt(i, r) : o2 = t; let l = i, a = qa(s15, t, e, i, r, n); return Fi(el(s15, o2, e, l, a === "C", r).length, Ni(a, n)); } function Va(s15, t, e) { var _a5; let i = 0, r = s15 - gt(s15, e), n = t - gt(t, e); for (let o2 = 0; o2 < Math.abs(r - n); o2++) { let l = Qo(s15, t) === "A" ? -1 : 1; ((_a5 = e.buffer.lines.get(r + l * o2)) == null ? void 0 : _a5.isWrapped) && i++; } return i; } function gt(s15, t) { let e = 0, i = t.buffer.lines.get(s15), r = i == null ? void 0 : i.isWrapped; for (; r && s15 >= 0 && s15 < t.rows; ) e++, i = t.buffer.lines.get(--s15), r = i == null ? void 0 : i.isWrapped; return e; } function qa(s15, t, e, i, r, n) { let o2; return sn(e, i, r, n).length > 0 ? o2 = i - gt(i, r) : o2 = t, s15 < e && o2 <= i || s15 >= e && o2 < i ? "C" : "D"; } function Qo(s15, t) { return s15 > t ? "A" : "B"; } function el(s15, t, e, i, r, n) { let o2 = s15, l = t, a = ""; for (; (o2 !== e || l !== i) && l >= 0 && l < n.buffer.lines.length; ) o2 += r ? 1 : -1, r && o2 > n.cols - 1 ? (a += n.buffer.translateBufferLineToString(l, false, s15, o2), o2 = 0, s15 = 0, l++) : !r && o2 < 0 && (a += n.buffer.translateBufferLineToString(l, false, 0, s15 + 1), o2 = n.cols - 1, s15 = o2, l--); return a + n.buffer.translateBufferLineToString(l, false, s15, o2); } function Ni(s15, t) { let e = t ? "O" : "["; return b.ESC + e + s15; } function Fi(s15, t) { s15 = Math.floor(s15); let e = ""; for (let i = 0; i < s15; i++) e += t; return e; } var on = class { constructor(t) { this._bufferService = t; this.isSelectAllActive = false; this.selectionStartLength = 0; } clearSelection() { this.selectionStart = void 0, this.selectionEnd = void 0, this.isSelectAllActive = false, this.selectionStartLength = 0; } get finalSelectionStart() { return this.isSelectAllActive ? [0, 0] : !this.selectionEnd || !this.selectionStart ? this.selectionStart : this.areSelectionValuesReversed() ? this.selectionEnd : this.selectionStart; } get finalSelectionEnd() { if (this.isSelectAllActive) return [this._bufferService.cols, this._bufferService.buffer.ybase + this._bufferService.rows - 1]; if (this.selectionStart) { if (!this.selectionEnd || this.areSelectionValuesReversed()) { let t = this.selectionStart[0] + this.selectionStartLength; return t > this._bufferService.cols ? t % this._bufferService.cols === 0 ? [this._bufferService.cols, this.selectionStart[1] + Math.floor(t / this._bufferService.cols) - 1] : [t % this._bufferService.cols, this.selectionStart[1] + Math.floor(t / this._bufferService.cols)] : [t, this.selectionStart[1]]; } if (this.selectionStartLength && this.selectionEnd[1] === this.selectionStart[1]) { let t = this.selectionStart[0] + this.selectionStartLength; return t > this._bufferService.cols ? [t % this._bufferService.cols, this.selectionStart[1] + Math.floor(t / this._bufferService.cols)] : [Math.max(t, this.selectionEnd[0]), this.selectionEnd[1]]; } return this.selectionEnd; } } areSelectionValuesReversed() { let t = this.selectionStart, e = this.selectionEnd; return !t || !e ? false : t[1] > e[1] || t[1] === e[1] && t[0] > e[0]; } handleTrim(t) { return this.selectionStart && (this.selectionStart[1] -= t), this.selectionEnd && (this.selectionEnd[1] -= t), this.selectionEnd && this.selectionEnd[1] < 0 ? (this.clearSelection(), true) : (this.selectionStart && this.selectionStart[1] < 0 && (this.selectionStart[1] = 0), false); } }; function ws(s15, t) { if (s15.start.y > s15.end.y) throw new Error(`Buffer range end (${s15.end.x}, ${s15.end.y}) cannot be before start (${s15.start.x}, ${s15.start.y})`); return t * (s15.end.y - s15.start.y) + (s15.end.x - s15.start.x + 1); } var Ds = 50; var Ya = 15; var ja = 50; var Xa = 500; var Za = "\xA0"; var Ja = new RegExp(Za, "g"); var ei = class extends D { constructor(e, i, r, n, o2, l, a, u, h2) { super(); this._element = e; this._screenElement = i; this._linkifier = r; this._bufferService = n; this._coreService = o2; this._mouseService = l; this._optionsService = a; this._renderService = u; this._coreBrowserService = h2; this._dragScrollAmount = 0; this._enabled = true; this._workCell = new q(); this._mouseDownTimeStamp = 0; this._oldHasSelection = false; this._oldSelectionStart = void 0; this._oldSelectionEnd = void 0; this._onLinuxMouseSelection = this._register(new v()); this.onLinuxMouseSelection = this._onLinuxMouseSelection.event; this._onRedrawRequest = this._register(new v()); this.onRequestRedraw = this._onRedrawRequest.event; this._onSelectionChange = this._register(new v()); this.onSelectionChange = this._onSelectionChange.event; this._onRequestScrollLines = this._register(new v()); this.onRequestScrollLines = this._onRequestScrollLines.event; this._mouseMoveListener = (c) => this._handleMouseMove(c), this._mouseUpListener = (c) => this._handleMouseUp(c), this._coreService.onUserInput(() => { this.hasSelection && this.clearSelection(); }), this._trimListener = this._bufferService.buffer.lines.onTrim((c) => this._handleTrim(c)), this._register(this._bufferService.buffers.onBufferActivate((c) => this._handleBufferActivate(c))), this.enable(), this._model = new on(this._bufferService), this._activeSelectionMode = 0, this._register(C(() => { this._removeMouseDownListeners(); })), this._register(this._bufferService.onResize((c) => { c.rowsChanged && this.clearSelection(); })); } reset() { this.clearSelection(); } disable() { this.clearSelection(), this._enabled = false; } enable() { this._enabled = true; } get selectionStart() { return this._model.finalSelectionStart; } get selectionEnd() { return this._model.finalSelectionEnd; } get hasSelection() { let e = this._model.finalSelectionStart, i = this._model.finalSelectionEnd; return !e || !i ? false : e[0] !== i[0] || e[1] !== i[1]; } get selectionText() { let e = this._model.finalSelectionStart, i = this._model.finalSelectionEnd; if (!e || !i) return ""; let r = this._bufferService.buffer, n = []; if (this._activeSelectionMode === 3) { if (e[0] === i[0]) return ""; let l = e[0] < i[0] ? e[0] : i[0], a = e[0] < i[0] ? i[0] : e[0]; for (let u = e[1]; u <= i[1]; u++) { let h2 = r.translateBufferLineToString(u, true, l, a); n.push(h2); } } else { let l = e[1] === i[1] ? i[0] : void 0; n.push(r.translateBufferLineToString(e[1], true, e[0], l)); for (let a = e[1] + 1; a <= i[1] - 1; a++) { let u = r.lines.get(a), h2 = r.translateBufferLineToString(a, true); (u == null ? void 0 : u.isWrapped) ? n[n.length - 1] += h2 : n.push(h2); } if (e[1] !== i[1]) { let a = r.lines.get(i[1]), u = r.translateBufferLineToString(i[1], true, 0, i[0]); a && a.isWrapped ? n[n.length - 1] += u : n.push(u); } } return n.map((l) => l.replace(Ja, " ")).join(Es ? `\r ` : ` `); } clearSelection() { this._model.clearSelection(), this._removeMouseDownListeners(), this.refresh(), this._onSelectionChange.fire(); } refresh(e) { this._refreshAnimationFrame || (this._refreshAnimationFrame = this._coreBrowserService.window.requestAnimationFrame(() => this._refresh())), Bi && e && this.selectionText.length && this._onLinuxMouseSelection.fire(this.selectionText); } _refresh() { this._refreshAnimationFrame = void 0, this._onRedrawRequest.fire({ start: this._model.finalSelectionStart, end: this._model.finalSelectionEnd, columnSelectMode: this._activeSelectionMode === 3 }); } _isClickInSelection(e) { let i = this._getMouseBufferCoords(e), r = this._model.finalSelectionStart, n = this._model.finalSelectionEnd; return !r || !n || !i ? false : this._areCoordsInSelection(i, r, n); } isCellInSelection(e, i) { let r = this._model.finalSelectionStart, n = this._model.finalSelectionEnd; return !r || !n ? false : this._areCoordsInSelection([e, i], r, n); } _areCoordsInSelection(e, i, r) { return e[1] > i[1] && e[1] < r[1] || i[1] === r[1] && e[1] === i[1] && e[0] >= i[0] && e[0] < r[0] || i[1] < r[1] && e[1] === r[1] && e[0] < r[0] || i[1] < r[1] && e[1] === i[1] && e[0] >= i[0]; } _selectWordAtCursor(e, i) { var _a5, _b; let r = (_b = (_a5 = this._linkifier.currentLink) == null ? void 0 : _a5.link) == null ? void 0 : _b.range; if (r) return this._model.selectionStart = [r.start.x - 1, r.start.y - 1], this._model.selectionStartLength = ws(r, this._bufferService.cols), this._model.selectionEnd = void 0, true; let n = this._getMouseBufferCoords(e); return n ? (this._selectWordAt(n, i), this._model.selectionEnd = void 0, true) : false; } selectAll() { this._model.isSelectAllActive = true, this.refresh(), this._onSelectionChange.fire(); } selectLines(e, i) { this._model.clearSelection(), e = Math.max(e, 0), i = Math.min(i, this._bufferService.buffer.lines.length - 1), this._model.selectionStart = [0, e], this._model.selectionEnd = [this._bufferService.cols, i], this.refresh(), this._onSelectionChange.fire(); } _handleTrim(e) { this._model.handleTrim(e) && this.refresh(); } _getMouseBufferCoords(e) { let i = this._mouseService.getCoords(e, this._screenElement, this._bufferService.cols, this._bufferService.rows, true); if (i) return i[0]--, i[1]--, i[1] += this._bufferService.buffer.ydisp, i; } _getMouseEventScrollAmount(e) { let i = Ci(this._coreBrowserService.window, e, this._screenElement)[1], r = this._renderService.dimensions.css.canvas.height; return i >= 0 && i <= r ? 0 : (i > r && (i -= r), i = Math.min(Math.max(i, -Ds), Ds), i /= Ds, i / Math.abs(i) + Math.round(i * (Ya - 1))); } shouldForceSelection(e) { return Zt ? e.altKey && this._optionsService.rawOptions.macOptionClickForcesSelection : e.shiftKey; } handleMouseDown(e) { if (this._mouseDownTimeStamp = e.timeStamp, !(e.button === 2 && this.hasSelection) && e.button === 0) { if (!this._enabled) { if (!this.shouldForceSelection(e)) return; e.stopPropagation(); } e.preventDefault(), this._dragScrollAmount = 0, this._enabled && e.shiftKey ? this._handleIncrementalClick(e) : e.detail === 1 ? this._handleSingleClick(e) : e.detail === 2 ? this._handleDoubleClick(e) : e.detail === 3 && this._handleTripleClick(e), this._addMouseDownListeners(), this.refresh(true); } } _addMouseDownListeners() { this._screenElement.ownerDocument && (this._screenElement.ownerDocument.addEventListener("mousemove", this._mouseMoveListener), this._screenElement.ownerDocument.addEventListener("mouseup", this._mouseUpListener)), this._dragScrollIntervalTimer = this._coreBrowserService.window.setInterval(() => this._dragScroll(), ja); } _removeMouseDownListeners() { this._screenElement.ownerDocument && (this._screenElement.ownerDocument.removeEventListener("mousemove", this._mouseMoveListener), this._screenElement.ownerDocument.removeEventListener("mouseup", this._mouseUpListener)), this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer), this._dragScrollIntervalTimer = void 0; } _handleIncrementalClick(e) { this._model.selectionStart && (this._model.selectionEnd = this._getMouseBufferCoords(e)); } _handleSingleClick(e) { if (this._model.selectionStartLength = 0, this._model.isSelectAllActive = false, this._activeSelectionMode = this.shouldColumnSelect(e) ? 3 : 0, this._model.selectionStart = this._getMouseBufferCoords(e), !this._model.selectionStart) return; this._model.selectionEnd = void 0; let i = this._bufferService.buffer.lines.get(this._model.selectionStart[1]); i && i.length !== this._model.selectionStart[0] && i.hasWidth(this._model.selectionStart[0]) === 0 && this._model.selectionStart[0]++; } _handleDoubleClick(e) { this._selectWordAtCursor(e, true) && (this._activeSelectionMode = 1); } _handleTripleClick(e) { let i = this._getMouseBufferCoords(e); i && (this._activeSelectionMode = 2, this._selectLineAt(i[1])); } shouldColumnSelect(e) { return e.altKey && !(Zt && this._optionsService.rawOptions.macOptionClickForcesSelection); } _handleMouseMove(e) { if (e.stopImmediatePropagation(), !this._model.selectionStart) return; let i = this._model.selectionEnd ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] : null; if (this._model.selectionEnd = this._getMouseBufferCoords(e), !this._model.selectionEnd) { this.refresh(true); return; } this._activeSelectionMode === 2 ? this._model.selectionEnd[1] < this._model.selectionStart[1] ? this._model.selectionEnd[0] = 0 : this._model.selectionEnd[0] = this._bufferService.cols : this._activeSelectionMode === 1 && this._selectToWordAt(this._model.selectionEnd), this._dragScrollAmount = this._getMouseEventScrollAmount(e), this._activeSelectionMode !== 3 && (this._dragScrollAmount > 0 ? this._model.selectionEnd[0] = this._bufferService.cols : this._dragScrollAmount < 0 && (this._model.selectionEnd[0] = 0)); let r = this._bufferService.buffer; if (this._model.selectionEnd[1] < r.lines.length) { let n = r.lines.get(this._model.selectionEnd[1]); n && n.hasWidth(this._model.selectionEnd[0]) === 0 && this._model.selectionEnd[0] < this._bufferService.cols && this._model.selectionEnd[0]++; } (!i || i[0] !== this._model.selectionEnd[0] || i[1] !== this._model.selectionEnd[1]) && this.refresh(true); } _dragScroll() { if (!(!this._model.selectionEnd || !this._model.selectionStart) && this._dragScrollAmount) { this._onRequestScrollLines.fire({ amount: this._dragScrollAmount, suppressScrollEvent: false }); let e = this._bufferService.buffer; this._dragScrollAmount > 0 ? (this._activeSelectionMode !== 3 && (this._model.selectionEnd[0] = this._bufferService.cols), this._model.selectionEnd[1] = Math.min(e.ydisp + this._bufferService.rows, e.lines.length - 1)) : (this._activeSelectionMode !== 3 && (this._model.selectionEnd[0] = 0), this._model.selectionEnd[1] = e.ydisp), this.refresh(); } } _handleMouseUp(e) { let i = e.timeStamp - this._mouseDownTimeStamp; if (this._removeMouseDownListeners(), this.selectionText.length <= 1 && i < Xa && e.altKey && this._optionsService.rawOptions.altClickMovesCursor) { if (this._bufferService.buffer.ybase === this._bufferService.buffer.ydisp) { let r = this._mouseService.getCoords(e, this._element, this._bufferService.cols, this._bufferService.rows, false); if (r && r[0] !== void 0 && r[1] !== void 0) { let n = Jo(r[0] - 1, r[1] - 1, this._bufferService, this._coreService.decPrivateModes.applicationCursorKeys); this._coreService.triggerDataEvent(n, true); } } } else this._fireEventIfSelectionChanged(); } _fireEventIfSelectionChanged() { let e = this._model.finalSelectionStart, i = this._model.finalSelectionEnd, r = !!e && !!i && (e[0] !== i[0] || e[1] !== i[1]); if (!r) { this._oldHasSelection && this._fireOnSelectionChange(e, i, r); return; } !e || !i || (!this._oldSelectionStart || !this._oldSelectionEnd || e[0] !== this._oldSelectionStart[0] || e[1] !== this._oldSelectionStart[1] || i[0] !== this._oldSelectionEnd[0] || i[1] !== this._oldSelectionEnd[1]) && this._fireOnSelectionChange(e, i, r); } _fireOnSelectionChange(e, i, r) { this._oldSelectionStart = e, this._oldSelectionEnd = i, this._oldHasSelection = r, this._onSelectionChange.fire(); } _handleBufferActivate(e) { this.clearSelection(), this._trimListener.dispose(), this._trimListener = e.activeBuffer.lines.onTrim((i) => this._handleTrim(i)); } _convertViewportColToCharacterIndex(e, i) { let r = i; for (let n = 0; i >= n; n++) { let o2 = e.loadCell(n, this._workCell).getChars().length; this._workCell.getWidth() === 0 ? r-- : o2 > 1 && i !== n && (r += o2 - 1); } return r; } setSelection(e, i, r) { this._model.clearSelection(), this._removeMouseDownListeners(), this._model.selectionStart = [e, i], this._model.selectionStartLength = r, this.refresh(), this._fireEventIfSelectionChanged(); } rightClickSelect(e) { this._isClickInSelection(e) || (this._selectWordAtCursor(e, false) && this.refresh(true), this._fireEventIfSelectionChanged()); } _getWordAt(e, i, r = true, n = true) { if (e[0] >= this._bufferService.cols) return; let o2 = this._bufferService.buffer, l = o2.lines.get(e[1]); if (!l) return; let a = o2.translateBufferLineToString(e[1], false), u = this._convertViewportColToCharacterIndex(l, e[0]), h2 = u, c = e[0] - u, d = 0, _2 = 0, p = 0, m = 0; if (a.charAt(u) === " ") { for (; u > 0 && a.charAt(u - 1) === " "; ) u--; for (; h2 < a.length && a.charAt(h2 + 1) === " "; ) h2++; } else { let R = e[0], O = e[0]; l.getWidth(R) === 0 && (d++, R--), l.getWidth(O) === 2 && (_2++, O++); let I = l.getString(O).length; for (I > 1 && (m += I - 1, h2 += I - 1); R > 0 && u > 0 && !this._isCharWordSeparator(l.loadCell(R - 1, this._workCell)); ) { l.loadCell(R - 1, this._workCell); let k = this._workCell.getChars().length; this._workCell.getWidth() === 0 ? (d++, R--) : k > 1 && (p += k - 1, u -= k - 1), u--, R--; } for (; O < l.length && h2 + 1 < a.length && !this._isCharWordSeparator(l.loadCell(O + 1, this._workCell)); ) { l.loadCell(O + 1, this._workCell); let k = this._workCell.getChars().length; this._workCell.getWidth() === 2 ? (_2++, O++) : k > 1 && (m += k - 1, h2 += k - 1), h2++, O++; } } h2++; let f = u + c - d + p, A = Math.min(this._bufferService.cols, h2 - u + d + _2 - p - m); if (!(!i && a.slice(u, h2).trim() === "")) { if (r && f === 0 && l.getCodePoint(0) !== 32) { let R = o2.lines.get(e[1] - 1); if (R && l.isWrapped && R.getCodePoint(this._bufferService.cols - 1) !== 32) { let O = this._getWordAt([this._bufferService.cols - 1, e[1] - 1], false, true, false); if (O) { let I = this._bufferService.cols - O.start; f -= I, A += I; } } } if (n && f + A === this._bufferService.cols && l.getCodePoint(this._bufferService.cols - 1) !== 32) { let R = o2.lines.get(e[1] + 1); if ((R == null ? void 0 : R.isWrapped) && R.getCodePoint(0) !== 32) { let O = this._getWordAt([0, e[1] + 1], false, false, true); O && (A += O.length); } } return { start: f, length: A }; } } _selectWordAt(e, i) { let r = this._getWordAt(e, i); if (r) { for (; r.start < 0; ) r.start += this._bufferService.cols, e[1]--; this._model.selectionStart = [r.start, e[1]], this._model.selectionStartLength = r.length; } } _selectToWordAt(e) { let i = this._getWordAt(e, true); if (i) { let r = e[1]; for (; i.start < 0; ) i.start += this._bufferService.cols, r--; if (!this._model.areSelectionValuesReversed()) for (; i.start + i.length > this._bufferService.cols; ) i.length -= this._bufferService.cols, r++; this._model.selectionEnd = [this._model.areSelectionValuesReversed() ? i.start : i.start + i.length, r]; } } _isCharWordSeparator(e) { return e.getWidth() === 0 ? false : this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars()) >= 0; } _selectLineAt(e) { let i = this._bufferService.buffer.getWrappedRangeForLine(e), r = { start: { x: 0, y: i.first }, end: { x: this._bufferService.cols - 1, y: i.last } }; this._model.selectionStart = [0, i.first], this._model.selectionEnd = void 0, this._model.selectionStartLength = ws(r, this._bufferService.cols); } }; ei = M([S(3, F), S(4, ge), S(5, Dt), S(6, H), S(7, ce), S(8, ae)], ei); var Hi = class { constructor() { this._data = {}; } set(t, e, i) { this._data[t] || (this._data[t] = {}), this._data[t][e] = i; } get(t, e) { return this._data[t] ? this._data[t][e] : void 0; } clear() { this._data = {}; } }; var Wi = class { constructor() { this._color = new Hi(); this._css = new Hi(); } setCss(t, e, i) { this._css.set(t, e, i); } getCss(t, e) { return this._css.get(t, e); } setColor(t, e, i) { this._color.set(t, e, i); } getColor(t, e) { return this._color.get(t, e); } clear() { this._color.clear(), this._css.clear(); } }; var re = Object.freeze((() => { let s15 = [z.toColor("#2e3436"), z.toColor("#cc0000"), z.toColor("#4e9a06"), z.toColor("#c4a000"), z.toColor("#3465a4"), z.toColor("#75507b"), z.toColor("#06989a"), z.toColor("#d3d7cf"), z.toColor("#555753"), z.toColor("#ef2929"), z.toColor("#8ae234"), z.toColor("#fce94f"), z.toColor("#729fcf"), z.toColor("#ad7fa8"), z.toColor("#34e2e2"), z.toColor("#eeeeec")], t = [0, 95, 135, 175, 215, 255]; for (let e = 0; e < 216; e++) { let i = t[e / 36 % 6 | 0], r = t[e / 6 % 6 | 0], n = t[e % 6]; s15.push({ css: j.toCss(i, r, n), rgba: j.toRgba(i, r, n) }); } for (let e = 0; e < 24; e++) { let i = 8 + e * 10; s15.push({ css: j.toCss(i, i, i), rgba: j.toRgba(i, i, i) }); } return s15; })()); var St = z.toColor("#ffffff"); var Ki = z.toColor("#000000"); var tl = z.toColor("#ffffff"); var il = Ki; var Ui = { css: "rgba(255, 255, 255, 0.3)", rgba: 4294967117 }; var Qa = St; var ti = class extends D { constructor(e) { super(); this._optionsService = e; this._contrastCache = new Wi(); this._halfContrastCache = new Wi(); this._onChangeColors = this._register(new v()); this.onChangeColors = this._onChangeColors.event; this._colors = { foreground: St, background: Ki, cursor: tl, cursorAccent: il, selectionForeground: void 0, selectionBackgroundTransparent: Ui, selectionBackgroundOpaque: U.blend(Ki, Ui), selectionInactiveBackgroundTransparent: Ui, selectionInactiveBackgroundOpaque: U.blend(Ki, Ui), scrollbarSliderBackground: U.opacity(St, 0.2), scrollbarSliderHoverBackground: U.opacity(St, 0.4), scrollbarSliderActiveBackground: U.opacity(St, 0.5), overviewRulerBorder: St, ansi: re.slice(), contrastCache: this._contrastCache, halfContrastCache: this._halfContrastCache }, this._updateRestoreColors(), this._setTheme(this._optionsService.rawOptions.theme), this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio", () => this._contrastCache.clear())), this._register(this._optionsService.onSpecificOptionChange("theme", () => this._setTheme(this._optionsService.rawOptions.theme))); } get colors() { return this._colors; } _setTheme(e = {}) { let i = this._colors; if (i.foreground = K(e.foreground, St), i.background = K(e.background, Ki), i.cursor = U.blend(i.background, K(e.cursor, tl)), i.cursorAccent = U.blend(i.background, K(e.cursorAccent, il)), i.selectionBackgroundTransparent = K(e.selectionBackground, Ui), i.selectionBackgroundOpaque = U.blend(i.background, i.selectionBackgroundTransparent), i.selectionInactiveBackgroundTransparent = K(e.selectionInactiveBackground, i.selectionBackgroundTransparent), i.selectionInactiveBackgroundOpaque = U.blend(i.background, i.selectionInactiveBackgroundTransparent), i.selectionForeground = e.selectionForeground ? K(e.selectionForeground, ps) : void 0, i.selectionForeground === ps && (i.selectionForeground = void 0), U.isOpaque(i.selectionBackgroundTransparent) && (i.selectionBackgroundTransparent = U.opacity(i.selectionBackgroundTransparent, 0.3)), U.isOpaque(i.selectionInactiveBackgroundTransparent) && (i.selectionInactiveBackgroundTransparent = U.opacity(i.selectionInactiveBackgroundTransparent, 0.3)), i.scrollbarSliderBackground = K(e.scrollbarSliderBackground, U.opacity(i.foreground, 0.2)), i.scrollbarSliderHoverBackground = K(e.scrollbarSliderHoverBackground, U.opacity(i.foreground, 0.4)), i.scrollbarSliderActiveBackground = K(e.scrollbarSliderActiveBackground, U.opacity(i.foreground, 0.5)), i.overviewRulerBorder = K(e.overviewRulerBorder, Qa), i.ansi = re.slice(), i.ansi[0] = K(e.black, re[0]), i.ansi[1] = K(e.red, re[1]), i.ansi[2] = K(e.green, re[2]), i.ansi[3] = K(e.yellow, re[3]), i.ansi[4] = K(e.blue, re[4]), i.ansi[5] = K(e.magenta, re[5]), i.ansi[6] = K(e.cyan, re[6]), i.ansi[7] = K(e.white, re[7]), i.ansi[8] = K(e.brightBlack, re[8]), i.ansi[9] = K(e.brightRed, re[9]), i.ansi[10] = K(e.brightGreen, re[10]), i.ansi[11] = K(e.brightYellow, re[11]), i.ansi[12] = K(e.brightBlue, re[12]), i.ansi[13] = K(e.brightMagenta, re[13]), i.ansi[14] = K(e.brightCyan, re[14]), i.ansi[15] = K(e.brightWhite, re[15]), e.extendedAnsi) { let r = Math.min(i.ansi.length - 16, e.extendedAnsi.length); for (let n = 0; n < r; n++) i.ansi[n + 16] = K(e.extendedAnsi[n], re[n + 16]); } this._contrastCache.clear(), this._halfContrastCache.clear(), this._updateRestoreColors(), this._onChangeColors.fire(this.colors); } restoreColor(e) { this._restoreColor(e), this._onChangeColors.fire(this.colors); } _restoreColor(e) { if (e === void 0) { for (let i = 0; i < this._restoreColors.ansi.length; ++i) this._colors.ansi[i] = this._restoreColors.ansi[i]; return; } switch (e) { case 256: this._colors.foreground = this._restoreColors.foreground; break; case 257: this._colors.background = this._restoreColors.background; break; case 258: this._colors.cursor = this._restoreColors.cursor; break; default: this._colors.ansi[e] = this._restoreColors.ansi[e]; } } modifyColors(e) { e(this._colors), this._onChangeColors.fire(this.colors); } _updateRestoreColors() { this._restoreColors = { foreground: this._colors.foreground, background: this._colors.background, cursor: this._colors.cursor, ansi: this._colors.ansi.slice() }; } }; ti = M([S(0, H)], ti); function K(s15, t) { if (s15 !== void 0) try { return z.toColor(s15); } catch (e) { } return t; } var Rs = class { constructor(...t) { this._entries = /* @__PURE__ */ new Map(); for (let [e, i] of t) this.set(e, i); } set(t, e) { let i = this._entries.get(t); return this._entries.set(t, e), i; } forEach(t) { for (let [e, i] of this._entries.entries()) t(e, i); } has(t) { return this._entries.has(t); } get(t) { return this._entries.get(t); } }; var ln = class { constructor() { this._services = new Rs(); this._services.set(xt, this); } setService(t, e) { this._services.set(t, e); } getService(t) { return this._services.get(t); } createInstance(t, ...e) { let i = Xs(t).sort((o2, l) => o2.index - l.index), r = []; for (let o2 of i) { let l = this._services.get(o2.id); if (!l) throw new Error(`[createInstance] ${t.name} depends on UNKNOWN service ${o2.id._id}.`); r.push(l); } let n = i.length > 0 ? i[0].index : e.length; if (e.length !== n) throw new Error(`[createInstance] First service dependency of ${t.name} at position ${n + 1} conflicts with ${e.length} static arguments`); return new t(...e, ...r); } }; var ec = { trace: 0, debug: 1, info: 2, warn: 3, error: 4, off: 5 }; var tc = "xterm.js: "; var ii = class extends D { constructor(e) { super(); this._optionsService = e; this._logLevel = 5; this._updateLogLevel(), this._register(this._optionsService.onSpecificOptionChange("logLevel", () => this._updateLogLevel())), ic = this; } get logLevel() { return this._logLevel; } _updateLogLevel() { this._logLevel = ec[this._optionsService.rawOptions.logLevel]; } _evalLazyOptionalParams(e) { for (let i = 0; i < e.length; i++) typeof e[i] == "function" && (e[i] = e[i]()); } _log(e, i, r) { this._evalLazyOptionalParams(r), e.call(console, (this._optionsService.options.logger ? "" : tc) + i, ...r); } trace(e, ...i) { var _a5, _b; this._logLevel <= 0 && this._log((_b = (_a5 = this._optionsService.options.logger) == null ? void 0 : _a5.trace.bind(this._optionsService.options.logger)) != null ? _b : console.log, e, i); } debug(e, ...i) { var _a5, _b; this._logLevel <= 1 && this._log((_b = (_a5 = this._optionsService.options.logger) == null ? void 0 : _a5.debug.bind(this._optionsService.options.logger)) != null ? _b : console.log, e, i); } info(e, ...i) { var _a5, _b; this._logLevel <= 2 && this._log((_b = (_a5 = this._optionsService.options.logger) == null ? void 0 : _a5.info.bind(this._optionsService.options.logger)) != null ? _b : console.info, e, i); } warn(e, ...i) { var _a5, _b; this._logLevel <= 3 && this._log((_b = (_a5 = this._optionsService.options.logger) == null ? void 0 : _a5.warn.bind(this._optionsService.options.logger)) != null ? _b : console.warn, e, i); } error(e, ...i) { var _a5, _b; this._logLevel <= 4 && this._log((_b = (_a5 = this._optionsService.options.logger) == null ? void 0 : _a5.error.bind(this._optionsService.options.logger)) != null ? _b : console.error, e, i); } }; ii = M([S(0, H)], ii); var ic; var zi = class extends D { constructor(e) { super(); this._maxLength = e; this.onDeleteEmitter = this._register(new v()); this.onDelete = this.onDeleteEmitter.event; this.onInsertEmitter = this._register(new v()); this.onInsert = this.onInsertEmitter.event; this.onTrimEmitter = this._register(new v()); this.onTrim = this.onTrimEmitter.event; this._array = new Array(this._maxLength), this._startIndex = 0, this._length = 0; } get maxLength() { return this._maxLength; } set maxLength(e) { if (this._maxLength === e) return; let i = new Array(e); for (let r = 0; r < Math.min(e, this.length); r++) i[r] = this._array[this._getCyclicIndex(r)]; this._array = i, this._maxLength = e, this._startIndex = 0; } get length() { return this._length; } set length(e) { if (e > this._length) for (let i = this._length; i < e; i++) this._array[i] = void 0; this._length = e; } get(e) { return this._array[this._getCyclicIndex(e)]; } set(e, i) { this._array[this._getCyclicIndex(e)] = i; } push(e) { this._array[this._getCyclicIndex(this._length)] = e, this._length === this._maxLength ? (this._startIndex = ++this._startIndex % this._maxLength, this.onTrimEmitter.fire(1)) : this._length++; } recycle() { if (this._length !== this._maxLength) throw new Error("Can only recycle when the buffer is full"); return this._startIndex = ++this._startIndex % this._maxLength, this.onTrimEmitter.fire(1), this._array[this._getCyclicIndex(this._length - 1)]; } get isFull() { return this._length === this._maxLength; } pop() { return this._array[this._getCyclicIndex(this._length-- - 1)]; } splice(e, i, ...r) { if (i) { for (let n = e; n < this._length - i; n++) this._array[this._getCyclicIndex(n)] = this._array[this._getCyclicIndex(n + i)]; this._length -= i, this.onDeleteEmitter.fire({ index: e, amount: i }); } for (let n = this._length - 1; n >= e; n--) this._array[this._getCyclicIndex(n + r.length)] = this._array[this._getCyclicIndex(n)]; for (let n = 0; n < r.length; n++) this._array[this._getCyclicIndex(e + n)] = r[n]; if (r.length && this.onInsertEmitter.fire({ index: e, amount: r.length }), this._length + r.length > this._maxLength) { let n = this._length + r.length - this._maxLength; this._startIndex += n, this._length = this._maxLength, this.onTrimEmitter.fire(n); } else this._length += r.length; } trimStart(e) { e > this._length && (e = this._length), this._startIndex += e, this._length -= e, this.onTrimEmitter.fire(e); } shiftElements(e, i, r) { if (!(i <= 0)) { if (e < 0 || e >= this._length) throw new Error("start argument out of range"); if (e + r < 0) throw new Error("Cannot shift elements in list beyond index 0"); if (r > 0) { for (let o2 = i - 1; o2 >= 0; o2--) this.set(e + o2 + r, this.get(e + o2)); let n = e + i + r - this._length; if (n > 0) for (this._length += n; this._length > this._maxLength; ) this._length--, this._startIndex++, this.onTrimEmitter.fire(1); } else for (let n = 0; n < i; n++) this.set(e + n + r, this.get(e + n)); } } _getCyclicIndex(e) { return (this._startIndex + e) % this._maxLength; } }; var B = 3; var X = Object.freeze(new De()); var an = 0; var Ls = 2; var Ze = class s12 { constructor(t, e, i = false) { this.isWrapped = i; this._combined = {}; this._extendedAttrs = {}; this._data = new Uint32Array(t * B); let r = e || q.fromCharData([0, ir, 1, 0]); for (let n = 0; n < t; ++n) this.setCell(n, r); this.length = t; } get(t) { let e = this._data[t * B + 0], i = e & 2097151; return [this._data[t * B + 1], e & 2097152 ? this._combined[t] : i ? Ce(i) : "", e >> 22, e & 2097152 ? this._combined[t].charCodeAt(this._combined[t].length - 1) : i]; } set(t, e) { this._data[t * B + 1] = e[0], e[1].length > 1 ? (this._combined[t] = e[1], this._data[t * B + 0] = t | 2097152 | e[2] << 22) : this._data[t * B + 0] = e[1].charCodeAt(0) | e[2] << 22; } getWidth(t) { return this._data[t * B + 0] >> 22; } hasWidth(t) { return this._data[t * B + 0] & 12582912; } getFg(t) { return this._data[t * B + 1]; } getBg(t) { return this._data[t * B + 2]; } hasContent(t) { return this._data[t * B + 0] & 4194303; } getCodePoint(t) { let e = this._data[t * B + 0]; return e & 2097152 ? this._combined[t].charCodeAt(this._combined[t].length - 1) : e & 2097151; } isCombined(t) { return this._data[t * B + 0] & 2097152; } getString(t) { let e = this._data[t * B + 0]; return e & 2097152 ? this._combined[t] : e & 2097151 ? Ce(e & 2097151) : ""; } isProtected(t) { return this._data[t * B + 2] & 536870912; } loadCell(t, e) { return an = t * B, e.content = this._data[an + 0], e.fg = this._data[an + 1], e.bg = this._data[an + 2], e.content & 2097152 && (e.combinedData = this._combined[t]), e.bg & 268435456 && (e.extended = this._extendedAttrs[t]), e; } setCell(t, e) { e.content & 2097152 && (this._combined[t] = e.combinedData), e.bg & 268435456 && (this._extendedAttrs[t] = e.extended), this._data[t * B + 0] = e.content, this._data[t * B + 1] = e.fg, this._data[t * B + 2] = e.bg; } setCellFromCodepoint(t, e, i, r) { r.bg & 268435456 && (this._extendedAttrs[t] = r.extended), this._data[t * B + 0] = e | i << 22, this._data[t * B + 1] = r.fg, this._data[t * B + 2] = r.bg; } addCodepointToCell(t, e, i) { let r = this._data[t * B + 0]; r & 2097152 ? this._combined[t] += Ce(e) : r & 2097151 ? (this._combined[t] = Ce(r & 2097151) + Ce(e), r &= -2097152, r |= 2097152) : r = e | 1 << 22, i && (r &= -12582913, r |= i << 22), this._data[t * B + 0] = r; } insertCells(t, e, i) { if (t %= this.length, t && this.getWidth(t - 1) === 2 && this.setCellFromCodepoint(t - 1, 0, 1, i), e < this.length - t) { let r = new q(); for (let n = this.length - t - e - 1; n >= 0; --n) this.setCell(t + e + n, this.loadCell(t + n, r)); for (let n = 0; n < e; ++n) this.setCell(t + n, i); } else for (let r = t; r < this.length; ++r) this.setCell(r, i); this.getWidth(this.length - 1) === 2 && this.setCellFromCodepoint(this.length - 1, 0, 1, i); } deleteCells(t, e, i) { if (t %= this.length, e < this.length - t) { let r = new q(); for (let n = 0; n < this.length - t - e; ++n) this.setCell(t + n, this.loadCell(t + e + n, r)); for (let n = this.length - e; n < this.length; ++n) this.setCell(n, i); } else for (let r = t; r < this.length; ++r) this.setCell(r, i); t && this.getWidth(t - 1) === 2 && this.setCellFromCodepoint(t - 1, 0, 1, i), this.getWidth(t) === 0 && !this.hasContent(t) && this.setCellFromCodepoint(t, 0, 1, i); } replaceCells(t, e, i, r = false) { if (r) { for (t && this.getWidth(t - 1) === 2 && !this.isProtected(t - 1) && this.setCellFromCodepoint(t - 1, 0, 1, i), e < this.length && this.getWidth(e - 1) === 2 && !this.isProtected(e) && this.setCellFromCodepoint(e, 0, 1, i); t < e && t < this.length; ) this.isProtected(t) || this.setCell(t, i), t++; return; } for (t && this.getWidth(t - 1) === 2 && this.setCellFromCodepoint(t - 1, 0, 1, i), e < this.length && this.getWidth(e - 1) === 2 && this.setCellFromCodepoint(e, 0, 1, i); t < e && t < this.length; ) this.setCell(t++, i); } resize(t, e) { if (t === this.length) return this._data.length * 4 * Ls < this._data.buffer.byteLength; let i = t * B; if (t > this.length) { if (this._data.buffer.byteLength >= i * 4) this._data = new Uint32Array(this._data.buffer, 0, i); else { let r = new Uint32Array(i); r.set(this._data), this._data = r; } for (let r = this.length; r < t; ++r) this.setCell(r, e); } else { this._data = this._data.subarray(0, i); let r = Object.keys(this._combined); for (let o2 = 0; o2 < r.length; o2++) { let l = parseInt(r[o2], 10); l >= t && delete this._combined[l]; } let n = Object.keys(this._extendedAttrs); for (let o2 = 0; o2 < n.length; o2++) { let l = parseInt(n[o2], 10); l >= t && delete this._extendedAttrs[l]; } } return this.length = t, i * 4 * Ls < this._data.buffer.byteLength; } cleanupMemory() { if (this._data.length * 4 * Ls < this._data.buffer.byteLength) { let t = new Uint32Array(this._data.length); return t.set(this._data), this._data = t, 1; } return 0; } fill(t, e = false) { if (e) { for (let i = 0; i < this.length; ++i) this.isProtected(i) || this.setCell(i, t); return; } this._combined = {}, this._extendedAttrs = {}; for (let i = 0; i < this.length; ++i) this.setCell(i, t); } copyFrom(t) { this.length !== t.length ? this._data = new Uint32Array(t._data) : this._data.set(t._data), this.length = t.length, this._combined = {}; for (let e in t._combined) this._combined[e] = t._combined[e]; this._extendedAttrs = {}; for (let e in t._extendedAttrs) this._extendedAttrs[e] = t._extendedAttrs[e]; this.isWrapped = t.isWrapped; } clone() { let t = new s12(0); t._data = new Uint32Array(this._data), t.length = this.length; for (let e in this._combined) t._combined[e] = this._combined[e]; for (let e in this._extendedAttrs) t._extendedAttrs[e] = this._extendedAttrs[e]; return t.isWrapped = this.isWrapped, t; } getTrimmedLength() { for (let t = this.length - 1; t >= 0; --t) if (this._data[t * B + 0] & 4194303) return t + (this._data[t * B + 0] >> 22); return 0; } getNoBgTrimmedLength() { for (let t = this.length - 1; t >= 0; --t) if (this._data[t * B + 0] & 4194303 || this._data[t * B + 2] & 50331648) return t + (this._data[t * B + 0] >> 22); return 0; } copyCellsFrom(t, e, i, r, n) { let o2 = t._data; if (n) for (let a = r - 1; a >= 0; a--) { for (let u = 0; u < B; u++) this._data[(i + a) * B + u] = o2[(e + a) * B + u]; o2[(e + a) * B + 2] & 268435456 && (this._extendedAttrs[i + a] = t._extendedAttrs[e + a]); } else for (let a = 0; a < r; a++) { for (let u = 0; u < B; u++) this._data[(i + a) * B + u] = o2[(e + a) * B + u]; o2[(e + a) * B + 2] & 268435456 && (this._extendedAttrs[i + a] = t._extendedAttrs[e + a]); } let l = Object.keys(t._combined); for (let a = 0; a < l.length; a++) { let u = parseInt(l[a], 10); u >= e && (this._combined[u - e + i] = t._combined[u]); } } translateToString(t, e, i, r) { e = e != null ? e : 0, i = i != null ? i : this.length, t && (i = Math.min(i, this.getTrimmedLength())), r && (r.length = 0); let n = ""; for (; e < i; ) { let o2 = this._data[e * B + 0], l = o2 & 2097151, a = o2 & 2097152 ? this._combined[e] : l ? Ce(l) : we; if (n += a, r) for (let u = 0; u < a.length; ++u) r.push(e); e += o2 >> 22 || 1; } return r && r.push(e), n; } }; function sl(s15, t, e, i, r, n) { let o2 = []; for (let l = 0; l < s15.length - 1; l++) { let a = l, u = s15.get(++a); if (!u.isWrapped) continue; let h2 = [s15.get(l)]; for (; a < s15.length && u.isWrapped; ) h2.push(u), u = s15.get(++a); if (!n && i >= l && i < a) { l += h2.length - 1; continue; } let c = 0, d = ri(h2, c, t), _2 = 1, p = 0; for (; _2 < h2.length; ) { let f = ri(h2, _2, t), A = f - p, R = e - d, O = Math.min(A, R); h2[c].copyCellsFrom(h2[_2], p, d, O, false), d += O, d === e && (c++, d = 0), p += O, p === f && (_2++, p = 0), d === 0 && c !== 0 && h2[c - 1].getWidth(e - 1) === 2 && (h2[c].copyCellsFrom(h2[c - 1], e - 1, d++, 1, false), h2[c - 1].setCell(e - 1, r)); } h2[c].replaceCells(d, e, r); let m = 0; for (let f = h2.length - 1; f > 0 && (f > c || h2[f].getTrimmedLength() === 0); f--) m++; m > 0 && (o2.push(l + h2.length - m), o2.push(m)), l += h2.length - 1; } return o2; } function ol(s15, t) { let e = [], i = 0, r = t[i], n = 0; for (let o2 = 0; o2 < s15.length; o2++) if (r === o2) { let l = t[++i]; s15.onDeleteEmitter.fire({ index: o2 - n, amount: l }), o2 += l - 1, n += l, r = t[++i]; } else e.push(o2); return { layout: e, countRemoved: n }; } function ll(s15, t) { let e = []; for (let i = 0; i < t.length; i++) e.push(s15.get(t[i])); for (let i = 0; i < e.length; i++) s15.set(i, e[i]); s15.length = t.length; } function al(s15, t, e) { let i = [], r = s15.map((a, u) => ri(s15, u, t)).reduce((a, u) => a + u), n = 0, o2 = 0, l = 0; for (; l < r; ) { if (r - l < e) { i.push(r - l); break; } n += e; let a = ri(s15, o2, t); n > a && (n -= a, o2++); let u = s15[o2].getWidth(n - 1) === 2; u && n--; let h2 = u ? e - 1 : e; i.push(h2), l += h2; } return i; } function ri(s15, t, e) { if (t === s15.length - 1) return s15[t].getTrimmedLength(); let i = !s15[t].hasContent(e - 1) && s15[t].getWidth(e - 1) === 1, r = s15[t + 1].getWidth(0) === 2; return i && r ? e - 1 : e; } var un = class un2 { constructor(t) { this.line = t; this.isDisposed = false; this._disposables = []; this._id = un2._nextId++; this._onDispose = this.register(new v()); this.onDispose = this._onDispose.event; } get id() { return this._id; } dispose() { this.isDisposed || (this.isDisposed = true, this.line = -1, this._onDispose.fire(), Ne(this._disposables), this._disposables.length = 0); } register(t) { return this._disposables.push(t), t; } }; un._nextId = 1; var cn = un; var ne = {}; var Je = ne.B; ne[0] = { "`": "\u25C6", a: "\u2592", b: "\u2409", c: "\u240C", d: "\u240D", e: "\u240A", f: "\xB0", g: "\xB1", h: "\u2424", i: "\u240B", j: "\u2518", k: "\u2510", l: "\u250C", m: "\u2514", n: "\u253C", o: "\u23BA", p: "\u23BB", q: "\u2500", r: "\u23BC", s: "\u23BD", t: "\u251C", u: "\u2524", v: "\u2534", w: "\u252C", x: "\u2502", y: "\u2264", z: "\u2265", "{": "\u03C0", "|": "\u2260", "}": "\xA3", "~": "\xB7" }; ne.A = { "#": "\xA3" }; ne.B = void 0; ne[4] = { "#": "\xA3", "@": "\xBE", "[": "ij", "\\": "\xBD", "]": "|", "{": "\xA8", "|": "f", "}": "\xBC", "~": "\xB4" }; ne.C = ne[5] = { "[": "\xC4", "\\": "\xD6", "]": "\xC5", "^": "\xDC", "`": "\xE9", "{": "\xE4", "|": "\xF6", "}": "\xE5", "~": "\xFC" }; ne.R = { "#": "\xA3", "@": "\xE0", "[": "\xB0", "\\": "\xE7", "]": "\xA7", "{": "\xE9", "|": "\xF9", "}": "\xE8", "~": "\xA8" }; ne.Q = { "@": "\xE0", "[": "\xE2", "\\": "\xE7", "]": "\xEA", "^": "\xEE", "`": "\xF4", "{": "\xE9", "|": "\xF9", "}": "\xE8", "~": "\xFB" }; ne.K = { "@": "\xA7", "[": "\xC4", "\\": "\xD6", "]": "\xDC", "{": "\xE4", "|": "\xF6", "}": "\xFC", "~": "\xDF" }; ne.Y = { "#": "\xA3", "@": "\xA7", "[": "\xB0", "\\": "\xE7", "]": "\xE9", "`": "\xF9", "{": "\xE0", "|": "\xF2", "}": "\xE8", "~": "\xEC" }; ne.E = ne[6] = { "@": "\xC4", "[": "\xC6", "\\": "\xD8", "]": "\xC5", "^": "\xDC", "`": "\xE4", "{": "\xE6", "|": "\xF8", "}": "\xE5", "~": "\xFC" }; ne.Z = { "#": "\xA3", "@": "\xA7", "[": "\xA1", "\\": "\xD1", "]": "\xBF", "{": "\xB0", "|": "\xF1", "}": "\xE7" }; ne.H = ne[7] = { "@": "\xC9", "[": "\xC4", "\\": "\xD6", "]": "\xC5", "^": "\xDC", "`": "\xE9", "{": "\xE4", "|": "\xF6", "}": "\xE5", "~": "\xFC" }; ne["="] = { "#": "\xF9", "@": "\xE0", "[": "\xE9", "\\": "\xE7", "]": "\xEA", "^": "\xEE", _: "\xE8", "`": "\xF4", "{": "\xE4", "|": "\xF6", "}": "\xFC", "~": "\xFB" }; var cl = 4294967295; var $i = class { constructor(t, e, i) { this._hasScrollback = t; this._optionsService = e; this._bufferService = i; this.ydisp = 0; this.ybase = 0; this.y = 0; this.x = 0; this.tabs = {}; this.savedY = 0; this.savedX = 0; this.savedCurAttrData = X.clone(); this.savedCharset = Je; this.markers = []; this._nullCell = q.fromCharData([0, ir, 1, 0]); this._whitespaceCell = q.fromCharData([0, we, 1, 32]); this._isClearing = false; this._memoryCleanupQueue = new Jt(); this._memoryCleanupPosition = 0; this._cols = this._bufferService.cols, this._rows = this._bufferService.rows, this.lines = new zi(this._getCorrectBufferLength(this._rows)), this.scrollTop = 0, this.scrollBottom = this._rows - 1, this.setupTabStops(); } getNullCell(t) { return t ? (this._nullCell.fg = t.fg, this._nullCell.bg = t.bg, this._nullCell.extended = t.extended) : (this._nullCell.fg = 0, this._nullCell.bg = 0, this._nullCell.extended = new rt()), this._nullCell; } getWhitespaceCell(t) { return t ? (this._whitespaceCell.fg = t.fg, this._whitespaceCell.bg = t.bg, this._whitespaceCell.extended = t.extended) : (this._whitespaceCell.fg = 0, this._whitespaceCell.bg = 0, this._whitespaceCell.extended = new rt()), this._whitespaceCell; } getBlankLine(t, e) { return new Ze(this._bufferService.cols, this.getNullCell(t), e); } get hasScrollback() { return this._hasScrollback && this.lines.maxLength > this._rows; } get isCursorInViewport() { let e = this.ybase + this.y - this.ydisp; return e >= 0 && e < this._rows; } _getCorrectBufferLength(t) { if (!this._hasScrollback) return t; let e = t + this._optionsService.rawOptions.scrollback; return e > cl ? cl : e; } fillViewportRows(t) { if (this.lines.length === 0) { t === void 0 && (t = X); let e = this._rows; for (; e--; ) this.lines.push(this.getBlankLine(t)); } } clear() { this.ydisp = 0, this.ybase = 0, this.y = 0, this.x = 0, this.lines = new zi(this._getCorrectBufferLength(this._rows)), this.scrollTop = 0, this.scrollBottom = this._rows - 1, this.setupTabStops(); } resize(t, e) { let i = this.getNullCell(X), r = 0, n = this._getCorrectBufferLength(e); if (n > this.lines.maxLength && (this.lines.maxLength = n), this.lines.length > 0) { if (this._cols < t) for (let l = 0; l < this.lines.length; l++) r += +this.lines.get(l).resize(t, i); let o2 = 0; if (this._rows < e) for (let l = this._rows; l < e; l++) this.lines.length < e + this.ybase && (this._optionsService.rawOptions.windowsMode || this._optionsService.rawOptions.windowsPty.backend !== void 0 || this._optionsService.rawOptions.windowsPty.buildNumber !== void 0 ? this.lines.push(new Ze(t, i)) : this.ybase > 0 && this.lines.length <= this.ybase + this.y + o2 + 1 ? (this.ybase--, o2++, this.ydisp > 0 && this.ydisp--) : this.lines.push(new Ze(t, i))); else for (let l = this._rows; l > e; l--) this.lines.length > e + this.ybase && (this.lines.length > this.ybase + this.y + 1 ? this.lines.pop() : (this.ybase++, this.ydisp++)); if (n < this.lines.maxLength) { let l = this.lines.length - n; l > 0 && (this.lines.trimStart(l), this.ybase = Math.max(this.ybase - l, 0), this.ydisp = Math.max(this.ydisp - l, 0), this.savedY = Math.max(this.savedY - l, 0)), this.lines.maxLength = n; } this.x = Math.min(this.x, t - 1), this.y = Math.min(this.y, e - 1), o2 && (this.y += o2), this.savedX = Math.min(this.savedX, t - 1), this.scrollTop = 0; } if (this.scrollBottom = e - 1, this._isReflowEnabled && (this._reflow(t, e), this._cols > t)) for (let o2 = 0; o2 < this.lines.length; o2++) r += +this.lines.get(o2).resize(t, i); this._cols = t, this._rows = e, this._memoryCleanupQueue.clear(), r > 0.1 * this.lines.length && (this._memoryCleanupPosition = 0, this._memoryCleanupQueue.enqueue(() => this._batchedMemoryCleanup())); } _batchedMemoryCleanup() { let t = true; this._memoryCleanupPosition >= this.lines.length && (this._memoryCleanupPosition = 0, t = false); let e = 0; for (; this._memoryCleanupPosition < this.lines.length; ) if (e += this.lines.get(this._memoryCleanupPosition++).cleanupMemory(), e > 100) return true; return t; } get _isReflowEnabled() { let t = this._optionsService.rawOptions.windowsPty; return t && t.buildNumber ? this._hasScrollback && t.backend === "conpty" && t.buildNumber >= 21376 : this._hasScrollback && !this._optionsService.rawOptions.windowsMode; } _reflow(t, e) { this._cols !== t && (t > this._cols ? this._reflowLarger(t, e) : this._reflowSmaller(t, e)); } _reflowLarger(t, e) { let i = this._optionsService.rawOptions.reflowCursorLine, r = sl(this.lines, this._cols, t, this.ybase + this.y, this.getNullCell(X), i); if (r.length > 0) { let n = ol(this.lines, r); ll(this.lines, n.layout), this._reflowLargerAdjustViewport(t, e, n.countRemoved); } } _reflowLargerAdjustViewport(t, e, i) { let r = this.getNullCell(X), n = i; for (; n-- > 0; ) this.ybase === 0 ? (this.y > 0 && this.y--, this.lines.length < e && this.lines.push(new Ze(t, r))) : (this.ydisp === this.ybase && this.ydisp--, this.ybase--); this.savedY = Math.max(this.savedY - i, 0); } _reflowSmaller(t, e) { let i = this._optionsService.rawOptions.reflowCursorLine, r = this.getNullCell(X), n = [], o2 = 0; for (let l = this.lines.length - 1; l >= 0; l--) { let a = this.lines.get(l); if (!a || !a.isWrapped && a.getTrimmedLength() <= t) continue; let u = [a]; for (; a.isWrapped && l > 0; ) a = this.lines.get(--l), u.unshift(a); if (!i) { let I = this.ybase + this.y; if (I >= l && I < l + u.length) continue; } let h2 = u[u.length - 1].getTrimmedLength(), c = al(u, this._cols, t), d = c.length - u.length, _2; this.ybase === 0 && this.y !== this.lines.length - 1 ? _2 = Math.max(0, this.y - this.lines.maxLength + d) : _2 = Math.max(0, this.lines.length - this.lines.maxLength + d); let p = []; for (let I = 0; I < d; I++) { let k = this.getBlankLine(X, true); p.push(k); } p.length > 0 && (n.push({ start: l + u.length + o2, newLines: p }), o2 += p.length), u.push(...p); let m = c.length - 1, f = c[m]; f === 0 && (m--, f = c[m]); let A = u.length - d - 1, R = h2; for (; A >= 0; ) { let I = Math.min(R, f); if (u[m] === void 0) break; if (u[m].copyCellsFrom(u[A], R - I, f - I, I, true), f -= I, f === 0 && (m--, f = c[m]), R -= I, R === 0) { A--; let k = Math.max(A, 0); R = ri(u, k, this._cols); } } for (let I = 0; I < u.length; I++) c[I] < t && u[I].setCell(c[I], r); let O = d - _2; for (; O-- > 0; ) this.ybase === 0 ? this.y < e - 1 ? (this.y++, this.lines.pop()) : (this.ybase++, this.ydisp++) : this.ybase < Math.min(this.lines.maxLength, this.lines.length + o2) - e && (this.ybase === this.ydisp && this.ydisp++, this.ybase++); this.savedY = Math.min(this.savedY + d, this.ybase + e - 1); } if (n.length > 0) { let l = [], a = []; for (let f = 0; f < this.lines.length; f++) a.push(this.lines.get(f)); let u = this.lines.length, h2 = u - 1, c = 0, d = n[c]; this.lines.length = Math.min(this.lines.maxLength, this.lines.length + o2); let _2 = 0; for (let f = Math.min(this.lines.maxLength - 1, u + o2 - 1); f >= 0; f--) if (d && d.start > h2 + _2) { for (let A = d.newLines.length - 1; A >= 0; A--) this.lines.set(f--, d.newLines[A]); f++, l.push({ index: h2 + 1, amount: d.newLines.length }), _2 += d.newLines.length, d = n[++c]; } else this.lines.set(f, a[h2--]); let p = 0; for (let f = l.length - 1; f >= 0; f--) l[f].index += p, this.lines.onInsertEmitter.fire(l[f]), p += l[f].amount; let m = Math.max(0, u + o2 - this.lines.maxLength); m > 0 && this.lines.onTrimEmitter.fire(m); } } translateBufferLineToString(t, e, i = 0, r) { let n = this.lines.get(t); return n ? n.translateToString(e, i, r) : ""; } getWrappedRangeForLine(t) { let e = t, i = t; for (; e > 0 && this.lines.get(e).isWrapped; ) e--; for (; i + 1 < this.lines.length && this.lines.get(i + 1).isWrapped; ) i++; return { first: e, last: i }; } setupTabStops(t) { for (t != null ? this.tabs[t] || (t = this.prevStop(t)) : (this.tabs = {}, t = 0); t < this._cols; t += this._optionsService.rawOptions.tabStopWidth) this.tabs[t] = true; } prevStop(t) { for (t == null && (t = this.x); !this.tabs[--t] && t > 0; ) ; return t >= this._cols ? this._cols - 1 : t < 0 ? 0 : t; } nextStop(t) { for (t == null && (t = this.x); !this.tabs[++t] && t < this._cols; ) ; return t >= this._cols ? this._cols - 1 : t < 0 ? 0 : t; } clearMarkers(t) { this._isClearing = true; for (let e = 0; e < this.markers.length; e++) this.markers[e].line === t && (this.markers[e].dispose(), this.markers.splice(e--, 1)); this._isClearing = false; } clearAllMarkers() { this._isClearing = true; for (let t = 0; t < this.markers.length; t++) this.markers[t].dispose(); this.markers.length = 0, this._isClearing = false; } addMarker(t) { let e = new cn(t); return this.markers.push(e), e.register(this.lines.onTrim((i) => { e.line -= i, e.line < 0 && e.dispose(); })), e.register(this.lines.onInsert((i) => { e.line >= i.index && (e.line += i.amount); })), e.register(this.lines.onDelete((i) => { e.line >= i.index && e.line < i.index + i.amount && e.dispose(), e.line > i.index && (e.line -= i.amount); })), e.register(e.onDispose(() => this._removeMarker(e))), e; } _removeMarker(t) { this._isClearing || this.markers.splice(this.markers.indexOf(t), 1); } }; var hn = class extends D { constructor(e, i) { super(); this._optionsService = e; this._bufferService = i; this._onBufferActivate = this._register(new v()); this.onBufferActivate = this._onBufferActivate.event; this.reset(), this._register(this._optionsService.onSpecificOptionChange("scrollback", () => this.resize(this._bufferService.cols, this._bufferService.rows))), this._register(this._optionsService.onSpecificOptionChange("tabStopWidth", () => this.setupTabStops())); } reset() { this._normal = new $i(true, this._optionsService, this._bufferService), this._normal.fillViewportRows(), this._alt = new $i(false, this._optionsService, this._bufferService), this._activeBuffer = this._normal, this._onBufferActivate.fire({ activeBuffer: this._normal, inactiveBuffer: this._alt }), this.setupTabStops(); } get alt() { return this._alt; } get active() { return this._activeBuffer; } get normal() { return this._normal; } activateNormalBuffer() { this._activeBuffer !== this._normal && (this._normal.x = this._alt.x, this._normal.y = this._alt.y, this._alt.clearAllMarkers(), this._alt.clear(), this._activeBuffer = this._normal, this._onBufferActivate.fire({ activeBuffer: this._normal, inactiveBuffer: this._alt })); } activateAltBuffer(e) { this._activeBuffer !== this._alt && (this._alt.fillViewportRows(e), this._alt.x = this._normal.x, this._alt.y = this._normal.y, this._activeBuffer = this._alt, this._onBufferActivate.fire({ activeBuffer: this._alt, inactiveBuffer: this._normal })); } resize(e, i) { this._normal.resize(e, i), this._alt.resize(e, i), this.setupTabStops(e); } setupTabStops(e) { this._normal.setupTabStops(e), this._alt.setupTabStops(e); } }; var ks = 2; var Cs = 1; var ni = class extends D { constructor(e) { super(); this.isUserScrolling = false; this._onResize = this._register(new v()); this.onResize = this._onResize.event; this._onScroll = this._register(new v()); this.onScroll = this._onScroll.event; this.cols = Math.max(e.rawOptions.cols || 0, ks), this.rows = Math.max(e.rawOptions.rows || 0, Cs), this.buffers = this._register(new hn(e, this)), this._register(this.buffers.onBufferActivate((i) => { this._onScroll.fire(i.activeBuffer.ydisp); })); } get buffer() { return this.buffers.active; } resize(e, i) { let r = this.cols !== e, n = this.rows !== i; this.cols = e, this.rows = i, this.buffers.resize(e, i), this._onResize.fire({ cols: e, rows: i, colsChanged: r, rowsChanged: n }); } reset() { this.buffers.reset(), this.isUserScrolling = false; } scroll(e, i = false) { let r = this.buffer, n; n = this._cachedBlankLine, (!n || n.length !== this.cols || n.getFg(0) !== e.fg || n.getBg(0) !== e.bg) && (n = r.getBlankLine(e, i), this._cachedBlankLine = n), n.isWrapped = i; let o2 = r.ybase + r.scrollTop, l = r.ybase + r.scrollBottom; if (r.scrollTop === 0) { let a = r.lines.isFull; l === r.lines.length - 1 ? a ? r.lines.recycle().copyFrom(n) : r.lines.push(n.clone()) : r.lines.splice(l + 1, 0, n.clone()), a ? this.isUserScrolling && (r.ydisp = Math.max(r.ydisp - 1, 0)) : (r.ybase++, this.isUserScrolling || r.ydisp++); } else { let a = l - o2 + 1; r.lines.shiftElements(o2 + 1, a - 1, -1), r.lines.set(l, n.clone()); } this.isUserScrolling || (r.ydisp = r.ybase), this._onScroll.fire(r.ydisp); } scrollLines(e, i) { let r = this.buffer; if (e < 0) { if (r.ydisp === 0) return; this.isUserScrolling = true; } else e + r.ydisp >= r.ybase && (this.isUserScrolling = false); let n = r.ydisp; r.ydisp = Math.max(Math.min(r.ydisp + e, r.ybase), 0), n !== r.ydisp && (i || this._onScroll.fire(r.ydisp)); } }; ni = M([S(0, H)], ni); var si = { cols: 80, rows: 24, cursorBlink: false, cursorStyle: "block", cursorWidth: 1, cursorInactiveStyle: "outline", customGlyphs: true, drawBoldTextInBrightColors: true, documentOverride: null, fastScrollModifier: "alt", fastScrollSensitivity: 5, fontFamily: "monospace", fontSize: 15, fontWeight: "normal", fontWeightBold: "bold", ignoreBracketedPasteMode: false, lineHeight: 1, letterSpacing: 0, linkHandler: null, logLevel: "info", logger: null, scrollback: 1e3, scrollOnEraseInDisplay: false, scrollOnUserInput: true, scrollSensitivity: 1, screenReaderMode: false, smoothScrollDuration: 0, macOptionIsMeta: false, macOptionClickForcesSelection: false, minimumContrastRatio: 1, disableStdin: false, allowProposedApi: false, allowTransparency: false, tabStopWidth: 8, theme: {}, reflowCursorLine: false, rescaleOverlappingGlyphs: false, rightClickSelectsWord: Zt, windowOptions: {}, windowsMode: false, windowsPty: {}, wordSeparator: " ()[]{}',\"`", altClickMovesCursor: true, convertEol: false, termName: "xterm", cancelEvents: false, overviewRuler: {} }; var nc = ["normal", "bold", "100", "200", "300", "400", "500", "600", "700", "800", "900"]; var dn = class extends D { constructor(e) { super(); this._onOptionChange = this._register(new v()); this.onOptionChange = this._onOptionChange.event; let i = { ...si }; for (let r in e) if (r in i) try { let n = e[r]; i[r] = this._sanitizeAndValidateOption(r, n); } catch (n) { console.error(n); } this.rawOptions = i, this.options = { ...i }, this._setupOptions(), this._register(C(() => { this.rawOptions.linkHandler = null, this.rawOptions.documentOverride = null; })); } onSpecificOptionChange(e, i) { return this.onOptionChange((r) => { r === e && i(this.rawOptions[e]); }); } onMultipleOptionChange(e, i) { return this.onOptionChange((r) => { e.indexOf(r) !== -1 && i(); }); } _setupOptions() { let e = (r) => { if (!(r in si)) throw new Error(`No option with key "${r}"`); return this.rawOptions[r]; }, i = (r, n) => { if (!(r in si)) throw new Error(`No option with key "${r}"`); n = this._sanitizeAndValidateOption(r, n), this.rawOptions[r] !== n && (this.rawOptions[r] = n, this._onOptionChange.fire(r)); }; for (let r in this.rawOptions) { let n = { get: e.bind(this, r), set: i.bind(this, r) }; Object.defineProperty(this.options, r, n); } } _sanitizeAndValidateOption(e, i) { switch (e) { case "cursorStyle": if (i || (i = si[e]), !sc(i)) throw new Error(`"${i}" is not a valid value for ${e}`); break; case "wordSeparator": i || (i = si[e]); break; case "fontWeight": case "fontWeightBold": if (typeof i == "number" && 1 <= i && i <= 1e3) break; i = nc.includes(i) ? i : si[e]; break; case "cursorWidth": i = Math.floor(i); case "lineHeight": case "tabStopWidth": if (i < 1) throw new Error(`${e} cannot be less than 1, value: ${i}`); break; case "minimumContrastRatio": i = Math.max(1, Math.min(21, Math.round(i * 10) / 10)); break; case "scrollback": if (i = Math.min(i, 4294967295), i < 0) throw new Error(`${e} cannot be less than 0, value: ${i}`); break; case "fastScrollSensitivity": case "scrollSensitivity": if (i <= 0) throw new Error(`${e} cannot be less than or equal to 0, value: ${i}`); break; case "rows": case "cols": if (!i && i !== 0) throw new Error(`${e} must be numeric, value: ${i}`); break; case "windowsPty": i = i != null ? i : {}; break; } return i; } }; function sc(s15) { return s15 === "block" || s15 === "underline" || s15 === "bar"; } function oi(s15, t = 5) { if (typeof s15 != "object") return s15; let e = Array.isArray(s15) ? [] : {}; for (let i in s15) e[i] = t <= 1 ? s15[i] : s15[i] && oi(s15[i], t - 1); return e; } var ul = Object.freeze({ insertMode: false }); var hl = Object.freeze({ applicationCursorKeys: false, applicationKeypad: false, bracketedPasteMode: false, cursorBlink: void 0, cursorStyle: void 0, origin: false, reverseWraparound: false, sendFocus: false, synchronizedOutput: false, wraparound: true }); var li = class extends D { constructor(e, i, r) { super(); this._bufferService = e; this._logService = i; this._optionsService = r; this.isCursorInitialized = false; this.isCursorHidden = false; this._onData = this._register(new v()); this.onData = this._onData.event; this._onUserInput = this._register(new v()); this.onUserInput = this._onUserInput.event; this._onBinary = this._register(new v()); this.onBinary = this._onBinary.event; this._onRequestScrollToBottom = this._register(new v()); this.onRequestScrollToBottom = this._onRequestScrollToBottom.event; this.modes = oi(ul), this.decPrivateModes = oi(hl); } reset() { this.modes = oi(ul), this.decPrivateModes = oi(hl); } triggerDataEvent(e, i = false) { if (this._optionsService.rawOptions.disableStdin) return; let r = this._bufferService.buffer; i && this._optionsService.rawOptions.scrollOnUserInput && r.ybase !== r.ydisp && this._onRequestScrollToBottom.fire(), i && this._onUserInput.fire(), this._logService.debug(`sending data "${e}"`), this._logService.trace("sending data (codes)", () => e.split("").map((n) => n.charCodeAt(0))), this._onData.fire(e); } triggerBinaryEvent(e) { this._optionsService.rawOptions.disableStdin || (this._logService.debug(`sending binary "${e}"`), this._logService.trace("sending binary (codes)", () => e.split("").map((i) => i.charCodeAt(0))), this._onBinary.fire(e)); } }; li = M([S(0, F), S(1, nr), S(2, H)], li); var dl = { NONE: { events: 0, restrict: () => false }, X10: { events: 1, restrict: (s15) => s15.button === 4 || s15.action !== 1 ? false : (s15.ctrl = false, s15.alt = false, s15.shift = false, true) }, VT200: { events: 19, restrict: (s15) => s15.action !== 32 }, DRAG: { events: 23, restrict: (s15) => !(s15.action === 32 && s15.button === 3) }, ANY: { events: 31, restrict: (s15) => true } }; function Ms(s15, t) { let e = (s15.ctrl ? 16 : 0) | (s15.shift ? 4 : 0) | (s15.alt ? 8 : 0); return s15.button === 4 ? (e |= 64, e |= s15.action) : (e |= s15.button & 3, s15.button & 4 && (e |= 64), s15.button & 8 && (e |= 128), s15.action === 32 ? e |= 32 : s15.action === 0 && !t && (e |= 3)), e; } var Ps = String.fromCharCode; var fl = { DEFAULT: (s15) => { let t = [Ms(s15, false) + 32, s15.col + 32, s15.row + 32]; return t[0] > 255 || t[1] > 255 || t[2] > 255 ? "" : `\x1B[M${Ps(t[0])}${Ps(t[1])}${Ps(t[2])}`; }, SGR: (s15) => { let t = s15.action === 0 && s15.button !== 4 ? "m" : "M"; return `\x1B[<${Ms(s15, true)};${s15.col};${s15.row}${t}`; }, SGR_PIXELS: (s15) => { let t = s15.action === 0 && s15.button !== 4 ? "m" : "M"; return `\x1B[<${Ms(s15, true)};${s15.x};${s15.y}${t}`; } }; var ai = class extends D { constructor(e, i, r) { super(); this._bufferService = e; this._coreService = i; this._optionsService = r; this._protocols = {}; this._encodings = {}; this._activeProtocol = ""; this._activeEncoding = ""; this._lastEvent = null; this._wheelPartialScroll = 0; this._onProtocolChange = this._register(new v()); this.onProtocolChange = this._onProtocolChange.event; for (let n of Object.keys(dl)) this.addProtocol(n, dl[n]); for (let n of Object.keys(fl)) this.addEncoding(n, fl[n]); this.reset(); } addProtocol(e, i) { this._protocols[e] = i; } addEncoding(e, i) { this._encodings[e] = i; } get activeProtocol() { return this._activeProtocol; } get areMouseEventsActive() { return this._protocols[this._activeProtocol].events !== 0; } set activeProtocol(e) { if (!this._protocols[e]) throw new Error(`unknown protocol "${e}"`); this._activeProtocol = e, this._onProtocolChange.fire(this._protocols[e].events); } get activeEncoding() { return this._activeEncoding; } set activeEncoding(e) { if (!this._encodings[e]) throw new Error(`unknown encoding "${e}"`); this._activeEncoding = e; } reset() { this.activeProtocol = "NONE", this.activeEncoding = "DEFAULT", this._lastEvent = null, this._wheelPartialScroll = 0; } consumeWheelEvent(e, i, r) { if (e.deltaY === 0 || e.shiftKey || i === void 0 || r === void 0) return 0; let n = i / r, o2 = this._applyScrollModifier(e.deltaY, e); return e.deltaMode === WheelEvent.DOM_DELTA_PIXEL ? (o2 /= n + 0, Math.abs(e.deltaY) < 50 && (o2 *= 0.3), this._wheelPartialScroll += o2, o2 = Math.floor(Math.abs(this._wheelPartialScroll)) * (this._wheelPartialScroll > 0 ? 1 : -1), this._wheelPartialScroll %= 1) : e.deltaMode === WheelEvent.DOM_DELTA_PAGE && (o2 *= this._bufferService.rows), o2; } _applyScrollModifier(e, i) { return i.altKey || i.ctrlKey || i.shiftKey ? e * this._optionsService.rawOptions.fastScrollSensitivity * this._optionsService.rawOptions.scrollSensitivity : e * this._optionsService.rawOptions.scrollSensitivity; } triggerMouseEvent(e) { if (e.col < 0 || e.col >= this._bufferService.cols || e.row < 0 || e.row >= this._bufferService.rows || e.button === 4 && e.action === 32 || e.button === 3 && e.action !== 32 || e.button !== 4 && (e.action === 2 || e.action === 3) || (e.col++, e.row++, e.action === 32 && this._lastEvent && this._equalEvents(this._lastEvent, e, this._activeEncoding === "SGR_PIXELS")) || !this._protocols[this._activeProtocol].restrict(e)) return false; let i = this._encodings[this._activeEncoding](e); return i && (this._activeEncoding === "DEFAULT" ? this._coreService.triggerBinaryEvent(i) : this._coreService.triggerDataEvent(i, true)), this._lastEvent = e, true; } explainEvents(e) { return { down: !!(e & 1), up: !!(e & 2), drag: !!(e & 4), move: !!(e & 8), wheel: !!(e & 16) }; } _equalEvents(e, i, r) { if (r) { if (e.x !== i.x || e.y !== i.y) return false; } else if (e.col !== i.col || e.row !== i.row) return false; return !(e.button !== i.button || e.action !== i.action || e.ctrl !== i.ctrl || e.alt !== i.alt || e.shift !== i.shift); } }; ai = M([S(0, F), S(1, ge), S(2, H)], ai); var Os = [[768, 879], [1155, 1158], [1160, 1161], [1425, 1469], [1471, 1471], [1473, 1474], [1476, 1477], [1479, 1479], [1536, 1539], [1552, 1557], [1611, 1630], [1648, 1648], [1750, 1764], [1767, 1768], [1770, 1773], [1807, 1807], [1809, 1809], [1840, 1866], [1958, 1968], [2027, 2035], [2305, 2306], [2364, 2364], [2369, 2376], [2381, 2381], [2385, 2388], [2402, 2403], [2433, 2433], [2492, 2492], [2497, 2500], [2509, 2509], [2530, 2531], [2561, 2562], [2620, 2620], [2625, 2626], [2631, 2632], [2635, 2637], [2672, 2673], [2689, 2690], [2748, 2748], [2753, 2757], [2759, 2760], [2765, 2765], [2786, 2787], [2817, 2817], [2876, 2876], [2879, 2879], [2881, 2883], [2893, 2893], [2902, 2902], [2946, 2946], [3008, 3008], [3021, 3021], [3134, 3136], [3142, 3144], [3146, 3149], [3157, 3158], [3260, 3260], [3263, 3263], [3270, 3270], [3276, 3277], [3298, 3299], [3393, 3395], [3405, 3405], [3530, 3530], [3538, 3540], [3542, 3542], [3633, 3633], [3636, 3642], [3655, 3662], [3761, 3761], [3764, 3769], [3771, 3772], [3784, 3789], [3864, 3865], [3893, 3893], [3895, 3895], [3897, 3897], [3953, 3966], [3968, 3972], [3974, 3975], [3984, 3991], [3993, 4028], [4038, 4038], [4141, 4144], [4146, 4146], [4150, 4151], [4153, 4153], [4184, 4185], [4448, 4607], [4959, 4959], [5906, 5908], [5938, 5940], [5970, 5971], [6002, 6003], [6068, 6069], [6071, 6077], [6086, 6086], [6089, 6099], [6109, 6109], [6155, 6157], [6313, 6313], [6432, 6434], [6439, 6440], [6450, 6450], [6457, 6459], [6679, 6680], [6912, 6915], [6964, 6964], [6966, 6970], [6972, 6972], [6978, 6978], [7019, 7027], [7616, 7626], [7678, 7679], [8203, 8207], [8234, 8238], [8288, 8291], [8298, 8303], [8400, 8431], [12330, 12335], [12441, 12442], [43014, 43014], [43019, 43019], [43045, 43046], [64286, 64286], [65024, 65039], [65056, 65059], [65279, 65279], [65529, 65531]]; var ac = [[68097, 68099], [68101, 68102], [68108, 68111], [68152, 68154], [68159, 68159], [119143, 119145], [119155, 119170], [119173, 119179], [119210, 119213], [119362, 119364], [917505, 917505], [917536, 917631], [917760, 917999]]; var se; function cc(s15, t) { let e = 0, i = t.length - 1, r; if (s15 < t[0][0] || s15 > t[i][1]) return false; for (; i >= e; ) if (r = e + i >> 1, s15 > t[r][1]) e = r + 1; else if (s15 < t[r][0]) i = r - 1; else return true; return false; } var fn = class { constructor() { this.version = "6"; if (!se) { se = new Uint8Array(65536), se.fill(1), se[0] = 0, se.fill(0, 1, 32), se.fill(0, 127, 160), se.fill(2, 4352, 4448), se[9001] = 2, se[9002] = 2, se.fill(2, 11904, 42192), se[12351] = 1, se.fill(2, 44032, 55204), se.fill(2, 63744, 64256), se.fill(2, 65040, 65050), se.fill(2, 65072, 65136), se.fill(2, 65280, 65377), se.fill(2, 65504, 65511); for (let t = 0; t < Os.length; ++t) se.fill(0, Os[t][0], Os[t][1] + 1); } } wcwidth(t) { return t < 32 ? 0 : t < 127 ? 1 : t < 65536 ? se[t] : cc(t, ac) ? 0 : t >= 131072 && t <= 196605 || t >= 196608 && t <= 262141 ? 2 : 1; } charProperties(t, e) { let i = this.wcwidth(t), r = i === 0 && e !== 0; if (r) { let n = Ae.extractWidth(e); n === 0 ? r = false : n > i && (i = n); } return Ae.createPropertyValue(0, i, r); } }; var Ae = class s13 { constructor() { this._providers = /* @__PURE__ */ Object.create(null); this._active = ""; this._onChange = new v(); this.onChange = this._onChange.event; let t = new fn(); this.register(t), this._active = t.version, this._activeProvider = t; } static extractShouldJoin(t) { return (t & 1) !== 0; } static extractWidth(t) { return t >> 1 & 3; } static extractCharKind(t) { return t >> 3; } static createPropertyValue(t, e, i = false) { return (t & 16777215) << 3 | (e & 3) << 1 | (i ? 1 : 0); } dispose() { this._onChange.dispose(); } get versions() { return Object.keys(this._providers); } get activeVersion() { return this._active; } set activeVersion(t) { if (!this._providers[t]) throw new Error(`unknown Unicode version "${t}"`); this._active = t, this._activeProvider = this._providers[t], this._onChange.fire(t); } register(t) { this._providers[t.version] = t; } wcwidth(t) { return this._activeProvider.wcwidth(t); } getStringCellWidth(t) { let e = 0, i = 0, r = t.length; for (let n = 0; n < r; ++n) { let o2 = t.charCodeAt(n); if (55296 <= o2 && o2 <= 56319) { if (++n >= r) return e + this.wcwidth(o2); let u = t.charCodeAt(n); 56320 <= u && u <= 57343 ? o2 = (o2 - 55296) * 1024 + u - 56320 + 65536 : e += this.wcwidth(u); } let l = this.charProperties(o2, i), a = s13.extractWidth(l); s13.extractShouldJoin(l) && (a -= s13.extractWidth(i)), e += a, i = l; } return e; } charProperties(t, e) { return this._activeProvider.charProperties(t, e); } }; var pn = class { constructor() { this.glevel = 0; this._charsets = []; } reset() { this.charset = void 0, this._charsets = [], this.glevel = 0; } setgLevel(t) { this.glevel = t, this.charset = this._charsets[t]; } setgCharset(t, e) { this._charsets[t] = e, this.glevel === t && (this.charset = e); } }; function Bs(s15) { var _a5; let e = (_a5 = s15.buffer.lines.get(s15.buffer.ybase + s15.buffer.y - 1)) == null ? void 0 : _a5.get(s15.cols - 1), i = s15.buffer.lines.get(s15.buffer.ybase + s15.buffer.y); i && e && (i.isWrapped = e[3] !== 0 && e[3] !== 32); } var Vi = 2147483647; var uc = 256; var ci = class s14 { constructor(t = 32, e = 32) { this.maxLength = t; this.maxSubParamsLength = e; if (e > uc) throw new Error("maxSubParamsLength must not be greater than 256"); this.params = new Int32Array(t), this.length = 0, this._subParams = new Int32Array(e), this._subParamsLength = 0, this._subParamsIdx = new Uint16Array(t), this._rejectDigits = false, this._rejectSubDigits = false, this._digitIsSub = false; } static fromArray(t) { let e = new s14(); if (!t.length) return e; for (let i = Array.isArray(t[0]) ? 1 : 0; i < t.length; ++i) { let r = t[i]; if (Array.isArray(r)) for (let n = 0; n < r.length; ++n) e.addSubParam(r[n]); else e.addParam(r); } return e; } clone() { let t = new s14(this.maxLength, this.maxSubParamsLength); return t.params.set(this.params), t.length = this.length, t._subParams.set(this._subParams), t._subParamsLength = this._subParamsLength, t._subParamsIdx.set(this._subParamsIdx), t._rejectDigits = this._rejectDigits, t._rejectSubDigits = this._rejectSubDigits, t._digitIsSub = this._digitIsSub, t; } toArray() { let t = []; for (let e = 0; e < this.length; ++e) { t.push(this.params[e]); let i = this._subParamsIdx[e] >> 8, r = this._subParamsIdx[e] & 255; r - i > 0 && t.push(Array.prototype.slice.call(this._subParams, i, r)); } return t; } reset() { this.length = 0, this._subParamsLength = 0, this._rejectDigits = false, this._rejectSubDigits = false, this._digitIsSub = false; } addParam(t) { if (this._digitIsSub = false, this.length >= this.maxLength) { this._rejectDigits = true; return; } if (t < -1) throw new Error("values lesser than -1 are not allowed"); this._subParamsIdx[this.length] = this._subParamsLength << 8 | this._subParamsLength, this.params[this.length++] = t > Vi ? Vi : t; } addSubParam(t) { if (this._digitIsSub = true, !!this.length) { if (this._rejectDigits || this._subParamsLength >= this.maxSubParamsLength) { this._rejectSubDigits = true; return; } if (t < -1) throw new Error("values lesser than -1 are not allowed"); this._subParams[this._subParamsLength++] = t > Vi ? Vi : t, this._subParamsIdx[this.length - 1]++; } } hasSubParams(t) { return (this._subParamsIdx[t] & 255) - (this._subParamsIdx[t] >> 8) > 0; } getSubParams(t) { let e = this._subParamsIdx[t] >> 8, i = this._subParamsIdx[t] & 255; return i - e > 0 ? this._subParams.subarray(e, i) : null; } getSubParamsAll() { let t = {}; for (let e = 0; e < this.length; ++e) { let i = this._subParamsIdx[e] >> 8, r = this._subParamsIdx[e] & 255; r - i > 0 && (t[e] = this._subParams.slice(i, r)); } return t; } addDigit(t) { let e; if (this._rejectDigits || !(e = this._digitIsSub ? this._subParamsLength : this.length) || this._digitIsSub && this._rejectSubDigits) return; let i = this._digitIsSub ? this._subParams : this.params, r = i[e - 1]; i[e - 1] = ~r ? Math.min(r * 10 + t, Vi) : t; } }; var qi = []; var mn = class { constructor() { this._state = 0; this._active = qi; this._id = -1; this._handlers = /* @__PURE__ */ Object.create(null); this._handlerFb = () => { }; this._stack = { paused: false, loopPosition: 0, fallThrough: false }; } registerHandler(t, e) { this._handlers[t] === void 0 && (this._handlers[t] = []); let i = this._handlers[t]; return i.push(e), { dispose: () => { let r = i.indexOf(e); r !== -1 && i.splice(r, 1); } }; } clearHandler(t) { this._handlers[t] && delete this._handlers[t]; } setHandlerFallback(t) { this._handlerFb = t; } dispose() { this._handlers = /* @__PURE__ */ Object.create(null), this._handlerFb = () => { }, this._active = qi; } reset() { if (this._state === 2) for (let t = this._stack.paused ? this._stack.loopPosition - 1 : this._active.length - 1; t >= 0; --t) this._active[t].end(false); this._stack.paused = false, this._active = qi, this._id = -1, this._state = 0; } _start() { if (this._active = this._handlers[this._id] || qi, !this._active.length) this._handlerFb(this._id, "START"); else for (let t = this._active.length - 1; t >= 0; t--) this._active[t].start(); } _put(t, e, i) { if (!this._active.length) this._handlerFb(this._id, "PUT", It(t, e, i)); else for (let r = this._active.length - 1; r >= 0; r--) this._active[r].put(t, e, i); } start() { this.reset(), this._state = 1; } put(t, e, i) { if (this._state !== 3) { if (this._state === 1) for (; e < i; ) { let r = t[e++]; if (r === 59) { this._state = 2, this._start(); break; } if (r < 48 || 57 < r) { this._state = 3; return; } this._id === -1 && (this._id = 0), this._id = this._id * 10 + r - 48; } this._state === 2 && i - e > 0 && this._put(t, e, i); } } end(t, e = true) { if (this._state !== 0) { if (this._state !== 3) if (this._state === 1 && this._start(), !this._active.length) this._handlerFb(this._id, "END", t); else { let i = false, r = this._active.length - 1, n = false; if (this._stack.paused && (r = this._stack.loopPosition - 1, i = e, n = this._stack.fallThrough, this._stack.paused = false), !n && i === false) { for (; r >= 0 && (i = this._active[r].end(t), i !== true); r--) if (i instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = r, this._stack.fallThrough = false, i; r--; } for (; r >= 0; r--) if (i = this._active[r].end(false), i instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = r, this._stack.fallThrough = true, i; } this._active = qi, this._id = -1, this._state = 0; } } }; var pe = class { constructor(t) { this._handler = t; this._data = ""; this._hitLimit = false; } start() { this._data = "", this._hitLimit = false; } put(t, e, i) { this._hitLimit || (this._data += It(t, e, i), this._data.length > 1e7 && (this._data = "", this._hitLimit = true)); } end(t) { let e = false; if (this._hitLimit) e = false; else if (t && (e = this._handler(this._data), e instanceof Promise)) return e.then((i) => (this._data = "", this._hitLimit = false, i)); return this._data = "", this._hitLimit = false, e; } }; var Yi = []; var _n = class { constructor() { this._handlers = /* @__PURE__ */ Object.create(null); this._active = Yi; this._ident = 0; this._handlerFb = () => { }; this._stack = { paused: false, loopPosition: 0, fallThrough: false }; } dispose() { this._handlers = /* @__PURE__ */ Object.create(null), this._handlerFb = () => { }, this._active = Yi; } registerHandler(t, e) { this._handlers[t] === void 0 && (this._handlers[t] = []); let i = this._handlers[t]; return i.push(e), { dispose: () => { let r = i.indexOf(e); r !== -1 && i.splice(r, 1); } }; } clearHandler(t) { this._handlers[t] && delete this._handlers[t]; } setHandlerFallback(t) { this._handlerFb = t; } reset() { if (this._active.length) for (let t = this._stack.paused ? this._stack.loopPosition - 1 : this._active.length - 1; t >= 0; --t) this._active[t].unhook(false); this._stack.paused = false, this._active = Yi, this._ident = 0; } hook(t, e) { if (this.reset(), this._ident = t, this._active = this._handlers[t] || Yi, !this._active.length) this._handlerFb(this._ident, "HOOK", e); else for (let i = this._active.length - 1; i >= 0; i--) this._active[i].hook(e); } put(t, e, i) { if (!this._active.length) this._handlerFb(this._ident, "PUT", It(t, e, i)); else for (let r = this._active.length - 1; r >= 0; r--) this._active[r].put(t, e, i); } unhook(t, e = true) { if (!this._active.length) this._handlerFb(this._ident, "UNHOOK", t); else { let i = false, r = this._active.length - 1, n = false; if (this._stack.paused && (r = this._stack.loopPosition - 1, i = e, n = this._stack.fallThrough, this._stack.paused = false), !n && i === false) { for (; r >= 0 && (i = this._active[r].unhook(t), i !== true); r--) if (i instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = r, this._stack.fallThrough = false, i; r--; } for (; r >= 0; r--) if (i = this._active[r].unhook(false), i instanceof Promise) return this._stack.paused = true, this._stack.loopPosition = r, this._stack.fallThrough = true, i; } this._active = Yi, this._ident = 0; } }; var ji = new ci(); ji.addParam(0); var Xi = class { constructor(t) { this._handler = t; this._data = ""; this._params = ji; this._hitLimit = false; } hook(t) { this._params = t.length > 1 || t.params[0] ? t.clone() : ji, this._data = "", this._hitLimit = false; } put(t, e, i) { this._hitLimit || (this._data += It(t, e, i), this._data.length > 1e7 && (this._data = "", this._hitLimit = true)); } unhook(t) { let e = false; if (this._hitLimit) e = false; else if (t && (e = this._handler(this._data, this._params), e instanceof Promise)) return e.then((i) => (this._params = ji, this._data = "", this._hitLimit = false, i)); return this._params = ji, this._data = "", this._hitLimit = false, e; } }; var Fs = class { constructor(t) { this.table = new Uint8Array(t); } setDefault(t, e) { this.table.fill(t << 4 | e); } add(t, e, i, r) { this.table[e << 8 | t] = i << 4 | r; } addMany(t, e, i, r) { for (let n = 0; n < t.length; n++) this.table[e << 8 | t[n]] = i << 4 | r; } }; var ke = 160; var hc = (function() { let s15 = new Fs(4095), e = Array.apply(null, Array(256)).map((a, u) => u), i = (a, u) => e.slice(a, u), r = i(32, 127), n = i(0, 24); n.push(25), n.push.apply(n, i(28, 32)); let o2 = i(0, 14), l; s15.setDefault(1, 0), s15.addMany(r, 0, 2, 0); for (l in o2) s15.addMany([24, 26, 153, 154], l, 3, 0), s15.addMany(i(128, 144), l, 3, 0), s15.addMany(i(144, 152), l, 3, 0), s15.add(156, l, 0, 0), s15.add(27, l, 11, 1), s15.add(157, l, 4, 8), s15.addMany([152, 158, 159], l, 0, 7), s15.add(155, l, 11, 3), s15.add(144, l, 11, 9); return s15.addMany(n, 0, 3, 0), s15.addMany(n, 1, 3, 1), s15.add(127, 1, 0, 1), s15.addMany(n, 8, 0, 8), s15.addMany(n, 3, 3, 3), s15.add(127, 3, 0, 3), s15.addMany(n, 4, 3, 4), s15.add(127, 4, 0, 4), s15.addMany(n, 6, 3, 6), s15.addMany(n, 5, 3, 5), s15.add(127, 5, 0, 5), s15.addMany(n, 2, 3, 2), s15.add(127, 2, 0, 2), s15.add(93, 1, 4, 8), s15.addMany(r, 8, 5, 8), s15.add(127, 8, 5, 8), s15.addMany([156, 27, 24, 26, 7], 8, 6, 0), s15.addMany(i(28, 32), 8, 0, 8), s15.addMany([88, 94, 95], 1, 0, 7), s15.addMany(r, 7, 0, 7), s15.addMany(n, 7, 0, 7), s15.add(156, 7, 0, 0), s15.add(127, 7, 0, 7), s15.add(91, 1, 11, 3), s15.addMany(i(64, 127), 3, 7, 0), s15.addMany(i(48, 60), 3, 8, 4), s15.addMany([60, 61, 62, 63], 3, 9, 4), s15.addMany(i(48, 60), 4, 8, 4), s15.addMany(i(64, 127), 4, 7, 0), s15.addMany([60, 61, 62, 63], 4, 0, 6), s15.addMany(i(32, 64), 6, 0, 6), s15.add(127, 6, 0, 6), s15.addMany(i(64, 127), 6, 0, 0), s15.addMany(i(32, 48), 3, 9, 5), s15.addMany(i(32, 48), 5, 9, 5), s15.addMany(i(48, 64), 5, 0, 6), s15.addMany(i(64, 127), 5, 7, 0), s15.addMany(i(32, 48), 4, 9, 5), s15.addMany(i(32, 48), 1, 9, 2), s15.addMany(i(32, 48), 2, 9, 2), s15.addMany(i(48, 127), 2, 10, 0), s15.addMany(i(48, 80), 1, 10, 0), s15.addMany(i(81, 88), 1, 10, 0), s15.addMany([89, 90, 92], 1, 10, 0), s15.addMany(i(96, 127), 1, 10, 0), s15.add(80, 1, 11, 9), s15.addMany(n, 9, 0, 9), s15.add(127, 9, 0, 9), s15.addMany(i(28, 32), 9, 0, 9), s15.addMany(i(32, 48), 9, 9, 12), s15.addMany(i(48, 60), 9, 8, 10), s15.addMany([60, 61, 62, 63], 9, 9, 10), s15.addMany(n, 11, 0, 11), s15.addMany(i(32, 128), 11, 0, 11), s15.addMany(i(28, 32), 11, 0, 11), s15.addMany(n, 10, 0, 10), s15.add(127, 10, 0, 10), s15.addMany(i(28, 32), 10, 0, 10), s15.addMany(i(48, 60), 10, 8, 10), s15.addMany([60, 61, 62, 63], 10, 0, 11), s15.addMany(i(32, 48), 10, 9, 12), s15.addMany(n, 12, 0, 12), s15.add(127, 12, 0, 12), s15.addMany(i(28, 32), 12, 0, 12), s15.addMany(i(32, 48), 12, 9, 12), s15.addMany(i(48, 64), 12, 0, 11), s15.addMany(i(64, 127), 12, 12, 13), s15.addMany(i(64, 127), 10, 12, 13), s15.addMany(i(64, 127), 9, 12, 13), s15.addMany(n, 13, 13, 13), s15.addMany(r, 13, 13, 13), s15.add(127, 13, 0, 13), s15.addMany([27, 156, 24, 26], 13, 14, 0), s15.add(ke, 0, 2, 0), s15.add(ke, 8, 5, 8), s15.add(ke, 6, 0, 6), s15.add(ke, 11, 0, 11), s15.add(ke, 13, 13, 13), s15; })(); var bn = class extends D { constructor(e = hc) { super(); this._transitions = e; this._parseStack = { state: 0, handlers: [], handlerPos: 0, transition: 0, chunkPos: 0 }; this.initialState = 0, this.currentState = this.initialState, this._params = new ci(), this._params.addParam(0), this._collect = 0, this.precedingJoinState = 0, this._printHandlerFb = (i, r, n) => { }, this._executeHandlerFb = (i) => { }, this._csiHandlerFb = (i, r) => { }, this._escHandlerFb = (i) => { }, this._errorHandlerFb = (i) => i, this._printHandler = this._printHandlerFb, this._executeHandlers = /* @__PURE__ */ Object.create(null), this._csiHandlers = /* @__PURE__ */ Object.create(null), this._escHandlers = /* @__PURE__ */ Object.create(null), this._register(C(() => { this._csiHandlers = /* @__PURE__ */ Object.create(null), this._executeHandlers = /* @__PURE__ */ Object.create(null), this._escHandlers = /* @__PURE__ */ Object.create(null); })), this._oscParser = this._register(new mn()), this._dcsParser = this._register(new _n()), this._errorHandler = this._errorHandlerFb, this.registerEscHandler({ final: "\\" }, () => true); } _identifier(e, i = [64, 126]) { let r = 0; if (e.prefix) { if (e.prefix.length > 1) throw new Error("only one byte as prefix supported"); if (r = e.prefix.charCodeAt(0), r && 60 > r || r > 63) throw new Error("prefix must be in range 0x3c .. 0x3f"); } if (e.intermediates) { if (e.intermediates.length > 2) throw new Error("only two bytes as intermediates are supported"); for (let o2 = 0; o2 < e.intermediates.length; ++o2) { let l = e.intermediates.charCodeAt(o2); if (32 > l || l > 47) throw new Error("intermediate must be in range 0x20 .. 0x2f"); r <<= 8, r |= l; } } if (e.final.length !== 1) throw new Error("final must be a single byte"); let n = e.final.charCodeAt(0); if (i[0] > n || n > i[1]) throw new Error(`final must be in range ${i[0]} .. ${i[1]}`); return r <<= 8, r |= n, r; } identToString(e) { let i = []; for (; e; ) i.push(String.fromCharCode(e & 255)), e >>= 8; return i.reverse().join(""); } setPrintHandler(e) { this._printHandler = e; } clearPrintHandler() { this._printHandler = this._printHandlerFb; } registerEscHandler(e, i) { let r = this._identifier(e, [48, 126]); this._escHandlers[r] === void 0 && (this._escHandlers[r] = []); let n = this._escHandlers[r]; return n.push(i), { dispose: () => { let o2 = n.indexOf(i); o2 !== -1 && n.splice(o2, 1); } }; } clearEscHandler(e) { this._escHandlers[this._identifier(e, [48, 126])] && delete this._escHandlers[this._identifier(e, [48, 126])]; } setEscHandlerFallback(e) { this._escHandlerFb = e; } setExecuteHandler(e, i) { this._executeHandlers[e.charCodeAt(0)] = i; } clearExecuteHandler(e) { this._executeHandlers[e.charCodeAt(0)] && delete this._executeHandlers[e.charCodeAt(0)]; } setExecuteHandlerFallback(e) { this._executeHandlerFb = e; } registerCsiHandler(e, i) { let r = this._identifier(e); this._csiHandlers[r] === void 0 && (this._csiHandlers[r] = []); let n = this._csiHandlers[r]; return n.push(i), { dispose: () => { let o2 = n.indexOf(i); o2 !== -1 && n.splice(o2, 1); } }; } clearCsiHandler(e) { this._csiHandlers[this._identifier(e)] && delete this._csiHandlers[this._identifier(e)]; } setCsiHandlerFallback(e) { this._csiHandlerFb = e; } registerDcsHandler(e, i) { return this._dcsParser.registerHandler(this._identifier(e), i); } clearDcsHandler(e) { this._dcsParser.clearHandler(this._identifier(e)); } setDcsHandlerFallback(e) { this._dcsParser.setHandlerFallback(e); } registerOscHandler(e, i) { return this._oscParser.registerHandler(e, i); } clearOscHandler(e) { this._oscParser.clearHandler(e); } setOscHandlerFallback(e) { this._oscParser.setHandlerFallback(e); } setErrorHandler(e) { this._errorHandler = e; } clearErrorHandler() { this._errorHandler = this._errorHandlerFb; } reset() { this.currentState = this.initialState, this._oscParser.reset(), this._dcsParser.reset(), this._params.reset(), this._params.addParam(0), this._collect = 0, this.precedingJoinState = 0, this._parseStack.state !== 0 && (this._parseStack.state = 2, this._parseStack.handlers = []); } _preserveStack(e, i, r, n, o2) { this._parseStack.state = e, this._parseStack.handlers = i, this._parseStack.handlerPos = r, this._parseStack.transition = n, this._parseStack.chunkPos = o2; } parse(e, i, r) { let n = 0, o2 = 0, l = 0, a; if (this._parseStack.state) if (this._parseStack.state === 2) this._parseStack.state = 0, l = this._parseStack.chunkPos + 1; else { if (r === void 0 || this._parseStack.state === 1) throw this._parseStack.state = 1, new Error("improper continuation due to previous async handler, giving up parsing"); let u = this._parseStack.handlers, h2 = this._parseStack.handlerPos - 1; switch (this._parseStack.state) { case 3: if (r === false && h2 > -1) { for (; h2 >= 0 && (a = u[h2](this._params), a !== true); h2--) if (a instanceof Promise) return this._parseStack.handlerPos = h2, a; } this._parseStack.handlers = []; break; case 4: if (r === false && h2 > -1) { for (; h2 >= 0 && (a = u[h2](), a !== true); h2--) if (a instanceof Promise) return this._parseStack.handlerPos = h2, a; } this._parseStack.handlers = []; break; case 6: if (n = e[this._parseStack.chunkPos], a = this._dcsParser.unhook(n !== 24 && n !== 26, r), a) return a; n === 27 && (this._parseStack.transition |= 1), this._params.reset(), this._params.addParam(0), this._collect = 0; break; case 5: if (n = e[this._parseStack.chunkPos], a = this._oscParser.end(n !== 24 && n !== 26, r), a) return a; n === 27 && (this._parseStack.transition |= 1), this._params.reset(), this._params.addParam(0), this._collect = 0; break; } this._parseStack.state = 0, l = this._parseStack.chunkPos + 1, this.precedingJoinState = 0, this.currentState = this._parseStack.transition & 15; } for (let u = l; u < i; ++u) { switch (n = e[u], o2 = this._transitions.table[this.currentState << 8 | (n < 160 ? n : ke)], o2 >> 4) { case 2: for (let m = u + 1; ; ++m) { if (m >= i || (n = e[m]) < 32 || n > 126 && n < ke) { this._printHandler(e, u, m), u = m - 1; break; } if (++m >= i || (n = e[m]) < 32 || n > 126 && n < ke) { this._printHandler(e, u, m), u = m - 1; break; } if (++m >= i || (n = e[m]) < 32 || n > 126 && n < ke) { this._printHandler(e, u, m), u = m - 1; break; } if (++m >= i || (n = e[m]) < 32 || n > 126 && n < ke) { this._printHandler(e, u, m), u = m - 1; break; } } break; case 3: this._executeHandlers[n] ? this._executeHandlers[n]() : this._executeHandlerFb(n), this.precedingJoinState = 0; break; case 0: break; case 1: if (this._errorHandler({ position: u, code: n, currentState: this.currentState, collect: this._collect, params: this._params, abort: false }).abort) return; break; case 7: let c = this._csiHandlers[this._collect << 8 | n], d = c ? c.length - 1 : -1; for (; d >= 0 && (a = c[d](this._params), a !== true); d--) if (a instanceof Promise) return this._preserveStack(3, c, d, o2, u), a; d < 0 && this._csiHandlerFb(this._collect << 8 | n, this._params), this.precedingJoinState = 0; break; case 8: do switch (n) { case 59: this._params.addParam(0); break; case 58: this._params.addSubParam(-1); break; default: this._params.addDigit(n - 48); } while (++u < i && (n = e[u]) > 47 && n < 60); u--; break; case 9: this._collect <<= 8, this._collect |= n; break; case 10: let _2 = this._escHandlers[this._collect << 8 | n], p = _2 ? _2.length - 1 : -1; for (; p >= 0 && (a = _2[p](), a !== true); p--) if (a instanceof Promise) return this._preserveStack(4, _2, p, o2, u), a; p < 0 && this._escHandlerFb(this._collect << 8 | n), this.precedingJoinState = 0; break; case 11: this._params.reset(), this._params.addParam(0), this._collect = 0; break; case 12: this._dcsParser.hook(this._collect << 8 | n, this._params); break; case 13: for (let m = u + 1; ; ++m) if (m >= i || (n = e[m]) === 24 || n === 26 || n === 27 || n > 127 && n < ke) { this._dcsParser.put(e, u, m), u = m - 1; break; } break; case 14: if (a = this._dcsParser.unhook(n !== 24 && n !== 26), a) return this._preserveStack(6, [], 0, o2, u), a; n === 27 && (o2 |= 1), this._params.reset(), this._params.addParam(0), this._collect = 0, this.precedingJoinState = 0; break; case 4: this._oscParser.start(); break; case 5: for (let m = u + 1; ; m++) if (m >= i || (n = e[m]) < 32 || n > 127 && n < ke) { this._oscParser.put(e, u, m), u = m - 1; break; } break; case 6: if (a = this._oscParser.end(n !== 24 && n !== 26), a) return this._preserveStack(5, [], 0, o2, u), a; n === 27 && (o2 |= 1), this._params.reset(), this._params.addParam(0), this._collect = 0, this.precedingJoinState = 0; break; } this.currentState = o2 & 15; } } }; var dc = /^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/; var fc = /^[\da-f]+$/; function Ws(s15) { if (!s15) return; let t = s15.toLowerCase(); if (t.indexOf("rgb:") === 0) { t = t.slice(4); let e = dc.exec(t); if (e) { let i = e[1] ? 15 : e[4] ? 255 : e[7] ? 4095 : 65535; return [Math.round(parseInt(e[1] || e[4] || e[7] || e[10], 16) / i * 255), Math.round(parseInt(e[2] || e[5] || e[8] || e[11], 16) / i * 255), Math.round(parseInt(e[3] || e[6] || e[9] || e[12], 16) / i * 255)]; } } else if (t.indexOf("#") === 0 && (t = t.slice(1), fc.exec(t) && [3, 6, 9, 12].includes(t.length))) { let e = t.length / 3, i = [0, 0, 0]; for (let r = 0; r < 3; ++r) { let n = parseInt(t.slice(e * r, e * r + e), 16); i[r] = e === 1 ? n << 4 : e === 2 ? n : e === 3 ? n >> 4 : n >> 8; } return i; } } function Hs(s15, t) { let e = s15.toString(16), i = e.length < 2 ? "0" + e : e; switch (t) { case 4: return e[0]; case 8: return i; case 12: return (i + i).slice(0, 3); default: return i + i; } } function ml(s15, t = 16) { let [e, i, r] = s15; return `rgb:${Hs(e, t)}/${Hs(i, t)}/${Hs(r, t)}`; } var mc = { "(": 0, ")": 1, "*": 2, "+": 3, "-": 1, ".": 2 }; var ut = 131072; var _l = 10; function bl(s15, t) { if (s15 > 24) return t.setWinLines || false; switch (s15) { case 1: return !!t.restoreWin; case 2: return !!t.minimizeWin; case 3: return !!t.setWinPosition; case 4: return !!t.setWinSizePixels; case 5: return !!t.raiseWin; case 6: return !!t.lowerWin; case 7: return !!t.refreshWin; case 8: return !!t.setWinSizeChars; case 9: return !!t.maximizeWin; case 10: return !!t.fullscreenWin; case 11: return !!t.getWinState; case 13: return !!t.getWinPosition; case 14: return !!t.getWinSizePixels; case 15: return !!t.getScreenSizePixels; case 16: return !!t.getCellSizePixels; case 18: return !!t.getWinSizeChars; case 19: return !!t.getScreenSizeChars; case 20: return !!t.getIconTitle; case 21: return !!t.getWinTitle; case 22: return !!t.pushTitle; case 23: return !!t.popTitle; case 24: return !!t.setWinLines; } return false; } var vl = 5e3; var gl = 0; var vn = class extends D { constructor(e, i, r, n, o2, l, a, u, h2 = new bn()) { super(); this._bufferService = e; this._charsetService = i; this._coreService = r; this._logService = n; this._optionsService = o2; this._oscLinkService = l; this._coreMouseService = a; this._unicodeService = u; this._parser = h2; this._parseBuffer = new Uint32Array(4096); this._stringDecoder = new er(); this._utf8Decoder = new tr(); this._windowTitle = ""; this._iconName = ""; this._windowTitleStack = []; this._iconNameStack = []; this._curAttrData = X.clone(); this._eraseAttrDataInternal = X.clone(); this._onRequestBell = this._register(new v()); this.onRequestBell = this._onRequestBell.event; this._onRequestRefreshRows = this._register(new v()); this.onRequestRefreshRows = this._onRequestRefreshRows.event; this._onRequestReset = this._register(new v()); this.onRequestReset = this._onRequestReset.event; this._onRequestSendFocus = this._register(new v()); this.onRequestSendFocus = this._onRequestSendFocus.event; this._onRequestSyncScrollBar = this._register(new v()); this.onRequestSyncScrollBar = this._onRequestSyncScrollBar.event; this._onRequestWindowsOptionsReport = this._register(new v()); this.onRequestWindowsOptionsReport = this._onRequestWindowsOptionsReport.event; this._onA11yChar = this._register(new v()); this.onA11yChar = this._onA11yChar.event; this._onA11yTab = this._register(new v()); this.onA11yTab = this._onA11yTab.event; this._onCursorMove = this._register(new v()); this.onCursorMove = this._onCursorMove.event; this._onLineFeed = this._register(new v()); this.onLineFeed = this._onLineFeed.event; this._onScroll = this._register(new v()); this.onScroll = this._onScroll.event; this._onTitleChange = this._register(new v()); this.onTitleChange = this._onTitleChange.event; this._onColor = this._register(new v()); this.onColor = this._onColor.event; this._parseStack = { paused: false, cursorStartX: 0, cursorStartY: 0, decodedLength: 0, position: 0 }; this._specialColors = [256, 257, 258]; this._register(this._parser), this._dirtyRowTracker = new Zi(this._bufferService), this._activeBuffer = this._bufferService.buffer, this._register(this._bufferService.buffers.onBufferActivate((c) => this._activeBuffer = c.activeBuffer)), this._parser.setCsiHandlerFallback((c, d) => { this._logService.debug("Unknown CSI code: ", { identifier: this._parser.identToString(c), params: d.toArray() }); }), this._parser.setEscHandlerFallback((c) => { this._logService.debug("Unknown ESC code: ", { identifier: this._parser.identToString(c) }); }), this._parser.setExecuteHandlerFallback((c) => { this._logService.debug("Unknown EXECUTE code: ", { code: c }); }), this._parser.setOscHandlerFallback((c, d, _2) => { this._logService.debug("Unknown OSC code: ", { identifier: c, action: d, data: _2 }); }), this._parser.setDcsHandlerFallback((c, d, _2) => { d === "HOOK" && (_2 = _2.toArray()), this._logService.debug("Unknown DCS code: ", { identifier: this._parser.identToString(c), action: d, payload: _2 }); }), this._parser.setPrintHandler((c, d, _2) => this.print(c, d, _2)), this._parser.registerCsiHandler({ final: "@" }, (c) => this.insertChars(c)), this._parser.registerCsiHandler({ intermediates: " ", final: "@" }, (c) => this.scrollLeft(c)), this._parser.registerCsiHandler({ final: "A" }, (c) => this.cursorUp(c)), this._parser.registerCsiHandler({ intermediates: " ", final: "A" }, (c) => this.scrollRight(c)), this._parser.registerCsiHandler({ final: "B" }, (c) => this.cursorDown(c)), this._parser.registerCsiHandler({ final: "C" }, (c) => this.cursorForward(c)), this._parser.registerCsiHandler({ final: "D" }, (c) => this.cursorBackward(c)), this._parser.registerCsiHandler({ final: "E" }, (c) => this.cursorNextLine(c)), this._parser.registerCsiHandler({ final: "F" }, (c) => this.cursorPrecedingLine(c)), this._parser.registerCsiHandler({ final: "G" }, (c) => this.cursorCharAbsolute(c)), this._parser.registerCsiHandler({ final: "H" }, (c) => this.cursorPosition(c)), this._parser.registerCsiHandler({ final: "I" }, (c) => this.cursorForwardTab(c)), this._parser.registerCsiHandler({ final: "J" }, (c) => this.eraseInDisplay(c, false)), this._parser.registerCsiHandler({ prefix: "?", final: "J" }, (c) => this.eraseInDisplay(c, true)), this._parser.registerCsiHandler({ final: "K" }, (c) => this.eraseInLine(c, false)), this._parser.registerCsiHandler({ prefix: "?", final: "K" }, (c) => this.eraseInLine(c, true)), this._parser.registerCsiHandler({ final: "L" }, (c) => this.insertLines(c)), this._parser.registerCsiHandler({ final: "M" }, (c) => this.deleteLines(c)), this._parser.registerCsiHandler({ final: "P" }, (c) => this.deleteChars(c)), this._parser.registerCsiHandler({ final: "S" }, (c) => this.scrollUp(c)), this._parser.registerCsiHandler({ final: "T" }, (c) => this.scrollDown(c)), this._parser.registerCsiHandler({ final: "X" }, (c) => this.eraseChars(c)), this._parser.registerCsiHandler({ final: "Z" }, (c) => this.cursorBackwardTab(c)), this._parser.registerCsiHandler({ final: "`" }, (c) => this.charPosAbsolute(c)), this._parser.registerCsiHandler({ final: "a" }, (c) => this.hPositionRelative(c)), this._parser.registerCsiHandler({ final: "b" }, (c) => this.repeatPrecedingCharacter(c)), this._parser.registerCsiHandler({ final: "c" }, (c) => this.sendDeviceAttributesPrimary(c)), this._parser.registerCsiHandler({ prefix: ">", final: "c" }, (c) => this.sendDeviceAttributesSecondary(c)), this._parser.registerCsiHandler({ final: "d" }, (c) => this.linePosAbsolute(c)), this._parser.registerCsiHandler({ final: "e" }, (c) => this.vPositionRelative(c)), this._parser.registerCsiHandler({ final: "f" }, (c) => this.hVPosition(c)), this._parser.registerCsiHandler({ final: "g" }, (c) => this.tabClear(c)), this._parser.registerCsiHandler({ final: "h" }, (c) => this.setMode(c)), this._parser.registerCsiHandler({ prefix: "?", final: "h" }, (c) => this.setModePrivate(c)), this._parser.registerCsiHandler({ final: "l" }, (c) => this.resetMode(c)), this._parser.registerCsiHandler({ prefix: "?", final: "l" }, (c) => this.resetModePrivate(c)), this._parser.registerCsiHandler({ final: "m" }, (c) => this.charAttributes(c)), this._parser.registerCsiHandler({ final: "n" }, (c) => this.deviceStatus(c)), this._parser.registerCsiHandler({ prefix: "?", final: "n" }, (c) => this.deviceStatusPrivate(c)), this._parser.registerCsiHandler({ intermediates: "!", final: "p" }, (c) => this.softReset(c)), this._parser.registerCsiHandler({ intermediates: " ", final: "q" }, (c) => this.setCursorStyle(c)), this._parser.registerCsiHandler({ final: "r" }, (c) => this.setScrollRegion(c)), this._parser.registerCsiHandler({ final: "s" }, (c) => this.saveCursor(c)), this._parser.registerCsiHandler({ final: "t" }, (c) => this.windowOptions(c)), this._parser.registerCsiHandler({ final: "u" }, (c) => this.restoreCursor(c)), this._parser.registerCsiHandler({ intermediates: "'", final: "}" }, (c) => this.insertColumns(c)), this._parser.registerCsiHandler({ intermediates: "'", final: "~" }, (c) => this.deleteColumns(c)), this._parser.registerCsiHandler({ intermediates: '"', final: "q" }, (c) => this.selectProtected(c)), this._parser.registerCsiHandler({ intermediates: "$", final: "p" }, (c) => this.requestMode(c, true)), this._parser.registerCsiHandler({ prefix: "?", intermediates: "$", final: "p" }, (c) => this.requestMode(c, false)), this._parser.setExecuteHandler(b.BEL, () => this.bell()), this._parser.setExecuteHandler(b.LF, () => this.lineFeed()), this._parser.setExecuteHandler(b.VT, () => this.lineFeed()), this._parser.setExecuteHandler(b.FF, () => this.lineFeed()), this._parser.setExecuteHandler(b.CR, () => this.carriageReturn()), this._parser.setExecuteHandler(b.BS, () => this.backspace()), this._parser.setExecuteHandler(b.HT, () => this.tab()), this._parser.setExecuteHandler(b.SO, () => this.shiftOut()), this._parser.setExecuteHandler(b.SI, () => this.shiftIn()), this._parser.setExecuteHandler(Ai.IND, () => this.index()), this._parser.setExecuteHandler(Ai.NEL, () => this.nextLine()), this._parser.setExecuteHandler(Ai.HTS, () => this.tabSet()), this._parser.registerOscHandler(0, new pe((c) => (this.setTitle(c), this.setIconName(c), true))), this._parser.registerOscHandler(1, new pe((c) => this.setIconName(c))), this._parser.registerOscHandler(2, new pe((c) => this.setTitle(c))), this._parser.registerOscHandler(4, new pe((c) => this.setOrReportIndexedColor(c))), this._parser.registerOscHandler(8, new pe((c) => this.setHyperlink(c))), this._parser.registerOscHandler(10, new pe((c) => this.setOrReportFgColor(c))), this._parser.registerOscHandler(11, new pe((c) => this.setOrReportBgColor(c))), this._parser.registerOscHandler(12, new pe((c) => this.setOrReportCursorColor(c))), this._parser.registerOscHandler(104, new pe((c) => this.restoreIndexedColor(c))), this._parser.registerOscHandler(110, new pe((c) => this.restoreFgColor(c))), this._parser.registerOscHandler(111, new pe((c) => this.restoreBgColor(c))), this._parser.registerOscHandler(112, new pe((c) => this.restoreCursorColor(c))), this._parser.registerEscHandler({ final: "7" }, () => this.saveCursor()), this._parser.registerEscHandler({ final: "8" }, () => this.restoreCursor()), this._parser.registerEscHandler({ final: "D" }, () => this.index()), this._parser.registerEscHandler({ final: "E" }, () => this.nextLine()), this._parser.registerEscHandler({ final: "H" }, () => this.tabSet()), this._parser.registerEscHandler({ final: "M" }, () => this.reverseIndex()), this._parser.registerEscHandler({ final: "=" }, () => this.keypadApplicationMode()), this._parser.registerEscHandler({ final: ">" }, () => this.keypadNumericMode()), this._parser.registerEscHandler({ final: "c" }, () => this.fullReset()), this._parser.registerEscHandler({ final: "n" }, () => this.setgLevel(2)), this._parser.registerEscHandler({ final: "o" }, () => this.setgLevel(3)), this._parser.registerEscHandler({ final: "|" }, () => this.setgLevel(3)), this._parser.registerEscHandler({ final: "}" }, () => this.setgLevel(2)), this._parser.registerEscHandler({ final: "~" }, () => this.setgLevel(1)), this._parser.registerEscHandler({ intermediates: "%", final: "@" }, () => this.selectDefaultCharset()), this._parser.registerEscHandler({ intermediates: "%", final: "G" }, () => this.selectDefaultCharset()); for (let c in ne) this._parser.registerEscHandler({ intermediates: "(", final: c }, () => this.selectCharset("(" + c)), this._parser.registerEscHandler({ intermediates: ")", final: c }, () => this.selectCharset(")" + c)), this._parser.registerEscHandler({ intermediates: "*", final: c }, () => this.selectCharset("*" + c)), this._parser.registerEscHandler({ intermediates: "+", final: c }, () => this.selectCharset("+" + c)), this._parser.registerEscHandler({ intermediates: "-", final: c }, () => this.selectCharset("-" + c)), this._parser.registerEscHandler({ intermediates: ".", final: c }, () => this.selectCharset("." + c)), this._parser.registerEscHandler({ intermediates: "/", final: c }, () => this.selectCharset("/" + c)); this._parser.registerEscHandler({ intermediates: "#", final: "8" }, () => this.screenAlignmentPattern()), this._parser.setErrorHandler((c) => (this._logService.error("Parsing error: ", c), c)), this._parser.registerDcsHandler({ intermediates: "$", final: "q" }, new Xi((c, d) => this.requestStatusString(c, d))); } getAttrData() { return this._curAttrData; } _preserveStack(e, i, r, n) { this._parseStack.paused = true, this._parseStack.cursorStartX = e, this._parseStack.cursorStartY = i, this._parseStack.decodedLength = r, this._parseStack.position = n; } _logSlowResolvingAsync(e) { this._logService.logLevel <= 3 && Promise.race([e, new Promise((i, r) => setTimeout(() => r("#SLOW_TIMEOUT"), vl))]).catch((i) => { if (i !== "#SLOW_TIMEOUT") throw i; console.warn(`async parser handler taking longer than ${vl} ms`); }); } _getCurrentLinkId() { return this._curAttrData.extended.urlId; } parse(e, i) { let r, n = this._activeBuffer.x, o2 = this._activeBuffer.y, l = 0, a = this._parseStack.paused; if (a) { if (r = this._parser.parse(this._parseBuffer, this._parseStack.decodedLength, i)) return this._logSlowResolvingAsync(r), r; n = this._parseStack.cursorStartX, o2 = this._parseStack.cursorStartY, this._parseStack.paused = false, e.length > ut && (l = this._parseStack.position + ut); } if (this._logService.logLevel <= 1 && this._logService.debug(`parsing data ${typeof e == "string" ? ` "${e}"` : ` "${Array.prototype.map.call(e, (c) => String.fromCharCode(c)).join("")}"`}`), this._logService.logLevel === 0 && this._logService.trace("parsing data (codes)", typeof e == "string" ? e.split("").map((c) => c.charCodeAt(0)) : e), this._parseBuffer.length < e.length && this._parseBuffer.length < ut && (this._parseBuffer = new Uint32Array(Math.min(e.length, ut))), a || this._dirtyRowTracker.clearRange(), e.length > ut) for (let c = l; c < e.length; c += ut) { let d = c + ut < e.length ? c + ut : e.length, _2 = typeof e == "string" ? this._stringDecoder.decode(e.substring(c, d), this._parseBuffer) : this._utf8Decoder.decode(e.subarray(c, d), this._parseBuffer); if (r = this._parser.parse(this._parseBuffer, _2)) return this._preserveStack(n, o2, _2, c), this._logSlowResolvingAsync(r), r; } else if (!a) { let c = typeof e == "string" ? this._stringDecoder.decode(e, this._parseBuffer) : this._utf8Decoder.decode(e, this._parseBuffer); if (r = this._parser.parse(this._parseBuffer, c)) return this._preserveStack(n, o2, c, 0), this._logSlowResolvingAsync(r), r; } (this._activeBuffer.x !== n || this._activeBuffer.y !== o2) && this._onCursorMove.fire(); let u = this._dirtyRowTracker.end + (this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp), h2 = this._dirtyRowTracker.start + (this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp); h2 < this._bufferService.rows && this._onRequestRefreshRows.fire({ start: Math.min(h2, this._bufferService.rows - 1), end: Math.min(u, this._bufferService.rows - 1) }); } print(e, i, r) { let n, o2, l = this._charsetService.charset, a = this._optionsService.rawOptions.screenReaderMode, u = this._bufferService.cols, h2 = this._coreService.decPrivateModes.wraparound, c = this._coreService.modes.insertMode, d = this._curAttrData, _2 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y); this._dirtyRowTracker.markDirty(this._activeBuffer.y), this._activeBuffer.x && r - i > 0 && _2.getWidth(this._activeBuffer.x - 1) === 2 && _2.setCellFromCodepoint(this._activeBuffer.x - 1, 0, 1, d); let p = this._parser.precedingJoinState; for (let m = i; m < r; ++m) { if (n = e[m], n < 127 && l) { let O = l[String.fromCharCode(n)]; O && (n = O.charCodeAt(0)); } let f = this._unicodeService.charProperties(n, p); o2 = Ae.extractWidth(f); let A = Ae.extractShouldJoin(f), R = A ? Ae.extractWidth(p) : 0; if (p = f, a && this._onA11yChar.fire(Ce(n)), this._getCurrentLinkId() && this._oscLinkService.addLineToLink(this._getCurrentLinkId(), this._activeBuffer.ybase + this._activeBuffer.y), this._activeBuffer.x + o2 - R > u) { if (h2) { let O = _2, I = this._activeBuffer.x - R; for (this._activeBuffer.x = R, this._activeBuffer.y++, this._activeBuffer.y === this._activeBuffer.scrollBottom + 1 ? (this._activeBuffer.y--, this._bufferService.scroll(this._eraseAttrData(), true)) : (this._activeBuffer.y >= this._bufferService.rows && (this._activeBuffer.y = this._bufferService.rows - 1), this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y).isWrapped = true), _2 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y), R > 0 && _2 instanceof Ze && _2.copyCellsFrom(O, I, 0, R, false); I < u; ) O.setCellFromCodepoint(I++, 0, 1, d); } else if (this._activeBuffer.x = u - 1, o2 === 2) continue; } if (A && this._activeBuffer.x) { let O = _2.getWidth(this._activeBuffer.x - 1) ? 1 : 2; _2.addCodepointToCell(this._activeBuffer.x - O, n, o2); for (let I = o2 - R; --I >= 0; ) _2.setCellFromCodepoint(this._activeBuffer.x++, 0, 0, d); continue; } if (c && (_2.insertCells(this._activeBuffer.x, o2 - R, this._activeBuffer.getNullCell(d)), _2.getWidth(u - 1) === 2 && _2.setCellFromCodepoint(u - 1, 0, 1, d)), _2.setCellFromCodepoint(this._activeBuffer.x++, n, o2, d), o2 > 0) for (; --o2; ) _2.setCellFromCodepoint(this._activeBuffer.x++, 0, 0, d); } this._parser.precedingJoinState = p, this._activeBuffer.x < u && r - i > 0 && _2.getWidth(this._activeBuffer.x) === 0 && !_2.hasContent(this._activeBuffer.x) && _2.setCellFromCodepoint(this._activeBuffer.x, 0, 1, d), this._dirtyRowTracker.markDirty(this._activeBuffer.y); } registerCsiHandler(e, i) { return e.final === "t" && !e.prefix && !e.intermediates ? this._parser.registerCsiHandler(e, (r) => bl(r.params[0], this._optionsService.rawOptions.windowOptions) ? i(r) : true) : this._parser.registerCsiHandler(e, i); } registerDcsHandler(e, i) { return this._parser.registerDcsHandler(e, new Xi(i)); } registerEscHandler(e, i) { return this._parser.registerEscHandler(e, i); } registerOscHandler(e, i) { return this._parser.registerOscHandler(e, new pe(i)); } bell() { return this._onRequestBell.fire(), true; } lineFeed() { return this._dirtyRowTracker.markDirty(this._activeBuffer.y), this._optionsService.rawOptions.convertEol && (this._activeBuffer.x = 0), this._activeBuffer.y++, this._activeBuffer.y === this._activeBuffer.scrollBottom + 1 ? (this._activeBuffer.y--, this._bufferService.scroll(this._eraseAttrData())) : this._activeBuffer.y >= this._bufferService.rows ? this._activeBuffer.y = this._bufferService.rows - 1 : this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y).isWrapped = false, this._activeBuffer.x >= this._bufferService.cols && this._activeBuffer.x--, this._dirtyRowTracker.markDirty(this._activeBuffer.y), this._onLineFeed.fire(), true; } carriageReturn() { return this._activeBuffer.x = 0, true; } backspace() { var _a5; if (!this._coreService.decPrivateModes.reverseWraparound) return this._restrictCursor(), this._activeBuffer.x > 0 && this._activeBuffer.x--, true; if (this._restrictCursor(this._bufferService.cols), this._activeBuffer.x > 0) this._activeBuffer.x--; else if (this._activeBuffer.x === 0 && this._activeBuffer.y > this._activeBuffer.scrollTop && this._activeBuffer.y <= this._activeBuffer.scrollBottom && ((_a5 = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)) == null ? void 0 : _a5.isWrapped)) { this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y).isWrapped = false, this._activeBuffer.y--, this._activeBuffer.x = this._bufferService.cols - 1; let e = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y); e.hasWidth(this._activeBuffer.x) && !e.hasContent(this._activeBuffer.x) && this._activeBuffer.x--; } return this._restrictCursor(), true; } tab() { if (this._activeBuffer.x >= this._bufferService.cols) return true; let e = this._activeBuffer.x; return this._activeBuffer.x = this._activeBuffer.nextStop(), this._optionsService.rawOptions.screenReaderMode && this._onA11yTab.fire(this._activeBuffer.x - e), true; } shiftOut() { return this._charsetService.setgLevel(1), true; } shiftIn() { return this._charsetService.setgLevel(0), true; } _restrictCursor(e = this._bufferService.cols - 1) { this._activeBuffer.x = Math.min(e, Math.max(0, this._activeBuffer.x)), this._activeBuffer.y = this._coreService.decPrivateModes.origin ? Math.min(this._activeBuffer.scrollBottom, Math.max(this._activeBuffer.scrollTop, this._activeBuffer.y)) : Math.min(this._bufferService.rows - 1, Math.max(0, this._activeBuffer.y)), this._dirtyRowTracker.markDirty(this._activeBuffer.y); } _setCursor(e, i) { this._dirtyRowTracker.markDirty(this._activeBuffer.y), this._coreService.decPrivateModes.origin ? (this._activeBuffer.x = e, this._activeBuffer.y = this._activeBuffer.scrollTop + i) : (this._activeBuffer.x = e, this._activeBuffer.y = i), this._restrictCursor(), this._dirtyRowTracker.markDirty(this._activeBuffer.y); } _moveCursor(e, i) { this._restrictCursor(), this._setCursor(this._activeBuffer.x + e, this._activeBuffer.y + i); } cursorUp(e) { let i = this._activeBuffer.y - this._activeBuffer.scrollTop; return i >= 0 ? this._moveCursor(0, -Math.min(i, e.params[0] || 1)) : this._moveCursor(0, -(e.params[0] || 1)), true; } cursorDown(e) { let i = this._activeBuffer.scrollBottom - this._activeBuffer.y; return i >= 0 ? this._moveCursor(0, Math.min(i, e.params[0] || 1)) : this._moveCursor(0, e.params[0] || 1), true; } cursorForward(e) { return this._moveCursor(e.params[0] || 1, 0), true; } cursorBackward(e) { return this._moveCursor(-(e.params[0] || 1), 0), true; } cursorNextLine(e) { return this.cursorDown(e), this._activeBuffer.x = 0, true; } cursorPrecedingLine(e) { return this.cursorUp(e), this._activeBuffer.x = 0, true; } cursorCharAbsolute(e) { return this._setCursor((e.params[0] || 1) - 1, this._activeBuffer.y), true; } cursorPosition(e) { return this._setCursor(e.length >= 2 ? (e.params[1] || 1) - 1 : 0, (e.params[0] || 1) - 1), true; } charPosAbsolute(e) { return this._setCursor((e.params[0] || 1) - 1, this._activeBuffer.y), true; } hPositionRelative(e) { return this._moveCursor(e.params[0] || 1, 0), true; } linePosAbsolute(e) { return this._setCursor(this._activeBuffer.x, (e.params[0] || 1) - 1), true; } vPositionRelative(e) { return this._moveCursor(0, e.params[0] || 1), true; } hVPosition(e) { return this.cursorPosition(e), true; } tabClear(e) { let i = e.params[0]; return i === 0 ? delete this._activeBuffer.tabs[this._activeBuffer.x] : i === 3 && (this._activeBuffer.tabs = {}), true; } cursorForwardTab(e) { if (this._activeBuffer.x >= this._bufferService.cols) return true; let i = e.params[0] || 1; for (; i--; ) this._activeBuffer.x = this._activeBuffer.nextStop(); return true; } cursorBackwardTab(e) { if (this._activeBuffer.x >= this._bufferService.cols) return true; let i = e.params[0] || 1; for (; i--; ) this._activeBuffer.x = this._activeBuffer.prevStop(); return true; } selectProtected(e) { let i = e.params[0]; return i === 1 && (this._curAttrData.bg |= 536870912), (i === 2 || i === 0) && (this._curAttrData.bg &= -536870913), true; } _eraseInBufferLine(e, i, r, n = false, o2 = false) { let l = this._activeBuffer.lines.get(this._activeBuffer.ybase + e); l.replaceCells(i, r, this._activeBuffer.getNullCell(this._eraseAttrData()), o2), n && (l.isWrapped = false); } _resetBufferLine(e, i = false) { let r = this._activeBuffer.lines.get(this._activeBuffer.ybase + e); r && (r.fill(this._activeBuffer.getNullCell(this._eraseAttrData()), i), this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase + e), r.isWrapped = false); } eraseInDisplay(e, i = false) { var _a5; this._restrictCursor(this._bufferService.cols); let r; switch (e.params[0]) { case 0: for (r = this._activeBuffer.y, this._dirtyRowTracker.markDirty(r), this._eraseInBufferLine(r++, this._activeBuffer.x, this._bufferService.cols, this._activeBuffer.x === 0, i); r < this._bufferService.rows; r++) this._resetBufferLine(r, i); this._dirtyRowTracker.markDirty(r); break; case 1: for (r = this._activeBuffer.y, this._dirtyRowTracker.markDirty(r), this._eraseInBufferLine(r, 0, this._activeBuffer.x + 1, true, i), this._activeBuffer.x + 1 >= this._bufferService.cols && (this._activeBuffer.lines.get(r + 1).isWrapped = false); r--; ) this._resetBufferLine(r, i); this._dirtyRowTracker.markDirty(0); break; case 2: if (this._optionsService.rawOptions.scrollOnEraseInDisplay) { for (r = this._bufferService.rows, this._dirtyRowTracker.markRangeDirty(0, r - 1); r-- && !((_a5 = this._activeBuffer.lines.get(this._activeBuffer.ybase + r)) == null ? void 0 : _a5.getTrimmedLength()); ) ; for (; r >= 0; r--) this._bufferService.scroll(this._eraseAttrData()); } else { for (r = this._bufferService.rows, this._dirtyRowTracker.markDirty(r - 1); r--; ) this._resetBufferLine(r, i); this._dirtyRowTracker.markDirty(0); } break; case 3: let n = this._activeBuffer.lines.length - this._bufferService.rows; n > 0 && (this._activeBuffer.lines.trimStart(n), this._activeBuffer.ybase = Math.max(this._activeBuffer.ybase - n, 0), this._activeBuffer.ydisp = Math.max(this._activeBuffer.ydisp - n, 0), this._onScroll.fire(0)); break; } return true; } eraseInLine(e, i = false) { switch (this._restrictCursor(this._bufferService.cols), e.params[0]) { case 0: this._eraseInBufferLine(this._activeBuffer.y, this._activeBuffer.x, this._bufferService.cols, this._activeBuffer.x === 0, i); break; case 1: this._eraseInBufferLine(this._activeBuffer.y, 0, this._activeBuffer.x + 1, false, i); break; case 2: this._eraseInBufferLine(this._activeBuffer.y, 0, this._bufferService.cols, true, i); break; } return this._dirtyRowTracker.markDirty(this._activeBuffer.y), true; } insertLines(e) { this._restrictCursor(); let i = e.params[0] || 1; if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true; let r = this._activeBuffer.ybase + this._activeBuffer.y, n = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom, o2 = this._bufferService.rows - 1 + this._activeBuffer.ybase - n + 1; for (; i--; ) this._activeBuffer.lines.splice(o2 - 1, 1), this._activeBuffer.lines.splice(r, 0, this._activeBuffer.getBlankLine(this._eraseAttrData())); return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom), this._activeBuffer.x = 0, true; } deleteLines(e) { this._restrictCursor(); let i = e.params[0] || 1; if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true; let r = this._activeBuffer.ybase + this._activeBuffer.y, n; for (n = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom, n = this._bufferService.rows - 1 + this._activeBuffer.ybase - n; i--; ) this._activeBuffer.lines.splice(r, 1), this._activeBuffer.lines.splice(n, 0, this._activeBuffer.getBlankLine(this._eraseAttrData())); return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom), this._activeBuffer.x = 0, true; } insertChars(e) { this._restrictCursor(); let i = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y); return i && (i.insertCells(this._activeBuffer.x, e.params[0] || 1, this._activeBuffer.getNullCell(this._eraseAttrData())), this._dirtyRowTracker.markDirty(this._activeBuffer.y)), true; } deleteChars(e) { this._restrictCursor(); let i = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y); return i && (i.deleteCells(this._activeBuffer.x, e.params[0] || 1, this._activeBuffer.getNullCell(this._eraseAttrData())), this._dirtyRowTracker.markDirty(this._activeBuffer.y)), true; } scrollUp(e) { let i = e.params[0] || 1; for (; i--; ) this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollTop, 1), this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollBottom, 0, this._activeBuffer.getBlankLine(this._eraseAttrData())); return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true; } scrollDown(e) { let i = e.params[0] || 1; for (; i--; ) this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollBottom, 1), this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollTop, 0, this._activeBuffer.getBlankLine(X)); return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true; } scrollLeft(e) { if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true; let i = e.params[0] || 1; for (let r = this._activeBuffer.scrollTop; r <= this._activeBuffer.scrollBottom; ++r) { let n = this._activeBuffer.lines.get(this._activeBuffer.ybase + r); n.deleteCells(0, i, this._activeBuffer.getNullCell(this._eraseAttrData())), n.isWrapped = false; } return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true; } scrollRight(e) { if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true; let i = e.params[0] || 1; for (let r = this._activeBuffer.scrollTop; r <= this._activeBuffer.scrollBottom; ++r) { let n = this._activeBuffer.lines.get(this._activeBuffer.ybase + r); n.insertCells(0, i, this._activeBuffer.getNullCell(this._eraseAttrData())), n.isWrapped = false; } return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true; } insertColumns(e) { if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true; let i = e.params[0] || 1; for (let r = this._activeBuffer.scrollTop; r <= this._activeBuffer.scrollBottom; ++r) { let n = this._activeBuffer.lines.get(this._activeBuffer.ybase + r); n.insertCells(this._activeBuffer.x, i, this._activeBuffer.getNullCell(this._eraseAttrData())), n.isWrapped = false; } return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true; } deleteColumns(e) { if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) return true; let i = e.params[0] || 1; for (let r = this._activeBuffer.scrollTop; r <= this._activeBuffer.scrollBottom; ++r) { let n = this._activeBuffer.lines.get(this._activeBuffer.ybase + r); n.deleteCells(this._activeBuffer.x, i, this._activeBuffer.getNullCell(this._eraseAttrData())), n.isWrapped = false; } return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom), true; } eraseChars(e) { this._restrictCursor(); let i = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y); return i && (i.replaceCells(this._activeBuffer.x, this._activeBuffer.x + (e.params[0] || 1), this._activeBuffer.getNullCell(this._eraseAttrData())), this._dirtyRowTracker.markDirty(this._activeBuffer.y)), true; } repeatPrecedingCharacter(e) { let i = this._parser.precedingJoinState; if (!i) return true; let r = e.params[0] || 1, n = Ae.extractWidth(i), o2 = this._activeBuffer.x - n, a = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y).getString(o2), u = new Uint32Array(a.length * r), h2 = 0; for (let d = 0; d < a.length; ) { let _2 = a.codePointAt(d) || 0; u[h2++] = _2, d += _2 > 65535 ? 2 : 1; } let c = h2; for (let d = 1; d < r; ++d) u.copyWithin(c, 0, h2), c += h2; return this.print(u, 0, c), true; } sendDeviceAttributesPrimary(e) { return e.params[0] > 0 || (this._is("xterm") || this._is("rxvt-unicode") || this._is("screen") ? this._coreService.triggerDataEvent(b.ESC + "[?1;2c") : this._is("linux") && this._coreService.triggerDataEvent(b.ESC + "[?6c")), true; } sendDeviceAttributesSecondary(e) { return e.params[0] > 0 || (this._is("xterm") ? this._coreService.triggerDataEvent(b.ESC + "[>0;276;0c") : this._is("rxvt-unicode") ? this._coreService.triggerDataEvent(b.ESC + "[>85;95;0c") : this._is("linux") ? this._coreService.triggerDataEvent(e.params[0] + "c") : this._is("screen") && this._coreService.triggerDataEvent(b.ESC + "[>83;40003;0c")), true; } _is(e) { return (this._optionsService.rawOptions.termName + "").indexOf(e) === 0; } setMode(e) { for (let i = 0; i < e.length; i++) switch (e.params[i]) { case 4: this._coreService.modes.insertMode = true; break; case 20: this._optionsService.options.convertEol = true; break; } return true; } setModePrivate(e) { for (let i = 0; i < e.length; i++) switch (e.params[i]) { case 1: this._coreService.decPrivateModes.applicationCursorKeys = true; break; case 2: this._charsetService.setgCharset(0, Je), this._charsetService.setgCharset(1, Je), this._charsetService.setgCharset(2, Je), this._charsetService.setgCharset(3, Je); break; case 3: this._optionsService.rawOptions.windowOptions.setWinLines && (this._bufferService.resize(132, this._bufferService.rows), this._onRequestReset.fire()); break; case 6: this._coreService.decPrivateModes.origin = true, this._setCursor(0, 0); break; case 7: this._coreService.decPrivateModes.wraparound = true; break; case 12: this._optionsService.options.cursorBlink = true; break; case 45: this._coreService.decPrivateModes.reverseWraparound = true; break; case 66: this._logService.debug("Serial port requested application keypad."), this._coreService.decPrivateModes.applicationKeypad = true, this._onRequestSyncScrollBar.fire(); break; case 9: this._coreMouseService.activeProtocol = "X10"; break; case 1e3: this._coreMouseService.activeProtocol = "VT200"; break; case 1002: this._coreMouseService.activeProtocol = "DRAG"; break; case 1003: this._coreMouseService.activeProtocol = "ANY"; break; case 1004: this._coreService.decPrivateModes.sendFocus = true, this._onRequestSendFocus.fire(); break; case 1005: this._logService.debug("DECSET 1005 not supported (see #2507)"); break; case 1006: this._coreMouseService.activeEncoding = "SGR"; break; case 1015: this._logService.debug("DECSET 1015 not supported (see #2507)"); break; case 1016: this._coreMouseService.activeEncoding = "SGR_PIXELS"; break; case 25: this._coreService.isCursorHidden = false; break; case 1048: this.saveCursor(); break; case 1049: this.saveCursor(); case 47: case 1047: this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()), this._coreService.isCursorInitialized = true, this._onRequestRefreshRows.fire(void 0), this._onRequestSyncScrollBar.fire(); break; case 2004: this._coreService.decPrivateModes.bracketedPasteMode = true; break; case 2026: this._coreService.decPrivateModes.synchronizedOutput = true; break; } return true; } resetMode(e) { for (let i = 0; i < e.length; i++) switch (e.params[i]) { case 4: this._coreService.modes.insertMode = false; break; case 20: this._optionsService.options.convertEol = false; break; } return true; } resetModePrivate(e) { for (let i = 0; i < e.length; i++) switch (e.params[i]) { case 1: this._coreService.decPrivateModes.applicationCursorKeys = false; break; case 3: this._optionsService.rawOptions.windowOptions.setWinLines && (this._bufferService.resize(80, this._bufferService.rows), this._onRequestReset.fire()); break; case 6: this._coreService.decPrivateModes.origin = false, this._setCursor(0, 0); break; case 7: this._coreService.decPrivateModes.wraparound = false; break; case 12: this._optionsService.options.cursorBlink = false; break; case 45: this._coreService.decPrivateModes.reverseWraparound = false; break; case 66: this._logService.debug("Switching back to normal keypad."), this._coreService.decPrivateModes.applicationKeypad = false, this._onRequestSyncScrollBar.fire(); break; case 9: case 1e3: case 1002: case 1003: this._coreMouseService.activeProtocol = "NONE"; break; case 1004: this._coreService.decPrivateModes.sendFocus = false; break; case 1005: this._logService.debug("DECRST 1005 not supported (see #2507)"); break; case 1006: this._coreMouseService.activeEncoding = "DEFAULT"; break; case 1015: this._logService.debug("DECRST 1015 not supported (see #2507)"); break; case 1016: this._coreMouseService.activeEncoding = "DEFAULT"; break; case 25: this._coreService.isCursorHidden = true; break; case 1048: this.restoreCursor(); break; case 1049: case 47: case 1047: this._bufferService.buffers.activateNormalBuffer(), e.params[i] === 1049 && this.restoreCursor(), this._coreService.isCursorInitialized = true, this._onRequestRefreshRows.fire(void 0), this._onRequestSyncScrollBar.fire(); break; case 2004: this._coreService.decPrivateModes.bracketedPasteMode = false; break; case 2026: this._coreService.decPrivateModes.synchronizedOutput = false, this._onRequestRefreshRows.fire(void 0); break; } return true; } requestMode(e, i) { let r; ((P) => (P[P.NOT_RECOGNIZED = 0] = "NOT_RECOGNIZED", P[P.SET = 1] = "SET", P[P.RESET = 2] = "RESET", P[P.PERMANENTLY_SET = 3] = "PERMANENTLY_SET", P[P.PERMANENTLY_RESET = 4] = "PERMANENTLY_RESET"))(r || (r = {})); let n = this._coreService.decPrivateModes, { activeProtocol: o2, activeEncoding: l } = this._coreMouseService, a = this._coreService, { buffers: u, cols: h2 } = this._bufferService, { active: c, alt: d } = u, _2 = this._optionsService.rawOptions, p = (A, R) => (a.triggerDataEvent(`${b.ESC}[${i ? "" : "?"}${A};${R}$y`), true), m = (A) => A ? 1 : 2, f = e.params[0]; return i ? f === 2 ? p(f, 4) : f === 4 ? p(f, m(a.modes.insertMode)) : f === 12 ? p(f, 3) : f === 20 ? p(f, m(_2.convertEol)) : p(f, 0) : f === 1 ? p(f, m(n.applicationCursorKeys)) : f === 3 ? p(f, _2.windowOptions.setWinLines ? h2 === 80 ? 2 : h2 === 132 ? 1 : 0 : 0) : f === 6 ? p(f, m(n.origin)) : f === 7 ? p(f, m(n.wraparound)) : f === 8 ? p(f, 3) : f === 9 ? p(f, m(o2 === "X10")) : f === 12 ? p(f, m(_2.cursorBlink)) : f === 25 ? p(f, m(!a.isCursorHidden)) : f === 45 ? p(f, m(n.reverseWraparound)) : f === 66 ? p(f, m(n.applicationKeypad)) : f === 67 ? p(f, 4) : f === 1e3 ? p(f, m(o2 === "VT200")) : f === 1002 ? p(f, m(o2 === "DRAG")) : f === 1003 ? p(f, m(o2 === "ANY")) : f === 1004 ? p(f, m(n.sendFocus)) : f === 1005 ? p(f, 4) : f === 1006 ? p(f, m(l === "SGR")) : f === 1015 ? p(f, 4) : f === 1016 ? p(f, m(l === "SGR_PIXELS")) : f === 1048 ? p(f, 1) : f === 47 || f === 1047 || f === 1049 ? p(f, m(c === d)) : f === 2004 ? p(f, m(n.bracketedPasteMode)) : f === 2026 ? p(f, m(n.synchronizedOutput)) : p(f, 0); } _updateAttrColor(e, i, r, n, o2) { return i === 2 ? (e |= 50331648, e &= -16777216, e |= De.fromColorRGB([r, n, o2])) : i === 5 && (e &= -50331904, e |= 33554432 | r & 255), e; } _extractColor(e, i, r) { let n = [0, 0, -1, 0, 0, 0], o2 = 0, l = 0; do { if (n[l + o2] = e.params[i + l], e.hasSubParams(i + l)) { let a = e.getSubParams(i + l), u = 0; do n[1] === 5 && (o2 = 1), n[l + u + 1 + o2] = a[u]; while (++u < a.length && u + l + 1 + o2 < n.length); break; } if (n[1] === 5 && l + o2 >= 2 || n[1] === 2 && l + o2 >= 5) break; n[1] && (o2 = 1); } while (++l + i < e.length && l + o2 < n.length); for (let a = 2; a < n.length; ++a) n[a] === -1 && (n[a] = 0); switch (n[0]) { case 38: r.fg = this._updateAttrColor(r.fg, n[1], n[3], n[4], n[5]); break; case 48: r.bg = this._updateAttrColor(r.bg, n[1], n[3], n[4], n[5]); break; case 58: r.extended = r.extended.clone(), r.extended.underlineColor = this._updateAttrColor(r.extended.underlineColor, n[1], n[3], n[4], n[5]); } return l; } _processUnderline(e, i) { i.extended = i.extended.clone(), (!~e || e > 5) && (e = 1), i.extended.underlineStyle = e, i.fg |= 268435456, e === 0 && (i.fg &= -268435457), i.updateExtended(); } _processSGR0(e) { e.fg = X.fg, e.bg = X.bg, e.extended = e.extended.clone(), e.extended.underlineStyle = 0, e.extended.underlineColor &= -67108864, e.updateExtended(); } charAttributes(e) { if (e.length === 1 && e.params[0] === 0) return this._processSGR0(this._curAttrData), true; let i = e.length, r, n = this._curAttrData; for (let o2 = 0; o2 < i; o2++) r = e.params[o2], r >= 30 && r <= 37 ? (n.fg &= -50331904, n.fg |= 16777216 | r - 30) : r >= 40 && r <= 47 ? (n.bg &= -50331904, n.bg |= 16777216 | r - 40) : r >= 90 && r <= 97 ? (n.fg &= -50331904, n.fg |= 16777216 | r - 90 | 8) : r >= 100 && r <= 107 ? (n.bg &= -50331904, n.bg |= 16777216 | r - 100 | 8) : r === 0 ? this._processSGR0(n) : r === 1 ? n.fg |= 134217728 : r === 3 ? n.bg |= 67108864 : r === 4 ? (n.fg |= 268435456, this._processUnderline(e.hasSubParams(o2) ? e.getSubParams(o2)[0] : 1, n)) : r === 5 ? n.fg |= 536870912 : r === 7 ? n.fg |= 67108864 : r === 8 ? n.fg |= 1073741824 : r === 9 ? n.fg |= 2147483648 : r === 2 ? n.bg |= 134217728 : r === 21 ? this._processUnderline(2, n) : r === 22 ? (n.fg &= -134217729, n.bg &= -134217729) : r === 23 ? n.bg &= -67108865 : r === 24 ? (n.fg &= -268435457, this._processUnderline(0, n)) : r === 25 ? n.fg &= -536870913 : r === 27 ? n.fg &= -67108865 : r === 28 ? n.fg &= -1073741825 : r === 29 ? n.fg &= 2147483647 : r === 39 ? (n.fg &= -67108864, n.fg |= X.fg & 16777215) : r === 49 ? (n.bg &= -67108864, n.bg |= X.bg & 16777215) : r === 38 || r === 48 || r === 58 ? o2 += this._extractColor(e, o2, n) : r === 53 ? n.bg |= 1073741824 : r === 55 ? n.bg &= -1073741825 : r === 59 ? (n.extended = n.extended.clone(), n.extended.underlineColor = -1, n.updateExtended()) : r === 100 ? (n.fg &= -67108864, n.fg |= X.fg & 16777215, n.bg &= -67108864, n.bg |= X.bg & 16777215) : this._logService.debug("Unknown SGR attribute: %d.", r); return true; } deviceStatus(e) { switch (e.params[0]) { case 5: this._coreService.triggerDataEvent(`${b.ESC}[0n`); break; case 6: let i = this._activeBuffer.y + 1, r = this._activeBuffer.x + 1; this._coreService.triggerDataEvent(`${b.ESC}[${i};${r}R`); break; } return true; } deviceStatusPrivate(e) { switch (e.params[0]) { case 6: let i = this._activeBuffer.y + 1, r = this._activeBuffer.x + 1; this._coreService.triggerDataEvent(`${b.ESC}[?${i};${r}R`); break; case 15: break; case 25: break; case 26: break; case 53: break; } return true; } softReset(e) { return this._coreService.isCursorHidden = false, this._onRequestSyncScrollBar.fire(), this._activeBuffer.scrollTop = 0, this._activeBuffer.scrollBottom = this._bufferService.rows - 1, this._curAttrData = X.clone(), this._coreService.reset(), this._charsetService.reset(), this._activeBuffer.savedX = 0, this._activeBuffer.savedY = this._activeBuffer.ybase, this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg, this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg, this._activeBuffer.savedCharset = this._charsetService.charset, this._coreService.decPrivateModes.origin = false, true; } setCursorStyle(e) { let i = e.length === 0 ? 1 : e.params[0]; if (i === 0) this._coreService.decPrivateModes.cursorStyle = void 0, this._coreService.decPrivateModes.cursorBlink = void 0; else { switch (i) { case 1: case 2: this._coreService.decPrivateModes.cursorStyle = "block"; break; case 3: case 4: this._coreService.decPrivateModes.cursorStyle = "underline"; break; case 5: case 6: this._coreService.decPrivateModes.cursorStyle = "bar"; break; } let r = i % 2 === 1; this._coreService.decPrivateModes.cursorBlink = r; } return true; } setScrollRegion(e) { let i = e.params[0] || 1, r; return (e.length < 2 || (r = e.params[1]) > this._bufferService.rows || r === 0) && (r = this._bufferService.rows), r > i && (this._activeBuffer.scrollTop = i - 1, this._activeBuffer.scrollBottom = r - 1, this._setCursor(0, 0)), true; } windowOptions(e) { if (!bl(e.params[0], this._optionsService.rawOptions.windowOptions)) return true; let i = e.length > 1 ? e.params[1] : 0; switch (e.params[0]) { case 14: i !== 2 && this._onRequestWindowsOptionsReport.fire(0); break; case 16: this._onRequestWindowsOptionsReport.fire(1); break; case 18: this._bufferService && this._coreService.triggerDataEvent(`${b.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`); break; case 22: (i === 0 || i === 2) && (this._windowTitleStack.push(this._windowTitle), this._windowTitleStack.length > _l && this._windowTitleStack.shift()), (i === 0 || i === 1) && (this._iconNameStack.push(this._iconName), this._iconNameStack.length > _l && this._iconNameStack.shift()); break; case 23: (i === 0 || i === 2) && this._windowTitleStack.length && this.setTitle(this._windowTitleStack.pop()), (i === 0 || i === 1) && this._iconNameStack.length && this.setIconName(this._iconNameStack.pop()); break; } return true; } saveCursor(e) { return this._activeBuffer.savedX = this._activeBuffer.x, this._activeBuffer.savedY = this._activeBuffer.ybase + this._activeBuffer.y, this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg, this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg, this._activeBuffer.savedCharset = this._charsetService.charset, true; } restoreCursor(e) { return this._activeBuffer.x = this._activeBuffer.savedX || 0, this._activeBuffer.y = Math.max(this._activeBuffer.savedY - this._activeBuffer.ybase, 0), this._curAttrData.fg = this._activeBuffer.savedCurAttrData.fg, this._curAttrData.bg = this._activeBuffer.savedCurAttrData.bg, this._charsetService.charset = this._savedCharset, this._activeBuffer.savedCharset && (this._charsetService.charset = this._activeBuffer.savedCharset), this._restrictCursor(), true; } setTitle(e) { return this._windowTitle = e, this._onTitleChange.fire(e), true; } setIconName(e) { return this._iconName = e, true; } setOrReportIndexedColor(e) { let i = [], r = e.split(";"); for (; r.length > 1; ) { let n = r.shift(), o2 = r.shift(); if (/^\d+$/.exec(n)) { let l = parseInt(n); if (Sl(l)) if (o2 === "?") i.push({ type: 0, index: l }); else { let a = Ws(o2); a && i.push({ type: 1, index: l, color: a }); } } } return i.length && this._onColor.fire(i), true; } setHyperlink(e) { let i = e.indexOf(";"); if (i === -1) return true; let r = e.slice(0, i).trim(), n = e.slice(i + 1); return n ? this._createHyperlink(r, n) : r.trim() ? false : this._finishHyperlink(); } _createHyperlink(e, i) { this._getCurrentLinkId() && this._finishHyperlink(); let r = e.split(":"), n, o2 = r.findIndex((l) => l.startsWith("id=")); return o2 !== -1 && (n = r[o2].slice(3) || void 0), this._curAttrData.extended = this._curAttrData.extended.clone(), this._curAttrData.extended.urlId = this._oscLinkService.registerLink({ id: n, uri: i }), this._curAttrData.updateExtended(), true; } _finishHyperlink() { return this._curAttrData.extended = this._curAttrData.extended.clone(), this._curAttrData.extended.urlId = 0, this._curAttrData.updateExtended(), true; } _setOrReportSpecialColor(e, i) { let r = e.split(";"); for (let n = 0; n < r.length && !(i >= this._specialColors.length); ++n, ++i) if (r[n] === "?") this._onColor.fire([{ type: 0, index: this._specialColors[i] }]); else { let o2 = Ws(r[n]); o2 && this._onColor.fire([{ type: 1, index: this._specialColors[i], color: o2 }]); } return true; } setOrReportFgColor(e) { return this._setOrReportSpecialColor(e, 0); } setOrReportBgColor(e) { return this._setOrReportSpecialColor(e, 1); } setOrReportCursorColor(e) { return this._setOrReportSpecialColor(e, 2); } restoreIndexedColor(e) { if (!e) return this._onColor.fire([{ type: 2 }]), true; let i = [], r = e.split(";"); for (let n = 0; n < r.length; ++n) if (/^\d+$/.exec(r[n])) { let o2 = parseInt(r[n]); Sl(o2) && i.push({ type: 2, index: o2 }); } return i.length && this._onColor.fire(i), true; } restoreFgColor(e) { return this._onColor.fire([{ type: 2, index: 256 }]), true; } restoreBgColor(e) { return this._onColor.fire([{ type: 2, index: 257 }]), true; } restoreCursorColor(e) { return this._onColor.fire([{ type: 2, index: 258 }]), true; } nextLine() { return this._activeBuffer.x = 0, this.index(), true; } keypadApplicationMode() { return this._logService.debug("Serial port requested application keypad."), this._coreService.decPrivateModes.applicationKeypad = true, this._onRequestSyncScrollBar.fire(), true; } keypadNumericMode() { return this._logService.debug("Switching back to normal keypad."), this._coreService.decPrivateModes.applicationKeypad = false, this._onRequestSyncScrollBar.fire(), true; } selectDefaultCharset() { return this._charsetService.setgLevel(0), this._charsetService.setgCharset(0, Je), true; } selectCharset(e) { return e.length !== 2 ? (this.selectDefaultCharset(), true) : (e[0] === "/" || this._charsetService.setgCharset(mc[e[0]], ne[e[1]] || Je), true); } index() { return this._restrictCursor(), this._activeBuffer.y++, this._activeBuffer.y === this._activeBuffer.scrollBottom + 1 ? (this._activeBuffer.y--, this._bufferService.scroll(this._eraseAttrData())) : this._activeBuffer.y >= this._bufferService.rows && (this._activeBuffer.y = this._bufferService.rows - 1), this._restrictCursor(), true; } tabSet() { return this._activeBuffer.tabs[this._activeBuffer.x] = true, true; } reverseIndex() { if (this._restrictCursor(), this._activeBuffer.y === this._activeBuffer.scrollTop) { let e = this._activeBuffer.scrollBottom - this._activeBuffer.scrollTop; this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase + this._activeBuffer.y, e, 1), this._activeBuffer.lines.set(this._activeBuffer.ybase + this._activeBuffer.y, this._activeBuffer.getBlankLine(this._eraseAttrData())), this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom); } else this._activeBuffer.y--, this._restrictCursor(); return true; } fullReset() { return this._parser.reset(), this._onRequestReset.fire(), true; } reset() { this._curAttrData = X.clone(), this._eraseAttrDataInternal = X.clone(); } _eraseAttrData() { return this._eraseAttrDataInternal.bg &= -67108864, this._eraseAttrDataInternal.bg |= this._curAttrData.bg & 67108863, this._eraseAttrDataInternal; } setgLevel(e) { return this._charsetService.setgLevel(e), true; } screenAlignmentPattern() { let e = new q(); e.content = 1 << 22 | 69, e.fg = this._curAttrData.fg, e.bg = this._curAttrData.bg, this._setCursor(0, 0); for (let i = 0; i < this._bufferService.rows; ++i) { let r = this._activeBuffer.ybase + this._activeBuffer.y + i, n = this._activeBuffer.lines.get(r); n && (n.fill(e), n.isWrapped = false); } return this._dirtyRowTracker.markAllDirty(), this._setCursor(0, 0), true; } requestStatusString(e, i) { let r = (a) => (this._coreService.triggerDataEvent(`${b.ESC}${a}${b.ESC}\\`), true), n = this._bufferService.buffer, o2 = this._optionsService.rawOptions, l = { block: 2, underline: 4, bar: 6 }; return r(e === '"q' ? `P1$r${this._curAttrData.isProtected() ? 1 : 0}"q` : e === '"p' ? 'P1$r61;1"p' : e === "r" ? `P1$r${n.scrollTop + 1};${n.scrollBottom + 1}r` : e === "m" ? "P1$r0m" : e === " q" ? `P1$r${l[o2.cursorStyle] - (o2.cursorBlink ? 1 : 0)} q` : "P0$r"); } markRangeDirty(e, i) { this._dirtyRowTracker.markRangeDirty(e, i); } }; var Zi = class { constructor(t) { this._bufferService = t; this.clearRange(); } clearRange() { this.start = this._bufferService.buffer.y, this.end = this._bufferService.buffer.y; } markDirty(t) { t < this.start ? this.start = t : t > this.end && (this.end = t); } markRangeDirty(t, e) { t > e && (gl = t, t = e, e = gl), t < this.start && (this.start = t), e > this.end && (this.end = e); } markAllDirty() { this.markRangeDirty(0, this._bufferService.rows - 1); } }; Zi = M([S(0, F)], Zi); function Sl(s15) { return 0 <= s15 && s15 < 256; } var _c = 5e7; var El = 12; var bc = 50; var gn = class extends D { constructor(e) { super(); this._action = e; this._writeBuffer = []; this._callbacks = []; this._pendingData = 0; this._bufferOffset = 0; this._isSyncWriting = false; this._syncCalls = 0; this._didUserInput = false; this._onWriteParsed = this._register(new v()); this.onWriteParsed = this._onWriteParsed.event; } handleUserInput() { this._didUserInput = true; } writeSync(e, i) { if (i !== void 0 && this._syncCalls > i) { this._syncCalls = 0; return; } if (this._pendingData += e.length, this._writeBuffer.push(e), this._callbacks.push(void 0), this._syncCalls++, this._isSyncWriting) return; this._isSyncWriting = true; let r; for (; r = this._writeBuffer.shift(); ) { this._action(r); let n = this._callbacks.shift(); n && n(); } this._pendingData = 0, this._bufferOffset = 2147483647, this._isSyncWriting = false, this._syncCalls = 0; } write(e, i) { if (this._pendingData > _c) throw new Error("write data discarded, use flow control to avoid losing data"); if (!this._writeBuffer.length) { if (this._bufferOffset = 0, this._didUserInput) { this._didUserInput = false, this._pendingData += e.length, this._writeBuffer.push(e), this._callbacks.push(i), this._innerWrite(); return; } setTimeout(() => this._innerWrite()); } this._pendingData += e.length, this._writeBuffer.push(e), this._callbacks.push(i); } _innerWrite(e = 0, i = true) { let r = e || performance.now(); for (; this._writeBuffer.length > this._bufferOffset; ) { let n = this._writeBuffer[this._bufferOffset], o2 = this._action(n, i); if (o2) { let a = (u) => performance.now() - r >= El ? setTimeout(() => this._innerWrite(0, u)) : this._innerWrite(r, u); o2.catch((u) => (queueMicrotask(() => { throw u; }), Promise.resolve(false))).then(a); return; } let l = this._callbacks[this._bufferOffset]; if (l && l(), this._bufferOffset++, this._pendingData -= n.length, performance.now() - r >= El) break; } this._writeBuffer.length > this._bufferOffset ? (this._bufferOffset > bc && (this._writeBuffer = this._writeBuffer.slice(this._bufferOffset), this._callbacks = this._callbacks.slice(this._bufferOffset), this._bufferOffset = 0), setTimeout(() => this._innerWrite())) : (this._writeBuffer.length = 0, this._callbacks.length = 0, this._pendingData = 0, this._bufferOffset = 0), this._onWriteParsed.fire(); } }; var ui = class { constructor(t) { this._bufferService = t; this._nextId = 1; this._entriesWithId = /* @__PURE__ */ new Map(); this._dataByLinkId = /* @__PURE__ */ new Map(); } registerLink(t) { let e = this._bufferService.buffer; if (t.id === void 0) { let a = e.addMarker(e.ybase + e.y), u = { data: t, id: this._nextId++, lines: [a] }; return a.onDispose(() => this._removeMarkerFromLink(u, a)), this._dataByLinkId.set(u.id, u), u.id; } let i = t, r = this._getEntryIdKey(i), n = this._entriesWithId.get(r); if (n) return this.addLineToLink(n.id, e.ybase + e.y), n.id; let o2 = e.addMarker(e.ybase + e.y), l = { id: this._nextId++, key: this._getEntryIdKey(i), data: i, lines: [o2] }; return o2.onDispose(() => this._removeMarkerFromLink(l, o2)), this._entriesWithId.set(l.key, l), this._dataByLinkId.set(l.id, l), l.id; } addLineToLink(t, e) { let i = this._dataByLinkId.get(t); if (i && i.lines.every((r) => r.line !== e)) { let r = this._bufferService.buffer.addMarker(e); i.lines.push(r), r.onDispose(() => this._removeMarkerFromLink(i, r)); } } getLinkData(t) { var _a5; return (_a5 = this._dataByLinkId.get(t)) == null ? void 0 : _a5.data; } _getEntryIdKey(t) { return `${t.id};;${t.uri}`; } _removeMarkerFromLink(t, e) { let i = t.lines.indexOf(e); i !== -1 && (t.lines.splice(i, 1), t.lines.length === 0 && (t.data.id !== void 0 && this._entriesWithId.delete(t.key), this._dataByLinkId.delete(t.id))); } }; ui = M([S(0, F)], ui); var Tl = false; var Sn = class extends D { constructor(e) { super(); this._windowsWrappingHeuristics = this._register(new ye()); this._onBinary = this._register(new v()); this.onBinary = this._onBinary.event; this._onData = this._register(new v()); this.onData = this._onData.event; this._onLineFeed = this._register(new v()); this.onLineFeed = this._onLineFeed.event; this._onResize = this._register(new v()); this.onResize = this._onResize.event; this._onWriteParsed = this._register(new v()); this.onWriteParsed = this._onWriteParsed.event; this._onScroll = this._register(new v()); this._instantiationService = new ln(), this.optionsService = this._register(new dn(e)), this._instantiationService.setService(H, this.optionsService), this._bufferService = this._register(this._instantiationService.createInstance(ni)), this._instantiationService.setService(F, this._bufferService), this._logService = this._register(this._instantiationService.createInstance(ii)), this._instantiationService.setService(nr, this._logService), this.coreService = this._register(this._instantiationService.createInstance(li)), this._instantiationService.setService(ge, this.coreService), this.coreMouseService = this._register(this._instantiationService.createInstance(ai)), this._instantiationService.setService(rr, this.coreMouseService), this.unicodeService = this._register(this._instantiationService.createInstance(Ae)), this._instantiationService.setService(Js, this.unicodeService), this._charsetService = this._instantiationService.createInstance(pn), this._instantiationService.setService(Zs, this._charsetService), this._oscLinkService = this._instantiationService.createInstance(ui), this._instantiationService.setService(sr, this._oscLinkService), this._inputHandler = this._register(new vn(this._bufferService, this._charsetService, this.coreService, this._logService, this.optionsService, this._oscLinkService, this.coreMouseService, this.unicodeService)), this._register($.forward(this._inputHandler.onLineFeed, this._onLineFeed)), this._register(this._inputHandler), this._register($.forward(this._bufferService.onResize, this._onResize)), this._register($.forward(this.coreService.onData, this._onData)), this._register($.forward(this.coreService.onBinary, this._onBinary)), this._register(this.coreService.onRequestScrollToBottom(() => this.scrollToBottom(true))), this._register(this.coreService.onUserInput(() => this._writeBuffer.handleUserInput())), this._register(this.optionsService.onMultipleOptionChange(["windowsMode", "windowsPty"], () => this._handleWindowsPtyOptionChange())), this._register(this._bufferService.onScroll(() => { this._onScroll.fire({ position: this._bufferService.buffer.ydisp }), this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop, this._bufferService.buffer.scrollBottom); })), this._writeBuffer = this._register(new gn((i, r) => this._inputHandler.parse(i, r))), this._register($.forward(this._writeBuffer.onWriteParsed, this._onWriteParsed)); } get onScroll() { return this._onScrollApi || (this._onScrollApi = this._register(new v()), this._onScroll.event((e) => { var _a5; (_a5 = this._onScrollApi) == null ? void 0 : _a5.fire(e.position); })), this._onScrollApi.event; } get cols() { return this._bufferService.cols; } get rows() { return this._bufferService.rows; } get buffers() { return this._bufferService.buffers; } get options() { return this.optionsService.options; } set options(e) { for (let i in e) this.optionsService.options[i] = e[i]; } write(e, i) { this._writeBuffer.write(e, i); } writeSync(e, i) { this._logService.logLevel <= 3 && !Tl && (this._logService.warn("writeSync is unreliable and will be removed soon."), Tl = true), this._writeBuffer.writeSync(e, i); } input(e, i = true) { this.coreService.triggerDataEvent(e, i); } resize(e, i) { isNaN(e) || isNaN(i) || (e = Math.max(e, ks), i = Math.max(i, Cs), this._bufferService.resize(e, i)); } scroll(e, i = false) { this._bufferService.scroll(e, i); } scrollLines(e, i) { this._bufferService.scrollLines(e, i); } scrollPages(e) { this.scrollLines(e * (this.rows - 1)); } scrollToTop() { this.scrollLines(-this._bufferService.buffer.ydisp); } scrollToBottom(e) { this.scrollLines(this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp); } scrollToLine(e) { let i = e - this._bufferService.buffer.ydisp; i !== 0 && this.scrollLines(i); } registerEscHandler(e, i) { return this._inputHandler.registerEscHandler(e, i); } registerDcsHandler(e, i) { return this._inputHandler.registerDcsHandler(e, i); } registerCsiHandler(e, i) { return this._inputHandler.registerCsiHandler(e, i); } registerOscHandler(e, i) { return this._inputHandler.registerOscHandler(e, i); } _setup() { this._handleWindowsPtyOptionChange(); } reset() { this._inputHandler.reset(), this._bufferService.reset(), this._charsetService.reset(), this.coreService.reset(), this.coreMouseService.reset(); } _handleWindowsPtyOptionChange() { let e = false, i = this.optionsService.rawOptions.windowsPty; i && i.buildNumber !== void 0 && i.buildNumber !== void 0 ? e = i.backend === "conpty" && i.buildNumber < 21376 : this.optionsService.rawOptions.windowsMode && (e = true), e ? this._enableWindowsWrappingHeuristics() : this._windowsWrappingHeuristics.clear(); } _enableWindowsWrappingHeuristics() { if (!this._windowsWrappingHeuristics.value) { let e = []; e.push(this.onLineFeed(Bs.bind(null, this._bufferService))), e.push(this.registerCsiHandler({ final: "H" }, () => (Bs(this._bufferService), false))), this._windowsWrappingHeuristics.value = C(() => { for (let i of e) i.dispose(); }); } } }; var gc = { 48: ["0", ")"], 49: ["1", "!"], 50: ["2", "@"], 51: ["3", "#"], 52: ["4", "$"], 53: ["5", "%"], 54: ["6", "^"], 55: ["7", "&"], 56: ["8", "*"], 57: ["9", "("], 186: [";", ":"], 187: ["=", "+"], 188: [",", "<"], 189: ["-", "_"], 190: [".", ">"], 191: ["/", "?"], 192: ["`", "~"], 219: ["[", "{"], 220: ["\\", "|"], 221: ["]", "}"], 222: ["'", '"'] }; function Il(s15, t, e, i) { var _a5; let r = { type: 0, cancel: false, key: void 0 }, n = (s15.shiftKey ? 1 : 0) | (s15.altKey ? 2 : 0) | (s15.ctrlKey ? 4 : 0) | (s15.metaKey ? 8 : 0); switch (s15.keyCode) { case 0: s15.key === "UIKeyInputUpArrow" ? t ? r.key = b.ESC + "OA" : r.key = b.ESC + "[A" : s15.key === "UIKeyInputLeftArrow" ? t ? r.key = b.ESC + "OD" : r.key = b.ESC + "[D" : s15.key === "UIKeyInputRightArrow" ? t ? r.key = b.ESC + "OC" : r.key = b.ESC + "[C" : s15.key === "UIKeyInputDownArrow" && (t ? r.key = b.ESC + "OB" : r.key = b.ESC + "[B"); break; case 8: r.key = s15.ctrlKey ? "\b" : b.DEL, s15.altKey && (r.key = b.ESC + r.key); break; case 9: if (s15.shiftKey) { r.key = b.ESC + "[Z"; break; } r.key = b.HT, r.cancel = true; break; case 13: r.key = s15.altKey ? b.ESC + b.CR : b.CR, r.cancel = true; break; case 27: r.key = b.ESC, s15.altKey && (r.key = b.ESC + b.ESC), r.cancel = true; break; case 37: if (s15.metaKey) break; n ? r.key = b.ESC + "[1;" + (n + 1) + "D" : t ? r.key = b.ESC + "OD" : r.key = b.ESC + "[D"; break; case 39: if (s15.metaKey) break; n ? r.key = b.ESC + "[1;" + (n + 1) + "C" : t ? r.key = b.ESC + "OC" : r.key = b.ESC + "[C"; break; case 38: if (s15.metaKey) break; n ? r.key = b.ESC + "[1;" + (n + 1) + "A" : t ? r.key = b.ESC + "OA" : r.key = b.ESC + "[A"; break; case 40: if (s15.metaKey) break; n ? r.key = b.ESC + "[1;" + (n + 1) + "B" : t ? r.key = b.ESC + "OB" : r.key = b.ESC + "[B"; break; case 45: !s15.shiftKey && !s15.ctrlKey && (r.key = b.ESC + "[2~"); break; case 46: n ? r.key = b.ESC + "[3;" + (n + 1) + "~" : r.key = b.ESC + "[3~"; break; case 36: n ? r.key = b.ESC + "[1;" + (n + 1) + "H" : t ? r.key = b.ESC + "OH" : r.key = b.ESC + "[H"; break; case 35: n ? r.key = b.ESC + "[1;" + (n + 1) + "F" : t ? r.key = b.ESC + "OF" : r.key = b.ESC + "[F"; break; case 33: s15.shiftKey ? r.type = 2 : s15.ctrlKey ? r.key = b.ESC + "[5;" + (n + 1) + "~" : r.key = b.ESC + "[5~"; break; case 34: s15.shiftKey ? r.type = 3 : s15.ctrlKey ? r.key = b.ESC + "[6;" + (n + 1) + "~" : r.key = b.ESC + "[6~"; break; case 112: n ? r.key = b.ESC + "[1;" + (n + 1) + "P" : r.key = b.ESC + "OP"; break; case 113: n ? r.key = b.ESC + "[1;" + (n + 1) + "Q" : r.key = b.ESC + "OQ"; break; case 114: n ? r.key = b.ESC + "[1;" + (n + 1) + "R" : r.key = b.ESC + "OR"; break; case 115: n ? r.key = b.ESC + "[1;" + (n + 1) + "S" : r.key = b.ESC + "OS"; break; case 116: n ? r.key = b.ESC + "[15;" + (n + 1) + "~" : r.key = b.ESC + "[15~"; break; case 117: n ? r.key = b.ESC + "[17;" + (n + 1) + "~" : r.key = b.ESC + "[17~"; break; case 118: n ? r.key = b.ESC + "[18;" + (n + 1) + "~" : r.key = b.ESC + "[18~"; break; case 119: n ? r.key = b.ESC + "[19;" + (n + 1) + "~" : r.key = b.ESC + "[19~"; break; case 120: n ? r.key = b.ESC + "[20;" + (n + 1) + "~" : r.key = b.ESC + "[20~"; break; case 121: n ? r.key = b.ESC + "[21;" + (n + 1) + "~" : r.key = b.ESC + "[21~"; break; case 122: n ? r.key = b.ESC + "[23;" + (n + 1) + "~" : r.key = b.ESC + "[23~"; break; case 123: n ? r.key = b.ESC + "[24;" + (n + 1) + "~" : r.key = b.ESC + "[24~"; break; default: if (s15.ctrlKey && !s15.shiftKey && !s15.altKey && !s15.metaKey) s15.keyCode >= 65 && s15.keyCode <= 90 ? r.key = String.fromCharCode(s15.keyCode - 64) : s15.keyCode === 32 ? r.key = b.NUL : s15.keyCode >= 51 && s15.keyCode <= 55 ? r.key = String.fromCharCode(s15.keyCode - 51 + 27) : s15.keyCode === 56 ? r.key = b.DEL : s15.keyCode === 219 ? r.key = b.ESC : s15.keyCode === 220 ? r.key = b.FS : s15.keyCode === 221 && (r.key = b.GS); else if ((!e || i) && s15.altKey && !s15.metaKey) { let l = (_a5 = gc[s15.keyCode]) == null ? void 0 : _a5[s15.shiftKey ? 1 : 0]; if (l) r.key = b.ESC + l; else if (s15.keyCode >= 65 && s15.keyCode <= 90) { let a = s15.ctrlKey ? s15.keyCode - 64 : s15.keyCode + 32, u = String.fromCharCode(a); s15.shiftKey && (u = u.toUpperCase()), r.key = b.ESC + u; } else if (s15.keyCode === 32) r.key = b.ESC + (s15.ctrlKey ? b.NUL : " "); else if (s15.key === "Dead" && s15.code.startsWith("Key")) { let a = s15.code.slice(3, 4); s15.shiftKey || (a = a.toLowerCase()), r.key = b.ESC + a, r.cancel = true; } } else e && !s15.altKey && !s15.ctrlKey && !s15.shiftKey && s15.metaKey ? s15.keyCode === 65 && (r.type = 1) : s15.key && !s15.ctrlKey && !s15.altKey && !s15.metaKey && s15.keyCode >= 48 && s15.key.length === 1 ? r.key = s15.key : s15.key && s15.ctrlKey && (s15.key === "_" && (r.key = b.US), s15.key === "@" && (r.key = b.NUL)); break; } return r; } var ee = 0; var En = class { constructor(t) { this._getKey = t; this._array = []; this._insertedValues = []; this._flushInsertedTask = new Jt(); this._isFlushingInserted = false; this._deletedIndices = []; this._flushDeletedTask = new Jt(); this._isFlushingDeleted = false; } clear() { this._array.length = 0, this._insertedValues.length = 0, this._flushInsertedTask.clear(), this._isFlushingInserted = false, this._deletedIndices.length = 0, this._flushDeletedTask.clear(), this._isFlushingDeleted = false; } insert(t) { this._flushCleanupDeleted(), this._insertedValues.length === 0 && this._flushInsertedTask.enqueue(() => this._flushInserted()), this._insertedValues.push(t); } _flushInserted() { let t = this._insertedValues.sort((n, o2) => this._getKey(n) - this._getKey(o2)), e = 0, i = 0, r = new Array(this._array.length + this._insertedValues.length); for (let n = 0; n < r.length; n++) i >= this._array.length || this._getKey(t[e]) <= this._getKey(this._array[i]) ? (r[n] = t[e], e++) : r[n] = this._array[i++]; this._array = r, this._insertedValues.length = 0; } _flushCleanupInserted() { !this._isFlushingInserted && this._insertedValues.length > 0 && this._flushInsertedTask.flush(); } delete(t) { if (this._flushCleanupInserted(), this._array.length === 0) return false; let e = this._getKey(t); if (e === void 0 || (ee = this._search(e), ee === -1) || this._getKey(this._array[ee]) !== e) return false; do if (this._array[ee] === t) return this._deletedIndices.length === 0 && this._flushDeletedTask.enqueue(() => this._flushDeleted()), this._deletedIndices.push(ee), true; while (++ee < this._array.length && this._getKey(this._array[ee]) === e); return false; } _flushDeleted() { this._isFlushingDeleted = true; let t = this._deletedIndices.sort((n, o2) => n - o2), e = 0, i = new Array(this._array.length - t.length), r = 0; for (let n = 0; n < this._array.length; n++) t[e] === n ? e++ : i[r++] = this._array[n]; this._array = i, this._deletedIndices.length = 0, this._isFlushingDeleted = false; } _flushCleanupDeleted() { !this._isFlushingDeleted && this._deletedIndices.length > 0 && this._flushDeletedTask.flush(); } *getKeyIterator(t) { if (this._flushCleanupInserted(), this._flushCleanupDeleted(), this._array.length !== 0 && (ee = this._search(t), !(ee < 0 || ee >= this._array.length) && this._getKey(this._array[ee]) === t)) do yield this._array[ee]; while (++ee < this._array.length && this._getKey(this._array[ee]) === t); } forEachByKey(t, e) { if (this._flushCleanupInserted(), this._flushCleanupDeleted(), this._array.length !== 0 && (ee = this._search(t), !(ee < 0 || ee >= this._array.length) && this._getKey(this._array[ee]) === t)) do e(this._array[ee]); while (++ee < this._array.length && this._getKey(this._array[ee]) === t); } values() { return this._flushCleanupInserted(), this._flushCleanupDeleted(), [...this._array].values(); } _search(t) { let e = 0, i = this._array.length - 1; for (; i >= e; ) { let r = e + i >> 1, n = this._getKey(this._array[r]); if (n > t) i = r - 1; else if (n < t) e = r + 1; else { for (; r > 0 && this._getKey(this._array[r - 1]) === t; ) r--; return r; } } return e; } }; var Us = 0; var yl = 0; var Tn = class extends D { constructor() { super(); this._decorations = new En((e) => e == null ? void 0 : e.marker.line); this._onDecorationRegistered = this._register(new v()); this.onDecorationRegistered = this._onDecorationRegistered.event; this._onDecorationRemoved = this._register(new v()); this.onDecorationRemoved = this._onDecorationRemoved.event; this._register(C(() => this.reset())); } get decorations() { return this._decorations.values(); } registerDecoration(e) { if (e.marker.isDisposed) return; let i = new Ks(e); if (i) { let r = i.marker.onDispose(() => i.dispose()), n = i.onDispose(() => { n.dispose(), i && (this._decorations.delete(i) && this._onDecorationRemoved.fire(i), r.dispose()); }); this._decorations.insert(i), this._onDecorationRegistered.fire(i); } return i; } reset() { for (let e of this._decorations.values()) e.dispose(); this._decorations.clear(); } *getDecorationsAtCell(e, i, r) { var _a5, _b, _c2; let n = 0, o2 = 0; for (let l of this._decorations.getKeyIterator(i)) n = (_a5 = l.options.x) != null ? _a5 : 0, o2 = n + ((_b = l.options.width) != null ? _b : 1), e >= n && e < o2 && (!r || ((_c2 = l.options.layer) != null ? _c2 : "bottom") === r) && (yield l); } forEachDecorationAtCell(e, i, r, n) { this._decorations.forEachByKey(i, (o2) => { var _a5, _b, _c2; Us = (_a5 = o2.options.x) != null ? _a5 : 0, yl = Us + ((_b = o2.options.width) != null ? _b : 1), e >= Us && e < yl && (!r || ((_c2 = o2.options.layer) != null ? _c2 : "bottom") === r) && n(o2); }); } }; var Ks = class extends Ee { constructor(e) { super(); this.options = e; this.onRenderEmitter = this.add(new v()); this.onRender = this.onRenderEmitter.event; this._onDispose = this.add(new v()); this.onDispose = this._onDispose.event; this._cachedBg = null; this._cachedFg = null; this.marker = e.marker, this.options.overviewRulerOptions && !this.options.overviewRulerOptions.position && (this.options.overviewRulerOptions.position = "full"); } get backgroundColorRGB() { return this._cachedBg === null && (this.options.backgroundColor ? this._cachedBg = z.toColor(this.options.backgroundColor) : this._cachedBg = void 0), this._cachedBg; } get foregroundColorRGB() { return this._cachedFg === null && (this.options.foregroundColor ? this._cachedFg = z.toColor(this.options.foregroundColor) : this._cachedFg = void 0), this._cachedFg; } dispose() { this._onDispose.fire(), super.dispose(); } }; var Sc = 1e3; var In = class { constructor(t, e = Sc) { this._renderCallback = t; this._debounceThresholdMS = e; this._lastRefreshMs = 0; this._additionalRefreshRequested = false; } dispose() { this._refreshTimeoutID && clearTimeout(this._refreshTimeoutID); } refresh(t, e, i) { this._rowCount = i, t = t !== void 0 ? t : 0, e = e !== void 0 ? e : this._rowCount - 1, this._rowStart = this._rowStart !== void 0 ? Math.min(this._rowStart, t) : t, this._rowEnd = this._rowEnd !== void 0 ? Math.max(this._rowEnd, e) : e; let r = performance.now(); if (r - this._lastRefreshMs >= this._debounceThresholdMS) this._lastRefreshMs = r, this._innerRefresh(); else if (!this._additionalRefreshRequested) { let n = r - this._lastRefreshMs, o2 = this._debounceThresholdMS - n; this._additionalRefreshRequested = true, this._refreshTimeoutID = window.setTimeout(() => { this._lastRefreshMs = performance.now(), this._innerRefresh(), this._additionalRefreshRequested = false, this._refreshTimeoutID = void 0; }, o2); } } _innerRefresh() { if (this._rowStart === void 0 || this._rowEnd === void 0 || this._rowCount === void 0) return; let t = Math.max(this._rowStart, 0), e = Math.min(this._rowEnd, this._rowCount - 1); this._rowStart = void 0, this._rowEnd = void 0, this._renderCallback(t, e); } }; var xl = 20; var wl = false; var Tt = class extends D { constructor(e, i, r, n) { super(); this._terminal = e; this._coreBrowserService = r; this._renderService = n; this._rowColumns = /* @__PURE__ */ new WeakMap(); this._liveRegionLineCount = 0; this._charsToConsume = []; this._charsToAnnounce = ""; let o2 = this._coreBrowserService.mainDocument; this._accessibilityContainer = o2.createElement("div"), this._accessibilityContainer.classList.add("xterm-accessibility"), this._rowContainer = o2.createElement("div"), this._rowContainer.setAttribute("role", "list"), this._rowContainer.classList.add("xterm-accessibility-tree"), this._rowElements = []; for (let l = 0; l < this._terminal.rows; l++) this._rowElements[l] = this._createAccessibilityTreeNode(), this._rowContainer.appendChild(this._rowElements[l]); if (this._topBoundaryFocusListener = (l) => this._handleBoundaryFocus(l, 0), this._bottomBoundaryFocusListener = (l) => this._handleBoundaryFocus(l, 1), this._rowElements[0].addEventListener("focus", this._topBoundaryFocusListener), this._rowElements[this._rowElements.length - 1].addEventListener("focus", this._bottomBoundaryFocusListener), this._accessibilityContainer.appendChild(this._rowContainer), this._liveRegion = o2.createElement("div"), this._liveRegion.classList.add("live-region"), this._liveRegion.setAttribute("aria-live", "assertive"), this._accessibilityContainer.appendChild(this._liveRegion), this._liveRegionDebouncer = this._register(new In(this._renderRows.bind(this))), !this._terminal.element) throw new Error("Cannot enable accessibility before Terminal.open"); wl ? (this._accessibilityContainer.classList.add("debug"), this._rowContainer.classList.add("debug"), this._debugRootContainer = o2.createElement("div"), this._debugRootContainer.classList.add("xterm"), this._debugRootContainer.appendChild(o2.createTextNode("------start a11y------")), this._debugRootContainer.appendChild(this._accessibilityContainer), this._debugRootContainer.appendChild(o2.createTextNode("------end a11y------")), this._terminal.element.insertAdjacentElement("afterend", this._debugRootContainer)) : this._terminal.element.insertAdjacentElement("afterbegin", this._accessibilityContainer), this._register(this._terminal.onResize((l) => this._handleResize(l.rows))), this._register(this._terminal.onRender((l) => this._refreshRows(l.start, l.end))), this._register(this._terminal.onScroll(() => this._refreshRows())), this._register(this._terminal.onA11yChar((l) => this._handleChar(l))), this._register(this._terminal.onLineFeed(() => this._handleChar(` `))), this._register(this._terminal.onA11yTab((l) => this._handleTab(l))), this._register(this._terminal.onKey((l) => this._handleKey(l.key))), this._register(this._terminal.onBlur(() => this._clearLiveRegion())), this._register(this._renderService.onDimensionsChange(() => this._refreshRowsDimensions())), this._register(L(o2, "selectionchange", () => this._handleSelectionChange())), this._register(this._coreBrowserService.onDprChange(() => this._refreshRowsDimensions())), this._refreshRowsDimensions(), this._refreshRows(), this._register(C(() => { wl ? this._debugRootContainer.remove() : this._accessibilityContainer.remove(), this._rowElements.length = 0; })); } _handleTab(e) { for (let i = 0; i < e; i++) this._handleChar(" "); } _handleChar(e) { this._liveRegionLineCount < xl + 1 && (this._charsToConsume.length > 0 ? this._charsToConsume.shift() !== e && (this._charsToAnnounce += e) : this._charsToAnnounce += e, e === ` ` && (this._liveRegionLineCount++, this._liveRegionLineCount === xl + 1 && (this._liveRegion.textContent += _i.get()))); } _clearLiveRegion() { this._liveRegion.textContent = "", this._liveRegionLineCount = 0; } _handleKey(e) { this._clearLiveRegion(), /\p{Control}/u.test(e) || this._charsToConsume.push(e); } _refreshRows(e, i) { this._liveRegionDebouncer.refresh(e, i, this._terminal.rows); } _renderRows(e, i) { let r = this._terminal.buffer, n = r.lines.length.toString(); for (let o2 = e; o2 <= i; o2++) { let l = r.lines.get(r.ydisp + o2), a = [], u = (l == null ? void 0 : l.translateToString(true, void 0, void 0, a)) || "", h2 = (r.ydisp + o2 + 1).toString(), c = this._rowElements[o2]; c && (u.length === 0 ? (c.textContent = "\xA0", this._rowColumns.set(c, [0, 1])) : (c.textContent = u, this._rowColumns.set(c, a)), c.setAttribute("aria-posinset", h2), c.setAttribute("aria-setsize", n), this._alignRowWidth(c)); } this._announceCharacters(); } _announceCharacters() { this._charsToAnnounce.length !== 0 && (this._liveRegion.textContent += this._charsToAnnounce, this._charsToAnnounce = ""); } _handleBoundaryFocus(e, i) { let r = e.target, n = this._rowElements[i === 0 ? 1 : this._rowElements.length - 2], o2 = r.getAttribute("aria-posinset"), l = i === 0 ? "1" : `${this._terminal.buffer.lines.length}`; if (o2 === l || e.relatedTarget !== n) return; let a, u; if (i === 0 ? (a = r, u = this._rowElements.pop(), this._rowContainer.removeChild(u)) : (a = this._rowElements.shift(), u = r, this._rowContainer.removeChild(a)), a.removeEventListener("focus", this._topBoundaryFocusListener), u.removeEventListener("focus", this._bottomBoundaryFocusListener), i === 0) { let h2 = this._createAccessibilityTreeNode(); this._rowElements.unshift(h2), this._rowContainer.insertAdjacentElement("afterbegin", h2); } else { let h2 = this._createAccessibilityTreeNode(); this._rowElements.push(h2), this._rowContainer.appendChild(h2); } this._rowElements[0].addEventListener("focus", this._topBoundaryFocusListener), this._rowElements[this._rowElements.length - 1].addEventListener("focus", this._bottomBoundaryFocusListener), this._terminal.scrollLines(i === 0 ? -1 : 1), this._rowElements[i === 0 ? 1 : this._rowElements.length - 2].focus(), e.preventDefault(), e.stopImmediatePropagation(); } _handleSelectionChange() { var _a5, _b; if (this._rowElements.length === 0) return; let e = this._coreBrowserService.mainDocument.getSelection(); if (!e) return; if (e.isCollapsed) { this._rowContainer.contains(e.anchorNode) && this._terminal.clearSelection(); return; } if (!e.anchorNode || !e.focusNode) { console.error("anchorNode and/or focusNode are null"); return; } let i = { node: e.anchorNode, offset: e.anchorOffset }, r = { node: e.focusNode, offset: e.focusOffset }; if ((i.node.compareDocumentPosition(r.node) & Node.DOCUMENT_POSITION_PRECEDING || i.node === r.node && i.offset > r.offset) && ([i, r] = [r, i]), i.node.compareDocumentPosition(this._rowElements[0]) & (Node.DOCUMENT_POSITION_CONTAINED_BY | Node.DOCUMENT_POSITION_FOLLOWING) && (i = { node: this._rowElements[0].childNodes[0], offset: 0 }), !this._rowContainer.contains(i.node)) return; let n = this._rowElements.slice(-1)[0]; if (r.node.compareDocumentPosition(n) & (Node.DOCUMENT_POSITION_CONTAINED_BY | Node.DOCUMENT_POSITION_PRECEDING) && (r = { node: n, offset: (_b = (_a5 = n.textContent) == null ? void 0 : _a5.length) != null ? _b : 0 }), !this._rowContainer.contains(r.node)) return; let o2 = ({ node: u, offset: h2 }) => { let c = u instanceof Text ? u.parentNode : u, d = parseInt(c == null ? void 0 : c.getAttribute("aria-posinset"), 10) - 1; if (isNaN(d)) return console.warn("row is invalid. Race condition?"), null; let _2 = this._rowColumns.get(c); if (!_2) return console.warn("columns is null. Race condition?"), null; let p = h2 < _2.length ? _2[h2] : _2.slice(-1)[0] + 1; return p >= this._terminal.cols && (++d, p = 0), { row: d, column: p }; }, l = o2(i), a = o2(r); if (!(!l || !a)) { if (l.row > a.row || l.row === a.row && l.column >= a.column) throw new Error("invalid range"); this._terminal.select(l.column, l.row, (a.row - l.row) * this._terminal.cols - l.column + a.column); } } _handleResize(e) { this._rowElements[this._rowElements.length - 1].removeEventListener("focus", this._bottomBoundaryFocusListener); for (let i = this._rowContainer.children.length; i < this._terminal.rows; i++) this._rowElements[i] = this._createAccessibilityTreeNode(), this._rowContainer.appendChild(this._rowElements[i]); for (; this._rowElements.length > e; ) this._rowContainer.removeChild(this._rowElements.pop()); this._rowElements[this._rowElements.length - 1].addEventListener("focus", this._bottomBoundaryFocusListener), this._refreshRowsDimensions(); } _createAccessibilityTreeNode() { let e = this._coreBrowserService.mainDocument.createElement("div"); return e.setAttribute("role", "listitem"), e.tabIndex = -1, this._refreshRowDimensions(e), e; } _refreshRowsDimensions() { if (this._renderService.dimensions.css.cell.height) { Object.assign(this._accessibilityContainer.style, { width: `${this._renderService.dimensions.css.canvas.width}px`, fontSize: `${this._terminal.options.fontSize}px` }), this._rowElements.length !== this._terminal.rows && this._handleResize(this._terminal.rows); for (let e = 0; e < this._terminal.rows; e++) this._refreshRowDimensions(this._rowElements[e]), this._alignRowWidth(this._rowElements[e]); } } _refreshRowDimensions(e) { e.style.height = `${this._renderService.dimensions.css.cell.height}px`; } _alignRowWidth(e) { var _a5, _b; e.style.transform = ""; let i = e.getBoundingClientRect().width, r = (_b = (_a5 = this._rowColumns.get(e)) == null ? void 0 : _a5.slice(-1)) == null ? void 0 : _b[0]; if (!r) return; let n = r * this._renderService.dimensions.css.cell.width; e.style.transform = `scaleX(${n / i})`; } }; Tt = M([S(1, xt), S(2, ae), S(3, ce)], Tt); var hi = class extends D { constructor(e, i, r, n, o2) { super(); this._element = e; this._mouseService = i; this._renderService = r; this._bufferService = n; this._linkProviderService = o2; this._linkCacheDisposables = []; this._isMouseOut = true; this._wasResized = false; this._activeLine = -1; this._onShowLinkUnderline = this._register(new v()); this.onShowLinkUnderline = this._onShowLinkUnderline.event; this._onHideLinkUnderline = this._register(new v()); this.onHideLinkUnderline = this._onHideLinkUnderline.event; this._register(C(() => { var _a5; Ne(this._linkCacheDisposables), this._linkCacheDisposables.length = 0, this._lastMouseEvent = void 0, (_a5 = this._activeProviderReplies) == null ? void 0 : _a5.clear(); })), this._register(this._bufferService.onResize(() => { this._clearCurrentLink(), this._wasResized = true; })), this._register(L(this._element, "mouseleave", () => { this._isMouseOut = true, this._clearCurrentLink(); })), this._register(L(this._element, "mousemove", this._handleMouseMove.bind(this))), this._register(L(this._element, "mousedown", this._handleMouseDown.bind(this))), this._register(L(this._element, "mouseup", this._handleMouseUp.bind(this))); } get currentLink() { return this._currentLink; } _handleMouseMove(e) { this._lastMouseEvent = e; let i = this._positionFromMouseEvent(e, this._element, this._mouseService); if (!i) return; this._isMouseOut = false; let r = e.composedPath(); for (let n = 0; n < r.length; n++) { let o2 = r[n]; if (o2.classList.contains("xterm")) break; if (o2.classList.contains("xterm-hover")) return; } (!this._lastBufferCell || i.x !== this._lastBufferCell.x || i.y !== this._lastBufferCell.y) && (this._handleHover(i), this._lastBufferCell = i); } _handleHover(e) { if (this._activeLine !== e.y || this._wasResized) { this._clearCurrentLink(), this._askForLink(e, false), this._wasResized = false; return; } this._currentLink && this._linkAtPosition(this._currentLink.link, e) || (this._clearCurrentLink(), this._askForLink(e, true)); } _askForLink(e, i) { var _a5, _b; (!this._activeProviderReplies || !i) && ((_a5 = this._activeProviderReplies) == null ? void 0 : _a5.forEach((n) => { n == null ? void 0 : n.forEach((o2) => { o2.link.dispose && o2.link.dispose(); }); }), this._activeProviderReplies = /* @__PURE__ */ new Map(), this._activeLine = e.y); let r = false; for (let [n, o2] of this._linkProviderService.linkProviders.entries()) i ? ((_b = this._activeProviderReplies) == null ? void 0 : _b.get(n)) && (r = this._checkLinkProviderResult(n, e, r)) : o2.provideLinks(e.y, (l) => { var _a6, _b2; if (this._isMouseOut) return; let a = l == null ? void 0 : l.map((u) => ({ link: u })); (_a6 = this._activeProviderReplies) == null ? void 0 : _a6.set(n, a), r = this._checkLinkProviderResult(n, e, r), ((_b2 = this._activeProviderReplies) == null ? void 0 : _b2.size) === this._linkProviderService.linkProviders.length && this._removeIntersectingLinks(e.y, this._activeProviderReplies); }); } _removeIntersectingLinks(e, i) { let r = /* @__PURE__ */ new Set(); for (let n = 0; n < i.size; n++) { let o2 = i.get(n); if (o2) for (let l = 0; l < o2.length; l++) { let a = o2[l], u = a.link.range.start.y < e ? 0 : a.link.range.start.x, h2 = a.link.range.end.y > e ? this._bufferService.cols : a.link.range.end.x; for (let c = u; c <= h2; c++) { if (r.has(c)) { o2.splice(l--, 1); break; } r.add(c); } } } } _checkLinkProviderResult(e, i, r) { var _a5; if (!this._activeProviderReplies) return r; let n = this._activeProviderReplies.get(e), o2 = false; for (let l = 0; l < e; l++) (!this._activeProviderReplies.has(l) || this._activeProviderReplies.get(l)) && (o2 = true); if (!o2 && n) { let l = n.find((a) => this._linkAtPosition(a.link, i)); l && (r = true, this._handleNewLink(l)); } if (this._activeProviderReplies.size === this._linkProviderService.linkProviders.length && !r) for (let l = 0; l < this._activeProviderReplies.size; l++) { let a = (_a5 = this._activeProviderReplies.get(l)) == null ? void 0 : _a5.find((u) => this._linkAtPosition(u.link, i)); if (a) { r = true, this._handleNewLink(a); break; } } return r; } _handleMouseDown() { this._mouseDownLink = this._currentLink; } _handleMouseUp(e) { if (!this._currentLink) return; let i = this._positionFromMouseEvent(e, this._element, this._mouseService); i && this._mouseDownLink && Ec(this._mouseDownLink.link, this._currentLink.link) && this._linkAtPosition(this._currentLink.link, i) && this._currentLink.link.activate(e, this._currentLink.link.text); } _clearCurrentLink(e, i) { !this._currentLink || !this._lastMouseEvent || (!e || !i || this._currentLink.link.range.start.y >= e && this._currentLink.link.range.end.y <= i) && (this._linkLeave(this._element, this._currentLink.link, this._lastMouseEvent), this._currentLink = void 0, Ne(this._linkCacheDisposables), this._linkCacheDisposables.length = 0); } _handleNewLink(e) { if (!this._lastMouseEvent) return; let i = this._positionFromMouseEvent(this._lastMouseEvent, this._element, this._mouseService); i && this._linkAtPosition(e.link, i) && (this._currentLink = e, this._currentLink.state = { decorations: { underline: e.link.decorations === void 0 ? true : e.link.decorations.underline, pointerCursor: e.link.decorations === void 0 ? true : e.link.decorations.pointerCursor }, isHovered: true }, this._linkHover(this._element, e.link, this._lastMouseEvent), e.link.decorations = {}, Object.defineProperties(e.link.decorations, { pointerCursor: { get: () => { var _a5, _b; return (_b = (_a5 = this._currentLink) == null ? void 0 : _a5.state) == null ? void 0 : _b.decorations.pointerCursor; }, set: (r) => { var _a5; ((_a5 = this._currentLink) == null ? void 0 : _a5.state) && this._currentLink.state.decorations.pointerCursor !== r && (this._currentLink.state.decorations.pointerCursor = r, this._currentLink.state.isHovered && this._element.classList.toggle("xterm-cursor-pointer", r)); } }, underline: { get: () => { var _a5, _b; return (_b = (_a5 = this._currentLink) == null ? void 0 : _a5.state) == null ? void 0 : _b.decorations.underline; }, set: (r) => { var _a5, _b, _c2; ((_a5 = this._currentLink) == null ? void 0 : _a5.state) && ((_c2 = (_b = this._currentLink) == null ? void 0 : _b.state) == null ? void 0 : _c2.decorations.underline) !== r && (this._currentLink.state.decorations.underline = r, this._currentLink.state.isHovered && this._fireUnderlineEvent(e.link, r)); } } }), this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((r) => { if (!this._currentLink) return; let n = r.start === 0 ? 0 : r.start + 1 + this._bufferService.buffer.ydisp, o2 = this._bufferService.buffer.ydisp + 1 + r.end; if (this._currentLink.link.range.start.y >= n && this._currentLink.link.range.end.y <= o2 && (this._clearCurrentLink(n, o2), this._lastMouseEvent)) { let l = this._positionFromMouseEvent(this._lastMouseEvent, this._element, this._mouseService); l && this._askForLink(l, false); } }))); } _linkHover(e, i, r) { var _a5; ((_a5 = this._currentLink) == null ? void 0 : _a5.state) && (this._currentLink.state.isHovered = true, this._currentLink.state.decorations.underline && this._fireUnderlineEvent(i, true), this._currentLink.state.decorations.pointerCursor && e.classList.add("xterm-cursor-pointer")), i.hover && i.hover(r, i.text); } _fireUnderlineEvent(e, i) { let r = e.range, n = this._bufferService.buffer.ydisp, o2 = this._createLinkUnderlineEvent(r.start.x - 1, r.start.y - n - 1, r.end.x, r.end.y - n - 1, void 0); (i ? this._onShowLinkUnderline : this._onHideLinkUnderline).fire(o2); } _linkLeave(e, i, r) { var _a5; ((_a5 = this._currentLink) == null ? void 0 : _a5.state) && (this._currentLink.state.isHovered = false, this._currentLink.state.decorations.underline && this._fireUnderlineEvent(i, false), this._currentLink.state.decorations.pointerCursor && e.classList.remove("xterm-cursor-pointer")), i.leave && i.leave(r, i.text); } _linkAtPosition(e, i) { let r = e.range.start.y * this._bufferService.cols + e.range.start.x, n = e.range.end.y * this._bufferService.cols + e.range.end.x, o2 = i.y * this._bufferService.cols + i.x; return r <= o2 && o2 <= n; } _positionFromMouseEvent(e, i, r) { let n = r.getCoords(e, i, this._bufferService.cols, this._bufferService.rows); if (n) return { x: n[0], y: n[1] + this._bufferService.buffer.ydisp }; } _createLinkUnderlineEvent(e, i, r, n, o2) { return { x1: e, y1: i, x2: r, y2: n, cols: this._bufferService.cols, fg: o2 }; } }; hi = M([S(1, Dt), S(2, ce), S(3, F), S(4, lr)], hi); function Ec(s15, t) { return s15.text === t.text && s15.range.start.x === t.range.start.x && s15.range.start.y === t.range.start.y && s15.range.end.x === t.range.end.x && s15.range.end.y === t.range.end.y; } var yn = class extends Sn { constructor(e = {}) { super(e); this._linkifier = this._register(new ye()); this.browser = tn; this._keyDownHandled = false; this._keyDownSeen = false; this._keyPressHandled = false; this._unprocessedDeadKey = false; this._accessibilityManager = this._register(new ye()); this._onCursorMove = this._register(new v()); this.onCursorMove = this._onCursorMove.event; this._onKey = this._register(new v()); this.onKey = this._onKey.event; this._onRender = this._register(new v()); this.onRender = this._onRender.event; this._onSelectionChange = this._register(new v()); this.onSelectionChange = this._onSelectionChange.event; this._onTitleChange = this._register(new v()); this.onTitleChange = this._onTitleChange.event; this._onBell = this._register(new v()); this.onBell = this._onBell.event; this._onFocus = this._register(new v()); this._onBlur = this._register(new v()); this._onA11yCharEmitter = this._register(new v()); this._onA11yTabEmitter = this._register(new v()); this._onWillOpen = this._register(new v()); this._setup(), this._decorationService = this._instantiationService.createInstance(Tn), this._instantiationService.setService(Be, this._decorationService), this._linkProviderService = this._instantiationService.createInstance(Qr), this._instantiationService.setService(lr, this._linkProviderService), this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(wt)), this._register(this._inputHandler.onRequestBell(() => this._onBell.fire())), this._register(this._inputHandler.onRequestRefreshRows((i) => { var _a5, _b; return this.refresh((_a5 = i == null ? void 0 : i.start) != null ? _a5 : 0, (_b = i == null ? void 0 : i.end) != null ? _b : this.rows - 1); })), this._register(this._inputHandler.onRequestSendFocus(() => this._reportFocus())), this._register(this._inputHandler.onRequestReset(() => this.reset())), this._register(this._inputHandler.onRequestWindowsOptionsReport((i) => this._reportWindowsOptions(i))), this._register(this._inputHandler.onColor((i) => this._handleColorEvent(i))), this._register($.forward(this._inputHandler.onCursorMove, this._onCursorMove)), this._register($.forward(this._inputHandler.onTitleChange, this._onTitleChange)), this._register($.forward(this._inputHandler.onA11yChar, this._onA11yCharEmitter)), this._register($.forward(this._inputHandler.onA11yTab, this._onA11yTabEmitter)), this._register(this._bufferService.onResize((i) => this._afterResize(i.cols, i.rows))), this._register(C(() => { var _a5, _b; this._customKeyEventHandler = void 0, (_b = (_a5 = this.element) == null ? void 0 : _a5.parentNode) == null ? void 0 : _b.removeChild(this.element); })); } get linkifier() { return this._linkifier.value; } get onFocus() { return this._onFocus.event; } get onBlur() { return this._onBlur.event; } get onA11yChar() { return this._onA11yCharEmitter.event; } get onA11yTab() { return this._onA11yTabEmitter.event; } get onWillOpen() { return this._onWillOpen.event; } _handleColorEvent(e) { if (this._themeService) for (let i of e) { let r, n = ""; switch (i.index) { case 256: r = "foreground", n = "10"; break; case 257: r = "background", n = "11"; break; case 258: r = "cursor", n = "12"; break; default: r = "ansi", n = "4;" + i.index; } switch (i.type) { case 0: let o2 = U.toColorRGB(r === "ansi" ? this._themeService.colors.ansi[i.index] : this._themeService.colors[r]); this.coreService.triggerDataEvent(`${b.ESC}]${n};${ml(o2)}${fs.ST}`); break; case 1: if (r === "ansi") this._themeService.modifyColors((l) => l.ansi[i.index] = j.toColor(...i.color)); else { let l = r; this._themeService.modifyColors((a) => a[l] = j.toColor(...i.color)); } break; case 2: this._themeService.restoreColor(i.index); break; } } } _setup() { super._setup(), this._customKeyEventHandler = void 0; } get buffer() { return this.buffers.active; } focus() { this.textarea && this.textarea.focus({ preventScroll: true }); } _handleScreenReaderModeOptionChange(e) { e ? !this._accessibilityManager.value && this._renderService && (this._accessibilityManager.value = this._instantiationService.createInstance(Tt, this)) : this._accessibilityManager.clear(); } _handleTextAreaFocus(e) { this.coreService.decPrivateModes.sendFocus && this.coreService.triggerDataEvent(b.ESC + "[I"), this.element.classList.add("focus"), this._showCursor(), this._onFocus.fire(); } blur() { var _a5; return (_a5 = this.textarea) == null ? void 0 : _a5.blur(); } _handleTextAreaBlur() { this.textarea.value = "", this.refresh(this.buffer.y, this.buffer.y), this.coreService.decPrivateModes.sendFocus && this.coreService.triggerDataEvent(b.ESC + "[O"), this.element.classList.remove("focus"), this._onBlur.fire(); } _syncTextArea() { if (!this.textarea || !this.buffer.isCursorInViewport || this._compositionHelper.isComposing || !this._renderService) return; let e = this.buffer.ybase + this.buffer.y, i = this.buffer.lines.get(e); if (!i) return; let r = Math.min(this.buffer.x, this.cols - 1), n = this._renderService.dimensions.css.cell.height, o2 = i.getWidth(r), l = this._renderService.dimensions.css.cell.width * o2, a = this.buffer.y * this._renderService.dimensions.css.cell.height, u = r * this._renderService.dimensions.css.cell.width; this.textarea.style.left = u + "px", this.textarea.style.top = a + "px", this.textarea.style.width = l + "px", this.textarea.style.height = n + "px", this.textarea.style.lineHeight = n + "px", this.textarea.style.zIndex = "-5"; } _initGlobal() { this._bindKeys(), this._register(L(this.element, "copy", (i) => { this.hasSelection() && Vs(i, this._selectionService); })); let e = (i) => qs(i, this.textarea, this.coreService, this.optionsService); this._register(L(this.textarea, "paste", e)), this._register(L(this.element, "paste", e)), Ss ? this._register(L(this.element, "mousedown", (i) => { i.button === 2 && Pn(i, this.textarea, this.screenElement, this._selectionService, this.options.rightClickSelectsWord); })) : this._register(L(this.element, "contextmenu", (i) => { Pn(i, this.textarea, this.screenElement, this._selectionService, this.options.rightClickSelectsWord); })), Bi && this._register(L(this.element, "auxclick", (i) => { i.button === 1 && Mn(i, this.textarea, this.screenElement); })); } _bindKeys() { this._register(L(this.textarea, "keyup", (e) => this._keyUp(e), true)), this._register(L(this.textarea, "keydown", (e) => this._keyDown(e), true)), this._register(L(this.textarea, "keypress", (e) => this._keyPress(e), true)), this._register(L(this.textarea, "compositionstart", () => this._compositionHelper.compositionstart())), this._register(L(this.textarea, "compositionupdate", (e) => this._compositionHelper.compositionupdate(e))), this._register(L(this.textarea, "compositionend", () => this._compositionHelper.compositionend())), this._register(L(this.textarea, "input", (e) => this._inputEvent(e), true)), this._register(this.onRender(() => this._compositionHelper.updateCompositionElements())); } open(e) { var _a5, _b, _c2; if (!e) throw new Error("Terminal requires a parent element."); if (e.isConnected || this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"), ((_a5 = this.element) == null ? void 0 : _a5.ownerDocument.defaultView) && this._coreBrowserService) { this.element.ownerDocument.defaultView !== this._coreBrowserService.window && (this._coreBrowserService.window = this.element.ownerDocument.defaultView); return; } this._document = e.ownerDocument, this.options.documentOverride && this.options.documentOverride instanceof Document && (this._document = this.optionsService.rawOptions.documentOverride), this.element = this._document.createElement("div"), this.element.dir = "ltr", this.element.classList.add("terminal"), this.element.classList.add("xterm"), e.appendChild(this.element); let i = this._document.createDocumentFragment(); this._viewportElement = this._document.createElement("div"), this._viewportElement.classList.add("xterm-viewport"), i.appendChild(this._viewportElement), this.screenElement = this._document.createElement("div"), this.screenElement.classList.add("xterm-screen"), this._register(L(this.screenElement, "mousemove", (o2) => this.updateCursorStyle(o2))), this._helperContainer = this._document.createElement("div"), this._helperContainer.classList.add("xterm-helpers"), this.screenElement.appendChild(this._helperContainer), i.appendChild(this.screenElement); let r = this.textarea = this._document.createElement("textarea"); this.textarea.classList.add("xterm-helper-textarea"), this.textarea.setAttribute("aria-label", mi.get()), Ts || this.textarea.setAttribute("aria-multiline", "false"), this.textarea.setAttribute("autocorrect", "off"), this.textarea.setAttribute("autocapitalize", "off"), this.textarea.setAttribute("spellcheck", "false"), this.textarea.tabIndex = 0, this._register(this.optionsService.onSpecificOptionChange("disableStdin", () => r.readOnly = this.optionsService.rawOptions.disableStdin)), this.textarea.readOnly = this.optionsService.rawOptions.disableStdin, this._coreBrowserService = this._register(this._instantiationService.createInstance(Jr, this.textarea, (_b = e.ownerDocument.defaultView) != null ? _b : window, ((_c2 = this._document) != null ? _c2 : typeof window < "u") ? window.document : null)), this._instantiationService.setService(ae, this._coreBrowserService), this._register(L(this.textarea, "focus", (o2) => this._handleTextAreaFocus(o2))), this._register(L(this.textarea, "blur", () => this._handleTextAreaBlur())), this._helperContainer.appendChild(this.textarea), this._charSizeService = this._instantiationService.createInstance(jt, this._document, this._helperContainer), this._instantiationService.setService(nt, this._charSizeService), this._themeService = this._instantiationService.createInstance(ti), this._instantiationService.setService(Re, this._themeService), this._characterJoinerService = this._instantiationService.createInstance(ct), this._instantiationService.setService(or, this._characterJoinerService), this._renderService = this._register(this._instantiationService.createInstance(Qt, this.rows, this.screenElement)), this._instantiationService.setService(ce, this._renderService), this._register(this._renderService.onRenderedViewportChange((o2) => this._onRender.fire(o2))), this.onResize((o2) => this._renderService.resize(o2.cols, o2.rows)), this._compositionView = this._document.createElement("div"), this._compositionView.classList.add("composition-view"), this._compositionHelper = this._instantiationService.createInstance($t, this.textarea, this._compositionView), this._helperContainer.appendChild(this._compositionView), this._mouseService = this._instantiationService.createInstance(Xt), this._instantiationService.setService(Dt, this._mouseService); let n = this._linkifier.value = this._register(this._instantiationService.createInstance(hi, this.screenElement)); this.element.appendChild(i); try { this._onWillOpen.fire(this.element); } catch (e2) { } this._renderService.hasRenderer() || this._renderService.setRenderer(this._createRenderer()), this._register(this.onCursorMove(() => { this._renderService.handleCursorMove(), this._syncTextArea(); })), this._register(this.onResize(() => this._renderService.handleResize(this.cols, this.rows))), this._register(this.onBlur(() => this._renderService.handleBlur())), this._register(this.onFocus(() => this._renderService.handleFocus())), this._viewport = this._register(this._instantiationService.createInstance(zt, this.element, this.screenElement)), this._register(this._viewport.onRequestScrollLines((o2) => { super.scrollLines(o2, false), this.refresh(0, this.rows - 1); })), this._selectionService = this._register(this._instantiationService.createInstance(ei, this.element, this.screenElement, n)), this._instantiationService.setService(Qs, this._selectionService), this._register(this._selectionService.onRequestScrollLines((o2) => this.scrollLines(o2.amount, o2.suppressScrollEvent))), this._register(this._selectionService.onSelectionChange(() => this._onSelectionChange.fire())), this._register(this._selectionService.onRequestRedraw((o2) => this._renderService.handleSelectionChanged(o2.start, o2.end, o2.columnSelectMode))), this._register(this._selectionService.onLinuxMouseSelection((o2) => { this.textarea.value = o2, this.textarea.focus(), this.textarea.select(); })), this._register($.any(this._onScroll.event, this._inputHandler.onScroll)(() => { var _a6; this._selectionService.refresh(), (_a6 = this._viewport) == null ? void 0 : _a6.queueSync(); })), this._register(this._instantiationService.createInstance(Gt, this.screenElement)), this._register(L(this.element, "mousedown", (o2) => this._selectionService.handleMouseDown(o2))), this.coreMouseService.areMouseEventsActive ? (this._selectionService.disable(), this.element.classList.add("enable-mouse-events")) : this._selectionService.enable(), this.options.screenReaderMode && (this._accessibilityManager.value = this._instantiationService.createInstance(Tt, this)), this._register(this.optionsService.onSpecificOptionChange("screenReaderMode", (o2) => this._handleScreenReaderModeOptionChange(o2))), this.options.overviewRuler.width && (this._overviewRulerRenderer = this._register(this._instantiationService.createInstance(bt, this._viewportElement, this.screenElement))), this.optionsService.onSpecificOptionChange("overviewRuler", (o2) => { !this._overviewRulerRenderer && o2 && this._viewportElement && this.screenElement && (this._overviewRulerRenderer = this._register(this._instantiationService.createInstance(bt, this._viewportElement, this.screenElement))); }), this._charSizeService.measure(), this.refresh(0, this.rows - 1), this._initGlobal(), this.bindMouse(); } _createRenderer() { return this._instantiationService.createInstance(Yt, this, this._document, this.element, this.screenElement, this._viewportElement, this._helperContainer, this.linkifier); } bindMouse() { let e = this, i = this.element; function r(l) { var _a5, _b, _c2, _d, _e3; let a = e._mouseService.getMouseReportCoords(l, e.screenElement); if (!a) return false; let u, h2; switch (l.overrideType || l.type) { case "mousemove": h2 = 32, l.buttons === void 0 ? (u = 3, l.button !== void 0 && (u = l.button < 3 ? l.button : 3)) : u = l.buttons & 1 ? 0 : l.buttons & 4 ? 1 : l.buttons & 2 ? 2 : 3; break; case "mouseup": h2 = 0, u = l.button < 3 ? l.button : 3; break; case "mousedown": h2 = 1, u = l.button < 3 ? l.button : 3; break; case "wheel": if (e._customWheelEventHandler && e._customWheelEventHandler(l) === false) return false; let c = l.deltaY; if (c === 0 || e.coreMouseService.consumeWheelEvent(l, (_d = (_c2 = (_b = (_a5 = e._renderService) == null ? void 0 : _a5.dimensions) == null ? void 0 : _b.device) == null ? void 0 : _c2.cell) == null ? void 0 : _d.height, (_e3 = e._coreBrowserService) == null ? void 0 : _e3.dpr) === 0) return false; h2 = c < 0 ? 0 : 1, u = 4; break; default: return false; } return h2 === void 0 || u === void 0 || u > 4 ? false : e.coreMouseService.triggerMouseEvent({ col: a.col, row: a.row, x: a.x, y: a.y, button: u, action: h2, ctrl: l.ctrlKey, alt: l.altKey, shift: l.shiftKey }); } let n = { mouseup: null, wheel: null, mousedrag: null, mousemove: null }, o2 = { mouseup: (l) => (r(l), l.buttons || (this._document.removeEventListener("mouseup", n.mouseup), n.mousedrag && this._document.removeEventListener("mousemove", n.mousedrag)), this.cancel(l)), wheel: (l) => (r(l), this.cancel(l, true)), mousedrag: (l) => { l.buttons && r(l); }, mousemove: (l) => { l.buttons || r(l); } }; this._register(this.coreMouseService.onProtocolChange((l) => { l ? (this.optionsService.rawOptions.logLevel === "debug" && this._logService.debug("Binding to mouse events:", this.coreMouseService.explainEvents(l)), this.element.classList.add("enable-mouse-events"), this._selectionService.disable()) : (this._logService.debug("Unbinding from mouse events."), this.element.classList.remove("enable-mouse-events"), this._selectionService.enable()), l & 8 ? n.mousemove || (i.addEventListener("mousemove", o2.mousemove), n.mousemove = o2.mousemove) : (i.removeEventListener("mousemove", n.mousemove), n.mousemove = null), l & 16 ? n.wheel || (i.addEventListener("wheel", o2.wheel, { passive: false }), n.wheel = o2.wheel) : (i.removeEventListener("wheel", n.wheel), n.wheel = null), l & 2 ? n.mouseup || (n.mouseup = o2.mouseup) : (this._document.removeEventListener("mouseup", n.mouseup), n.mouseup = null), l & 4 ? n.mousedrag || (n.mousedrag = o2.mousedrag) : (this._document.removeEventListener("mousemove", n.mousedrag), n.mousedrag = null); })), this.coreMouseService.activeProtocol = this.coreMouseService.activeProtocol, this._register(L(i, "mousedown", (l) => { if (l.preventDefault(), this.focus(), !(!this.coreMouseService.areMouseEventsActive || this._selectionService.shouldForceSelection(l))) return r(l), n.mouseup && this._document.addEventListener("mouseup", n.mouseup), n.mousedrag && this._document.addEventListener("mousemove", n.mousedrag), this.cancel(l); })), this._register(L(i, "wheel", (l) => { var _a5, _b, _c2, _d, _e3; if (!n.wheel) { if (this._customWheelEventHandler && this._customWheelEventHandler(l) === false) return false; if (!this.buffer.hasScrollback) { if (l.deltaY === 0) return false; if (e.coreMouseService.consumeWheelEvent(l, (_d = (_c2 = (_b = (_a5 = e._renderService) == null ? void 0 : _a5.dimensions) == null ? void 0 : _b.device) == null ? void 0 : _c2.cell) == null ? void 0 : _d.height, (_e3 = e._coreBrowserService) == null ? void 0 : _e3.dpr) === 0) return this.cancel(l, true); let h2 = b.ESC + (this.coreService.decPrivateModes.applicationCursorKeys ? "O" : "[") + (l.deltaY < 0 ? "A" : "B"); return this.coreService.triggerDataEvent(h2, true), this.cancel(l, true); } } }, { passive: false })); } refresh(e, i) { var _a5; (_a5 = this._renderService) == null ? void 0 : _a5.refreshRows(e, i); } updateCursorStyle(e) { var _a5; ((_a5 = this._selectionService) == null ? void 0 : _a5.shouldColumnSelect(e)) ? this.element.classList.add("column-select") : this.element.classList.remove("column-select"); } _showCursor() { this.coreService.isCursorInitialized || (this.coreService.isCursorInitialized = true, this.refresh(this.buffer.y, this.buffer.y)); } scrollLines(e, i) { this._viewport ? this._viewport.scrollLines(e) : super.scrollLines(e, i), this.refresh(0, this.rows - 1); } scrollPages(e) { this.scrollLines(e * (this.rows - 1)); } scrollToTop() { this.scrollLines(-this._bufferService.buffer.ydisp); } scrollToBottom(e) { e && this._viewport ? this._viewport.scrollToLine(this.buffer.ybase, true) : this.scrollLines(this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp); } scrollToLine(e) { let i = e - this._bufferService.buffer.ydisp; i !== 0 && this.scrollLines(i); } paste(e) { Cn(e, this.textarea, this.coreService, this.optionsService); } attachCustomKeyEventHandler(e) { this._customKeyEventHandler = e; } attachCustomWheelEventHandler(e) { this._customWheelEventHandler = e; } registerLinkProvider(e) { return this._linkProviderService.registerLinkProvider(e); } registerCharacterJoiner(e) { if (!this._characterJoinerService) throw new Error("Terminal must be opened first"); let i = this._characterJoinerService.register(e); return this.refresh(0, this.rows - 1), i; } deregisterCharacterJoiner(e) { if (!this._characterJoinerService) throw new Error("Terminal must be opened first"); this._characterJoinerService.deregister(e) && this.refresh(0, this.rows - 1); } get markers() { return this.buffer.markers; } registerMarker(e) { return this.buffer.addMarker(this.buffer.ybase + this.buffer.y + e); } registerDecoration(e) { return this._decorationService.registerDecoration(e); } hasSelection() { return this._selectionService ? this._selectionService.hasSelection : false; } select(e, i, r) { this._selectionService.setSelection(e, i, r); } getSelection() { return this._selectionService ? this._selectionService.selectionText : ""; } getSelectionPosition() { if (!(!this._selectionService || !this._selectionService.hasSelection)) return { start: { x: this._selectionService.selectionStart[0], y: this._selectionService.selectionStart[1] }, end: { x: this._selectionService.selectionEnd[0], y: this._selectionService.selectionEnd[1] } }; } clearSelection() { var _a5; (_a5 = this._selectionService) == null ? void 0 : _a5.clearSelection(); } selectAll() { var _a5; (_a5 = this._selectionService) == null ? void 0 : _a5.selectAll(); } selectLines(e, i) { var _a5; (_a5 = this._selectionService) == null ? void 0 : _a5.selectLines(e, i); } _keyDown(e) { if (this._keyDownHandled = false, this._keyDownSeen = true, this._customKeyEventHandler && this._customKeyEventHandler(e) === false) return false; let i = this.browser.isMac && this.options.macOptionIsMeta && e.altKey; if (!i && !this._compositionHelper.keydown(e)) return this.options.scrollOnUserInput && this.buffer.ybase !== this.buffer.ydisp && this.scrollToBottom(true), false; !i && (e.key === "Dead" || e.key === "AltGraph") && (this._unprocessedDeadKey = true); let r = Il(e, this.coreService.decPrivateModes.applicationCursorKeys, this.browser.isMac, this.options.macOptionIsMeta); if (this.updateCursorStyle(e), r.type === 3 || r.type === 2) { let n = this.rows - 1; return this.scrollLines(r.type === 2 ? -n : n), this.cancel(e, true); } if (r.type === 1 && this.selectAll(), this._isThirdLevelShift(this.browser, e) || (r.cancel && this.cancel(e, true), !r.key) || e.key && !e.ctrlKey && !e.altKey && !e.metaKey && e.key.length === 1 && e.key.charCodeAt(0) >= 65 && e.key.charCodeAt(0) <= 90) return true; if (this._unprocessedDeadKey) return this._unprocessedDeadKey = false, true; if ((r.key === b.ETX || r.key === b.CR) && (this.textarea.value = ""), this._onKey.fire({ key: r.key, domEvent: e }), this._showCursor(), this.coreService.triggerDataEvent(r.key, true), !this.optionsService.rawOptions.screenReaderMode || e.altKey || e.ctrlKey) return this.cancel(e, true); this._keyDownHandled = true; } _isThirdLevelShift(e, i) { let r = e.isMac && !this.options.macOptionIsMeta && i.altKey && !i.ctrlKey && !i.metaKey || e.isWindows && i.altKey && i.ctrlKey && !i.metaKey || e.isWindows && i.getModifierState("AltGraph"); return i.type === "keypress" ? r : r && (!i.keyCode || i.keyCode > 47); } _keyUp(e) { this._keyDownSeen = false, !(this._customKeyEventHandler && this._customKeyEventHandler(e) === false) && (Tc(e) || this.focus(), this.updateCursorStyle(e), this._keyPressHandled = false); } _keyPress(e) { let i; if (this._keyPressHandled = false, this._keyDownHandled || this._customKeyEventHandler && this._customKeyEventHandler(e) === false) return false; if (this.cancel(e), e.charCode) i = e.charCode; else if (e.which === null || e.which === void 0) i = e.keyCode; else if (e.which !== 0 && e.charCode !== 0) i = e.which; else return false; return !i || (e.altKey || e.ctrlKey || e.metaKey) && !this._isThirdLevelShift(this.browser, e) ? false : (i = String.fromCharCode(i), this._onKey.fire({ key: i, domEvent: e }), this._showCursor(), this.coreService.triggerDataEvent(i, true), this._keyPressHandled = true, this._unprocessedDeadKey = false, true); } _inputEvent(e) { if (e.data && e.inputType === "insertText" && (!e.composed || !this._keyDownSeen) && !this.optionsService.rawOptions.screenReaderMode) { if (this._keyPressHandled) return false; this._unprocessedDeadKey = false; let i = e.data; return this.coreService.triggerDataEvent(i, true), this.cancel(e), true; } return false; } resize(e, i) { if (e === this.cols && i === this.rows) { this._charSizeService && !this._charSizeService.hasValidSize && this._charSizeService.measure(); return; } super.resize(e, i); } _afterResize(e, i) { var _a5; (_a5 = this._charSizeService) == null ? void 0 : _a5.measure(); } clear() { if (!(this.buffer.ybase === 0 && this.buffer.y === 0)) { this.buffer.clearAllMarkers(), this.buffer.lines.set(0, this.buffer.lines.get(this.buffer.ybase + this.buffer.y)), this.buffer.lines.length = 1, this.buffer.ydisp = 0, this.buffer.ybase = 0, this.buffer.y = 0; for (let e = 1; e < this.rows; e++) this.buffer.lines.push(this.buffer.getBlankLine(X)); this._onScroll.fire({ position: this.buffer.ydisp }), this.refresh(0, this.rows - 1); } } reset() { var _a5; this.options.rows = this.rows, this.options.cols = this.cols; let e = this._customKeyEventHandler; this._setup(), super.reset(), (_a5 = this._selectionService) == null ? void 0 : _a5.reset(), this._decorationService.reset(), this._customKeyEventHandler = e, this.refresh(0, this.rows - 1); } clearTextureAtlas() { var _a5; (_a5 = this._renderService) == null ? void 0 : _a5.clearTextureAtlas(); } _reportFocus() { var _a5; ((_a5 = this.element) == null ? void 0 : _a5.classList.contains("focus")) ? this.coreService.triggerDataEvent(b.ESC + "[I") : this.coreService.triggerDataEvent(b.ESC + "[O"); } _reportWindowsOptions(e) { if (this._renderService) switch (e) { case 0: let i = this._renderService.dimensions.css.canvas.width.toFixed(0), r = this._renderService.dimensions.css.canvas.height.toFixed(0); this.coreService.triggerDataEvent(`${b.ESC}[4;${r};${i}t`); break; case 1: let n = this._renderService.dimensions.css.cell.width.toFixed(0), o2 = this._renderService.dimensions.css.cell.height.toFixed(0); this.coreService.triggerDataEvent(`${b.ESC}[6;${o2};${n}t`); break; } } cancel(e, i) { if (!(!this.options.cancelEvents && !i)) return e.preventDefault(), e.stopPropagation(), false; } }; function Tc(s15) { return s15.keyCode === 16 || s15.keyCode === 17 || s15.keyCode === 18; } var xn = class { constructor() { this._addons = []; } dispose() { for (let t = this._addons.length - 1; t >= 0; t--) this._addons[t].instance.dispose(); } loadAddon(t, e) { let i = { instance: e, dispose: e.dispose, isDisposed: false }; this._addons.push(i), e.dispose = () => this._wrappedAddonDispose(i), e.activate(t); } _wrappedAddonDispose(t) { if (t.isDisposed) return; let e = -1; for (let i = 0; i < this._addons.length; i++) if (this._addons[i] === t) { e = i; break; } if (e === -1) throw new Error("Could not dispose an addon that has not been loaded"); t.isDisposed = true, t.dispose.apply(t.instance), this._addons.splice(e, 1); } }; var wn = class { constructor(t) { this._line = t; } get isWrapped() { return this._line.isWrapped; } get length() { return this._line.length; } getCell(t, e) { if (!(t < 0 || t >= this._line.length)) return e ? (this._line.loadCell(t, e), e) : this._line.loadCell(t, new q()); } translateToString(t, e, i) { return this._line.translateToString(t, e, i); } }; var Ji = class { constructor(t, e) { this._buffer = t; this.type = e; } init(t) { return this._buffer = t, this; } get cursorY() { return this._buffer.y; } get cursorX() { return this._buffer.x; } get viewportY() { return this._buffer.ydisp; } get baseY() { return this._buffer.ybase; } get length() { return this._buffer.lines.length; } getLine(t) { let e = this._buffer.lines.get(t); if (e) return new wn(e); } getNullCell() { return new q(); } }; var Dn = class extends D { constructor(e) { super(); this._core = e; this._onBufferChange = this._register(new v()); this.onBufferChange = this._onBufferChange.event; this._normal = new Ji(this._core.buffers.normal, "normal"), this._alternate = new Ji(this._core.buffers.alt, "alternate"), this._core.buffers.onBufferActivate(() => this._onBufferChange.fire(this.active)); } get active() { if (this._core.buffers.active === this._core.buffers.normal) return this.normal; if (this._core.buffers.active === this._core.buffers.alt) return this.alternate; throw new Error("Active buffer is neither normal nor alternate"); } get normal() { return this._normal.init(this._core.buffers.normal); } get alternate() { return this._alternate.init(this._core.buffers.alt); } }; var Rn = class { constructor(t) { this._core = t; } registerCsiHandler(t, e) { return this._core.registerCsiHandler(t, (i) => e(i.toArray())); } addCsiHandler(t, e) { return this.registerCsiHandler(t, e); } registerDcsHandler(t, e) { return this._core.registerDcsHandler(t, (i, r) => e(i, r.toArray())); } addDcsHandler(t, e) { return this.registerDcsHandler(t, e); } registerEscHandler(t, e) { return this._core.registerEscHandler(t, e); } addEscHandler(t, e) { return this.registerEscHandler(t, e); } registerOscHandler(t, e) { return this._core.registerOscHandler(t, e); } addOscHandler(t, e) { return this.registerOscHandler(t, e); } }; var Ln = class { constructor(t) { this._core = t; } register(t) { this._core.unicodeService.register(t); } get versions() { return this._core.unicodeService.versions; } get activeVersion() { return this._core.unicodeService.activeVersion; } set activeVersion(t) { this._core.unicodeService.activeVersion = t; } }; var Ic = ["cols", "rows"]; var Ue = 0; var Dl = class extends D { constructor(t) { super(), this._core = this._register(new yn(t)), this._addonManager = this._register(new xn()), this._publicOptions = { ...this._core.options }; let e = (r) => this._core.options[r], i = (r, n) => { this._checkReadonlyOptions(r), this._core.options[r] = n; }; for (let r in this._core.options) { let n = { get: e.bind(this, r), set: i.bind(this, r) }; Object.defineProperty(this._publicOptions, r, n); } } _checkReadonlyOptions(t) { if (Ic.includes(t)) throw new Error(`Option "${t}" can only be set in the constructor`); } _checkProposedApi() { if (!this._core.optionsService.rawOptions.allowProposedApi) throw new Error("You must set the allowProposedApi option to true to use proposed API"); } get onBell() { return this._core.onBell; } get onBinary() { return this._core.onBinary; } get onCursorMove() { return this._core.onCursorMove; } get onData() { return this._core.onData; } get onKey() { return this._core.onKey; } get onLineFeed() { return this._core.onLineFeed; } get onRender() { return this._core.onRender; } get onResize() { return this._core.onResize; } get onScroll() { return this._core.onScroll; } get onSelectionChange() { return this._core.onSelectionChange; } get onTitleChange() { return this._core.onTitleChange; } get onWriteParsed() { return this._core.onWriteParsed; } get element() { return this._core.element; } get parser() { return this._parser || (this._parser = new Rn(this._core)), this._parser; } get unicode() { return this._checkProposedApi(), new Ln(this._core); } get textarea() { return this._core.textarea; } get rows() { return this._core.rows; } get cols() { return this._core.cols; } get buffer() { return this._buffer || (this._buffer = this._register(new Dn(this._core))), this._buffer; } get markers() { return this._checkProposedApi(), this._core.markers; } get modes() { let t = this._core.coreService.decPrivateModes, e = "none"; switch (this._core.coreMouseService.activeProtocol) { case "X10": e = "x10"; break; case "VT200": e = "vt200"; break; case "DRAG": e = "drag"; break; case "ANY": e = "any"; break; } return { applicationCursorKeysMode: t.applicationCursorKeys, applicationKeypadMode: t.applicationKeypad, bracketedPasteMode: t.bracketedPasteMode, insertMode: this._core.coreService.modes.insertMode, mouseTrackingMode: e, originMode: t.origin, reverseWraparoundMode: t.reverseWraparound, sendFocusMode: t.sendFocus, synchronizedOutputMode: t.synchronizedOutput, wraparoundMode: t.wraparound }; } get options() { return this._publicOptions; } set options(t) { for (let e in t) this._publicOptions[e] = t[e]; } blur() { this._core.blur(); } focus() { this._core.focus(); } input(t, e = true) { this._core.input(t, e); } resize(t, e) { this._verifyIntegers(t, e), this._core.resize(t, e); } open(t) { this._core.open(t); } attachCustomKeyEventHandler(t) { this._core.attachCustomKeyEventHandler(t); } attachCustomWheelEventHandler(t) { this._core.attachCustomWheelEventHandler(t); } registerLinkProvider(t) { return this._core.registerLinkProvider(t); } registerCharacterJoiner(t) { return this._checkProposedApi(), this._core.registerCharacterJoiner(t); } deregisterCharacterJoiner(t) { this._checkProposedApi(), this._core.deregisterCharacterJoiner(t); } registerMarker(t = 0) { return this._verifyIntegers(t), this._core.registerMarker(t); } registerDecoration(t) { var _a5, _b, _c2; return this._checkProposedApi(), this._verifyPositiveIntegers((_a5 = t.x) != null ? _a5 : 0, (_b = t.width) != null ? _b : 0, (_c2 = t.height) != null ? _c2 : 0), this._core.registerDecoration(t); } hasSelection() { return this._core.hasSelection(); } select(t, e, i) { this._verifyIntegers(t, e, i), this._core.select(t, e, i); } getSelection() { return this._core.getSelection(); } getSelectionPosition() { return this._core.getSelectionPosition(); } clearSelection() { this._core.clearSelection(); } selectAll() { this._core.selectAll(); } selectLines(t, e) { this._verifyIntegers(t, e), this._core.selectLines(t, e); } dispose() { super.dispose(); } scrollLines(t) { this._verifyIntegers(t), this._core.scrollLines(t); } scrollPages(t) { this._verifyIntegers(t), this._core.scrollPages(t); } scrollToTop() { this._core.scrollToTop(); } scrollToBottom() { this._core.scrollToBottom(); } scrollToLine(t) { this._verifyIntegers(t), this._core.scrollToLine(t); } clear() { this._core.clear(); } write(t, e) { this._core.write(t, e); } writeln(t, e) { this._core.write(t), this._core.write(`\r `, e); } paste(t) { this._core.paste(t); } refresh(t, e) { this._verifyIntegers(t, e), this._core.refresh(t, e); } reset() { this._core.reset(); } clearTextureAtlas() { this._core.clearTextureAtlas(); } loadAddon(t) { this._addonManager.loadAddon(this, t); } static get strings() { return { get promptLabel() { return mi.get(); }, set promptLabel(t) { mi.set(t); }, get tooMuchOutput() { return _i.get(); }, set tooMuchOutput(t) { _i.set(t); } }; } _verifyIntegers(...t) { for (Ue of t) if (Ue === 1 / 0 || isNaN(Ue) || Ue % 1 !== 0) throw new Error("This API only accepts integers"); } _verifyPositiveIntegers(...t) { for (Ue of t) if (Ue && (Ue === 1 / 0 || isNaN(Ue) || Ue % 1 !== 0 || Ue < 0)) throw new Error("This API only accepts positive integers"); } }; // node_modules/@xterm/addon-fit/lib/addon-fit.mjs var h = 2; var _ = 1; var o = class { activate(e) { this._terminal = e; } dispose() { } fit() { let e = this.proposeDimensions(); if (!e || !this._terminal || isNaN(e.cols) || isNaN(e.rows)) return; let t = this._terminal._core; (this._terminal.rows !== e.rows || this._terminal.cols !== e.cols) && (t._renderService.clear(), this._terminal.resize(e.cols, e.rows)); } proposeDimensions() { var _a5; if (!this._terminal || !this._terminal.element || !this._terminal.element.parentElement) return; let t = this._terminal._core._renderService.dimensions; if (t.css.cell.width === 0 || t.css.cell.height === 0) return; let s15 = this._terminal.options.scrollback === 0 ? 0 : ((_a5 = this._terminal.options.overviewRuler) == null ? void 0 : _a5.width) || 14, r = window.getComputedStyle(this._terminal.element.parentElement), l = parseInt(r.getPropertyValue("height")), a = Math.max(0, parseInt(r.getPropertyValue("width"))), i = window.getComputedStyle(this._terminal.element), n = { top: parseInt(i.getPropertyValue("padding-top")), bottom: parseInt(i.getPropertyValue("padding-bottom")), right: parseInt(i.getPropertyValue("padding-right")), left: parseInt(i.getPropertyValue("padding-left")) }, m = n.top + n.bottom, d = n.right + n.left, c = l - m, p = a - d - s15; return { cols: Math.max(h, Math.floor(p / t.css.cell.width)), rows: Math.max(_, Math.floor(c / t.css.cell.height)) }; } }; // runtime-utils.ts var import_node_crypto = require("node:crypto"); function formatActiveFileMention(fileName) { return `@${fileName.trim()} `; } function formatActiveFolderMention(filePath) { const trimmed = filePath.trim(); if (!trimmed) { return "@./ "; } const lastSlash = trimmed.lastIndexOf("/"); if (lastSlash <= 0) { return "@./ "; } return `@${trimmed.slice(0, lastSlash)}/ `; } function isCodexLikeCommand(command) { if (typeof command !== "string") { return false; } const trimmed = command.trim(); if (!trimmed) { return false; } return trimmed === "codex" || /^codex(\s|$)/.test(trimmed); } function migrateRuntimeSettings(raw, defaults, generateId = defaultGenerateRuntimeId) { const fallbackDefaults = defaults.length > 0 ? defaults.map((d) => ({ ...d })) : [{ id: generateId(), name: "Default", command: "" }]; if (raw && Array.isArray(raw.runtimes)) { const sanitized = sanitizeRuntimes(raw.runtimes, generateId); if (sanitized.length > 0) { const selected = typeof raw.selectedRuntimeId === "string" && sanitized.some((r) => r.id === raw.selectedRuntimeId) ? raw.selectedRuntimeId : sanitized[0].id; return { runtimes: sanitized, selectedRuntimeId: selected }; } } const runtimes = fallbackDefaults; if (raw && typeof raw.command === "string" && raw.command.trim()) { const claude = runtimes.find((r) => r.id === "claude"); if (claude) { claude.command = raw.command.trim(); } } if (raw && typeof raw.codexCommand === "string" && raw.codexCommand.trim()) { const codex = runtimes.find((r) => r.id === "codex"); if (codex) { codex.command = raw.codexCommand.trim(); } } const legacyRuntime = typeof (raw == null ? void 0 : raw.runtime) === "string" && (raw.runtime === "claude" || raw.runtime === "codex") ? raw.runtime : void 0; const selectedRuntimeId = legacyRuntime && runtimes.some((r) => r.id === legacyRuntime) ? legacyRuntime : runtimes[0].id; return { runtimes, selectedRuntimeId }; } function sanitizeRuntimes(raw, generateId) { const result = []; const seenIds = /* @__PURE__ */ new Set(); for (const entry of raw) { if (!entry || typeof entry !== "object") continue; const candidate = entry; const name = typeof candidate.name === "string" ? candidate.name : ""; const command = typeof candidate.command === "string" ? candidate.command : ""; let id = typeof candidate.id === "string" && candidate.id.trim() ? candidate.id : generateId(); while (seenIds.has(id)) { id = generateId(); } seenIds.add(id); result.push({ id, name, command }); } return result; } function defaultGenerateRuntimeId() { return (0, import_node_crypto.randomUUID)(); } function resolvePluginDir(pluginDir, vaultBasePath, pathApi) { if (!pluginDir) { return void 0; } if (pathApi.isAbsolute(pluginDir)) { return pluginDir; } if (!vaultBasePath) { return void 0; } return pathApi.resolve(vaultBasePath, pluginDir); } function mergePathEntries(currentPath, extras, platform) { const delimiter = platform === "win32" ? ";" : ":"; const existing = (currentPath || "").split(delimiter).filter(Boolean); const set = new Set(existing); for (const entry of extras) { if (!entry || set.has(entry)) { continue; } set.add(entry); existing.push(entry); } return existing.join(delimiter); } function resolveExecutableInPath(executable, pathValue, platform, existsSync2, pathApi) { if (!pathValue) { return void 0; } const delimiter = platform === "win32" ? ";" : ":"; const candidates = pathValue.split(delimiter).filter(Boolean); const fileName = platform === "win32" ? `${executable}.exe` : executable; for (const dir of candidates) { const fullPath = pathApi.join(dir, fileName); if (existsSync2(fullPath)) { return fullPath; } } return void 0; } function detectNodeExecutable(configuredValue, platform, env, existsSync2, pathApi) { const configured = configuredValue == null ? void 0 : configuredValue.trim(); if (configured && configured.toLowerCase() !== "auto") { return configured; } const fromPath = resolveExecutableInPath("node", env.PATH, platform, existsSync2, pathApi); if (fromPath) { return fromPath; } const home = env.HOME || env.USERPROFILE || ""; const defaults = platform === "win32" ? [ "C:\\Program Files\\nodejs\\node.exe", "C:\\Program Files (x86)\\nodejs\\node.exe" ] : [ "/opt/homebrew/bin/node", "/usr/local/bin/node", "/usr/bin/node", home ? pathApi.join(home, ".volta", "bin", "node") : "", home ? pathApi.join(home, ".nvm", "current", "bin", "node") : "" ]; for (const candidate of defaults) { if (candidate && existsSync2(candidate)) { return candidate; } } return "node"; } // session-utils.ts function runtimeMatches(runtime, target) { const wanted = target.trim().toLowerCase(); if (!wanted) { return false; } if (runtime.id.trim().toLowerCase() === wanted) { return true; } return runtime.name.trim().toLowerCase() === wanted; } function resolveRuntimeForAutomation(runtimes, declared, defaultId) { var _a5, _b, _c2; const wanted = (declared != null ? declared : "").trim(); if (wanted) { return (_a5 = runtimes.find((runtime) => runtimeMatches(runtime, wanted))) != null ? _a5 : null; } return (_c2 = (_b = runtimes.find((runtime) => runtime.id === defaultId)) != null ? _b : runtimes[0]) != null ? _c2 : null; } function nextSessionLabel(existingLabels, runtimeName) { const base = runtimeName.trim() || "(Unnamed)"; const taken = new Set(existingLabels); if (!taken.has(base)) { return base; } let counter = 2; while (taken.has(`${base} (${counter})`)) { counter += 1; } return `${base} (${counter})`; } function canOpenSession(currentCount, max) { if (!Number.isFinite(max) || max <= 0) { return true; } return currentCount < max; } function tabDotClass(opts) { if (opts.running && opts.activity === "working") { return opts.origin === "automation" ? "is-automation" : "is-working"; } return "is-idle"; } // automation.ts var import_cron_parser = __toESM(require_dist()); var FRONTMATTER_RE = /^---\s*\r?\n([\s\S]*?)\r?\n---\s*(?:\r?\n)?([\s\S]*)$/; function splitFrontmatter(content) { var _a5; const match = FRONTMATTER_RE.exec(content); if (!match) { return { yaml: null, body: content }; } return { yaml: match[1], body: (_a5 = match[2]) != null ? _a5 : "" }; } function basenameWithoutExt(filePath) { const lastSlash = filePath.lastIndexOf("/"); const file = lastSlash >= 0 ? filePath.slice(lastSlash + 1) : filePath; const dot = file.lastIndexOf("."); return dot > 0 ? file.slice(0, dot) : file; } function parseAutomationFile(content, filePath, parseYaml2) { const fallbackName = basenameWithoutExt(filePath); const { yaml, body } = splitFrontmatter(content); if (yaml === null) { return { ok: false, error: { path: filePath, name: fallbackName, reason: "Missing frontmatter block (expected `---` fenced YAML at top of file)." } }; } let parsed; try { parsed = parseYaml2(yaml); } catch (err) { return { ok: false, error: { path: filePath, name: fallbackName, reason: `YAML parse error: ${err.message}` } }; } if (!parsed || typeof parsed !== "object") { return { ok: false, error: { path: filePath, name: fallbackName, reason: "Frontmatter must be a YAML mapping." } }; } const fm = parsed; const hasInterval = fm.interval !== void 0 && fm.interval !== null; const hasCron = typeof fm.cron === "string" && fm.cron.trim().length > 0; if (hasInterval && hasCron) { return { ok: false, error: { path: filePath, name: typeof fm.name === "string" && fm.name.trim() ? fm.name.trim() : fallbackName, reason: "`interval` and `cron` are mutually exclusive \u2014 set only one." } }; } if (!hasInterval && !hasCron) { return { ok: false, error: { path: filePath, name: typeof fm.name === "string" && fm.name.trim() ? fm.name.trim() : fallbackName, reason: "Missing schedule: set either `interval` (minutes) or `cron`." } }; } let interval = null; if (hasInterval) { const raw = fm.interval; if (typeof raw !== "number" || !Number.isFinite(raw) || !Number.isInteger(raw) || raw < 1) { return { ok: false, error: { path: filePath, name: typeof fm.name === "string" && fm.name.trim() ? fm.name.trim() : fallbackName, reason: "`interval` must be an integer >= 1 (minutes)." } }; } interval = raw; } let cron = null; if (hasCron) { const expr = fm.cron.trim(); try { import_cron_parser.CronExpressionParser.parse(expr); } catch (err) { return { ok: false, error: { path: filePath, name: typeof fm.name === "string" && fm.name.trim() ? fm.name.trim() : fallbackName, reason: `Invalid cron expression: ${err.message}` } }; } cron = expr; } const trimmedBody = body.trim(); if (!trimmedBody) { return { ok: false, error: { path: filePath, name: typeof fm.name === "string" && fm.name.trim() ? fm.name.trim() : fallbackName, reason: "Prompt body is empty (write the prompt below the frontmatter)." } }; } return { ok: true, entry: { path: filePath, name: typeof fm.name === "string" && fm.name.trim() ? fm.name.trim() : fallbackName, enabled: typeof fm.enabled === "boolean" ? fm.enabled : true, interval, cron, runtime: typeof fm.runtime === "string" && fm.runtime.trim() ? fm.runtime.trim() : null, appendNewline: typeof fm.appendNewline === "boolean" ? fm.appendNewline : true, body: trimmedBody } }; } function computeNextRun(entry, lastRun, now) { if (entry.interval !== null) { if (lastRun === null) { return now; } return lastRun + entry.interval * 6e4; } if (entry.cron !== null) { try { const reference = lastRun != null ? lastRun : now - 1; const it = import_cron_parser.CronExpressionParser.parse(entry.cron, { currentDate: new Date(reference) }); return it.next().getTime(); } catch (e) { return null; } } return null; } function describeSchedule(entry) { if (entry.interval !== null) { return entry.interval === 1 ? "every 1 min" : `every ${entry.interval} min`; } if (entry.cron !== null) { return `cron: ${entry.cron}`; } return "no schedule"; } function pushHistory(history, record, limit) { const next = [record, ...history]; if (next.length > limit) { next.length = limit; } return next; } function buildPromptPreview(body, maxLen = 120) { const oneLine = body.replace(/\s+/g, " ").trim(); if (oneLine.length <= maxLen) { return oneLine; } return `${oneLine.slice(0, maxLen - 1)}\u2026`; } // automations-modal.ts var import_obsidian = require("obsidian"); var AutomationsModal = class extends import_obsidian.Modal { constructor(app, plugin) { super(app); this.currentTab = "automations"; this.tabsHostEl = null; this.bodyEl = null; this.unsubscribe = null; this.plugin = plugin; } onOpen() { this.modalEl.addClass("any-ai-cli-automations-modal"); this.titleEl.setText("Automations"); this.contentEl.empty(); this.tabsHostEl = this.contentEl.createDiv({ cls: "any-ai-cli-am-tabs" }); this.bodyEl = this.contentEl.createDiv({ cls: "any-ai-cli-am-body" }); this.renderTabs(); this.renderBody(); this.unsubscribe = this.plugin.onAutomationsChanged(() => { this.renderBody(); }); } onClose() { var _a5; (_a5 = this.unsubscribe) == null ? void 0 : _a5.call(this); this.unsubscribe = null; this.contentEl.empty(); } renderTabs() { if (!this.tabsHostEl) return; this.tabsHostEl.empty(); const tabs = [ { id: "automations", label: "Automations" }, { id: "history", label: "History" } ]; for (const tab of tabs) { const btn = this.tabsHostEl.createEl("button", { text: tab.label, cls: `any-ai-cli-am-tab${this.currentTab === tab.id ? " is-active" : ""}` }); btn.addEventListener("click", () => { if (this.currentTab !== tab.id) { this.currentTab = tab.id; this.renderTabs(); this.renderBody(); } }); } } renderBody() { if (!this.bodyEl) return; this.bodyEl.empty(); if (this.currentTab === "automations") { this.renderAutomationsTab(this.bodyEl); } else { this.renderHistoryTab(this.bodyEl); } } renderAutomationsTab(host) { var _a5; const folder = this.plugin.settings.automationsFolder.trim(); if (!folder) { host.createEl("p", { text: "No automations folder configured. Set one in plugin settings to get started.", cls: "any-ai-cli-am-empty" }); return; } const entries = this.plugin.getAutomations(); const errors = this.plugin.getAutomationErrors(); const enabledCount = entries.filter((e) => e.enabled).length; const disabledCount = entries.length - enabledCount; const info = host.createEl("p", { cls: "any-ai-cli-am-info" }); info.setText( `${entries.length} automation${entries.length === 1 ? "" : "s"} (${enabledCount} enabled, ${disabledCount} disabled) \u2014 folder: ${folder}` ); if (errors.length > 0) { const errBox = host.createDiv({ cls: "any-ai-cli-am-errors" }); errBox.createEl("strong", { text: `${errors.length} file${errors.length === 1 ? "" : "s"} could not be parsed:` }); const list = errBox.createEl("ul"); for (const err of errors) { const item = list.createEl("li"); item.createSpan({ text: err.path, cls: "any-ai-cli-am-error-path" }); item.createSpan({ text: ` \u2014 ${err.reason}` }); } } if (entries.length === 0) { host.createEl("p", { text: "No automations found in the configured folder.", cls: "any-ai-cli-am-empty" }); return; } const table = host.createEl("table", { cls: "any-ai-cli-am-table" }); const thead = table.createEl("thead").createEl("tr"); for (const label of ["Name", "Schedule", "Last run", "Next run", "Status", "Actions"]) { thead.createEl("th", { text: label }); } const tbody = table.createEl("tbody"); const now = Date.now(); for (const entry of entries) { const tr2 = tbody.createEl("tr"); if (!entry.enabled) tr2.addClass("is-disabled"); tr2.createEl("td", { text: entry.name }); tr2.createEl("td", { text: describeSchedule(entry) }); const lastRun = (_a5 = this.plugin.settings.automationsLastRun[entry.path]) != null ? _a5 : null; tr2.createEl("td", { text: lastRun ? formatRelative(lastRun, now) : "never" }); const nextRun = entry.enabled ? computeNextRun(entry, lastRun, now) : null; tr2.createEl("td", { text: nextRun === null ? "\u2014" : nextRun <= now ? "due now" : formatRelative(nextRun, now) }); const statusCell = tr2.createEl("td"); const badge = statusCell.createSpan({ text: entry.enabled ? "enabled" : "disabled", cls: `any-ai-cli-am-badge ${entry.enabled ? "is-enabled" : "is-disabled"}` }); if (entry.runtime) { badge.setAttribute("title", `Requires runtime "${entry.runtime}"`); } const actionsCell = tr2.createEl("td", { cls: "any-ai-cli-am-actions" }); const runBtn = actionsCell.createEl("button", { text: "Run now" }); runBtn.setAttribute("title", "Open a new session tab and send this prompt."); runBtn.addEventListener("click", () => { void this.plugin.triggerAutomation(entry, "manual"); }); const openBtn = actionsCell.createEl("button", { text: "Open" }); (0, import_obsidian.setIcon)(openBtn.createSpan(), "external-link"); openBtn.addEventListener("click", () => { void this.app.workspace.openLinkText(entry.path, "", true); this.close(); }); } } renderHistoryTab(host) { const history = this.plugin.settings.automationsHistory; const toolbar = host.createDiv({ cls: "any-ai-cli-am-history-toolbar" }); toolbar.createEl("p", { text: `${history.length} entr${history.length === 1 ? "y" : "ies"} (most recent first, capped at ${this.plugin.settings.automationsHistoryLimit}).`, cls: "any-ai-cli-am-info" }); const actions = toolbar.createDiv({ cls: "any-ai-cli-am-history-actions" }); const clearBtn = actions.createEl("button", { text: "Clear history" }); clearBtn.disabled = history.length === 0; clearBtn.addEventListener("click", () => { this.plugin.clearAutomationHistory(); new import_obsidian.Notice("Automation history cleared.", 2500); }); const exportBtn = actions.createEl("button", { text: "Export as markdown" }); exportBtn.disabled = history.length === 0; exportBtn.addEventListener("click", () => { void this.exportHistory(history); }); if (history.length === 0) { host.createEl("p", { text: "No runs recorded yet.", cls: "any-ai-cli-am-empty" }); return; } const list = host.createEl("ul", { cls: "any-ai-cli-am-history-list" }); for (const record of history) { const li2 = list.createEl("li", { cls: "any-ai-cli-am-history-item" }); li2.createSpan({ text: formatDateTime(record.ts), cls: "any-ai-cli-am-history-ts" }); li2.createSpan({ text: record.name, cls: "any-ai-cli-am-history-name" }); li2.createSpan({ text: record.status, cls: `any-ai-cli-am-badge is-${record.status}` }); li2.createSpan({ text: record.source, cls: "any-ai-cli-am-history-source" }); const detail = record.reason || record.promptPreview || ""; if (detail) { li2.createSpan({ text: detail, cls: "any-ai-cli-am-history-detail" }); } } } async exportHistory(history) { const now = /* @__PURE__ */ new Date(); const lines = []; lines.push(`# Automations history \u2014 exported ${formatDateTime(now.getTime())}`, ""); lines.push("| Time | Name | Status | Source | Detail | Path |"); lines.push("| --- | --- | --- | --- | --- | --- |"); for (const r of history) { const detail = (r.reason || r.promptPreview || "").replace(/\|/g, "\\|"); lines.push( `| ${formatDateTime(r.ts)} | ${r.name.replace(/\|/g, "\\|")} | ${r.status} | ${r.source} | ${detail} | ${r.path} |` ); } const stamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`; const base = `automations-history-${stamp}`; let fileName = `${base}.md`; let counter = 1; while (this.app.vault.getAbstractFileByPath(fileName)) { fileName = `${base}-${counter}.md`; counter += 1; } try { const file = await this.app.vault.create(fileName, lines.join("\n")); await this.app.workspace.openLinkText(file.path, "", true); this.close(); } catch (err) { new import_obsidian.Notice(`Export failed: ${err.message}`, 5e3); } } }; function pad(n) { return n < 10 ? `0${n}` : `${n}`; } function formatDateTime(ts2) { const d = new Date(ts2); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; } function formatRelative(ts2, now) { const diff = ts2 - now; const absMs = Math.abs(diff); const sec = Math.round(absMs / 1e3); const min = Math.round(sec / 60); const hr3 = Math.round(min / 60); const day = Math.round(hr3 / 24); const arrow = diff < 0 ? "ago" : "in"; let value; if (sec < 60) value = `${sec}s`; else if (min < 60) value = `${min}m`; else if (hr3 < 24) value = `${hr3}h`; else value = `${day}d`; return diff < 0 ? `${value} ${arrow}` : `${arrow} ${value}`; } // main.ts var VIEW_TYPE_CLAUDE = "claude-cli-view"; var CODEX_DEFAULT_COMMAND = "codex --no-alt-screen -c check_for_update_on_startup=false -c hide_full_access_warning=true -c hide_world_writable_warning=true -c hide_rate_limit_model_nudge=true"; var DEFAULT_RUNTIMES = [ { id: "claude", name: "Claude", command: "claude" }, { id: "codex", name: "Codex", command: CODEX_DEFAULT_COMMAND } ]; var DEFAULT_IDLE_TIMEOUT_SECONDS = 10; var DEFAULT_SETTINGS = { runtimes: DEFAULT_RUNTIMES.map((runtime) => ({ ...runtime })), selectedRuntimeId: "claude", autoRestartOnRuntimeSwitch: true, autoStart: true, nodeExecutable: "auto", automationsFolder: "", automationsLastRun: {}, automationsHistory: [], automationsHistoryLimit: 200, autoCloseAutomationSessions: true, autoCloseAutomationSessionsOnIdle: false, idleTimeoutSeconds: DEFAULT_IDLE_TIMEOUT_SECONDS, maxConcurrentSessions: 8, verboseProxyLogs: false }; var AUTOMATION_TICK_MS = 3e4; var EXAMPLE_AUTOMATION_CONTENT = `--- # ============================================================ # Any AI CLI \u2014 automation file. Every available option is shown # below. The text AFTER the closing "---" is the prompt that gets # sent to the running CLI. # ============================================================ # name (string, optional) # Display name shown in the Automations modal. Defaults to the # filename (without ".md") when omitted. name: Hello world # enabled (true | false, optional, default true) # When false, the scheduler never auto-fires this automation. It # still appears in the modal (greyed out) and can be triggered by # hand with the "Run now" button. enabled: true # ----- Schedule: set EXACTLY ONE of "interval" or "cron" ----- # interval (integer minutes, >= 1) # Fire every N minutes. The first run happens on the next tick # after the plugin loads; subsequent runs are N minutes apart. interval: 60 # cron (string, standard 5-field expression) # Alternative to "interval". To use it: comment out "interval" # above, then uncomment ONE line below. Fields are: # minute hour day-of-month month day-of-week # cron: "*/30 * * * *" # every 30 minutes # cron: "0 9 * * *" # every day at 09:00 # cron: "0 9 * * 1-5" # weekdays at 09:00 # cron: "0 */2 * * *" # every 2 hours, on the hour # cron: "0 8 1 * *" # 08:00 on the 1st of each month # runtime (string, optional) # Which runtime to spawn for this automation, matched by its id OR its # display name (case-insensitive). Each run opens its own session tab. # Remove the line to use the default runtime (set in plugin settings). # Runs naming an unconfigured runtime are skipped and logged in History. runtime: Claude # appendNewline (true | false, optional, default true) # Append an Enter keystroke after the prompt so the CLI executes it. # Set false only if you want the text inserted without submitting. appendNewline: true --- Say hello and tell me the current date and time. `; var AUTOMATION_DOCS_FILENAME = "AUTOMATION-DOCS.md"; var AUTOMATION_DOCS_CONTENT = `# Any AI CLI \u2014 Automations reference This file documents every option an automation file accepts. It is generated by the **Create example automation** button and is safe to delete \u2014 it is regenerated (overwritten) each time you press that button. It is **not** itself an automation (it has no frontmatter schedule), so the scheduler ignores it. ## How an automation file works An automation is a Markdown file in your configured automations folder. It has two parts: 1. A **YAML frontmatter block** fenced by \`---\` at the very top of the file. It holds the options below (schedule, runtime, etc.). 2. The **prompt body**: everything after the closing \`---\`. This text is sent to the CLI when the automation fires. \`\`\`markdown --- name: My automation interval: 60 runtime: Claude --- Write the prompt that gets sent to the CLI here. \`\`\` Each run opens its own session tab for the chosen runtime, waits for the CLI to finish booting, then types the prompt body (optionally followed by Enter). ## Options ### \`name\` \u2014 string, optional Display name shown in the Automations modal and in the run History. - **Default:** the filename without its \`.md\` extension. - **Example:** \`name: Daily standup notes\` ### \`enabled\` \u2014 true | false, optional Master switch for automatic firing. - **Default:** \`true\`. - When \`false\`, the scheduler never auto-fires this automation. It still shows in the modal (greyed out) and can be triggered manually with **Run now**. - **Example:** \`enabled: false\` ### Schedule \u2014 set EXACTLY ONE of \`interval\` or \`cron\` Every automation needs a schedule. You must provide **either** \`interval\` **or** \`cron\`, never both and never neither \u2014 files that break this rule are reported as errors in the modal. #### \`interval\` \u2014 integer minutes (>= 1) Fire every N minutes. The first run happens on the next scheduler tick after the plugin loads; subsequent runs are N minutes apart. - Must be a whole number \`>= 1\`. - **Examples:** \`interval: 15\` (every 15 min), \`interval: 1440\` (once a day). #### \`cron\` \u2014 string, standard 5-field expression Fire on a calendar schedule. Quote the value so YAML treats it as a string. The five space-separated fields are: \`\`\` minute hour day-of-month month day-of-week \`\`\` | Field | Allowed values | |--------------|-----------------------| | minute | 0\u201359 | | hour | 0\u201323 | | day-of-month | 1\u201331 | | month | 1\u201312 | | day-of-week | 0\u20137 (0 and 7 = Sunday)| Common patterns (\`*\` = any, \`*/n\` = every n, \`a-b\` = range, \`a,b\` = list): | Expression | Meaning | |---------------------|----------------------------------| | \`"*/30 * * * *"\` | every 30 minutes | | \`"0 9 * * *"\` | every day at 09:00 | | \`"0 9 * * 1-5"\` | weekdays at 09:00 | | \`"0 */2 * * *"\` | every 2 hours, on the hour | | \`"30 8,17 * * *"\` | at 08:30 and 17:30 every day | | \`"0 8 1 * *"\` | 08:00 on the 1st of each month | - **Example:** \`cron: "0 9 * * 1-5"\` ### \`runtime\` \u2014 string, optional Which configured runtime to spawn for this automation, matched by its **id** OR its **display name** (case-insensitive). - **Default:** the default runtime set in plugin settings (when the line is omitted). - A run naming a runtime that is not configured is **skipped** and logged in History. - **Example:** \`runtime: Claude\` ### \`appendNewline\` \u2014 true | false, optional Whether to send an Enter keystroke after the prompt so the CLI executes it. - **Default:** \`true\`. - Set \`false\` only if you want the text inserted into the input box **without** submitting (e.g. to let yourself review/edit before pressing Enter). - **Example:** \`appendNewline: false\` ### Prompt body \u2014 required Everything after the closing \`---\` is the prompt. It must not be empty, otherwise the file is reported as an error. Multi-line prompts are supported. ## Validation rules (summary) A file is reported as an error in the modal (and never fires) when: - the frontmatter block is missing; - both \`interval\` and \`cron\` are set, or neither is; - \`interval\` is not an integer \`>= 1\`; - \`cron\` is not a valid 5-field expression; - the prompt body is empty. ## Running and history - The scheduler ticks periodically; due automations fire automatically (unless \`enabled: false\`). - The **Automations** modal lists every file with its schedule, last run, next run and status, plus a per-row **Run now** and **Open file**. - The **History** tab keeps a capped, chronological log of runs; you can clear it or export it as a date-stamped Markdown note. `; function cloneDefaultRuntimes() { return DEFAULT_RUNTIMES.map((runtime) => ({ ...runtime })); } var SESSION_READY_QUIET_MS = 800; var SESSION_READY_MAX_MS = 1e4; function createSessionTerminal() { const terminal = new Dl({ cursorBlink: true, convertEol: true, fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, monospace", fontSize: 13, scrollback: 3e3, theme: { background: "#0f1115", foreground: "#e6e6e6" } }); const fitAddon = new o(); terminal.loadAddon(fitAddon); return { terminal, fitAddon }; } var CliSession = class { constructor(params) { this.processHandle = null; this.status = "Idle"; this.pendingRestart = false; // Live activity: "working" while the CLI emits output, "idle" after it goes // quiet. Drives the tab dot colour and (for automations) idle auto-close. this.activity = "idle"; // Set true once an automation prompt has been sent, so idle auto-close only // fires after the automation actually ran (not during boot). this.closeOnIdleArmed = false; this.onActivityChange = null; this.activityTimer = null; this.ready = false; this.resolveReady = null; this.settleTimer = null; this.maxWaitTimer = null; this.id = params.id; this.runtimeId = params.runtimeId; this.label = params.label; this.origin = params.origin; this.terminal = params.terminal; this.fitAddon = params.fitAddon; this.hostEl = params.hostEl; this.resetReady(); } clearReadyTimers() { if (this.settleTimer !== null) { activeWindow.clearTimeout(this.settleTimer); this.settleTimer = null; } if (this.maxWaitTimer !== null) { activeWindow.clearTimeout(this.maxWaitTimer); this.maxWaitTimer = null; } } /** Arm a fresh readiness promise for a (re)spawn, and reset activity state. */ resetReady() { this.ready = false; this.clearReadyTimers(); if (this.activityTimer !== null) { activeWindow.clearTimeout(this.activityTimer); this.activityTimer = null; } this.activity = "idle"; this.closeOnIdleArmed = false; this.whenReady = new Promise((resolve2) => { this.resolveReady = resolve2; }); } markReady() { var _a5; if (this.ready) { return; } this.ready = true; this.clearReadyTimers(); (_a5 = this.resolveReady) == null ? void 0 : _a5.call(this); this.resolveReady = null; } /** Hard cap so a session never blocks an automation forever. */ armReadyMaxWait(delayMs) { if (this.maxWaitTimer !== null) { activeWindow.clearTimeout(this.maxWaitTimer); } this.maxWaitTimer = activeWindow.setTimeout(() => this.markReady(), delayMs); } /** Each output chunk (re)arms a quiet-period timer; readiness is declared * once the CLI stops emitting for `quietMs`, i.e. its input box is drawn. */ noteOutputActivity(quietMs) { if (this.ready) { return; } if (this.settleTimer !== null) { activeWindow.clearTimeout(this.settleTimer); } this.settleTimer = activeWindow.setTimeout(() => this.markReady(), quietMs); } /** Each output chunk marks the session "working" and (re)arms a quiet timer * that flips it back to "idle" after `idleMs` of silence. */ noteActivity(idleMs) { var _a5; if (this.activity !== "working") { this.activity = "working"; (_a5 = this.onActivityChange) == null ? void 0 : _a5.call(this); } if (this.activityTimer !== null) { activeWindow.clearTimeout(this.activityTimer); } this.activityTimer = activeWindow.setTimeout(() => { var _a6; this.activityTimer = null; if (this.activity !== "idle") { this.activity = "idle"; (_a6 = this.onActivityChange) == null ? void 0 : _a6.call(this); } }, idleMs); } /** Force the idle state immediately (e.g. when the process exits). */ markIdle() { var _a5; if (this.activityTimer !== null) { activeWindow.clearTimeout(this.activityTimer); this.activityTimer = null; } if (this.activity !== "idle") { this.activity = "idle"; (_a5 = this.onActivityChange) == null ? void 0 : _a5.call(this); } } isRunning() { return this.processHandle !== null; } writeSystemLine(message) { this.terminal.write("\r\x1B[2K"); this.terminal.writeln(message); } sendPrompt(text, submitWithEnter) { if (!this.processHandle) { throw new Error("CLI process is not running"); } this.processHandle.write(text); if (submitWithEnter) { const handle = this.processHandle; activeWindow.setTimeout(() => { try { handle.write("\r"); } catch (e) { } }, 120); } this.closeOnIdleArmed = true; this.writeSystemLine(`[Automation prompt injected]`); } dispose() { this.clearReadyTimers(); if (this.activityTimer !== null) { activeWindow.clearTimeout(this.activityTimer); this.activityTimer = null; } try { this.terminal.dispose(); } catch (e) { } this.hostEl.remove(); } }; var ClaudeCliView = class extends import_obsidian2.ItemView { constructor(leaf, plugin) { super(leaf); this.sessions = []; this.activeSessionId = null; this.tabBarEl = null; this.terminalsHostEl = null; this.emptyHintEl = null; this.statusEl = null; this.resizeObserver = null; this.stopBtn = null; this.restartBtn = null; this.clearBtn = null; this.plugin = plugin; } getViewType() { return VIEW_TYPE_CLAUDE; } getDisplayText() { return "Any AI CLI"; } getIcon() { return "bot"; } onOpen() { this.contentEl.empty(); this.contentEl.addClass("claude-cli-view"); this.tabBarEl = this.contentEl.createDiv({ cls: "claude-cli-tabbar" }); const toolbarEl = this.contentEl.createDiv({ cls: "claude-cli-toolbar" }); const primaryRowEl = toolbarEl.createDiv({ cls: "claude-cli-toolbar-row" }); const newBtn = primaryRowEl.createEl("button", { text: "New session" }); const stopBtn = primaryRowEl.createEl("button", { text: "Stop" }); const restartBtn = primaryRowEl.createEl("button", { text: "Restart" }); const clearBtn = primaryRowEl.createEl("button", { text: "Clear" }); this.setButtonIcon(newBtn, "plus", "New session"); this.setButtonIcon(stopBtn, "square", "Stop"); this.setButtonIcon(restartBtn, "refresh-cw", "Restart"); this.setButtonIcon(clearBtn, "eraser", "Clear"); newBtn.addClass("claude-cli-btn-primary"); stopBtn.addClass("claude-cli-btn-danger"); this.stopBtn = stopBtn; this.restartBtn = restartBtn; this.clearBtn = clearBtn; const secondaryRowEl = toolbarEl.createDiv({ cls: "claude-cli-toolbar-row" }); const mentionBtn = secondaryRowEl.createEl("button", { text: "@active file" }); const folderMentionBtn = secondaryRowEl.createEl("button", { text: "@active folder" }); const automationsBtn = secondaryRowEl.createEl("button", { text: "Automations" }); this.setButtonIcon(mentionBtn, "file-plus", "@active file"); this.setButtonIcon(folderMentionBtn, "folder-plus", "@active folder"); this.setButtonIcon(automationsBtn, "calendar-clock", "Automations"); mentionBtn.addClass("claude-cli-btn-info"); folderMentionBtn.addClass("claude-cli-btn-info"); automationsBtn.addClass("claude-cli-btn-info"); this.statusEl = this.contentEl.createDiv({ cls: "claude-cli-status" }); newBtn.addEventListener("click", (evt) => this.openNewSessionMenu(evt)); stopBtn.addEventListener("click", () => this.stopActiveSession()); restartBtn.addEventListener("click", () => this.restartActiveSession()); clearBtn.addEventListener("click", () => { var _a5; return (_a5 = this.getActiveSession()) == null ? void 0 : _a5.terminal.clear(); }); mentionBtn.addEventListener("click", () => this.insertActiveFileMention()); folderMentionBtn.addEventListener("click", () => this.insertActiveFolderMention()); automationsBtn.addEventListener("click", () => { new AutomationsModal(this.app, this.plugin).open(); }); this.terminalsHostEl = this.contentEl.createDiv({ cls: "claude-cli-terminals" }); this.emptyHintEl = this.terminalsHostEl.createDiv({ cls: "claude-cli-empty-hint" }); this.emptyHintEl.setText("No session running. Use the + button to launch a runtime."); this.resizeObserver = new ResizeObserver(() => { var _a5, _b; const session = this.getActiveSession(); if (!session) { return; } session.fitAddon.fit(); if (session.processHandle) { (_b = (_a5 = session.processHandle).resize) == null ? void 0 : _b.call( _a5, Math.max(20, session.terminal.cols || 120), Math.max(10, session.terminal.rows || 30) ); } }); this.resizeObserver.observe(this.contentEl); this.renderTabBar(); this.updateEmptyState(); this.updateToolbarState(); if (this.plugin.settings.autoStart) { const runtime = this.getSelectedRuntime(); if (runtime) { this.startSession({ runtimeId: runtime.id, origin: "manual" }); } else { this.setStatus("No runtime configured. Add one in plugin settings."); } } else { this.setStatus("Idle"); } return Promise.resolve(); } onClose() { var _a5, _b; for (const session of this.sessions) { try { (_a5 = session.processHandle) == null ? void 0 : _a5.kill("SIGTERM"); } catch (e) { } session.dispose(); } this.sessions = []; this.activeSessionId = null; (_b = this.resizeObserver) == null ? void 0 : _b.disconnect(); this.resizeObserver = null; this.statusEl = null; this.tabBarEl = null; this.terminalsHostEl = null; this.emptyHintEl = null; return Promise.resolve(); } getActiveSession() { if (!this.activeSessionId) { return null; } return this.findSession(this.activeSessionId); } findSession(id) { var _a5; return (_a5 = this.sessions.find((s15) => s15.id === id)) != null ? _a5 : null; } isProcessRunning() { return this.sessions.some((s15) => s15.isRunning()); } startSession(params) { if (!this.terminalsHostEl) { return null; } const runtime = this.plugin.settings.runtimes.find((r) => r.id === params.runtimeId); if (!runtime) { const message = "Runtime not configured. Add one in plugin settings."; this.setStatus(message); new import_obsidian2.Notice(message, 6e3); return null; } if (!canOpenSession(this.sessions.length, this.plugin.settings.maxConcurrentSessions)) { const message = `Session limit reached (${this.plugin.settings.maxConcurrentSessions}). Close a tab first.`; this.setStatus(message); new import_obsidian2.Notice(message, 6e3); return null; } const command = (runtime.command || "").trim(); if (!command) { const message = `Runtime "${runtime.name || "(Unnamed)"}" has an empty command. Set one in plugin settings.`; this.setStatus(message); new import_obsidian2.Notice(message, 6e3); return null; } const hostEl = this.terminalsHostEl.createDiv({ cls: "claude-cli-terminal" }); const { terminal, fitAddon } = createSessionTerminal(); terminal.open(hostEl); fitAddon.fit(); const label = nextSessionLabel( this.sessions.map((s15) => s15.label), runtime.name || "(Unnamed)" ); const session = new CliSession({ id: (0, import_node_crypto2.randomUUID)(), runtimeId: runtime.id, label, origin: params.origin, terminal, fitAddon, hostEl }); this.sessions.push(session); terminal.onData((data) => { var _a5; return (_a5 = session.processHandle) == null ? void 0 : _a5.write(data); }); session.onActivityChange = () => { this.renderTabBar(); if (session.activity === "idle" && session.origin === "automation" && session.isRunning() && session.closeOnIdleArmed && this.plugin.settings.autoCloseAutomationSessionsOnIdle) { this.closeSession(session.id); } }; session.writeSystemLine(`CLI session ready (${label}).`); this.setActiveSession(session.id); this.spawnIntoSession(session, runtime); this.renderTabBar(); this.updateToolbarState(); return session; } closeSession(id) { var _a5, _b, _c2; const index = this.sessions.findIndex((s15) => s15.id === id); if (index < 0) { return; } const session = this.sessions[index]; try { (_a5 = session.processHandle) == null ? void 0 : _a5.kill("SIGTERM"); } catch (e) { } session.processHandle = null; session.markReady(); session.dispose(); this.sessions.splice(index, 1); if (this.activeSessionId === id) { this.activeSessionId = null; const next = (_c2 = (_b = this.sessions[index]) != null ? _b : this.sessions[index - 1]) != null ? _c2 : null; if (next) { this.setActiveSession(next.id); } } this.renderTabBar(); this.updateEmptyState(); this.updateToolbarState(); if (!this.getActiveSession()) { this.setStatus("Idle"); } } setActiveSession(id) { var _a5, _b; const session = this.findSession(id); if (!session) { return; } this.activeSessionId = id; for (const s15 of this.sessions) { s15.hostEl.toggleClass("is-hidden", s15.id !== id); } this.updateEmptyState(); this.renderTabBar(); session.fitAddon.fit(); (_b = (_a5 = session.processHandle) == null ? void 0 : _a5.resize) == null ? void 0 : _b.call( _a5, Math.max(20, session.terminal.cols || 120), Math.max(10, session.terminal.rows || 30) ); session.terminal.focus(); this.setStatus(session.status); this.updateToolbarState(); } sendAutomationPromptTo(sessionId, text, submitWithEnter) { const session = this.findSession(sessionId); if (!session) { throw new Error("Session no longer exists"); } session.sendPrompt(text, submitWithEnter); } // Called by the plugin when the configured runtimes change in settings. refreshRuntimeSelect() { this.renderTabBar(); } spawnIntoSession(session, runtime) { const label = session.label; const command = (runtime.command || "").trim(); if (!command) { const message = `Runtime "${runtime.name || "(Unnamed)"}" has an empty command. Set one in plugin settings.`; session.writeSystemLine(`[${message}]`); session.status = message; if (this.activeSessionId === session.id) { this.setStatus(message); } session.markReady(); return false; } const codexLike = isCodexLikeCommand(command); if (codexLike) { session.terminal.reset(); session.fitAddon.fit(); } session.resetReady(); session.writeSystemLine(`[Starting: ${command}]`); session.status = `Starting in vault folder (${process.platform})...`; if (this.activeSessionId === session.id) { this.setStatus(session.status); } try { const vaultPath = getVaultBasePath(this.app); if (!vaultPath) { const message = `Unable to resolve current vault path. ${label} was not started.`; session.writeSystemLine(`[${message}]`); session.status = message; if (this.activeSessionId === session.id) { this.setStatus(message); } new import_obsidian2.Notice(message, 6e3); session.markReady(); return false; } if (!fs2.existsSync(vaultPath)) { const message = `Vault path does not exist: ${vaultPath}`; session.writeSystemLine(`[${message}]`); session.status = message; if (this.activeSessionId === session.id) { this.setStatus(message); } new import_obsidian2.Notice(message, 6e3); session.markReady(); return false; } const shellEnv = getShellEnv(); if (codexLike) { shellEnv.NO_COLOR = "1"; shellEnv.CLICOLOR = "0"; shellEnv.FORCE_COLOR = "0"; } const helperHandle = spawnPtyProxy({ command, cwd: vaultPath, env: shellEnv, cols: Math.max(20, session.terminal.cols || 120), rows: Math.max(10, session.terminal.rows || 30), nodeExecutable: this.plugin.settings.nodeExecutable, pluginDir: this.plugin.manifest.dir, vaultPath, verbose: this.plugin.settings.verboseProxyLogs }); session.processHandle = makeProxyAdapter(helperHandle); } catch (error) { const message = `Failed to start process: ${error.message}`; session.writeSystemLine(`[${message}]`); session.status = message; if (this.activeSessionId === session.id) { this.setStatus(message); } new import_obsidian2.Notice(message, 7e3); session.processHandle = null; session.markReady(); return false; } session.status = "Running"; if (this.activeSessionId === session.id) { this.setStatus("Running"); } session.armReadyMaxWait(SESSION_READY_MAX_MS); session.processHandle.onData((data) => { session.terminal.write(data); session.noteOutputActivity(SESSION_READY_QUIET_MS); session.noteActivity(this.plugin.settings.idleTimeoutSeconds * 1e3); }); session.processHandle.onExit((exitCode, signal) => { session.processHandle = null; session.markReady(); session.markIdle(); if (session.pendingRestart) { session.pendingRestart = false; const current = this.plugin.settings.runtimes.find((r) => r.id === session.runtimeId); if (current) { this.spawnIntoSession(session, current); this.renderTabBar(); this.updateToolbarState(); return; } } const message = `Process exited (code=${exitCode}, signal=${signal})`; session.writeSystemLine(`[${message}]`); session.status = message; if (this.activeSessionId === session.id) { this.setStatus(message); } if (session.origin === "automation" && this.plugin.settings.autoCloseAutomationSessions) { this.closeSession(session.id); return; } this.renderTabBar(); this.updateToolbarState(); }); if (this.activeSessionId === session.id) { session.fitAddon.fit(); } return true; } stopActiveSession() { const session = this.getActiveSession(); if (!session || !session.processHandle) { return; } session.writeSystemLine(`[Stopping ${session.label} process...]`); session.status = "Stopping..."; this.setStatus("Stopping..."); try { session.processHandle.kill("SIGTERM"); } catch (error) { const message = `Failed to stop process: ${error.message}`; session.writeSystemLine(`[${message}]`); session.status = message; this.setStatus(message); new import_obsidian2.Notice(message, 6e3); } } restartActiveSession() { const session = this.getActiveSession(); if (!session) { return; } const runtime = this.plugin.settings.runtimes.find((r) => r.id === session.runtimeId); if (!runtime) { new import_obsidian2.Notice("Runtime is no longer configured.", 6e3); return; } if (session.processHandle) { session.pendingRestart = true; session.writeSystemLine(`[Restart requested: ${session.label}]`); session.status = "Restarting..."; this.setStatus("Restarting..."); try { session.processHandle.kill("SIGTERM"); } catch (e) { session.pendingRestart = false; } return; } this.spawnIntoSession(session, runtime); this.renderTabBar(); this.updateToolbarState(); } openNewSessionMenu(evt) { const runtimes = this.plugin.settings.runtimes; if (runtimes.length === 0) { new import_obsidian2.Notice("No runtime configured. Add one in plugin settings.", 6e3); return; } if (runtimes.length === 1) { this.startSession({ runtimeId: runtimes[0].id, origin: "manual" }); return; } const menu = new import_obsidian2.Menu(); for (const runtime of runtimes) { menu.addItem( (item) => item.setTitle(runtime.name || "(Unnamed)").setIcon("terminal").onClick(() => { this.startSession({ runtimeId: runtime.id, origin: "manual" }); }) ); } menu.showAtMouseEvent(evt); } renderTabBar() { if (!this.tabBarEl) { return; } this.tabBarEl.empty(); for (const session of this.sessions) { const tabEl = this.tabBarEl.createDiv({ cls: `claude-cli-tab${session.id === this.activeSessionId ? " is-active" : ""}` }); const dotCls = tabDotClass({ running: session.isRunning(), activity: session.activity, origin: session.origin }); tabEl.createSpan({ cls: `claude-cli-tab-dot ${dotCls}` }); if (session.origin === "automation") { const autoIcon = tabEl.createSpan({ cls: "claude-cli-tab-auto" }); (0, import_obsidian2.setIcon)(autoIcon, "calendar-clock"); } tabEl.createSpan({ text: session.label, cls: "claude-cli-tab-label" }); const closeEl = tabEl.createSpan({ cls: "claude-cli-tab-close" }); (0, import_obsidian2.setIcon)(closeEl, "x"); closeEl.setAttribute("aria-label", "Close session"); closeEl.addEventListener("click", (evt) => { evt.stopPropagation(); this.closeSession(session.id); }); tabEl.addEventListener("click", () => { if (session.id !== this.activeSessionId) { this.setActiveSession(session.id); } }); } const newTabEl = this.tabBarEl.createDiv({ cls: "claude-cli-tab-new" }); (0, import_obsidian2.setIcon)(newTabEl, "plus"); newTabEl.setAttribute("aria-label", "New session"); newTabEl.addEventListener("click", (evt) => this.openNewSessionMenu(evt)); } updateEmptyState() { if (!this.emptyHintEl) { return; } this.emptyHintEl.toggleClass("is-hidden", this.sessions.length > 0); } updateToolbarState() { var _a5; const session = this.getActiveSession(); const running = (_a5 = session == null ? void 0 : session.isRunning()) != null ? _a5 : false; if (this.stopBtn) { this.stopBtn.disabled = !running; } if (this.restartBtn) { this.restartBtn.disabled = !session; } if (this.clearBtn) { this.clearBtn.disabled = !session; } } setStatus(message) { var _a5; (_a5 = this.statusEl) == null ? void 0 : _a5.setText(`Status: ${message}`); } getSelectedRuntime() { var _a5, _b; const { runtimes, selectedRuntimeId } = this.plugin.settings; return (_b = (_a5 = runtimes.find((r) => r.id === selectedRuntimeId)) != null ? _a5 : runtimes[0]) != null ? _b : null; } insertActiveFileMention() { const session = this.getActiveSession(); const activeFile = this.app.workspace.getActiveFile(); if (!activeFile) { const message = "No active file detected."; this.setStatus(message); new import_obsidian2.Notice(message, 4e3); return; } if (!session || !session.processHandle) { const message = "No running session. Start one before inserting a file mention."; this.setStatus(message); new import_obsidian2.Notice(message, 5e3); return; } const mention = formatActiveFileMention(activeFile.path); session.processHandle.write(mention); session.terminal.focus(); this.setStatus(`Inserted ${mention.trim()}`); } insertActiveFolderMention() { const session = this.getActiveSession(); const activeFile = this.app.workspace.getActiveFile(); if (!activeFile) { const message = "No active file detected."; this.setStatus(message); new import_obsidian2.Notice(message, 4e3); return; } if (!session || !session.processHandle) { const message = "No running session. Start one before inserting a folder mention."; this.setStatus(message); new import_obsidian2.Notice(message, 5e3); return; } const mention = formatActiveFolderMention(activeFile.path); session.processHandle.write(mention); session.terminal.focus(); this.setStatus(`Inserted ${mention.trim()}`); } setButtonIcon(buttonEl, iconName, label) { buttonEl.empty(); buttonEl.addClass("claude-cli-btn"); const iconEl = buttonEl.createSpan({ cls: "claude-cli-btn-icon" }); (0, import_obsidian2.setIcon)(iconEl, iconName); buttonEl.createSpan({ text: label }); } }; var ClaudeCliPlugin = class extends import_obsidian2.Plugin { constructor() { super(...arguments); this.automationEntries = /* @__PURE__ */ new Map(); this.automationErrors = /* @__PURE__ */ new Map(); this.automationListeners = /* @__PURE__ */ new Set(); } async onload() { await this.loadSettings(); this.registerView(VIEW_TYPE_CLAUDE, (leaf) => new ClaudeCliView(leaf, this)); this.addRibbonIcon("bot", "Open AI CLI panel", () => { void this.activateView(); }); this.addCommand({ id: "open-panel", name: "Open panel", callback: () => { void this.activateView(); } }); this.addSettingTab(new ClaudeCliSettingTab(this.app, this)); this.app.workspace.onLayoutReady(() => { this.loadAutomations(); this.runAutomationTick(); }); const refreshOnVaultChange = (file) => { const folder = this.settings.automationsFolder; if (!folder || !file) return; if (file.path === folder || file.path.startsWith(`${folder}/`)) { this.loadAutomations(); } }; this.registerEvent(this.app.vault.on("create", refreshOnVaultChange)); this.registerEvent(this.app.vault.on("modify", refreshOnVaultChange)); this.registerEvent(this.app.vault.on("delete", refreshOnVaultChange)); this.registerEvent( this.app.vault.on("rename", (file, oldPath) => { refreshOnVaultChange(file); const folder = this.settings.automationsFolder; if (folder && (oldPath === folder || oldPath.startsWith(`${folder}/`))) { this.loadAutomations(); } }) ); this.registerInterval(activeWindow.setInterval(() => this.runAutomationTick(), AUTOMATION_TICK_MS)); } onunload() { } getAutomations() { return Array.from(this.automationEntries.values()).sort( (a, b2) => a.name.localeCompare(b2.name) ); } getAutomationErrors() { return Array.from(this.automationErrors.values()); } onAutomationsChanged(listener) { this.automationListeners.add(listener); return () => this.automationListeners.delete(listener); } notifyAutomationsChanged() { this.automationListeners.forEach((listener) => { try { listener(); } catch (e) { } }); } loadAutomations() { this.automationEntries.clear(); this.automationErrors.clear(); const folderPath = this.settings.automationsFolder.trim(); if (!folderPath) { this.notifyAutomationsChanged(); return; } const folder = this.app.vault.getFolderByPath(folderPath); if (!folder) { this.notifyAutomationsChanged(); return; } const files = []; const walk = (f) => { for (const child of f.children) { if (child instanceof import_obsidian2.TFile && child.extension === "md") { if (child.name === AUTOMATION_DOCS_FILENAME) continue; files.push(child); } else if (child instanceof import_obsidian2.TFolder) { walk(child); } } }; walk(folder); void Promise.all( files.map(async (file) => { try { const content = await this.app.vault.cachedRead(file); const result = parseAutomationFile(content, file.path, (yaml) => (0, import_obsidian2.parseYaml)(yaml)); if (result.ok) { this.automationEntries.set(file.path, result.entry); } else { this.automationErrors.set(file.path, result.error); } } catch (err) { this.automationErrors.set(file.path, { path: file.path, name: file.basename, reason: `Read error: ${err.message}` }); } }) ).then(() => { this.notifyAutomationsChanged(); }); } runAutomationTick() { var _a5; if (this.automationEntries.size === 0) return; const now = Date.now(); for (const entry of this.automationEntries.values()) { if (!entry.enabled) continue; const last = (_a5 = this.settings.automationsLastRun[entry.path]) != null ? _a5 : null; const next = computeNextRun(entry, last, now); if (next !== null && next <= now) { void this.triggerAutomation(entry, "scheduler"); } } } async triggerAutomation(entry, source) { const now = Date.now(); const baseRecord = { ts: now, path: entry.path, name: entry.name, source }; const runtime = resolveRuntimeForAutomation( this.settings.runtimes, entry.runtime, this.settings.selectedRuntimeId ); if (!runtime) { const reason = entry.runtime ? `Runtime "${entry.runtime}" not configured` : "No runtime configured"; this.recordHistory({ ...baseRecord, status: "skipped", reason }); if (source === "manual") { new import_obsidian2.Notice(`Automation "${entry.name}" skipped \u2014 ${reason.toLowerCase()}.`, 5e3); } return; } const started = await this.activateViewAndStartSession({ runtimeId: runtime.id, origin: "automation" }); if (!started) { const reason = "Could not open a session"; this.recordHistory({ ...baseRecord, status: "error", reason }); if (source === "manual") { new import_obsidian2.Notice(`Automation "${entry.name}" failed \u2014 ${reason.toLowerCase()}.`, 5e3); } return; } const { view, session } = started; try { await session.whenReady; view.sendAutomationPromptTo(session.id, entry.body, entry.appendNewline); this.recordHistory({ ...baseRecord, status: "ran", runtimeId: session.runtimeId, promptPreview: buildPromptPreview(entry.body) }); this.settings.automationsLastRun[entry.path] = now; await this.saveSettings(); if (source === "manual") { new import_obsidian2.Notice(`Automation "${entry.name}" sent.`, 3e3); } } catch (err) { this.recordHistory({ ...baseRecord, status: "error", reason: err.message }); new import_obsidian2.Notice(`Automation "${entry.name}" failed: ${err.message}`, 6e3); } } async activateViewAndStartSession(params) { await this.activateView(); const leaf = this.app.workspace.getLeavesOfType(VIEW_TYPE_CLAUDE)[0]; const view = leaf == null ? void 0 : leaf.view; if (!(view instanceof ClaudeCliView)) { return null; } const session = view.startSession(params); if (!session) { return null; } return { view, session }; } recordHistory(record) { this.settings.automationsHistory = pushHistory( this.settings.automationsHistory, record, this.settings.automationsHistoryLimit ); void this.saveSettings(); this.notifyAutomationsChanged(); } clearAutomationHistory() { this.settings.automationsHistory = []; void this.saveSettings(); this.notifyAutomationsChanged(); } async createExampleAutomation() { const folder = this.settings.automationsFolder.trim().replace(/\/+$/, ""); if (!folder) { throw new Error("Set an automations folder first."); } if (!this.app.vault.getFolderByPath(folder)) { await this.app.vault.createFolder(folder); } let target = `${folder}/hello-world.md`; let counter = 1; while (this.app.vault.getAbstractFileByPath(target)) { target = `${folder}/hello-world-${counter}.md`; counter += 1; } const example = await this.app.vault.create(target, EXAMPLE_AUTOMATION_CONTENT); const docsPath = `${folder}/${AUTOMATION_DOCS_FILENAME}`; const existingDocs = this.app.vault.getAbstractFileByPath(docsPath); let docs; if (existingDocs instanceof import_obsidian2.TFile) { await this.app.vault.modify(existingDocs, AUTOMATION_DOCS_CONTENT); docs = existingDocs; } else { docs = await this.app.vault.create(docsPath, AUTOMATION_DOCS_CONTENT); } this.loadAutomations(); return { example, docs }; } async activateView() { var _a5; const { workspace } = this.app; let leaf = (_a5 = workspace.getLeavesOfType(VIEW_TYPE_CLAUDE)[0]) != null ? _a5 : null; if (!leaf) { leaf = workspace.getRightLeaf(false); if (!leaf) { return; } await leaf.setViewState({ type: VIEW_TYPE_CLAUDE, active: true }); } await workspace.revealLeaf(leaf); } async loadSettings() { var _a5; const raw = (_a5 = await this.loadData()) != null ? _a5 : {}; const { runtimes, selectedRuntimeId } = migrateRuntimeSettings(raw, cloneDefaultRuntimes()); this.settings = { runtimes, selectedRuntimeId, autoRestartOnRuntimeSwitch: typeof raw.autoRestartOnRuntimeSwitch === "boolean" ? raw.autoRestartOnRuntimeSwitch : DEFAULT_SETTINGS.autoRestartOnRuntimeSwitch, autoStart: typeof raw.autoStart === "boolean" ? raw.autoStart : DEFAULT_SETTINGS.autoStart, nodeExecutable: typeof raw.nodeExecutable === "string" && raw.nodeExecutable.trim() ? raw.nodeExecutable : DEFAULT_SETTINGS.nodeExecutable, automationsFolder: typeof raw.automationsFolder === "string" ? raw.automationsFolder : DEFAULT_SETTINGS.automationsFolder, automationsLastRun: sanitizeLastRun(raw.automationsLastRun), automationsHistory: sanitizeHistory(raw.automationsHistory), automationsHistoryLimit: typeof raw.automationsHistoryLimit === "number" && Number.isInteger(raw.automationsHistoryLimit) && raw.automationsHistoryLimit > 0 ? raw.automationsHistoryLimit : DEFAULT_SETTINGS.automationsHistoryLimit, autoCloseAutomationSessions: typeof raw.autoCloseAutomationSessions === "boolean" ? raw.autoCloseAutomationSessions : DEFAULT_SETTINGS.autoCloseAutomationSessions, autoCloseAutomationSessionsOnIdle: typeof raw.autoCloseAutomationSessionsOnIdle === "boolean" ? raw.autoCloseAutomationSessionsOnIdle : DEFAULT_SETTINGS.autoCloseAutomationSessionsOnIdle, idleTimeoutSeconds: typeof raw.idleTimeoutSeconds === "number" && Number.isInteger(raw.idleTimeoutSeconds) && raw.idleTimeoutSeconds >= 1 ? raw.idleTimeoutSeconds : DEFAULT_SETTINGS.idleTimeoutSeconds, maxConcurrentSessions: typeof raw.maxConcurrentSessions === "number" && Number.isInteger(raw.maxConcurrentSessions) && raw.maxConcurrentSessions >= 0 ? raw.maxConcurrentSessions : DEFAULT_SETTINGS.maxConcurrentSessions, verboseProxyLogs: typeof raw.verboseProxyLogs === "boolean" ? raw.verboseProxyLogs : DEFAULT_SETTINGS.verboseProxyLogs }; } async saveSettings() { await this.saveData(this.settings); } notifyRuntimesChanged() { this.app.workspace.getLeavesOfType(VIEW_TYPE_CLAUDE).forEach((leaf) => { const view = leaf.view; if (view instanceof ClaudeCliView) { view.refreshRuntimeSelect(); } }); } }; var ClaudeCliSettingTab = class extends import_obsidian2.PluginSettingTab { constructor(app, plugin) { super(app, plugin); this.plugin = plugin; } display() { const { containerEl } = this; containerEl.empty(); new import_obsidian2.Setting(containerEl).setName("Default runtime").setDesc("Runtime selected by default when opening the panel (and used by auto-start).").addDropdown((dropdown) => { const runtimes = this.plugin.settings.runtimes; if (runtimes.length === 0) { dropdown.addOption("", "No runtime configured"); dropdown.setDisabled(true); } else { for (const runtime of runtimes) { dropdown.addOption(runtime.id, runtime.name || "(Unnamed)"); } const validSelection = runtimes.some((r) => r.id === this.plugin.settings.selectedRuntimeId); dropdown.setValue( validSelection ? this.plugin.settings.selectedRuntimeId : runtimes[0].id ); } dropdown.onChange(async (value) => { if (!value) { return; } this.plugin.settings.selectedRuntimeId = value; await this.plugin.saveSettings(); this.plugin.notifyRuntimesChanged(); }); }); new import_obsidian2.Setting(containerEl).setName("Auto-start").setDesc("Automatically start the selected default runtime when the panel opens.").addToggle( (toggle) => toggle.setValue(this.plugin.settings.autoStart).onChange(async (value) => { this.plugin.settings.autoStart = value; await this.plugin.saveSettings(); }) ); new import_obsidian2.Setting(containerEl).setName("Max concurrent sessions").setDesc("Maximum number of session tabs that can run at once (0 = unlimited). Protects against runaway automation spawns.").addText( (text) => text.setPlaceholder("8").setValue(String(this.plugin.settings.maxConcurrentSessions)).onChange(async (value) => { const parsed = Number.parseInt(value.trim(), 10); this.plugin.settings.maxConcurrentSessions = Number.isInteger(parsed) && parsed >= 0 ? parsed : DEFAULT_SETTINGS.maxConcurrentSessions; await this.plugin.saveSettings(); }) ); new import_obsidian2.Setting(containerEl).setName("Runtimes").setHeading(); containerEl.createEl("p", { text: "Configure the runtimes available from the sidebar new-session menu. Each entry needs a display name and a launch command. Add as many as you want.", cls: "setting-item-description" }); const runtimesListEl = containerEl.createDiv({ cls: "claude-cli-runtimes-list" }); if (this.plugin.settings.runtimes.length === 0) { runtimesListEl.createEl("p", { text: "No runtimes configured yet. Use the button below to create one.", cls: "setting-item-description" }); } this.plugin.settings.runtimes.forEach((runtime, index) => { const setting = new import_obsidian2.Setting(runtimesListEl).setClass("claude-cli-runtime-item"); setting.infoEl.detach(); setting.addText( (text) => text.setPlaceholder("Name").setValue(runtime.name).onChange(async (value) => { this.plugin.settings.runtimes[index].name = value; await this.plugin.saveSettings(); this.plugin.notifyRuntimesChanged(); }) ).addText((text) => { text.setPlaceholder("Launch command").setValue(runtime.command).onChange(async (value) => { this.plugin.settings.runtimes[index].command = value; await this.plugin.saveSettings(); }); text.inputEl.addClass("claude-cli-runtime-command-input"); }).addExtraButton( (btn) => btn.setIcon("trash-2").setTooltip("Remove runtime").onClick(async () => { if (this.plugin.settings.runtimes.length <= 1) { new import_obsidian2.Notice("Keep at least one runtime configured.", 4e3); return; } const removed = this.plugin.settings.runtimes.splice(index, 1)[0]; if (this.plugin.settings.selectedRuntimeId === removed.id) { this.plugin.settings.selectedRuntimeId = this.plugin.settings.runtimes[0].id; } await this.plugin.saveSettings(); this.plugin.notifyRuntimesChanged(); this.display(); }) ); }); new import_obsidian2.Setting(containerEl).addButton( (btn) => btn.setButtonText("Add runtime").setIcon("plus").onClick(async () => { this.plugin.settings.runtimes.push({ id: defaultGenerateRuntimeId(), name: "New runtime", command: "" }); await this.plugin.saveSettings(); this.plugin.notifyRuntimesChanged(); this.display(); }) ); new import_obsidian2.Setting(containerEl).setName("Automations").setHeading(); containerEl.createEl("p", { text: "Folder containing prompt automations. Each Markdown file is one automation (frontmatter sets the schedule; body is the prompt sent to the running CLI). See readme for the file format.", cls: "setting-item-description" }); new import_obsidian2.Setting(containerEl).setName("Automations folder").setDesc("Vault-relative path. Leave empty to disable automations.").addText( (text) => text.setPlaceholder("Automations").setValue(this.plugin.settings.automationsFolder).onChange(async (value) => { this.plugin.settings.automationsFolder = value.trim(); await this.plugin.saveSettings(); this.plugin.loadAutomations(); }) ); new import_obsidian2.Setting(containerEl).setName("Reload automations").setDesc("Force a re-scan of the automations folder (otherwise scans happen on vault changes).").addButton( (btn) => btn.setButtonText("Reload now").setIcon("refresh-cw").onClick(() => { this.plugin.loadAutomations(); new import_obsidian2.Notice("Automations reloaded.", 2500); }) ); new import_obsidian2.Setting(containerEl).setName("Create example automation").setDesc("Write a hello-world automation file plus an AUTOMATION-DOCS.md reference (every option explained) into the folder above.").addButton( (btn) => btn.setButtonText("Create example").setIcon("file-plus").onClick(async () => { try { const { example, docs } = await this.plugin.createExampleAutomation(); new import_obsidian2.Notice(`Created ${example.path} and ${docs.path}`, 4e3); await this.app.workspace.openLinkText(example.path, "", true); } catch (err) { new import_obsidian2.Notice(err.message, 5e3); } }) ); new import_obsidian2.Setting(containerEl).setName("Auto-close automation sessions on exit").setDesc("When an automation-spawned session's process exits, close its tab automatically so tabs don't pile up.").addToggle( (toggle) => toggle.setValue(this.plugin.settings.autoCloseAutomationSessions).onChange(async (value) => { this.plugin.settings.autoCloseAutomationSessions = value; await this.plugin.saveSettings(); }) ); new import_obsidian2.Setting(containerEl).setName("Auto-close automation sessions when idle").setDesc("Close an automation tab once its CLI goes quiet after the prompt ran (the AI finished its turn), even if the process stays alive. Off by default \u2014 a long task that pauses output beyond the idle timeout could be closed early.").addToggle( (toggle) => toggle.setValue(this.plugin.settings.autoCloseAutomationSessionsOnIdle).onChange(async (value) => { this.plugin.settings.autoCloseAutomationSessionsOnIdle = value; await this.plugin.saveSettings(); }) ); new import_obsidian2.Setting(containerEl).setName("Idle timeout (seconds)").setDesc("How long a CLI must stay quiet before a session counts as finished \u2014 turns the tab dot gray and triggers the idle auto-close above. Default 10.").addText( (text) => text.setPlaceholder(String(DEFAULT_IDLE_TIMEOUT_SECONDS)).setValue(String(this.plugin.settings.idleTimeoutSeconds)).onChange(async (value) => { const parsed = Number.parseInt(value.trim(), 10); this.plugin.settings.idleTimeoutSeconds = Number.isInteger(parsed) && parsed >= 1 ? parsed : DEFAULT_SETTINGS.idleTimeoutSeconds; await this.plugin.saveSettings(); }) ); new import_obsidian2.Setting(containerEl).setName("Advanced").setHeading(); new import_obsidian2.Setting(containerEl).setName("Node executable").setDesc("Path to the node binary used by the proxy. Leave as 'auto' for automatic detection.").addText( (text) => text.setPlaceholder("Auto").setValue(this.plugin.settings.nodeExecutable).onChange(async (value) => { this.plugin.settings.nodeExecutable = value.trim() || "auto"; await this.plugin.saveSettings(); }) ); new import_obsidian2.Setting(containerEl).setName("Verbose proxy logs").setDesc("Print the proxy's diagnostic messages (node-pty / python bridge / pipe fallback) in the terminal. Off by default \u2014 these are normal fallback notes, not errors. Real launch failures are always shown. Takes effect on the next session start.").addToggle( (toggle) => toggle.setValue(this.plugin.settings.verboseProxyLogs).onChange(async (value) => { this.plugin.settings.verboseProxyLogs = value; await this.plugin.saveSettings(); }) ); } }; function resolvePluginDir2(pluginDir, vaultBasePath, path2) { return resolvePluginDir(pluginDir, vaultBasePath, path2); } function getVaultBasePath(app) { const adapter = app.vault.adapter; if (adapter instanceof import_obsidian2.FileSystemAdapter) { return adapter.getBasePath(); } return void 0; } function getShellEnv() { const home = os2.homedir(); const env = { ...process.env, TERM: "xterm-256color" }; const extraPaths = []; if (process.platform === "darwin") { extraPaths.push( "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin" ); } else if (process.platform === "linux") { extraPaths.push( "/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin" ); } else if (process.platform === "win32") { const appData = process.env.APPDATA; const localAppData = process.env.LOCALAPPDATA; const userProfile = process.env.USERPROFILE; if (appData) extraPaths.push(path.join(appData, "npm")); if (localAppData) extraPaths.push(path.join(localAppData, "Microsoft", "WindowsApps")); if (userProfile) extraPaths.push(path.join(userProfile, "scoop", "shims")); } if (home) { extraPaths.push( path.join(home, ".local", "bin"), path.join(home, ".npm-global", "bin"), path.join(home, ".volta", "bin"), path.join(home, ".asdf", "shims"), path.join(home, "Library", "pnpm"), path.join(home, ".local", "share", "pnpm"), path.join(home, ".lmstudio", "bin") ); const nvmVersionsDir = path.join(home, ".nvm", "versions", "node"); if (fs2.existsSync(nvmVersionsDir)) { try { const versions = fs2.readdirSync(nvmVersionsDir, { withFileTypes: true }); for (const version of versions) { if (version.isDirectory()) { extraPaths.push(path.join(nvmVersionsDir, version.name, "bin")); } } } catch (e) { } } } env.PATH = mergePathEntries2(env.PATH, extraPaths); return env; } function mergePathEntries2(currentPath, extras) { return mergePathEntries(currentPath, extras, process.platform); } function writeProxyFileIfNeeded(targetPath, source) { try { if (fs2.existsSync(targetPath) && fs2.readFileSync(targetPath, "utf8") === source) { return; } } catch (e) { } fs2.writeFileSync(targetPath, source); } function ensureProxyFiles(pluginDir) { writeProxyFileIfNeeded(path.join(pluginDir, "pty-proxy.js"), 'let pty = null;\nlet ptyLoadError = null;\ntry {\n pty = require("node-pty");\n} catch (error) {\n ptyLoadError = error;\n}\nconst { spawn } = require("child_process");\nconst fs = require("fs");\n\n// Diagnostic logger. The node-pty -> python bridge -> pipe -> script fallback\n// chain is normal operation when the optional native `node-pty` module is not\n// installed, so its info/warn chatter is hidden from the terminal by default\n// and only shown when verbose proxy logging is enabled. Real launch failures\n// (error/fatal) are always surfaced so a blank terminal never goes unexplained.\nfunction makeLogger(verbose) {\n const write = (line) => process.stderr.write(line);\n return {\n info(message) {\n if (verbose) write(`[proxy-info] ${message}\\n`);\n },\n warn(message) {\n if (verbose) write(`[proxy-warn] ${message}\\n`);\n },\n error(message) {\n write(`[proxy-error] ${message}\\n`);\n }\n };\n}\n\nfunction decodePayload(raw) {\n if (!raw) {\n throw new Error("Missing proxy payload");\n }\n const json = Buffer.from(raw, "base64").toString("utf8");\n return JSON.parse(json);\n}\n\nfunction getLaunchSpecs(command) {\n if (process.platform === "win32") {\n const comspec = process.env.ComSpec || process.env.COMSPEC || "C:\\\\Windows\\\\System32\\\\cmd.exe";\n return [{ file: comspec, args: ["/d", "/s", "/c", command] }];\n }\n\n const candidates = [process.env.SHELL, "/bin/zsh", "/bin/bash", "/bin/sh"].filter(Boolean);\n const unique = Array.from(new Set(candidates));\n\n const launches = [];\n for (const shell of unique) {\n if (shell.endsWith("/sh")) {\n launches.push({ file: shell, args: ["-c", command] });\n } else {\n launches.push({ file: shell, args: ["-lc", command] });\n }\n }\n\n if (launches.length === 0) {\n launches.push({ file: "/bin/sh", args: ["-c", command] });\n }\n\n return launches;\n}\n\nfunction spawnWithFallback(launches, options) {\n if (!pty) {\n const reason = ptyLoadError ? ptyLoadError.message : "node-pty not loaded";\n throw new Error(`node-pty unavailable: ${reason}`);\n }\n const failures = [];\n for (const launch of launches) {\n try {\n return pty.spawn(launch.file, launch.args, options);\n } catch (error) {\n failures.push(`${launch.file}: ${error.message}`);\n }\n }\n throw new Error(`All launch attempts failed. ${failures.join(" | ")}`);\n}\n\nfunction spawnPipeWithFallback(launches, options) {\n const failures = [];\n for (const launch of launches) {\n try {\n const child = spawn(launch.file, launch.args, {\n cwd: options.cwd,\n env: options.env,\n stdio: ["pipe", "pipe", "pipe"]\n });\n return child;\n } catch (error) {\n failures.push(`${launch.file}: ${error.message}`);\n }\n }\n throw new Error(`All pipe launch attempts failed. ${failures.join(" | ")}`);\n}\n\nfunction buildScriptLaunches(command, launches) {\n if (process.platform === "win32") {\n return [];\n }\n if (!fs.existsSync("/usr/bin/script") && !fs.existsSync("/bin/script")) {\n return [];\n }\n\n const scriptBin = fs.existsSync("/usr/bin/script") ? "/usr/bin/script" : "/bin/script";\n const wrappers = [];\n\n // macOS/BSD script syntax\n for (const launch of launches) {\n wrappers.push({\n file: scriptBin,\n args: ["-q", "/dev/null", launch.file, ...launch.args]\n });\n }\n\n // GNU script syntax fallback\n wrappers.push({\n file: scriptBin,\n args: ["-q", "-c", command, "/dev/null"]\n });\n\n return wrappers;\n}\n\nfunction isCodexCommand(command) {\n if (!command || typeof command !== "string") {\n return false;\n }\n const trimmed = command.trim();\n return trimmed === "codex" || trimmed.startsWith("codex ");\n}\n\nfunction resolvePythonExecutable() {\n const candidates = [\n process.env.PYTHON,\n "/opt/homebrew/bin/python3",\n "/usr/local/bin/python3",\n "/usr/bin/python3",\n "python3",\n "python"\n ].filter(Boolean);\n\n for (const candidate of candidates) {\n if (candidate.includes("/")) {\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n continue;\n }\n return candidate;\n }\n\n return "python3";\n}\n\nfunction spawnPythonBridge(payload, launches) {\n if (process.platform === "win32") {\n throw new Error("python PTY bridge is not available on Windows");\n }\n\n const path = require("path");\n const bridgePath = path.join(__dirname, "pty-bridge.py");\n if (!fs.existsSync(bridgePath)) {\n throw new Error(`missing python bridge script: ${bridgePath}`);\n }\n\n const pythonExec = resolvePythonExecutable();\n const encoded = Buffer.from(\n JSON.stringify({\n cwd: payload.cwd,\n env: payload.env,\n launches,\n cols: payload.cols,\n rows: payload.rows\n }),\n "utf8"\n ).toString("base64");\n\n return spawn(pythonExec, [bridgePath, encoded], {\n cwd: payload.cwd,\n env: payload.env,\n stdio: ["pipe", "pipe", "pipe"]\n });\n}\n\nasync function main() {\n const payload = decodePayload(process.argv[2]);\n const log = makeLogger(Boolean(payload.verbose));\n const launches = getLaunchSpecs(payload.command);\n\n let term;\n let mode = "pty";\n try {\n term = spawnWithFallback(launches, {\n name: "xterm-256color",\n cols: Math.max(20, Number(payload.cols) || 120),\n rows: Math.max(10, Number(payload.rows) || 30),\n cwd: payload.cwd,\n env: {\n ...payload.env,\n TERM: "xterm-256color"\n },\n useConpty: process.platform === "win32"\n });\n } catch (error) {\n log.warn(`PTY unavailable, switching to pipe mode: ${error.message}`);\n mode = "pipe";\n try {\n const fallbackEnv = {\n ...payload.env,\n TERM: "xterm-256color"\n };\n const scriptLaunches = buildScriptLaunches(payload.command, launches);\n const codexCommand = isCodexCommand(payload.command);\n\n if (!term) {\n try {\n term = spawnPythonBridge(\n {\n cwd: payload.cwd,\n env: fallbackEnv,\n cols: Math.max(20, Number(payload.cols) || 120),\n rows: Math.max(10, Number(payload.rows) || 30)\n },\n launches\n );\n log.info("python PTY bridge fallback started");\n } catch (pythonError) {\n log.warn(`python bridge failed, trying direct pipe: ${pythonError.message}`);\n try {\n term = spawnPipeWithFallback(launches, {\n cwd: payload.cwd,\n env: fallbackEnv\n });\n log.info("direct pipe fallback started");\n } catch (pipeError) {\n if (codexCommand) {\n log.error(pipeError.message);\n process.exit(1);\n return;\n }\n if (scriptLaunches.length === 0) {\n log.error(pipeError.message);\n process.exit(1);\n return;\n }\n\n log.warn(`direct pipe failed, trying system \'script\': ${pipeError.message}`);\n try {\n term = spawnPipeWithFallback(scriptLaunches, {\n cwd: payload.cwd,\n env: fallbackEnv\n });\n } catch (scriptError) {\n log.error(scriptError.message);\n process.exit(1);\n return;\n }\n }\n }\n }\n log.info(`fallback process started (pid=${term.pid})`);\n } catch (outerError) {\n log.error(outerError.message);\n process.exit(1);\n return;\n }\n }\n\n if (mode === "pty") {\n term.onData((data) => {\n process.stdout.write(data);\n });\n\n term.onExit(({ exitCode }) => {\n process.exit(exitCode ?? 0);\n });\n\n process.stdin.on("data", (chunk) => {\n term.write(chunk.toString("utf8"));\n });\n process.stdin.resume();\n } else {\n term.stdout.on("data", (chunk) => {\n process.stdout.write(typeof chunk === "string" ? chunk : chunk.toString("utf8"));\n });\n term.stderr.on("data", (chunk) => {\n process.stdout.write(typeof chunk === "string" ? chunk : chunk.toString("utf8"));\n });\n term.on("exit", (code) => {\n process.exit(code ?? 0);\n });\n process.stdin.on("data", (chunk) => {\n if (term.stdin.writable) {\n term.stdin.write(chunk);\n }\n });\n process.stdin.resume();\n }\n\n process.on("message", (message) => {\n if (!message || typeof message !== "object") {\n return;\n }\n if (mode === "pty" && message.type === "resize") {\n const cols = Math.max(20, Number(message.cols) || 120);\n const rows = Math.max(10, Number(message.rows) || 30);\n try {\n term.resize(cols, rows);\n } catch {\n // Ignore resize errors.\n }\n }\n });\n\n const shutdown = () => {\n try {\n term.kill("SIGTERM");\n } catch {\n // Ignore shutdown errors.\n }\n };\n\n process.on("SIGTERM", shutdown);\n process.on("SIGINT", shutdown);\n}\n\nmain().catch((error) => {\n process.stderr.write(`[proxy-fatal] ${error.message}\\n`);\n process.exit(1);\n});\n'); writeProxyFileIfNeeded(path.join(pluginDir, "pty-bridge.py"), `#!/usr/bin/env python3 import base64 import json import os import pty import fcntl import select import struct import sys import termios def decode_payload(raw: str): if not raw: raise ValueError("missing payload") decoded = base64.b64decode(raw.encode("utf-8")).decode("utf-8") return json.loads(decoded) def as_exit_code(status: int) -> int: if os.WIFEXITED(status): return os.WEXITSTATUS(status) if os.WIFSIGNALED(status): return 128 + os.WTERMSIG(status) return 1 def set_winsize(fd: int, rows: int, cols: int) -> None: packed = struct.pack("HHHH", rows, cols, 0, 0) fcntl.ioctl(fd, termios.TIOCSWINSZ, packed) def stream_pty(pid: int, fd: int) -> int: stdin_open = True while True: readers = [fd] if stdin_open: readers.append(sys.stdin.fileno()) ready, _, _ = select.select(readers, [], []) if fd in ready: try: chunk = os.read(fd, 4096) except OSError: chunk = b"" if not chunk: break os.write(sys.stdout.fileno(), chunk) if stdin_open and sys.stdin.fileno() in ready: try: chunk = os.read(sys.stdin.fileno(), 4096) except OSError: chunk = b"" if not chunk: stdin_open = False else: os.write(fd, chunk) _, status = os.waitpid(pid, 0) return as_exit_code(status) def main() -> int: payload = decode_payload(sys.argv[1] if len(sys.argv) > 1 else "") cwd = payload.get("cwd") if cwd: os.chdir(cwd) env = payload.get("env") or {} for key, value in env.items(): if value is None: continue os.environ[str(key)] = str(value) launches = payload.get("launches") or [] cols = int(payload.get("cols") or 120) rows = int(payload.get("rows") or 30) cols = max(20, cols) rows = max(10, rows) if not launches: print("[py-bridge-error] no launch specs provided", file=sys.stderr) return 1 failures = [] for launch in launches: file = launch.get("file") args = launch.get("args") or [] argv = [str(file)] + [str(x) for x in args] try: pid, fd = pty.fork() if pid == 0: os.execvpe(str(file), argv, os.environ) set_winsize(fd, rows, cols) return stream_pty(pid, fd) except OSError as error: failures.append(f"{file}: {error}") print(f"[py-bridge-error] all launch attempts failed: {' | '.join(failures)}", file=sys.stderr) return 1 if __name__ == "__main__": raise SystemExit(main()) `); } function spawnPtyProxy(params) { const resolvedPluginDir = resolvePluginDir2(params.pluginDir, params.vaultPath, path); if (resolvedPluginDir) { ensureProxyFiles(resolvedPluginDir); } const scriptPath = resolvedPluginDir ? path.join(resolvedPluginDir, "pty-proxy.js") : path.resolve("pty-proxy.js"); if (!fs2.existsSync(scriptPath)) { throw new Error(`Missing proxy script: ${scriptPath}`); } const payload = Buffer.from( JSON.stringify({ command: params.command, cwd: params.cwd, env: params.env, cols: params.cols, rows: params.rows, verbose: Boolean(params.verbose) }), "utf8" ).toString("base64"); const nodeExecutable = detectNodeExecutable( params.nodeExecutable, process.platform, params.env, fs2.existsSync, path ); return (0, import_child_process.spawn)(nodeExecutable, [scriptPath, payload], { cwd: params.cwd, env: params.env, stdio: ["pipe", "pipe", "pipe", "ipc"] }); } function sanitizeLastRun(raw) { if (!raw || typeof raw !== "object") { return {}; } const out = {}; for (const [key, value] of Object.entries(raw)) { if (typeof key === "string" && key && typeof value === "number" && Number.isFinite(value)) { out[key] = value; } } return out; } function sanitizeHistory(raw) { if (!Array.isArray(raw)) { return []; } const out = []; for (const entry of raw) { if (!entry || typeof entry !== "object") continue; const r = entry; if (typeof r.ts !== "number" || typeof r.path !== "string" || typeof r.name !== "string" || r.source !== "scheduler" && r.source !== "manual" || r.status !== "ran" && r.status !== "skipped" && r.status !== "error") { continue; } out.push({ ts: r.ts, path: r.path, name: r.name, source: r.source, status: r.status, reason: typeof r.reason === "string" ? r.reason : void 0, runtimeId: typeof r.runtimeId === "string" ? r.runtimeId : null, promptPreview: typeof r.promptPreview === "string" ? r.promptPreview : void 0 }); } return out; } function makeProxyAdapter(handle) { var _a5, _b; const dataCallbacks = []; const exitCallbacks = []; const pendingData = []; let pendingExit = null; const emitData = (chunk) => { const text = typeof chunk === "string" ? chunk : chunk.toString("utf8"); if (dataCallbacks.length === 0) { pendingData.push(text); return; } dataCallbacks.forEach((callback) => callback(text)); }; const emitExit = (code, signal) => { const exitCode = code != null ? code : -1; const exitSignal = signal != null ? signal : "none"; if (exitCallbacks.length === 0) { pendingExit = { code: exitCode, signal: exitSignal }; return; } exitCallbacks.forEach((callback) => callback(exitCode, exitSignal)); }; (_a5 = handle.stdout) == null ? void 0 : _a5.on("data", emitData); (_b = handle.stderr) == null ? void 0 : _b.on("data", emitData); handle.on("exit", emitExit); return { write(data) { var _a6; if ((_a6 = handle.stdin) == null ? void 0 : _a6.writable) { handle.stdin.write(data); } }, resize(cols, rows) { if (typeof handle.send === "function") { handle.send({ type: "resize", cols, rows }); } }, kill(signal) { handle.kill(signal); }, onData(callback) { dataCallbacks.push(callback); if (pendingData.length > 0) { pendingData.splice(0, pendingData.length).forEach((chunk) => callback(chunk)); } }, onExit(callback) { exitCallbacks.push(callback); if (pendingExit) { callback(pendingExit.code, pendingExit.signal); pendingExit = null; } } }; } /*! Bundled license information: @xterm/xterm/lib/xterm.mjs: @xterm/addon-fit/lib/addon-fit.mjs: (** * Copyright (c) 2014-2024 The xterm.js authors. All rights reserved. * @license MIT * * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) * @license MIT * * Originally forked from (with the author's permission): * Fabrice Bellard's javascript vt100 for jslinux: * http://bellard.org/jslinux/ * Copyright (c) 2011 Fabrice Bellard *) */