commit 97c035dfbf10309f68a5c56981fcdc2d3e8a5aa2 Author: bl3kunja-FW Date: Fri Sep 25 17:45:32 2026 +0200 vault backup: 2026-09-25 17:45:32 diff --git a/.obsidian/app.json b/.obsidian/app.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/.obsidian/app.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/.obsidian/appearance.json b/.obsidian/appearance.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/.obsidian/appearance.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/.obsidian/community-plugins.json b/.obsidian/community-plugins.json new file mode 100644 index 0000000..9fb994b --- /dev/null +++ b/.obsidian/community-plugins.json @@ -0,0 +1,5 @@ +[ + "obsidian-git", + "tasknotes", + "advanced-canvas" +] \ No newline at end of file diff --git a/.obsidian/core-plugins.json b/.obsidian/core-plugins.json new file mode 100644 index 0000000..639b90d --- /dev/null +++ b/.obsidian/core-plugins.json @@ -0,0 +1,33 @@ +{ + "file-explorer": true, + "global-search": true, + "switcher": true, + "graph": true, + "backlink": true, + "canvas": true, + "outgoing-link": true, + "tag-pane": true, + "footnotes": false, + "properties": true, + "page-preview": true, + "daily-notes": true, + "templates": true, + "note-composer": true, + "command-palette": true, + "slash-command": false, + "editor-status": true, + "bookmarks": true, + "markdown-importer": false, + "zk-prefixer": false, + "random-note": false, + "outline": true, + "word-count": true, + "slides": false, + "audio-recorder": false, + "workspaces": false, + "file-recovery": true, + "publish": false, + "sync": true, + "bases": true, + "webviewer": false +} \ No newline at end of file diff --git a/.obsidian/plugins/advanced-canvas/main.js b/.obsidian/plugins/advanced-canvas/main.js new file mode 100644 index 0000000..11393b4 --- /dev/null +++ b/.obsidian/plugins/advanced-canvas/main.js @@ -0,0 +1,8585 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ESBUILD +if you want to view the source, please visit the github repository of this plugin +*/ + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/main.ts +var main_exports = {}; +__export(main_exports, { + default: () => AdvancedCanvasPlugin +}); +module.exports = __toCommonJS(main_exports); +var import_obsidian22 = require("obsidian"); + +// src/utils/icons-helper.ts +var import_obsidian = require("obsidian"); +var CUSTOM_ICONS = { + "shape-pill": ``, + "shape-parallelogram": ``, + "shape-predefined-process": ` + + + + + + `, + "shape-document": ``, + "shape-database": ` + + + + + `, + "border-solid": ``, + "border-dashed": ``, + "border-dotted": ``, + "path-solid": ``, + "path-dotted": ``, + "path-short-dashed": ``, + "path-long-dashed": ``, + "arrow-triangle": ``, + "arrow-triangle-outline": ``, + "arrow-thin-triangle": ``, + "arrow-halved-triangle": ``, + "arrow-diamond": ``, + "arrow-diamond-outline": ``, + "arrow-circle": ``, + "arrow-circle-outline": ``, + "pathfinding-method-bezier": ``, + "pathfinding-method-square": ``, + "arrows-selected": ` + + + + + + + + + + `, + "arrow-right-selected": ` + + + + + + + + `, + "arrow-left-selected": ` + + + + + + + + ` +}; +var IconsHelper = class { + static addIcons() { + for (const [id, svg] of Object.entries(CUSTOM_ICONS)) { + (0, import_obsidian.addIcon)(id, svg); + } + } +}; + +// src/utils/debug-helper.ts +var DebugHelper = class { + constructor(plugin) { + this.logging = true; + this.nodeAddedCount = 0; + this.nodeChangedCount = 0; + this.edgeAddedCount = 0; + this.edgeChangedCount = 0; + this.plugin = plugin; + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:canvas-changed", + (_canvas) => { + this.nodeAddedCount = 0; + this.nodeChangedCount = 0; + this.edgeAddedCount = 0; + this.edgeChangedCount = 0; + } + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-added", + (_canvas, _node) => { + if (this.logging) console.debug("\u{1F7E2} NodeAdded"); + this.nodeAddedCount++; + } + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-changed", + (_canvas, _node) => { + if (this.logging) console.debug("\u{1F7E1} NodeChanged"); + this.nodeChangedCount++; + } + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:edge-added", + (_canvas, _edge) => { + if (this.logging) console.debug("\u{1F7E2} EdgeAdded"); + this.edgeAddedCount++; + } + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:edge-changed", + (_canvas, _edge) => { + if (this.logging) console.debug("\u{1F7E1} EdgeChanged"); + this.edgeChangedCount++; + } + )); + } + resetEfficiency() { + this.nodeAddedCount = 0; + this.nodeChangedCount = 0; + this.edgeAddedCount = 0; + this.edgeChangedCount = 0; + } + logEfficiency() { + const canvas = this.plugin.getCurrentCanvas(); + if (!canvas) return; + console.debug("NodeAdded Efficiency:", this.nodeAddedCount / canvas.nodes.size); + console.debug("NodeChanged Efficiency:", this.nodeChangedCount / canvas.nodes.size); + console.debug("EdgeAdded Efficiency:", this.edgeAddedCount / canvas.edges.size); + console.debug("EdgeChanged Efficiency:", this.edgeChangedCount / canvas.edges.size); + } + static markBBox(canvas, bbox, duration = -1) { + const node = canvas.createTextNode({ + pos: { x: bbox.minX, y: bbox.minY }, + size: { width: bbox.maxX - bbox.minX, height: bbox.maxY - bbox.minY }, + text: "", + focus: false + }); + node.setData({ + ...node.getData(), + id: "debug-bbox", + color: "1", + styleAttributes: { + border: "invisible" + } + }); + if (duration >= 0) { + window.setTimeout(() => { + canvas.removeNode(node); + }, duration); + } + } +}; + +// src/settings.ts +var import_obsidian4 = require("obsidian"); + +// src/utils/bbox-helper.ts +var BBoxHelper = class { + static combineBBoxes(bboxes) { + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const bbox of bboxes) { + minX = Math.min(minX, bbox.minX); + minY = Math.min(minY, bbox.minY); + maxX = Math.max(maxX, bbox.maxX); + maxY = Math.max(maxY, bbox.maxY); + } + return { minX, minY, maxX, maxY }; + } + static scaleBBox(bbox, scale) { + const diffX = (scale - 1) * (bbox.maxX - bbox.minX); + const diffY = (scale - 1) * (bbox.maxY - bbox.minY); + return { + minX: bbox.minX - diffX / 2, + maxX: bbox.maxX + diffX / 2, + minY: bbox.minY - diffY / 2, + maxY: bbox.maxY + diffY / 2 + }; + } + static isColliding(bbox1, bbox2) { + return bbox1.minX <= bbox2.maxX && bbox1.maxX >= bbox2.minX && bbox1.minY <= bbox2.maxY && bbox1.maxY >= bbox2.minY; + } + static insideBBox(position, bbox, canTouchEdge) { + if ("x" in position) { + const x = position.x, y = position.y; + return canTouchEdge ? x >= bbox.minX && x <= bbox.maxX && y >= bbox.minY && y <= bbox.maxY : x > bbox.minX && x < bbox.maxX && y > bbox.minY && y < bbox.maxY; + } + return canTouchEdge ? position.minX >= bbox.minX && position.maxX <= bbox.maxX && position.minY >= bbox.minY && position.maxY <= bbox.maxY : position.minX > bbox.minX && position.maxX < bbox.maxX && position.minY > bbox.minY && position.maxY < bbox.maxY; + } + static enlargeBBox(bbox, padding) { + return { + minX: bbox.minX - padding, + minY: bbox.minY - padding, + maxX: bbox.maxX + padding, + maxY: bbox.maxY + padding + }; + } + static moveInDirection(position, side, distance) { + switch (side) { + case "top": + return { x: position.x, y: position.y - distance }; + case "right": + return { x: position.x + distance, y: position.y }; + case "bottom": + return { x: position.x, y: position.y + distance }; + case "left": + return { x: position.x - distance, y: position.y }; + } + } + static getCenterOfBBoxSide(bbox, side) { + switch (side) { + case "top": + return { x: (bbox.minX + bbox.maxX) / 2, y: bbox.minY }; + case "right": + return { x: bbox.maxX, y: (bbox.minY + bbox.maxY) / 2 }; + case "bottom": + return { x: (bbox.minX + bbox.maxX) / 2, y: bbox.maxY }; + case "left": + return { x: bbox.minX, y: (bbox.minY + bbox.maxY) / 2 }; + } + } + static getSideVector(side) { + switch (side) { + case "top": + return { x: 0, y: 1 }; + case "right": + return { x: 1, y: 0 }; + case "bottom": + return { x: 0, y: -1 }; + case "left": + return { x: -1, y: 0 }; + default: + return { x: 0, y: 0 }; + } + } + static getOppositeSide(side) { + switch (side) { + case "top": + return "bottom"; + case "right": + return "left"; + case "bottom": + return "top"; + case "left": + return "right"; + } + } + static isHorizontal(side) { + return side === "left" || side === "right"; + } + static direction(side) { + return side === "right" || side === "bottom" ? 1 : -1; + } +}; + +// src/utils/canvas-helper.ts +var import_obsidian2 = require("obsidian"); +var _CanvasHelper = class _CanvasHelper { + static canvasCommand(plugin, check, run) { + return (checking) => { + const canvas = plugin.getCurrentCanvas(); + if (checking) return canvas !== null && check(canvas); + if (canvas) void run(canvas); + return true; + }; + } + static createControlMenuButton(menuOption) { + const quickSetting = activeWindow.createDiv(); + if (menuOption.id) quickSetting.id = menuOption.id; + quickSetting.classList.add("canvas-control-item"); + (0, import_obsidian2.setIcon)(quickSetting, menuOption.icon); + (0, import_obsidian2.setTooltip)(quickSetting, menuOption.label, { placement: "left" }); + quickSetting.addEventListener("click", () => { + var _a; + return (_a = menuOption.callback) == null ? void 0 : _a.call(menuOption); + }); + return quickSetting; + } + static addControlMenuButton(controlGroup, element) { + var _a; + if (element.id) (_a = controlGroup.querySelector(`#${element.id}`)) == null ? void 0 : _a.remove(); + controlGroup.appendChild(element); + } + static createCardMenuOption(canvas, menuOption, previewNodeSize, onPlaced, onRightClick) { + const menuOptionElement = activeWindow.createDiv(); + if (menuOption.id) menuOptionElement.id = menuOption.id; + menuOptionElement.classList.add("canvas-card-menu-button"); + menuOptionElement.classList.add("mod-draggable"); + (0, import_obsidian2.setIcon)(menuOptionElement, menuOption.icon); + (0, import_obsidian2.setTooltip)(menuOptionElement, menuOption.label, { placement: "top" }); + menuOptionElement.addEventListener("click", (_e) => { + onPlaced(canvas, this.getCenterCoordinates(canvas, previewNodeSize())); + }); + if (onRightClick) menuOptionElement.addEventListener("contextmenu", (e) => { + e.preventDefault(); + onRightClick(e); + }); + menuOptionElement.addEventListener("pointerdown", (e) => { + canvas.dragTempNode(e, previewNodeSize(), (pos) => { + canvas.deselectAll(); + onPlaced(canvas, pos); + }); + }); + return menuOptionElement; + } + static addCardMenuOption(canvas, element) { + var _a; + if (element.id) (_a = canvas == null ? void 0 : canvas.cardMenuEl.querySelector(`#${element.id}`)) == null ? void 0 : _a.remove(); + canvas == null ? void 0 : canvas.cardMenuEl.appendChild(element); + } + static createPopupMenuOption(menuOption) { + const menuOptionElement = activeWindow.createEl("button"); + if (menuOption.id) menuOptionElement.id = menuOption.id; + menuOptionElement.classList.add("clickable-icon"); + (0, import_obsidian2.setIcon)(menuOptionElement, menuOption.icon); + (0, import_obsidian2.setTooltip)(menuOptionElement, menuOption.label, { placement: "top" }); + menuOptionElement.addEventListener("click", () => { + var _a; + return (_a = menuOption.callback) == null ? void 0 : _a.call(menuOption); + }); + return menuOptionElement; + } + static createExpandablePopupMenuOption(menuOption, subMenuOptions) { + const menuOptionElement = this.createPopupMenuOption({ + ...menuOption, + callback: () => { + var _a, _b, _c; + const submenuId = `${menuOption.id}-submenu`; + if (menuOptionElement.classList.contains("is-active")) { + menuOptionElement.classList.remove("is-active"); + (_b = (_a = menuOptionElement.parentElement) == null ? void 0 : _a.querySelector(`#${submenuId}`)) == null ? void 0 : _b.remove(); + return; + } + menuOptionElement.classList.add("is-active"); + const submenu = (_c = menuOptionElement.parentElement) == null ? void 0 : _c.createDiv(); + if (!submenu) return; + submenu.id = submenuId; + submenu.classList.add("canvas-submenu"); + for (const subMenuOption of subMenuOptions) { + const subMenuOptionElement = this.createPopupMenuOption(subMenuOption); + submenu.appendChild(subMenuOptionElement); + } + } + }); + return menuOptionElement; + } + static addPopupMenuOption(canvas, element, index = -1) { + var _a; + const popupMenuEl = (_a = canvas == null ? void 0 : canvas.menu) == null ? void 0 : _a.menuEl; + if (!popupMenuEl) return; + if (element.id) { + const optionToReplace = popupMenuEl.querySelector(`#${element.id}`); + if (optionToReplace && index === -1) index = Array.from(popupMenuEl.children).indexOf(optionToReplace) - 1; + optionToReplace == null ? void 0 : optionToReplace.remove(); + } + const sisterElement = index >= 0 ? popupMenuEl.children[index] : popupMenuEl.children[popupMenuEl.children.length + index]; + popupMenuEl.insertAfter(element, sisterElement); + } + static getCenterCoordinates(canvas, nodeSize) { + const viewBounds = canvas.getViewportBBox(); + return { + x: (viewBounds.minX + viewBounds.maxX) / 2 - nodeSize.width / 2, + y: (viewBounds.minY + viewBounds.maxY) / 2 - nodeSize.height / 2 + }; + } + static getBBox(canvasElements) { + const bBoxes = canvasElements.map((element) => { + if ("getBBox" in element) return element.getBBox(); + if (element.x !== void 0 && element.y !== void 0 && element.width !== void 0 && element.height !== void 0) + return { minX: element.x, minY: element.y, maxX: element.x + element.width, maxY: element.y + element.height }; + return null; + }).filter((bbox) => bbox !== null); + return BBoxHelper.combineBBoxes(bBoxes); + } + static getSmallestAllowedZoomBBox(canvas, bbox) { + if (canvas.screenshotting) return bbox; + if (canvas.canvasRect.width === 0 || canvas.canvasRect.height === 0) return bbox; + const widthZoom = canvas.canvasRect.width / (bbox.maxX - bbox.minX); + const heightZoom = canvas.canvasRect.height / (bbox.maxY - bbox.minY); + const requiredZoom = Math.min(widthZoom, heightZoom); + if (requiredZoom > _CanvasHelper.MAX_ALLOWED_ZOOM) { + const scaleFactor = requiredZoom / _CanvasHelper.MAX_ALLOWED_ZOOM; + return BBoxHelper.scaleBBox(bbox, scaleFactor); + } + return bbox; + } + static addStyleAttributesToPopup(plugin, canvas, styleAttributes, currentStyleAttributes, setStyleAttribute) { + if (!plugin.settings.getSetting("combineCustomStylesInDropdown")) + this.addStyleAttributesButtons(canvas, styleAttributes, currentStyleAttributes, setStyleAttribute); + else this.addStyleAttributesDropdownMenu(canvas, styleAttributes, currentStyleAttributes, setStyleAttribute); + } + static addStyleAttributesButtons(canvas, stylableAttributes, currentStyleAttributes, setStyleAttribute) { + var _a; + for (const stylableAttribute of stylableAttributes) { + const selectedStyle = (_a = stylableAttribute.options.find((option) => currentStyleAttributes[stylableAttribute.key] === option.value)) != null ? _a : stylableAttribute.options.find((value) => value.value === null); + if (!selectedStyle) { + console.warn(`No "null" style option found for stylable attribute "${stylableAttribute.key}"`); + continue; + } + const menuOption = _CanvasHelper.createExpandablePopupMenuOption({ + id: `menu-option-${stylableAttribute.key}`, + label: stylableAttribute.label, + icon: selectedStyle.icon + }, stylableAttribute.options.map((styleOption) => ({ + label: styleOption.label, + icon: styleOption.icon, + callback: () => { + setStyleAttribute(stylableAttribute, styleOption.value); + currentStyleAttributes[stylableAttribute.key] = styleOption.value; + (0, import_obsidian2.setIcon)(menuOption, styleOption.icon); + menuOption.dispatchEvent(new Event("click")); + } + }))); + _CanvasHelper.addPopupMenuOption(canvas, menuOption); + } + } + static addStyleAttributesDropdownMenu(canvas, stylableAttributes, currentStyleAttributes, setStyleAttribute) { + var _a, _b; + const STYLE_MENU_ID = "style-menu"; + const STYLE_MENU_DROPDOWN_ID = "style-menu-dropdown"; + const STYLE_MENU_DROPDOWN_SUBMENU_ID = "style-menu-dropdown-submenu"; + const popupMenuElement = (_a = canvas == null ? void 0 : canvas.menu) == null ? void 0 : _a.menuEl; + if (!popupMenuElement) return; + (_b = popupMenuElement.querySelector(`#${STYLE_MENU_ID}`)) == null ? void 0 : _b.remove(); + const styleMenuButtonElement = popupMenuElement.createEl("button"); + styleMenuButtonElement.id = STYLE_MENU_ID; + styleMenuButtonElement.classList.add("clickable-icon"); + (0, import_obsidian2.setIcon)(styleMenuButtonElement, "paintbrush"); + (0, import_obsidian2.setTooltip)(styleMenuButtonElement, "Style", { placement: "top" }); + styleMenuButtonElement.addEventListener("click", () => { + var _a2, _b2, _c; + const isOpen = styleMenuButtonElement.classList.toggle("has-active-menu"); + if (!isOpen) { + (_a2 = popupMenuElement.querySelector(`#${STYLE_MENU_DROPDOWN_ID}`)) == null ? void 0 : _a2.remove(); + (_b2 = popupMenuElement.querySelector(`#${STYLE_MENU_DROPDOWN_SUBMENU_ID}`)) == null ? void 0 : _b2.remove(); + return; + } + const styleMenuDropdownElement = popupMenuElement.createDiv(); + styleMenuDropdownElement.id = STYLE_MENU_DROPDOWN_ID; + styleMenuDropdownElement.classList.add("menu"); + const styleMenuDropdownScrollElement = styleMenuDropdownElement.createDiv(); + styleMenuDropdownScrollElement.classList.add("menu-scroll"); + const styleMenuDropdownGroupElement = styleMenuDropdownScrollElement.createDiv(); + styleMenuDropdownGroupElement.classList.add("menu-group"); + styleMenuDropdownElement.setCssStyles({ position: "absolute", maxHeight: "initial" }); + styleMenuDropdownElement.setCssStyles({ top: `${popupMenuElement.getBoundingClientRect().height}px` }); + const canvasWrapperCenterX = canvas.wrapperEl.getBoundingClientRect().left + canvas.wrapperEl.getBoundingClientRect().width / 2; + const leftPosition = styleMenuButtonElement.getBoundingClientRect().left - popupMenuElement.getBoundingClientRect().left; + const rightPosition = popupMenuElement.getBoundingClientRect().right - styleMenuButtonElement.getBoundingClientRect().right; + if (popupMenuElement.getBoundingClientRect().left + leftPosition < canvasWrapperCenterX) + styleMenuDropdownElement.setCssStyles({ left: `${leftPosition}px` }); + else styleMenuDropdownElement.setCssStyles({ right: `${rightPosition}px` }); + for (const stylableAttribute of stylableAttributes) { + const stylableAttributeElement = styleMenuDropdownGroupElement.createDiv(); + stylableAttributeElement.classList.add("menu-item"); + stylableAttributeElement.classList.add("tappable"); + const iconElement = stylableAttributeElement.createDiv(); + iconElement.classList.add("menu-item-icon"); + let selectedStyle = (_c = stylableAttribute.options.find((option) => currentStyleAttributes[stylableAttribute.key] === option.value)) != null ? _c : stylableAttribute.options.find((value) => value.value === null); + if (!selectedStyle) continue; + (0, import_obsidian2.setIcon)(iconElement, selectedStyle.icon); + const labelElement = stylableAttributeElement.createDiv(); + labelElement.classList.add("menu-item-title"); + labelElement.textContent = stylableAttribute.label; + const expandIconElement = stylableAttributeElement.createDiv(); + expandIconElement.classList.add("menu-item-icon"); + (0, import_obsidian2.setIcon)(expandIconElement, "chevron-right"); + stylableAttributeElement.addEventListener("pointerenter", () => { + stylableAttributeElement.classList.add("selected"); + }); + stylableAttributeElement.addEventListener("pointerleave", () => { + stylableAttributeElement.classList.remove("selected"); + }); + stylableAttributeElement.addEventListener("click", () => { + var _a3; + (_a3 = popupMenuElement.querySelector(`#${STYLE_MENU_DROPDOWN_SUBMENU_ID}`)) == null ? void 0 : _a3.remove(); + const styleMenuDropdownSubmenuElement = popupMenuElement.createDiv(); + styleMenuDropdownSubmenuElement.id = STYLE_MENU_DROPDOWN_SUBMENU_ID; + styleMenuDropdownSubmenuElement.classList.add("menu"); + const styleMenuDropdownSubmenuScrollElement = styleMenuDropdownSubmenuElement.createDiv(); + styleMenuDropdownSubmenuScrollElement.classList.add("menu-scroll"); + const styleMenuDropdownSubmenuGroupElement = styleMenuDropdownSubmenuScrollElement.createDiv(); + styleMenuDropdownSubmenuGroupElement.classList.add("menu-group"); + styleMenuDropdownSubmenuElement.setCssStyles({ position: "absolute", maxHeight: "initial" }); + const topOffset = parseFloat(window.getComputedStyle(styleMenuDropdownElement).getPropertyValue("padding-top")) + (styleMenuDropdownElement.offsetHeight - styleMenuDropdownElement.clientHeight) / 2; + styleMenuDropdownSubmenuElement.setCssStyles({ top: `${stylableAttributeElement.getBoundingClientRect().top - topOffset - popupMenuElement.getBoundingClientRect().top}px` }); + const leftPosition2 = styleMenuDropdownElement.getBoundingClientRect().right - popupMenuElement.getBoundingClientRect().left; + const rightPosition2 = popupMenuElement.getBoundingClientRect().right - styleMenuDropdownElement.getBoundingClientRect().left; + if (popupMenuElement.getBoundingClientRect().left + leftPosition2 < canvasWrapperCenterX) + styleMenuDropdownSubmenuElement.setCssStyles({ left: `${leftPosition2}px` }); + else styleMenuDropdownSubmenuElement.setCssStyles({ right: `${rightPosition2}px` }); + for (const styleOption of stylableAttribute.options) { + const styleMenuDropdownSubmenuOptionElement = this.createDropdownOptionElement({ + label: styleOption.label, + icon: styleOption.icon, + callback: () => { + setStyleAttribute(stylableAttribute, styleOption.value); + currentStyleAttributes[stylableAttribute.key] = styleOption.value; + selectedStyle = styleOption; + (0, import_obsidian2.setIcon)(iconElement, styleOption.icon); + styleMenuDropdownSubmenuElement.remove(); + } + }); + if (selectedStyle === styleOption) { + styleMenuDropdownSubmenuOptionElement.classList.add("mod-selected"); + const selectedIconElement = styleMenuDropdownSubmenuOptionElement.createDiv(); + selectedIconElement.classList.add("menu-item-icon"); + selectedIconElement.classList.add("mod-selected"); + (0, import_obsidian2.setIcon)(selectedIconElement, "check"); + } + styleMenuDropdownSubmenuGroupElement.appendChild(styleMenuDropdownSubmenuOptionElement); + } + }); + } + }); + } + static createDropdownOptionElement(menuOption) { + const menuDropdownOptionElement = activeWindow.createDiv(); + menuDropdownOptionElement.classList.add("menu-item"); + menuDropdownOptionElement.classList.add("tappable"); + const iconElement = menuDropdownOptionElement.createDiv(); + iconElement.classList.add("menu-item-icon"); + (0, import_obsidian2.setIcon)(iconElement, menuOption.icon); + const labelElement = menuDropdownOptionElement.createDiv(); + labelElement.classList.add("menu-item-title"); + labelElement.textContent = menuOption.label; + menuDropdownOptionElement.addEventListener("pointerenter", () => { + menuDropdownOptionElement.classList.add("selected"); + }); + menuDropdownOptionElement.addEventListener("pointerleave", () => { + menuDropdownOptionElement.classList.remove("selected"); + }); + menuDropdownOptionElement.addEventListener("click", () => { + var _a; + (_a = menuOption.callback) == null ? void 0 : _a.call(menuOption); + }); + return menuDropdownOptionElement; + } + static createDropdownSeparatorElement() { + const separatorElement = activeWindow.createDiv(); + separatorElement.classList.add("menu-separator"); + return separatorElement; + } + static alignToGrid(value, gridSize = this.GRID_SIZE) { + return Math.round(value / gridSize) * gridSize; + } + static getBestSideForFloatingEdge(sourcePos, target) { + const targetBBox = target.getBBox(); + const possibleSides = ["top", "right", "bottom", "left"]; + const possibleTargetPos = possibleSides.map((side) => [side, BBoxHelper.getCenterOfBBoxSide(targetBBox, side)]); + let bestSide = null; + let bestDistance = Infinity; + for (const [side, pos] of possibleTargetPos) { + const distance = Math.sqrt(Math.pow(sourcePos.x - pos.x, 2) + Math.pow(sourcePos.y - pos.y, 2)); + if (distance < bestDistance) { + bestDistance = distance; + bestSide = side; + } + } + return bestSide; + } + static selectEdgesForNodes(canvas, direction) { + const selection = canvas.getSelectionData(); + if (selection.nodes.length === 0) return; + const edges = /* @__PURE__ */ new Set(); + for (const nodeData of selection.nodes) { + const node = canvas.nodes.get(nodeData.id); + if (!node) continue; + for (const edge of canvas.getEdgesForNode(node)) { + switch (direction) { + case "connected": + edges.add(edge); + break; + case "incoming": + if (edge.to.node === node) edges.add(edge); + break; + case "outgoing": + if (edge.from.node === node) edges.add(edge); + break; + } + } + } + canvas.updateSelection(() => { + canvas.selection = edges; + }); + } +}; +_CanvasHelper.GRID_SIZE = 20; +_CanvasHelper.MAX_ALLOWED_ZOOM = 1; +var CanvasHelper = _CanvasHelper; + +// src/canvas-extensions/canvas-extension.ts +var CanvasExtension = class { + constructor(plugin) { + this.plugin = plugin; + const isEnabled = this.isEnabled(); + if (!(isEnabled === true || this.plugin.settings.getSetting(isEnabled))) + return; + this.init(); + } +}; + +// src/utils/svg-path-helper.ts +var SvgPathHelper = class { + static smoothenPathArray(positions, tension) { + let newPositions = [...positions]; + if (positions.length <= 2) return newPositions; + newPositions = [positions[0]]; + for (let i = 1; i < positions.length - 2; i++) { + const p1 = positions[i]; + const p2 = positions[i + 1]; + const p3 = positions[i + 2]; + const t1 = (1 - tension) / 2; + const t2 = 1 - t1; + const x = t2 * t2 * t2 * p1.x + 3 * t2 * t2 * t1 * p2.x + 3 * t2 * t1 * t1 * p3.x + t1 * t1 * t1 * p2.x; + const y = t2 * t2 * t2 * p1.y + 3 * t2 * t2 * t1 * p2.y + 3 * t2 * t1 * t1 * p3.y + t1 * t1 * t1 * p2.y; + newPositions.push({ x, y }); + } + const lastPoint = positions[positions.length - 1]; + newPositions.push(lastPoint); + return newPositions; + } + static pathArrayToSvgPath(positions) { + for (let i = 0; i < positions.length - 2; i++) { + const p1 = positions[i]; + const p2 = positions[i + 1]; + const p3 = positions[i + 2]; + const currentDirection = { + x: p2.x - p1.x, + y: p2.y - p1.y + }; + const nextDirection = { + x: p3.x - p2.x, + y: p3.y - p2.y + }; + if (currentDirection.x !== nextDirection.x && currentDirection.y !== nextDirection.y) continue; + positions.splice(i + 1, 1); + i--; + } + return positions.map( + (position, index) => `${index === 0 ? "M" : "L"} ${position.x} ${position.y}` + ).join(" "); + } + static pathArrayToRoundedSvgPath(pathArray, targetRadius) { + if (pathArray.length < 3) + return this.pathArrayToSvgPath(pathArray); + pathArray = pathArray.filter((position, index) => { + if (index === 0) return true; + const previous = pathArray[index - 1]; + return !(position.x === previous.x && position.y === previous.y); + }); + const commands = []; + commands.push(`M ${pathArray[0].x} ${pathArray[0].y}`); + for (let i = 1; i < pathArray.length - 1; i++) { + const previous = pathArray[i - 1]; + const current = pathArray[i]; + const next = pathArray[i + 1]; + const prevDelta = { x: current.x - previous.x, y: current.y - previous.y }; + const nextDelta = { x: next.x - current.x, y: next.y - current.y }; + const prevLen = Math.sqrt(prevDelta.x * prevDelta.x + prevDelta.y * prevDelta.y); + const nextLen = Math.sqrt(nextDelta.x * nextDelta.x + nextDelta.y * nextDelta.y); + const prevUnit = prevLen ? { x: prevDelta.x / prevLen, y: prevDelta.y / prevLen } : { x: 0, y: 0 }; + const nextUnit = nextLen ? { x: nextDelta.x / nextLen, y: nextDelta.y / nextLen } : { x: 0, y: 0 }; + let dot = prevUnit.x * nextUnit.x + prevUnit.y * nextUnit.y; + dot = Math.max(-1, Math.min(1, dot)); + const angle = Math.acos(dot); + if (angle < 0.01 || Math.abs(Math.PI - angle) < 0.01) { + commands.push(`L ${current.x} ${current.y}`); + continue; + } + const desiredOffset = targetRadius * Math.tan(angle / 2); + const d = Math.min(desiredOffset, prevLen / 2, nextLen / 2); + const effectiveRadius = d / Math.tan(angle / 2); + const firstAnchor = { + x: current.x - prevUnit.x * d, + y: current.y - prevUnit.y * d + }; + const secondAnchor = { + x: current.x + nextUnit.x * d, + y: current.y + nextUnit.y * d + }; + commands.push(`L ${firstAnchor.x} ${firstAnchor.y}`); + const cross = prevDelta.x * nextDelta.y - prevDelta.y * nextDelta.x; + const sweepFlag = cross < 0 ? 0 : 1; + commands.push(`A ${effectiveRadius} ${effectiveRadius} 0 0 ${sweepFlag} ${secondAnchor.x} ${secondAnchor.y}`); + } + const last = pathArray[pathArray.length - 1]; + commands.push(`L ${last.x} ${last.y}`); + return commands.join(" "); + } +}; + +// src/canvas-extensions/advanced-styles/edge-pathfinding-methods/edge-pathfinding-method.ts +var EdgePathfindingMethod = class { + constructor(plugin, canvas, fromNodeBBox, fromPos, fromBBoxSidePos, fromSide, toNodeBBox, toPos, toBBoxSidePos, toSide) { + this.plugin = plugin; + this.canvas = canvas; + this.fromNodeBBox = fromNodeBBox; + this.fromPos = fromPos; + this.fromBBoxSidePos = fromBBoxSidePos; + this.fromSide = fromSide; + this.toNodeBBox = toNodeBBox; + this.toPos = toPos; + this.toBBoxSidePos = toBBoxSidePos; + this.toSide = toSide; + } +}; + +// src/canvas-extensions/advanced-styles/edge-pathfinding-methods/pathfinding-a-star.ts +var MAX_MS_CALCULATION = 100; +var BASIC_DIRECTIONS = [ + { dx: 1, dy: 0 }, + { dx: -1, dy: 0 }, + { dx: 0, dy: 1 }, + { dx: 0, dy: -1 } +]; +var DIAGONAL_DIRECTIONS = [ + { dx: 1, dy: 1 }, + { dx: -1, dy: 1 }, + { dx: 1, dy: -1 }, + { dx: -1, dy: -1 } +]; +var DIAGONAL_COST = Math.sqrt(2); +var ROUND_PATH_RADIUS = 5; +var SMOOTHEN_PATH_TENSION = 0.2; +var Node = class { + constructor(x, y) { + this.x = x; + this.y = y; + this.gCost = 0; + this.hCost = 0; + this.fCost = 0; + this.parent = null; + } +}; +var MinHeap = class { + constructor() { + this.items = []; + } + get size() { + return this.items.length; + } + push(node) { + const items = this.items; + items.push(node); + let index = items.length - 1; + while (index > 0) { + const parentIndex = index - 1 >> 1; + if (items[parentIndex].fCost <= node.fCost) break; + items[index] = items[parentIndex]; + index = parentIndex; + } + items[index] = node; + } + pop() { + const items = this.items; + const top = items[0]; + if (top === void 0) return null; + const last = items.pop(); + if (items.length > 0) { + let index = 0; + while (true) { + const leftIndex = 2 * index + 1; + if (leftIndex >= items.length) break; + const rightIndex = leftIndex + 1; + let smallestIndex = leftIndex; + if (rightIndex < items.length && items[rightIndex].fCost < items[leftIndex].fCost) + smallestIndex = rightIndex; + if (items[smallestIndex].fCost >= last.fCost) break; + items[index] = items[smallestIndex]; + index = smallestIndex; + } + items[index] = last; + } + return top; + } +}; +var EdgePathfindingAStar = class extends EdgePathfindingMethod { + getPath() { + const nodeBBoxes = [...this.canvas.nodes.values()].filter((node) => { + const nodeData = node.getData(); + if (nodeData.portal === true) return false; + const nodeBBox = node.getBBox(); + const nodeContainsFromPos = BBoxHelper.insideBBox(this.fromPos, nodeBBox, true); + const nodeContainsToPos = BBoxHelper.insideBBox(this.toPos, nodeBBox, true); + return !nodeContainsFromPos && !nodeContainsToPos; + }).map((node) => node.getBBox()); + const fromPosWithMargin = BBoxHelper.moveInDirection(this.fromPos, this.fromSide, 10); + const toPosWithMargin = BBoxHelper.moveInDirection(this.toPos, this.toSide, 10); + const allowDiagonal = this.plugin.settings.getSetting("edgeStylePathfinderAllowDiagonal"); + const pathArray = this.aStarAlgorithm(fromPosWithMargin, toPosWithMargin, nodeBBoxes, CanvasHelper.GRID_SIZE / 2, allowDiagonal); + if (!pathArray) return null; + pathArray.splice(0, 0, this.fromPos); + pathArray.splice(pathArray.length, 0, this.toPos); + let svgPath; + const roundPath = this.plugin.settings.getSetting("edgeStylePathfinderPathRounded"); + if (roundPath) { + if (allowDiagonal) + svgPath = SvgPathHelper.pathArrayToSvgPath(SvgPathHelper.smoothenPathArray(pathArray, SMOOTHEN_PATH_TENSION)); + else + svgPath = SvgPathHelper.pathArrayToRoundedSvgPath(pathArray, ROUND_PATH_RADIUS); + } else svgPath = SvgPathHelper.pathArrayToSvgPath(pathArray); + return { + svgPath, + center: pathArray[Math.floor(pathArray.length / 2)], + rotateArrows: false + }; + } + aStarAlgorithm(fromPos, toPos, obstacles, gridResolution, allowDiagonal) { + const start = new Node( + Math.floor(fromPos.x / gridResolution) * gridResolution, + Math.floor(fromPos.y / gridResolution) * gridResolution + ); + if (this.fromSide === "right" && fromPos.x !== start.x) start.x += gridResolution; + if (this.fromSide === "bottom" && fromPos.y !== start.y) start.y += gridResolution; + const end = new Node( + Math.floor(toPos.x / gridResolution) * gridResolution, + Math.floor(toPos.y / gridResolution) * gridResolution + ); + if (this.toSide === "right" && toPos.x !== end.x) end.x += gridResolution; + if (this.toSide === "bottom" && toPos.y !== end.y) end.y += gridResolution; + if (this.isInsideObstacle(start, obstacles) || this.isInsideObstacle(end, obstacles)) return null; + const openSet = new MinHeap(); + openSet.push(start); + const closedSet = /* @__PURE__ */ new Set(); + const bestGCost = /* @__PURE__ */ new Map([[`${start.x},${start.y}`, 0]]); + const startTimestamp = performance.now(); + while (openSet.size > 0) { + if (performance.now() - startTimestamp > MAX_MS_CALCULATION) + return null; + const current = openSet.pop(); + const currentKey = `${current.x},${current.y}`; + if (closedSet.has(currentKey)) + continue; + closedSet.add(currentKey); + if (current.x === end.x && current.y === end.y) + return [fromPos, ...this.reconstructPath(current), toPos].map((node) => ({ x: node.x, y: node.y })); + if (!(current.x === start.x && current.y === start.y) && this.isTouchingObstacle(current, obstacles)) + continue; + for (const neighbor of this.getPossibleNeighbors(current, obstacles, gridResolution, allowDiagonal)) { + const neighborKey = `${neighbor.x},${neighbor.y}`; + if (closedSet.has(neighborKey)) + continue; + const tentativeGCost = current.gCost + (allowDiagonal ? this.getMovementCost({ + dx: neighbor.x - current.x, + dy: neighbor.y - current.y + }) : 1); + const previousGCost = bestGCost.get(neighborKey); + if (previousGCost === void 0 || tentativeGCost < previousGCost) { + neighbor.parent = current; + neighbor.gCost = tentativeGCost; + neighbor.hCost = this.heuristic(neighbor, end); + neighbor.fCost = neighbor.gCost + neighbor.hCost; + bestGCost.set(neighborKey, tentativeGCost); + openSet.push(neighbor); + } + } + } + return null; + } + // Manhattan distance + heuristic(node, end) { + return Math.abs(node.x - end.x) + Math.abs(node.y - end.y); + } + // Define a function to check if a position isn't inside any obstacle + isTouchingObstacle(node, obstacles) { + return obstacles.some((obstacle) => BBoxHelper.insideBBox(node, obstacle, true)); + } + isInsideObstacle(node, obstacles) { + return obstacles.some((obstacle) => BBoxHelper.insideBBox(node, obstacle, false)); + } + // Define a function to calculate movement cost based on direction + getMovementCost(direction) { + return direction.dx !== 0 && direction.dy !== 0 ? DIAGONAL_COST : 1; + } + getPossibleNeighbors(node, obstacles, gridResolution, allowDiagonal) { + const neighbors = []; + const availableDirections = allowDiagonal ? [...BASIC_DIRECTIONS, ...DIAGONAL_DIRECTIONS] : BASIC_DIRECTIONS; + for (const direction of availableDirections) { + const neighbor = new Node( + node.x + direction.dx * gridResolution, + node.y + direction.dy * gridResolution + ); + neighbor.gCost = node.gCost + this.getMovementCost(direction); + if (this.isInsideObstacle(neighbor, obstacles)) continue; + neighbors.push(neighbor); + } + return neighbors; + } + reconstructPath(node) { + const path = []; + while (node) { + path.push(node); + node = node.parent; + } + return path.reverse(); + } +}; + +// src/canvas-extensions/advanced-styles/edge-pathfinding-methods/pathfinding-direct.ts +var EdgePathfindingDirect = class extends EdgePathfindingMethod { + getPath() { + return { + svgPath: SvgPathHelper.pathArrayToSvgPath([this.fromPos, this.toPos]), + center: { + x: (this.fromPos.x + this.toPos.x) / 2, + y: (this.fromPos.y + this.toPos.y) / 2 + }, + rotateArrows: true + }; + } +}; + +// src/canvas-extensions/advanced-styles/edge-pathfinding-methods/pathfinding-square.ts +var ROUNDED_EDGE_RADIUS = 5; +var EdgePathfindingSquare = class extends EdgePathfindingMethod { + getPath() { + const pathArray = []; + let center = { + x: (this.fromPos.x + this.toPos.x) / 2, + y: (this.fromPos.y + this.toPos.y) / 2 + }; + const idealCenter = BBoxHelper.isHorizontal(this.fromSide) ? { + x: this.toBBoxSidePos.x, + y: this.fromBBoxSidePos.y + } : { + x: this.fromBBoxSidePos.x, + y: this.toBBoxSidePos.y + }; + const isPathCollidingAtFrom = this.fromSide === "top" && idealCenter.y > this.fromPos.y || this.fromSide === "bottom" && idealCenter.y < this.fromPos.y || this.fromSide === "left" && idealCenter.x > this.fromPos.x || this.fromSide === "right" && idealCenter.x < this.fromPos.x; + const isPathCollidingAtTo = this.toSide === "top" && idealCenter.y > this.toPos.y || this.toSide === "bottom" && idealCenter.y < this.toPos.y || this.toSide === "left" && idealCenter.x > this.toPos.x || this.toSide === "right" && idealCenter.x < this.toPos.x; + if (this.fromSide === this.toSide) { + const uPath = this.getUPath(this.fromPos, this.toPos, this.fromSide, this.toSide); + pathArray.push(...uPath.pathArray); + center = uPath.center; + } else if (BBoxHelper.isHorizontal(this.fromSide) === BBoxHelper.isHorizontal(this.toSide)) { + let zPath; + if (!isPathCollidingAtFrom || !isPathCollidingAtTo) { + zPath = this.getZPath(this.fromPos, this.toPos, this.fromSide, this.toSide); + pathArray.push(...zPath.pathArray); + } else { + const fromDirection = BBoxHelper.direction(this.fromSide); + const firstFromDetourPoint = BBoxHelper.isHorizontal(this.fromSide) ? { + x: CanvasHelper.alignToGrid(this.fromBBoxSidePos.x + fromDirection * CanvasHelper.GRID_SIZE), + y: this.fromBBoxSidePos.y + } : { + x: this.fromBBoxSidePos.x, + y: CanvasHelper.alignToGrid(this.fromBBoxSidePos.y + fromDirection * CanvasHelper.GRID_SIZE) + }; + const toDirection = BBoxHelper.direction(this.toSide); + const firstToDetourPoint = BBoxHelper.isHorizontal(this.toSide) ? { + x: CanvasHelper.alignToGrid(this.toBBoxSidePos.x + toDirection * CanvasHelper.GRID_SIZE), + y: this.toBBoxSidePos.y + } : { + x: this.toBBoxSidePos.x, + y: CanvasHelper.alignToGrid(this.toBBoxSidePos.y + toDirection * CanvasHelper.GRID_SIZE) + }; + const newFromSide = BBoxHelper.isHorizontal(this.fromSide) ? firstFromDetourPoint.y < this.fromPos.y ? "top" : "bottom" : firstFromDetourPoint.x < firstToDetourPoint.x ? "right" : "left"; + zPath = this.getZPath(firstFromDetourPoint, firstToDetourPoint, newFromSide, BBoxHelper.getOppositeSide(newFromSide)); + pathArray.push(this.fromPos); + pathArray.push(...zPath.pathArray); + pathArray.push(this.toPos); + } + center = zPath.center; + } else { + if (isPathCollidingAtFrom || isPathCollidingAtTo) { + if (isPathCollidingAtFrom && isPathCollidingAtTo) { + const direction = BBoxHelper.direction(this.fromSide); + let firstFromDetourPoint; + let secondFromDetourPoint; + if (BBoxHelper.isHorizontal(this.fromSide)) { + const combinedBBoxes = BBoxHelper.combineBBoxes([this.fromNodeBBox, this.toNodeBBox]); + firstFromDetourPoint = { + x: CanvasHelper.alignToGrid((direction > 0 ? combinedBBoxes.maxX : combinedBBoxes.minX) + direction * CanvasHelper.GRID_SIZE), + y: this.fromBBoxSidePos.y + }; + secondFromDetourPoint = { + x: firstFromDetourPoint.x, + y: BBoxHelper.getCenterOfBBoxSide(this.fromNodeBBox, this.toSide).y + }; + } else { + const combinedBBoxes = BBoxHelper.combineBBoxes([this.fromNodeBBox, this.toNodeBBox]); + firstFromDetourPoint = { + x: this.fromBBoxSidePos.x, + y: CanvasHelper.alignToGrid((direction > 0 ? combinedBBoxes.maxY : combinedBBoxes.minY) + direction * CanvasHelper.GRID_SIZE) + }; + secondFromDetourPoint = { + x: BBoxHelper.getCenterOfBBoxSide(this.fromNodeBBox, this.toSide).x, + y: firstFromDetourPoint.y + }; + } + const uPath = this.getUPath(secondFromDetourPoint, this.toPos, this.toSide, this.toSide); + pathArray.push(this.fromPos); + pathArray.push(firstFromDetourPoint); + pathArray.push(...uPath.pathArray); + center = pathArray[Math.floor(pathArray.length / 2)]; + } else { + if (isPathCollidingAtFrom) { + const direction = BBoxHelper.direction(this.fromSide); + const firstFromDetourPoint = BBoxHelper.isHorizontal(this.fromSide) ? { + x: CanvasHelper.alignToGrid(this.fromBBoxSidePos.x + direction * CanvasHelper.GRID_SIZE), + y: this.fromBBoxSidePos.y + } : { + x: this.fromBBoxSidePos.x, + y: CanvasHelper.alignToGrid(this.fromBBoxSidePos.y + direction * CanvasHelper.GRID_SIZE) + }; + const useUPath = BBoxHelper.isHorizontal(this.fromSide) ? this.toPos.y > BBoxHelper.getCenterOfBBoxSide(this.fromNodeBBox, BBoxHelper.getOppositeSide(this.toSide)).y === BBoxHelper.direction(this.toSide) > 0 : this.toPos.x > BBoxHelper.getCenterOfBBoxSide(this.fromNodeBBox, BBoxHelper.getOppositeSide(this.toSide)).x === BBoxHelper.direction(this.toSide) > 0; + const connectionSide = useUPath ? this.toSide : BBoxHelper.getOppositeSide(this.toSide); + const secondFromDetourPoint = BBoxHelper.isHorizontal(this.fromSide) ? { + x: firstFromDetourPoint.x, + y: BBoxHelper.getCenterOfBBoxSide(this.fromNodeBBox, connectionSide).y + } : { + x: BBoxHelper.getCenterOfBBoxSide(this.fromNodeBBox, connectionSide).x, + y: firstFromDetourPoint.y + }; + const path = useUPath ? this.getUPath(secondFromDetourPoint, this.toPos, this.toSide, this.toSide) : this.getZPath(secondFromDetourPoint, this.toPos, this.toSide, this.toSide); + pathArray.push(this.fromPos); + pathArray.push(firstFromDetourPoint); + pathArray.push(...path.pathArray); + center = path.center; + } + if (isPathCollidingAtTo) { + const direction = BBoxHelper.direction(this.toSide); + const firstToDetourPoint = BBoxHelper.isHorizontal(this.toSide) ? { + x: CanvasHelper.alignToGrid(this.toBBoxSidePos.x + direction * CanvasHelper.GRID_SIZE), + y: this.toBBoxSidePos.y + } : { + x: this.toBBoxSidePos.x, + y: CanvasHelper.alignToGrid(this.toBBoxSidePos.y + direction * CanvasHelper.GRID_SIZE) + }; + const useUPath = BBoxHelper.isHorizontal(this.toSide) ? this.fromPos.y > BBoxHelper.getCenterOfBBoxSide(this.toNodeBBox, BBoxHelper.getOppositeSide(this.fromSide)).y === BBoxHelper.direction(this.fromSide) > 0 : this.fromPos.x > BBoxHelper.getCenterOfBBoxSide(this.toNodeBBox, BBoxHelper.getOppositeSide(this.fromSide)).x === BBoxHelper.direction(this.fromSide) > 0; + const connectionSide = useUPath ? this.fromSide : BBoxHelper.getOppositeSide(this.fromSide); + const secondToDetourPoint = BBoxHelper.isHorizontal(this.toSide) ? { + x: firstToDetourPoint.x, + y: BBoxHelper.getCenterOfBBoxSide(this.toNodeBBox, connectionSide).y + } : { + x: BBoxHelper.getCenterOfBBoxSide(this.toNodeBBox, connectionSide).x, + y: firstToDetourPoint.y + }; + const path = useUPath ? this.getUPath(this.fromPos, secondToDetourPoint, this.fromSide, this.fromSide) : this.getZPath(this.fromPos, secondToDetourPoint, this.fromSide, this.fromSide); + pathArray.push(...path.pathArray); + pathArray.push(secondToDetourPoint); + pathArray.push(firstToDetourPoint); + pathArray.push(this.toPos); + center = path.center; + } + } + } else { + pathArray.push( + this.fromPos, + idealCenter, + this.toPos + ); + center = { + x: pathArray[1].x, + y: pathArray[1].y + }; + } + } + const svgPath = this.plugin.settings.getSetting("edgeStyleSquarePathRounded") ? SvgPathHelper.pathArrayToRoundedSvgPath(pathArray, ROUNDED_EDGE_RADIUS) : SvgPathHelper.pathArrayToSvgPath(pathArray); + return { svgPath, center, rotateArrows: false }; + } + getUPath(fromPos, toPos, fromSide, toSide) { + const direction = BBoxHelper.direction(fromSide); + if (BBoxHelper.isHorizontal(fromSide)) { + const xExtremum = direction > 0 ? Math.max(fromPos.x, toPos.x) : Math.min(fromPos.x, toPos.x); + const x = CanvasHelper.alignToGrid(xExtremum + direction * CanvasHelper.GRID_SIZE); + return { + pathArray: [ + fromPos, + { x, y: fromPos.y }, + { x, y: toPos.y }, + toPos + ], + center: { + x, + y: (fromPos.y + toPos.y) / 2 + } + }; + } else { + const yExtremum = direction > 0 ? Math.max(fromPos.y, toPos.y) : Math.min(fromPos.y, toPos.y); + const y = CanvasHelper.alignToGrid(yExtremum + direction * CanvasHelper.GRID_SIZE); + return { + pathArray: [ + fromPos, + { x: fromPos.x, y }, + { x: toPos.x, y }, + toPos + ], + center: { + x: (fromPos.x + toPos.x) / 2, + y + } + }; + } + } + getZPath(fromPos, toPos, fromSide, toSide) { + if (BBoxHelper.isHorizontal(fromSide)) { + const midX = fromPos.x + (toPos.x - fromPos.x) / 2; + return { + pathArray: [ + fromPos, + { x: midX, y: fromPos.y }, + { x: midX, y: toPos.y }, + toPos + ], + center: { + x: midX, + y: (fromPos.y + toPos.y) / 2 + } + }; + } else { + const midY = fromPos.y + (toPos.y - fromPos.y) / 2; + return { + pathArray: [ + fromPos, + { x: fromPos.x, y: midY }, + { x: toPos.x, y: midY }, + toPos + ], + center: { + x: (fromPos.x + toPos.x) / 2, + y: midY + } + }; + } + } +}; + +// src/utils/text-helper.ts +var TextHelper = class { + static toCamelCase(str) { + return str.replace(/-./g, (x) => x[1].toUpperCase()); + } + static toTitleCase(str) { + return str.toLowerCase().split(" ").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" "); + } +}; + +// src/canvas-extensions/advanced-styles/style-config.ts +function styleAttributeValidator(json) { + var _a; + const hasKey = json.key !== void 0; + const hasLabel = json.label !== void 0; + const hasOptions = Array.isArray(json.options); + if (!hasKey) console.error('Style attribute is missing the "key" property'); + if (!hasLabel) console.error('Style attribute is missing the "label" property'); + if (!hasOptions) console.error('Style attribute is missing the "options" property or it is not an array'); + json.key = TextHelper.toCamelCase(json.key); + let optionsValid = true; + let hasDefault = false; + for (const option of json.options) { + const hasIcon = option.icon !== void 0; + const hasLabel2 = option.label !== void 0; + const hasValue = option.value !== void 0; + if (!hasIcon) console.error(`Style attribute option (${String((_a = option.value) != null ? _a : option.label)}) is missing the "icon" property`); + if (!hasLabel2) console.error(`Style attribute option (${String(option.value)}) is missing the "label" property`); + if (!hasValue) console.error(`Style attribute option (${String(option.label)}) is missing the "value" property`); + if (!hasIcon || !hasLabel2 || !hasValue) optionsValid = false; + if (option.value === null) hasDefault = true; + } + if (!hasDefault) console.error('Style attribute is missing a default option (option with a "value" of null)'); + const isValid = hasKey && hasLabel && hasOptions && optionsValid && hasDefault; + return isValid ? json : null; +} +var BUILTIN_NODE_STYLE_ATTRIBUTES = [ + { + key: "textAlign", + label: "Text Alignment", + nodeTypes: ["text"], + options: [ + { + icon: "align-left", + label: "Left", + value: null + }, + { + icon: "align-center", + label: "Center", + value: "center" + }, + { + icon: "align-right", + label: "Right", + value: "right" + } + ] + }, + { + key: "shape", + label: "Shape", + nodeTypes: ["text"], + options: [ + { + icon: "rectangle-horizontal", + label: "Round Rectangle", + value: null + }, + { + icon: "shape-pill", + label: "Pill", + value: "pill" + }, + { + icon: "diamond", + label: "Diamond", + value: "diamond" + }, + { + icon: "shape-parallelogram", + label: "Parallelogram", + value: "parallelogram" + }, + { + icon: "circle", + label: "Circle", + value: "circle" + }, + { + icon: "shape-predefined-process", + label: "Predefined Process", + value: "predefined-process" + }, + { + icon: "shape-document", + label: "Document", + value: "document" + }, + { + icon: "shape-database", + label: "Database", + value: "database" + } + ] + }, + { + key: "border", + label: "Border", + options: [ + { + icon: "border-solid", + label: "Solid", + value: null + }, + { + icon: "border-dashed", + label: "Dashed", + value: "dashed" + }, + { + icon: "border-dotted", + label: "Dotted", + value: "dotted" + }, + { + icon: "eye-off", + label: "Invisible", + value: "invisible" + } + ] + } +]; +var BUILTIN_EDGE_STYLE_ATTRIBUTES = [ + { + key: "path", + label: "Path Style", + options: [ + { + icon: "path-solid", + label: "Solid", + value: null + }, + { + icon: "path-dotted", + label: "Dotted", + value: "dotted" + }, + { + icon: "path-short-dashed", + label: "Short Dashed", + value: "short-dashed" + }, + { + icon: "path-long-dashed", + label: "Long Dashed", + value: "long-dashed" + } + ] + }, + { + key: "arrow", + label: "Arrow Style", + options: [ + { + icon: "arrow-triangle", + label: "Triangle", + value: null + }, + { + icon: "arrow-triangle-outline", + label: "Triangle Outline", + value: "triangle-outline" + }, + { + icon: "arrow-thin-triangle", + label: "Thin Triangle", + value: "thin-triangle" + }, + { + icon: "arrow-halved-triangle", + label: "Halved Triangle", + value: "halved-triangle" + }, + { + icon: "arrow-diamond", + label: "Diamond", + value: "diamond" + }, + { + icon: "arrow-diamond-outline", + label: "Diamond Outline", + value: "diamond-outline" + }, + { + icon: "arrow-circle", + label: "Circle", + value: "circle" + }, + { + icon: "arrow-circle-outline", + label: "Circle Outline", + value: "circle-outline" + }, + { + icon: "tally-1", + label: "Blunt", + value: "blunt" + } + ] + }, + { + key: "pathfindingMethod", + label: "Pathfinding Method", + options: [ + { + icon: "pathfinding-method-bezier", + label: "Bezier", + value: null + }, + { + icon: "slash", + label: "Direct", + value: "direct" + }, + { + icon: "pathfinding-method-square", + label: "Square", + value: "square" + }, + { + icon: "map", + label: "A*", + value: "a-star" + } + ] + } +]; + +// src/managers/css-styles-config-manager.ts +var import_obsidian3 = require("obsidian"); +var CssStylesConfigManager = class { + constructor(plugin, trigger, validate) { + this.plugin = plugin; + this.validate = validate; + this.cachedConfig = null; + this.configRegex = new RegExp(`\\/\\*\\s*@${trigger}\\s*\\n([\\s\\S]*?)\\*\\/`, "g"); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "css-change", + () => { + this.cachedConfig = null; + } + )); + } + getStyles() { + if (this.cachedConfig) return this.cachedConfig; + this.cachedConfig = []; + const styleSheets = activeDocument.styleSheets; + for (let i = 0; i < styleSheets.length; i++) { + const sheet = styleSheets.item(i); + if (!sheet) continue; + const styleSheetConfigs = this.parseStyleConfigsFromCSS(sheet); + for (const config of styleSheetConfigs) { + const validConfig = this.validate(config); + if (!validConfig) continue; + this.cachedConfig.push(validConfig); + } + } + return this.cachedConfig; + } + parseStyleConfigsFromCSS(sheet) { + var _a, _b; + const textContent = (_b = (_a = sheet == null ? void 0 : sheet.ownerNode) == null ? void 0 : _a.textContent) == null ? void 0 : _b.trim(); + if (!textContent) return []; + const configs = []; + const matches = textContent.matchAll(this.configRegex); + for (const match of matches) { + const yamlString = match[1]; + if (!yamlString) continue; + let configYaml; + try { + configYaml = (0, import_obsidian3.parseYaml)(yamlString); + } catch (e) { + continue; + } + configs.push(configYaml); + } + return configs; + } +}; + +// src/canvas-extensions/advanced-styles/edge-styles.ts +var GET_EDGE_CSS_STYLES_MANAGER = (plugin) => new CssStylesConfigManager(plugin, "advanced-canvas-edge-style", styleAttributeValidator); +var EDGE_PATHFINDING_METHODS = { + "direct": EdgePathfindingDirect, + "square": EdgePathfindingSquare, + "a-star": EdgePathfindingAStar +}; +var MAX_LIVE_UPDATE_SELECTION_SIZE = 5; +var EdgeStylesExtension = class extends CanvasExtension { + isEnabled() { + return "edgesStylingFeatureEnabled"; + } + init() { + this.cssStylesManager = GET_EDGE_CSS_STYLES_MANAGER(this.plugin); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:popup-menu-created", + (canvas) => this.onPopupMenuCreated(canvas) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:edge-changed", + (canvas, edge) => this.onEdgeChanged(canvas, edge) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:edge-center-requested", + (canvas, edge, center) => this.onEdgeCenterRequested(canvas, edge, center) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-added", + (canvas, node) => { + if (canvas.dirty.size > 1 && !canvas.isPasting) return; + this.updateAllEdgesInArea(canvas, node.getBBox()); + } + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-moved", + // Only update edges this way if a node got moved with the arrow keys + (canvas, node, keyboard) => node.initialized && keyboard ? this.updateAllEdgesInArea(canvas, node.getBBox()) : void 0 + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-removed", + (canvas, node) => this.updateAllEdgesInArea(canvas, node.getBBox()) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:dragging-state-changed", + (canvas, isDragging) => { + if (isDragging) return; + const selectedNodes = canvas.getSelectionData().nodes.map((nodeData) => canvas.nodes.get(nodeData.id)).filter((node) => node !== void 0); + const selectedNodeBBoxes = selectedNodes.map((node) => node.getBBox()); + const selectedNodeBBox = BBoxHelper.combineBBoxes(selectedNodeBBoxes); + this.updateAllEdgesInArea(canvas, selectedNodeBBox); + } + )); + } + // Skip if isDragging and setting isn't enabled and not connecting an edge + shouldUpdateEdge(canvas) { + return !canvas.isDragging || this.plugin.settings.getSetting("edgeStyleUpdateWhileDragging") || canvas.canvasEl.hasClass("is-connecting"); + } + onPopupMenuCreated(canvas) { + var _a; + const selectedEdges = [...canvas.selection].filter((item) => item.path !== void 0); + if (canvas.readonly || selectedEdges.length === 0 || selectedEdges.length !== canvas.selection.size) + return; + CanvasHelper.addStyleAttributesToPopup( + this.plugin, + canvas, + [ + ...BUILTIN_EDGE_STYLE_ATTRIBUTES, + /* Legacy */ + ...this.plugin.settings.getSetting("customEdgeStyleAttributes"), + ...this.cssStylesManager.getStyles() + ], + (_a = selectedEdges[0].getData().styleAttributes) != null ? _a : {}, + (attribute, value) => this.setStyleAttributeForSelection(canvas, attribute, value) + ); + } + setStyleAttributeForSelection(canvas, attribute, value) { + const selectedEdges = [...canvas.selection].filter((item) => item.path !== void 0); + for (const edge of selectedEdges) { + const edgeData = edge.getData(); + edge.setData({ + ...edgeData, + styleAttributes: { + ...edgeData.styleAttributes, + [attribute.key]: value + } + }); + } + canvas.pushHistory(canvas.getData()); + } + updateAllEdgesInArea(canvas, bbox) { + if (!this.shouldUpdateEdge(canvas)) return; + for (const edge of canvas.edges.values()) { + if (!BBoxHelper.isColliding(edge.getBBox(), bbox)) continue; + canvas.markDirty(edge); + } + } + onEdgeChanged(canvas, edge) { + var _a, _b, _c, _d, _e, _f, _g; + if (!canvas.dirty.has(edge) && !canvas.selection.has(edge)) return; + if (!this.shouldUpdateEdge(canvas)) { + const tooManySelected = canvas.selection.size > MAX_LIVE_UPDATE_SELECTION_SIZE; + if (tooManySelected) return; + const groupNodesSelected = [...canvas.selection].some((item) => { + var _a2; + return ((_a2 = item.getData()) == null ? void 0 : _a2.type) === "group"; + }); + if (groupNodesSelected) return; + } + const edgeData = edge.getData(); + if (!edge.bezier) return; + edge.center = void 0; + edge.updatePath(); + const pathfindingMethod = (_a = edgeData.styleAttributes) == null ? void 0 : _a.pathfindingMethod; + if (pathfindingMethod && pathfindingMethod in EDGE_PATHFINDING_METHODS) { + const fromNodeBBox = edge.from.node.getBBox(); + const fromBBoxSidePos = BBoxHelper.getCenterOfBBoxSide(fromNodeBBox, edge.from.side); + const fromPos = edge.from.end === "none" ? fromBBoxSidePos : edge.bezier.from; + const toNodeBBox = edge.to.node.getBBox(); + const toBBoxSidePos = BBoxHelper.getCenterOfBBoxSide(toNodeBBox, edge.to.side); + const toPos = edge.to.end === "none" ? toBBoxSidePos : edge.bezier.to; + const PathfindingConstructor = EDGE_PATHFINDING_METHODS[pathfindingMethod]; + const path = new PathfindingConstructor( + this.plugin, + canvas, + fromNodeBBox, + fromPos, + fromBBoxSidePos, + edge.from.side, + toNodeBBox, + toPos, + toBBoxSidePos, + edge.to.side + ).getPath(); + if (!path) return; + edge.center = path.center; + edge.path.interaction.setAttr("d", path == null ? void 0 : path.svgPath); + edge.path.display.setAttr("d", path == null ? void 0 : path.svgPath); + } + (_b = edge.labelElement) == null ? void 0 : _b.render(); + const arrowPolygonPoints = this.getArrowPolygonPoints((_c = edgeData.styleAttributes) == null ? void 0 : _c.arrow); + if ((_d = edge.fromLineEnd) == null ? void 0 : _d.el) (_e = edge.fromLineEnd.el.querySelector("polygon")) == null ? void 0 : _e.setAttribute("points", arrowPolygonPoints); + if ((_f = edge.toLineEnd) == null ? void 0 : _f.el) (_g = edge.toLineEnd.el.querySelector("polygon")) == null ? void 0 : _g.setAttribute("points", arrowPolygonPoints); + } + onEdgeCenterRequested(_canvas, edge, center) { + var _a, _b, _c, _d; + center.x = (_b = (_a = edge.center) == null ? void 0 : _a.x) != null ? _b : center.x; + center.y = (_d = (_c = edge.center) == null ? void 0 : _c.y) != null ? _d : center.y; + } + getArrowPolygonPoints(arrowStyle) { + if (arrowStyle === "halved-triangle") + return `-2,0 7.5,12 -2,12`; + else if (arrowStyle === "thin-triangle") + return `0,0 7,10 0,0 0,10 0,0 -7,10`; + else if (arrowStyle === "diamond" || arrowStyle === "diamond-outline") + return `0,0 5,10 0,20 -5,10`; + else if (arrowStyle === "circle" || arrowStyle === "circle-outline") + return `0 0, 4.95 1.8, 7.5 6.45, 6.6 11.7, 2.7 15, -2.7 15, -6.6 11.7, -7.5 6.45, -4.95 1.8`; + else if (arrowStyle === "blunt") + return `-10,8 10,8 10,6 -10,6`; + else + return `0,0 6.5,10.4 -6.5,10.4`; + } +}; + +// src/canvas-extensions/advanced-styles/node-styles.ts +var GET_NODE_CSS_STYLES_MANAGER = (plugin) => new CssStylesConfigManager(plugin, "advanced-canvas-node-style", styleAttributeValidator); +var NodeStylesExtension = class extends CanvasExtension { + isEnabled() { + return "nodeStylingFeatureEnabled"; + } + init() { + this.cssStylesManager = GET_NODE_CSS_STYLES_MANAGER(this.plugin); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:popup-menu-created", + (canvas) => this.onPopupMenuCreated(canvas) + )); + } + onPopupMenuCreated(canvas) { + var _a; + const selectionNodeData = canvas.getSelectionData().nodes; + if (canvas.readonly || selectionNodeData.length === 0 || selectionNodeData.length !== canvas.selection.size) + return; + const selectedNodeTypes = new Set(selectionNodeData.map((node) => node.type)); + const availableNodeStyles = [ + ...BUILTIN_NODE_STYLE_ATTRIBUTES, + /* Legacy */ + ...this.plugin.settings.getSetting("customNodeStyleAttributes"), + ...this.cssStylesManager.getStyles() + ].filter((style) => !style.nodeTypes || style.nodeTypes.some((type) => selectedNodeTypes.has(type))); + CanvasHelper.addStyleAttributesToPopup( + this.plugin, + canvas, + availableNodeStyles, + (_a = selectionNodeData[0].styleAttributes) != null ? _a : {}, + (attribute, value) => this.setStyleAttributeForSelection(canvas, attribute, value) + ); + } + setStyleAttributeForSelection(canvas, attribute, value) { + const selectionNodeData = canvas.getSelectionData().nodes; + for (const nodeData of selectionNodeData) { + const node = canvas.nodes.get(nodeData.id); + if (!node) continue; + if (attribute.nodeTypes && !attribute.nodeTypes.includes(nodeData.type)) continue; + node.setData({ + ...nodeData, + styleAttributes: { + ...nodeData.styleAttributes, + [attribute.key]: value + } + }); + } + canvas.pushHistory(canvas.getData()); + } +}; + +// src/canvas-extensions/variable-breakpoint-canvas-extension.ts +var VARIABLE_BREAKPOINT_CSS_VAR = "--variable-breakpoint"; +var VariableBreakpointCanvasExtension = class extends CanvasExtension { + isEnabled() { + return "variableBreakpointFeatureEnabled"; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-breakpoint-changed", + (canvas, node, breakpointRef) => this.onNodeBreakpointChanged(canvas, node, breakpointRef) + )); + } + onNodeBreakpointChanged(canvas, node, breakpointRef) { + if (!node.initialized) return; + if (node.breakpoint === void 0) { + const computedStyle = window.getComputedStyle(node.nodeEl); + const variableBreakpointString = computedStyle.getPropertyValue(VARIABLE_BREAKPOINT_CSS_VAR); + let numberBreakpoint; + if (variableBreakpointString.length > 0 && !isNaN(numberBreakpoint = parseFloat(variableBreakpointString))) + node.breakpoint = numberBreakpoint; + else node.breakpoint = null; + } + if (node.breakpoint === null) return; + breakpointRef.value = canvas.zoom > node.breakpoint; + } +}; + +// src/settings.ts +var README_URL = "https://github.com/Developer-Mike/obsidian-advanced-canvas?tab=readme-ov-file"; +var KOFI_PAGE_URL = "https://ko-fi.com/X8X27IA08"; +var DEFAULT_SETTINGS_VALUES = { + nodeTypeOnDoubleClick: "text", + alignNewNodesToGrid: true, + defaultTextNodeDimensions: [260, 60], + defaultFileNodeDimensions: [400, 400], + minNodeSize: 60, + maxNodeWidth: -1, + disableFontSizeRelativeToZoom: false, + canvasMetadataCompatibilityEnabled: true, + enableSingleNodeLinks: true, + enableSingleNodePopupReferenceCopy: false, + combineCustomStylesInDropdown: false, + nodeStylingFeatureEnabled: true, + customNodeStyleAttributes: [], + defaultTextNodeColor: 0, + defaultTextNodeStyleAttributes: {}, + nodeTemplates: [], + edgesStylingFeatureEnabled: true, + customEdgeStyleAttributes: [], + inheritEdgeColorFromNode: false, + defaultEdgeColor: 0, + defaultEdgeLineDirection: "unidirectional", + defaultEdgeStyleAttributes: {}, + edgeStyleUpdateWhileDragging: false, + edgeStyleSquarePathRounded: true, + edgeStylePathfinderAllowDiagonal: false, + edgeStylePathfinderPathRounded: true, + variableBreakpointFeatureEnabled: false, + zOrderingControlFeatureEnabled: false, + zOrderingControlShowOneLayerShiftOptions: false, + aspectRatioControlFeatureEnabled: false, + commandsFeatureEnabled: true, + zoomToClonedNode: true, + cloneNodeMargin: 20, + expandNodeStepSize: 20, + nativeFileSearchEnabled: true, + floatingEdgeFeatureEnabled: true, + allowFloatingEdgeCreation: false, + newEdgeFromSideFloating: false, + flipEdgeFeatureEnabled: true, + betterExportFeatureEnabled: true, + betterReadonlyEnabled: false, + hideBackgroundGridWhenInReadonly: true, + disableNodePopup: false, + disableZoom: false, + disablePan: false, + readingModeFixEnabled: false, + autoResizeNodeFeatureEnabled: false, + autoResizeNodeEnabledByDefault: false, + autoResizeNodeMaxHeight: -1, + autoResizeNodeSnapToGrid: true, + collapsibleGroupsFeatureEnabled: true, + collapsedGroupPreviewOnDrag: true, + focusModeFeatureEnabled: false, + presentationFeatureEnabled: true, + showSetStartNodeInPopup: false, + defaultSlideDimensions: [1200, 675], + wrapInSlidePadding: 20, + resetViewportOnPresentationEnd: true, + useArrowKeysToChangeSlides: true, + usePgUpPgDownKeysToChangeSlides: true, + useDirectionalSlideNavigation: false, + zoomToSlideWithoutPadding: true, + useUnclampedZoomWhilePresenting: false, + fullscreenPresentationEnabled: true, + slideTransitionAnimationDuration: 0.5, + slideTransitionAnimationIntensity: 1.25, + pdfAnnotationFeatureEnabled: false, + pdfPagesGap: 60, + pdfPageSizeFactor: 1.5, + pdfPageResolution: 1.5, + canvasEncapsulationEnabled: false, + portalsFeatureEnabled: true, + autoFileNodeEdgesFeatureEnabled: false, + autoFileNodeEdgesFrontmatterKey: "canvas-edges", + edgeHighlightEnabled: false, + highlightIncomingEdges: false, + edgeSelectionEnabled: false, + selectEdgeByDirection: false +}; +var SettingsManager = class { + constructor(plugin) { + this.plugin = plugin; + this.nodeCssStylesManager = GET_NODE_CSS_STYLES_MANAGER(plugin); + this.edgeCssStylesManager = GET_EDGE_CSS_STYLES_MANAGER(plugin); + } + async loadSettings() { + this.settings = Object.assign({}, DEFAULT_SETTINGS_VALUES, await this.plugin.loadData()); + this.plugin.app.workspace.trigger("advanced-canvas:settings-changed"); + } + async saveSettings() { + await this.plugin.saveData(this.settings); + } + getSetting(key) { + return this.settings[key]; + } + async setSetting(data) { + this.settings = Object.assign(this.settings, data); + await this.saveSettings(); + this.plugin.app.workspace.trigger("advanced-canvas:settings-changed"); + } + addSettingsTab() { + this.settingsTab = new AdvancedCanvasPluginSettingTab(this.plugin, this); + this.plugin.addSettingTab(this.settingsTab); + } +}; +var AdvancedCanvasPluginSettingTab = class extends import_obsidian4.PluginSettingTab { + constructor(plugin, settingsManager) { + super(plugin.app, plugin); + this.settingsManager = settingsManager; + } + getKeyIndexFromSettingKey(settingKey) { + const match = settingKey.match(/^(.*)\[(.+)\]$/); + if (match) return { + key: match[1], + index: isNaN(Number(match[2])) ? match[2] : Number(match[2]) + }; + return { key: settingKey, index: null }; + } + getControlValue(settingKey) { + const { key, index } = this.getKeyIndexFromSettingKey(settingKey); + const value = this.settingsManager.getSetting(key); + if (typeof index === "number" && Array.isArray(value)) + return value[index]; + if (typeof index === "string") + return value[index]; + return value; + } + async setControlValue(settingKey, value) { + const { key, index } = this.getKeyIndexFromSettingKey(settingKey); + if (index !== null) { + const current = this.settingsManager.getSetting(key); + if (typeof index === "number" && Array.isArray(current)) { + current[index] = value; + return await this.settingsManager.setSetting({ [key]: current }); + } else if (typeof index === "string") { + if (value === "") delete current[index]; + else current[index] = value; + return await this.settingsManager.setSetting({ [key]: current }); + } + } + await this.settingsManager.setSetting({ [key]: value }); + } + getDocumentationButton(section, label) { + return { + name: label ? `Open ${label} documentation` : "Open documentation", + action: () => window.open(`${README_URL}#${section}`, "_blank") + }; + } + getSettingDefinitions() { + return [ + // Ko-fi banner + { + type: "group", + items: [ + { + name: "Support me on Ko-fi", + desc: "If you like this plugin, consider supporting its development <3", + action: () => window.open(KOFI_PAGE_URL, "_blank") + } + ] + }, + // General settings + { + name: "Node type on double click", + desc: "The type of node that will be created when double clicking on the canvas.", + control: { + type: "dropdown", + key: "nodeTypeOnDoubleClick", + options: { + "text": "Text", + "file": "File" + } + } + }, + { + name: "Always align new nodes to grid", + desc: "Aligns new nodes to the grid.", + control: { + type: "toggle", + key: "alignNewNodesToGrid" + } + }, + { + type: "page", + name: "Text node dimensions", + desc: "The default dimensions of a text node.", + items: [ + { + name: "Width", + desc: "The default width of a text node.", + control: { + type: "number", + key: "defaultTextNodeDimensions[0]" + } + }, + { + name: "Height", + desc: "The default height of a text node.", + control: { + type: "number", + key: "defaultTextNodeDimensions[1]" + } + } + ] + }, + { + type: "page", + name: "File node dimensions", + desc: "The default dimensions of a file node.", + items: [ + { + name: "Width", + desc: "The default width of a file node.", + control: { + type: "number", + key: "defaultFileNodeDimensions[0]" + } + }, + { + name: "Height", + desc: "The default height of a file node.", + control: { + type: "number", + key: "defaultFileNodeDimensions[1]" + } + } + ] + }, + { + type: "page", + name: "Node size limits", + desc: "The minimum and maximum size of a node.", + items: [ + { + name: "Minimum node width/height", + desc: "The minimum size of a node.", + control: { + type: "number", + key: "minNodeSize" + } + }, + { + name: "Maximum node width", + desc: "The maximum width of a node. Set to -1 for no limit.", + control: { + type: "number", + key: "maxNodeWidth" + } + } + ] + }, + { + name: "Disable font size relative to zoom", + desc: "The font size of group node titles and edge labels will not increase when zooming out.", + control: { + type: "toggle", + key: "disableFontSizeRelativeToZoom" + } + }, + // Extended commands + { + type: "group", + heading: "Extended commands", + items: [ + { + name: "Show commands in command palette", + desc: "Features a bunch of commands that can be used to manipulate the canvas and its content.", + control: { + type: "toggle", + key: "commandsFeatureEnabled" + } + }, + { + type: "page", + name: `Extended commands configuration`, + visible: () => this.getControlValue("commandsFeatureEnabled"), + items: [ + { + name: "Zoom to cloned node", + desc: "Zooms to the cloned node after creation.", + control: { + type: "toggle", + key: "zoomToClonedNode" + } + }, + { + name: "Clone node margin", + desc: "The margin between the cloned node and the source node.", + control: { + type: "number", + key: "cloneNodeMargin" + } + }, + { + name: "Expand node step size", + desc: "The step size for expanding the node.", + control: { + type: "number", + key: "expandNodeStepSize" + } + } + ] + }, + this.getDocumentationButton("canvas-commands") + ] + }, + // Metadata compatibility + { + type: "group", + heading: "Metadata compatibility", + items: [ + { + name: "Enable canvas metadata compatibility", + desc: "Makes .canvas files compatible with the backlinks and outgoing links feature and show the connections in the graph view.", + control: { + type: "toggle", + key: "canvasMetadataCompatibilityEnabled" + } + }, + { + type: "page", + name: "Canvas metadata compatibility settings", + visible: () => this.getControlValue("canvasMetadataCompatibilityEnabled"), + items: [ + { + name: "Support linking to a node using a [[wikilink]]", + desc: 'Link and embed a node using [[canvas-file#node-id]]. (Use the "Copy wikilink to node" command to get an id.)', + control: { + type: "toggle", + key: "enableSingleNodeLinks" + } + }, + { + name: "Show button to copy node [[wikilink]]", + desc: "Shows a button in the node popup to copy the [[wikilink]] of the node for easy reference in other notes.", + control: { + type: "toggle", + key: "enableSingleNodePopupReferenceCopy" + } + } + ] + }, + this.getDocumentationButton("canvas-metadata-compatibility") + ] + }, + // Native-like file search + { + type: "group", + heading: "Native-like file search", + items: [ + { + name: "Enable native-like file search", + desc: "Quickly locate text within your canvas using the native Obsidian search interface.", + control: { + type: "toggle", + key: "nativeFileSearchEnabled" + } + }, + this.getDocumentationButton("native-like-file-search") + ] + }, + // Auto file node edges + { + type: "group", + heading: "Auto file node edges", + items: [ + { + name: "Enable auto file node edges", + desc: "Automatically create edges between file nodes based on their frontmatter links.", + control: { + type: "toggle", + key: "autoFileNodeEdgesFeatureEnabled" + } + }, + { + type: "page", + name: "Auto file node edges settings", + visible: () => this.getControlValue("autoFileNodeEdgesFeatureEnabled"), + items: [ + { + name: "Frontmatter key name", + desc: "The frontmatter key to fetch the outgoing edges from. (Keep the default to ensure best compatibility.)", + control: { + type: "text", + key: "autoFileNodeEdgesFrontmatterKey" + } + } + ] + }, + this.getDocumentationButton("auto-file-node-edges") + ] + }, + // Portals + { + type: "group", + heading: "Portals", + items: [ + { + name: "Enable portals", + desc: "Create portals to other canvases.", + control: { + type: "toggle", + key: "portalsFeatureEnabled" + } + }, + this.getDocumentationButton("portals") + ] + }, + // Collapsible groups + { + type: "group", + heading: "Collapsible groups", + items: [ + { + name: "Enable collapsible groups", + desc: "Group nodes can be collapsed and expanded to keep the canvas organized.", + control: { + type: "toggle", + key: "collapsibleGroupsFeatureEnabled" + } + }, + { + type: "page", + name: "Collapsible groups settings", + visible: () => this.getControlValue("collapsibleGroupsFeatureEnabled"), + items: [ + { + name: "Collapsed group preview on drag", + desc: "Shows the border of a collapsed group while dragging a node.", + control: { + type: "toggle", + key: "collapsedGroupPreviewOnDrag" + } + } + ] + }, + this.getDocumentationButton("collapsible-groups") + ] + }, + // Node/Edge styles + { + type: "group", + heading: "Node/Edge styles", + items: [ + { + name: "Combine new style settings in dropdown", + desc: "Combine all style attributes of Advanced Canvas in a single dropdown.", + control: { + type: "toggle", + key: "combineCustomStylesInDropdown" + } + }, + this.getDocumentationButton("custom-styles", "custom styles"), + { + name: "Enable node styling", + desc: "Allows you to style nodes without limits.", + control: { + type: "toggle", + key: "nodeStylingFeatureEnabled" + } + }, + { + type: "page", + name: "Node styles", + desc: "Manage custom node styles.", + visible: () => this.getControlValue("nodeStylingFeatureEnabled"), + items: [ + { + name: "Default text node color", + desc: "The default color of a text node. The default range is from 0 to 6, where 0 is no color. The range can be extended by using the Custom Colors feature of Advanced Canvas.", + control: { + type: "number", + key: "defaultTextNodeColor" + } + } + ] + }, + { + type: "page", + name: "Default node style", + desc: "The default style of a node. The default style is applied to all newly created nodes.", + items: [ + ...BUILTIN_NODE_STYLE_ATTRIBUTES, + // BUILTINS + ...this.settingsManager.nodeCssStylesManager.getStyles(), + // CUSTOM CSS STYLES + ...this.settingsManager.getSetting("customNodeStyleAttributes") + // LEGACY CUSTOM STYLES + ].map((value) => { + var _a, _b; + return { + name: value.label, + control: { + type: "dropdown", + key: `defaultTextNodeStyleAttributes[${value.key}]`, + defaultValue: (_b = (_a = value.options.find((option) => option.value === null)) == null ? void 0 : _a.value) != null ? _b : "", + options: value.options.reduce((acc, option) => { + var _a2; + acc[(_a2 = option.value) != null ? _a2 : ""] = option.label; + return acc; + }, {}) + } + }; + }) + }, + this.getDocumentationButton("node-styles", "node styling"), + { + name: "Enable edges styling", + desc: "Allows you to style edges without limits.", + control: { + type: "toggle", + key: "edgesStylingFeatureEnabled" + } + }, + { + type: "page", + name: "Edge styles", + desc: "Manage custom edge styles.", + visible: () => this.getControlValue("edgesStylingFeatureEnabled"), + items: [ + { + name: "Inherit edge color from node", + desc: "When creating a new edge by dragging from a node, the edge will inherit the color of the node it is dragged from.", + control: { + type: "toggle", + key: "inheritEdgeColorFromNode" + } + }, + { + name: "Default edge color", + desc: "The default color of an edge. The default range is from 0 to 6, where 0 is no color. The range can be extended by using the Custom Colors feature of Advanced Canvas.", + control: { + type: "number", + key: "defaultEdgeColor" + } + }, + { + name: "Default edge line direction", + desc: "The default line direction of an edge.", + control: { + type: "dropdown", + key: "defaultEdgeLineDirection", + options: { + "nondirectional": "Nondirectional", + "unidirectional": "Unidirectional", + "bidirectional": "Bidirectional" + } + } + }, + { + name: "Update edge style while dragging", + desc: "Updates the edge style while dragging an edge. (Can be very slow)", + control: { + type: "toggle", + key: "edgeStyleUpdateWhileDragging" + } + }, + { + name: "Round square path edges", + desc: "Rounds the corners of square path edges.", + control: { + type: "toggle", + key: "edgeStyleSquarePathRounded" + } + }, + { + name: "Allow diagonal A* paths", + desc: "Allows diagonal paths for the A* path style.", + control: { + type: "toggle", + key: "edgeStylePathfinderAllowDiagonal" + } + }, + { + name: "Round A* path edges", + desc: "Rounds the A* path style.", + control: { + type: "toggle", + key: "edgeStylePathfinderPathRounded" + } + } + ] + }, + { + type: "page", + name: "Default edge style", + desc: "The default style of an edge. The default style is applied to all newly created edges.", + items: [ + ...BUILTIN_EDGE_STYLE_ATTRIBUTES, + // BUILTINS + ...this.settingsManager.edgeCssStylesManager.getStyles(), + // CUSTOM CSS STYLES + ...this.settingsManager.getSetting("customEdgeStyleAttributes") + // LEGACY CUSTOM STYLES + ].map((value) => { + var _a, _b; + return { + name: value.label, + control: { + type: "dropdown", + key: `defaultEdgeStyleAttributes[${value.key}]`, + defaultValue: (_b = (_a = value.options.find((option) => option.value === null)) == null ? void 0 : _a.value) != null ? _b : "", + options: value.options.reduce((acc, option) => { + var _a2; + acc[(_a2 = option.value) != null ? _a2 : ""] = option.label; + return acc; + }, {}) + } + }; + }) + }, + this.getDocumentationButton("edge-styles", "edge styling") + ] + }, + // Floating edges + { + type: "group", + heading: "Floating edges", + items: [ + { + name: "Enable floating edges", + desc: "Floating edges are automatically placed on the most suitable side of the node.", + control: { + type: "toggle", + key: "floatingEdgeFeatureEnabled" + } + }, + { + type: "page", + name: "Floating edges settings", + visible: () => this.getControlValue("floatingEdgeFeatureEnabled"), + items: [ + { + name: "Allow floating edge creation", + desc: "Create floating edges by dragging over the target node without placing the edge on a specific side connection point. (If disabled, floating edges can only be created and used by other Advanced Canvas features.)", + control: { + type: "toggle", + key: "allowFloatingEdgeCreation" + } + }, + { + name: "New edge from side floating", + desc: 'The "from" side of new edges will always be floating.', + control: { + type: "toggle", + key: "newEdgeFromSideFloating" + } + } + ] + }, + this.getDocumentationButton("floating-edges-automatic-edge-side") + ] + }, + // Flip edges + { + type: "group", + heading: "Flip edges", + items: [ + { + name: "Enable flip edges", + desc: "Flip the direction of edges using the popup menu.", + control: { + type: "toggle", + key: "flipEdgeFeatureEnabled" + } + }, + this.getDocumentationButton("flip-edge") + ] + }, + // Presentations + { + type: "group", + heading: "Presentations", + items: [ + { + name: "Enable presentations", + desc: "Create a presentation from your canvas.", + control: { + type: "toggle", + key: "presentationFeatureEnabled" + } + }, + { + type: "page", + name: "Presentations settings", + visible: () => this.getControlValue("presentationFeatureEnabled"), + items: [ + { + name: 'Show "Set Start Node" in node popup', + desc: 'Shows the "Set Start Node" option in the node popup. If not enabled, you can still set the start node using the corresponding command.', + control: { + type: "toggle", + key: "showSetStartNodeInPopup" + } + }, + { + type: "page", + name: "Default slide dimensions", + desc: "The default dimensions of a slide.", + items: [ + { + name: "Width", + desc: "The default width of a slide.", + control: { + type: "number", + key: "defaultSlideDimensions[0]" + } + }, + { + name: "Height", + desc: "The default height of a slide.", + control: { + type: "number", + key: "defaultSlideDimensions[1]" + } + } + ] + }, + { + name: "Wrap in slide padding", + desc: "The padding of the slide when wrapping the canvas in a slide.", + control: { + type: "number", + key: "wrapInSlidePadding" + } + }, + { + name: "Reset viewport on presentation end", + desc: "Resets the viewport to the original position after the presentation ends.", + control: { + type: "toggle", + key: "resetViewportOnPresentationEnd" + } + }, + { + name: "Use arrow keys to change slides", + desc: "Use the arrow keys to change slides in presentation mode.", + control: { + type: "toggle", + key: "useArrowKeysToChangeSlides" + } + }, + { + name: "Use PgUp/PgDown keys to change slides", + desc: "Use the PgUp/PgDown keys to change slides in presentation mode. (Makes the presentation mode compatible with most presentation remotes.)", + control: { + type: "toggle", + key: "usePgUpPgDownKeysToChangeSlides" + } + }, + { + name: "Use directional slide navigation", + desc: "Navigating with the arrow keys will try to navigate along the slide's edge in the pressed direction instead of just navigating forward or backward in the slide order.", + control: { + type: "toggle", + key: "useDirectionalSlideNavigation" + } + }, + { + name: "Zoom to slide without padding", + desc: "Zooms to the slide without padding.", + control: { + type: "toggle", + key: "zoomToSlideWithoutPadding" + } + }, + { + name: "Use unclamped zoom while presenting", + desc: "The zoom will not be clamped while presenting.", + control: { + type: "toggle", + key: "useUnclampedZoomWhilePresenting" + } + }, + { + name: "Enter fullscreen while presenting", + desc: "Presentations automatically request fullscreen. Disable to keep Obsidian windowed during presentations.", + control: { + type: "toggle", + key: "fullscreenPresentationEnabled" + } + }, + { + name: "Slide transition animation duration", + desc: "The duration of the slide transition animation in seconds. Set to 0 to disable the animation.", + control: { + type: "number", + key: "slideTransitionAnimationDuration" + } + }, + { + name: "Slide transition animation intensity", + desc: "The intensity of the slide transition animation. The higher the value, the more the canvas will zoom out before zooming in on the next slide.", + control: { + type: "number", + key: "slideTransitionAnimationIntensity" + } + } + ] + }, + this.getDocumentationButton("presentation-mode") + ] + }, + // PDF annotation + { + type: "group", + heading: "PDF annotation", + items: [ + { + name: "Enable PDF annotation", + desc: "Annotate PDF files in the canvas.", + control: { + type: "toggle", + key: "pdfAnnotationFeatureEnabled" + } + }, + { + type: "page", + name: "PDF annotation settings", + visible: () => this.getControlValue("pdfAnnotationFeatureEnabled"), + items: [ + { + name: "PDF pages gap", + desc: "The gap between PDF pages in pixels.", + control: { + type: "number", + key: "pdfPagesGap" + } + }, + { + name: "PDF page size factor", + desc: "The size factor of the PDF pages. The higher the value, the larger the newly created PDF pages will be.", + control: { + type: "number", + key: "pdfPageSizeFactor" + } + }, + { + name: "PDF page resolution", + desc: "The resolution of the PDF pages. The higher the value, the sharper the pages will be (heavily affects performance).", + control: { + type: "number", + key: "pdfPageResolution" + } + } + ] + }, + this.getDocumentationButton("pdf-annotation") + ] + }, + // Z-Ordering controls + { + type: "group", + heading: "Z-Ordering controls", + items: [ + { + name: "Enable Z-Ordering controls", + desc: "Change the persistent z-index of nodes using the context menu.", + control: { + type: "toggle", + key: "zOrderingControlFeatureEnabled" + } + }, + { + type: "page", + name: "Z-Ordering controls settings", + visible: () => this.getControlValue("zOrderingControlFeatureEnabled"), + items: [ + { + name: "Show one layer shift options", + desc: "Move nodes one layer forward or backward.", + control: { + type: "toggle", + key: "zOrderingControlShowOneLayerShiftOptions" + } + } + ] + }, + this.getDocumentationButton("z-ordering-control") + ] + }, + // Aspect ratio control + { + type: "group", + heading: "Aspect ratio control", + items: [ + { + name: "Enable aspect ratio control", + desc: "Change the aspect ratio of nodes using the context menu.", + control: { + type: "toggle", + key: "aspectRatioControlFeatureEnabled" + } + } + ] + }, + // Variable breakpoint + { + type: "group", + heading: "Variable breakpoint", + items: [ + { + name: "Enable variable breakpoint", + desc: `Change the zoom breakpoint (the zoom level at which the nodes won't render their content anymore) on a per-node basis using the ${VARIABLE_BREAKPOINT_CSS_VAR} CSS variable.`, + control: { + type: "toggle", + key: "variableBreakpointFeatureEnabled" + } + }, + this.getDocumentationButton("variable-breakpoints") + ] + }, + // Alternative text rendering + { + type: "group", + heading: "Alternative text rendering", + items: [ + { + name: "Enable alternative text rendering", + desc: "Tries to synchronize editing and reading view rendering. Caution: Causes visual inconsistencies compared to the default Obsidian reading view.", + control: { + type: "toggle", + key: "readingModeFixEnabled" + } + }, + this.getDocumentationButton("alternative-text-rendering") + ] + }, + // Auto resize node + { + type: "group", + heading: "Auto resize node", + items: [ + { + name: "Enable auto resize node", + desc: "Automatically resize the height of a node to fit the content.", + control: { + type: "toggle", + key: "autoResizeNodeFeatureEnabled" + } + }, + { + type: "page", + name: "Auto resize node settings", + visible: () => this.getControlValue("autoResizeNodeFeatureEnabled"), + items: [ + { + name: "Enable auto resize by default", + desc: "The auto resize feature will be enabled by default for all nodes.", + control: { + type: "toggle", + key: "autoResizeNodeEnabledByDefault" + } + }, + { + name: "Max height", + desc: "The maximum height of the node when auto resizing (-1 for unlimited).", + control: { + type: "number", + key: "autoResizeNodeMaxHeight" + } + }, + { + name: "Snap to grid", + desc: "The height of the node will snap to the grid.", + control: { + type: "toggle", + key: "autoResizeNodeSnapToGrid" + } + } + ] + }, + this.getDocumentationButton("auto-node-resizing") + ] + }, + // Canvas encapsulation + { + type: "group", + heading: "Canvas encapsulation", + items: [ + { + name: "Enable canvas encapsulation", + desc: "Encapsulate a selection of nodes and edges into a new canvas using the context menu.", + control: { + type: "toggle", + key: "canvasEncapsulationEnabled" + } + }, + this.getDocumentationButton("encapsulate-selection") + ] + }, + // Better readonly + { + type: "group", + heading: "Better readonly", + items: [ + { + name: "Enable better readonly", + desc: "Improve the readonly mode.", + control: { + type: "toggle", + key: "betterReadonlyEnabled" + } + }, + { + type: "page", + name: "Better readonly settings", + visible: () => this.getControlValue("betterReadonlyEnabled"), + items: [ + { + name: "Hide background grid when in readonly", + desc: "Hides the background grid when in readonly mode.", + control: { + type: "toggle", + key: "hideBackgroundGridWhenInReadonly" + } + }, + { + name: "Disable node popup", + desc: "Disables the node popup in readonly mode.", + control: { + type: "toggle", + key: "disableNodePopup" + } + }, + { + name: "Disable zoom", + desc: "Disables zooming in readonly mode.", + control: { + type: "toggle", + key: "disableZoom" + } + }, + { + name: "Disable pan", + desc: "Disables panning in readonly mode.", + control: { + type: "toggle", + key: "disablePan" + } + } + ] + }, + this.getDocumentationButton("better-readonly") + ] + }, + // Edge highlight + { + type: "group", + heading: "Edge highlight", + items: [ + { + name: "Enable edge highlight", + desc: "Highlight outgoing (and optionally incoming) edges of a selected node.", + control: { + type: "toggle", + key: "edgeHighlightEnabled" + } + }, + { + type: "page", + name: "Edge highlight settings", + visible: () => this.getControlValue("edgeHighlightEnabled"), + items: [ + { + name: "Highlight incoming edges", + desc: "Also highlights incoming edges.", + control: { + type: "toggle", + key: "highlightIncomingEdges" + } + } + ] + }, + this.getDocumentationButton("edge-highlight") + ] + }, + // Edge selection + { + type: "group", + heading: "Edge selection", + items: [ + { + name: "Enable edge selection", + desc: "Select edges connected to the selected node(s) using the popup menu.", + control: { + type: "toggle", + key: "edgeSelectionEnabled" + } + }, + { + type: "page", + name: "Edge selection settings", + visible: () => this.getControlValue("edgeSelectionEnabled"), + items: [ + { + name: "Select edge by direction", + desc: "Select incoming or outgoing edges using separate popup menu items.", + control: { + type: "toggle", + key: "selectEdgeByDirection" + } + } + ] + }, + this.getDocumentationButton("edge-selection") + ] + }, + // Focus Mode + { + type: "group", + heading: "Focus Mode", + items: [ + { + name: "Enable focus mode", + desc: "Focus on a single node and blur all other nodes.", + control: { + type: "toggle", + key: "focusModeFeatureEnabled" + } + }, + this.getDocumentationButton("focus-mode") + ] + }, + // Better export + { + type: "group", + heading: "Better export", + items: [ + { + name: "Enable better export", + desc: "Export to PNG/SVG with transparency and other options.", + control: { + type: "toggle", + key: "betterExportFeatureEnabled" + } + }, + this.getDocumentationButton("image-export") + ] + } + ]; + } +}; + +// src/managers/windows-manager.ts +var WindowsManager = class { + constructor(plugin) { + this.windows = [window]; + this.plugin = plugin; + this.plugin.registerEvent(this.plugin.app.workspace.on( + "window-open", + (_win, window2) => this.windows.push(window2) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "window-close", + (_win, window2) => this.windows = this.windows.filter((w) => w !== window2) + )); + } +}; + +// src/patchers/canvas-patcher.ts +var import_view = require("@codemirror/view"); + +// node_modules/monkey-around/mjs/index.js +function around(obj, factories) { + const removers = Object.keys(factories).map((key) => around1(obj, key, factories[key])); + return removers.length === 1 ? removers[0] : function() { + removers.forEach((r) => r()); + }; +} +function around1(obj, method, createWrapper) { + const original = obj[method], hadOwn = obj.hasOwnProperty(method); + let current = createWrapper(original); + if (original) + Object.setPrototypeOf(current, original); + Object.setPrototypeOf(wrapper, current); + obj[method] = wrapper; + return remove; + function wrapper(...args) { + if (current === original && obj[method] === wrapper) + remove(); + return current.apply(this, args); + } + function remove() { + if (obj[method] === wrapper) { + if (hadOwn) + obj[method] = original; + else + delete obj[method]; + } + if (current === original) + return; + current = original; + Object.setPrototypeOf(wrapper, original || Function); + } +} + +// src/patchers/canvas-patcher.ts +var import_obsidian5 = require("obsidian"); + +// src/utils/migration-helper.ts +var CURRENT_SPEC_VERSION = "1.0-1.0"; +var _MigrationHelper = class _MigrationHelper { + static needsMigration(canvas) { + var _a; + return ((_a = canvas.metadata) == null ? void 0 : _a.version) !== CURRENT_SPEC_VERSION; + } + static migrate(canvas) { + var _a, _b; + let version = (_b = (_a = canvas.metadata) == null ? void 0 : _a.version) != null ? _b : "undefined"; + if (version === CURRENT_SPEC_VERSION) return canvas; + while (version !== CURRENT_SPEC_VERSION) { + const migrationFunction = _MigrationHelper.MIGRATIONS[version]; + if (!migrationFunction) { + console.error(`No migration function found for version ${version}. Critical error!`); + break; + } + const { version: newVersion, canvas: migratedCanvas } = migrationFunction(canvas); + version = newVersion; + canvas = migratedCanvas; + if (!canvas.metadata) canvas.metadata = { version, frontmatter: {} }; + else canvas.metadata.version = version; + } + return canvas; + } +}; +_MigrationHelper.MIGRATIONS = { + undefined: (canvas) => { + var _a, _b, _c, _d; + const TARGET_SPEC_VERSION = "1.0-1.0"; + let startNode; + const globalInterdimensionalEdges = {}; + for (const node of (_a = canvas.nodes) != null ? _a : []) { + node.dynamicHeight = node.autoResizeHeight; + delete node.autoResizeHeight; + node.ratio = node.sideRatio; + delete node.sideRatio; + node.collapsed = node.isCollapsed; + delete node.isCollapsed; + if (node.portalToFile) { + node.portal = true; + delete node.portalToFile; + } + if (node.isStartNode) { + startNode = node.id; + delete node.isStartNode; + } + if (node.edgesToNodeFromPortal) { + const edgesToNodeFromPortal = node.edgesToNodeFromPortal; + for (const [portalId, edges] of Object.entries(edgesToNodeFromPortal)) { + if (!(portalId in globalInterdimensionalEdges)) globalInterdimensionalEdges[portalId] = []; + for (const edge of edges) { + if (edge.fromNode !== node.id) edge.fromNode = `${portalId}-${edge.fromNode}`; + if (edge.toNode !== node.id) edge.toNode = `${portalId}-${edge.toNode}`; + } + (_b = globalInterdimensionalEdges[portalId]) == null ? void 0 : _b.push(...edges); + } + delete node.edgesToNodeFromPortal; + } + } + for (const node of (_c = canvas.nodes) != null ? _c : []) { + if (!(node.id in globalInterdimensionalEdges)) continue; + node.interdimensionalEdges = globalInterdimensionalEdges[node.id]; + } + (_d = canvas.metadata) != null ? _d : canvas.metadata = { + version: TARGET_SPEC_VERSION, + frontmatter: {}, + startNode + }; + return { version: TARGET_SPEC_VERSION, canvas }; + } +}; +var MigrationHelper = _MigrationHelper; + +// node_modules/tiny-jsonc/dist/index.js +var stringOrCommentRe = /("(?:\\?[^])*?")|(\/\/.*)|(\/\*[^]*?\*\/)/g; +var stringOrTrailingCommaRe = /("(?:\\?[^])*?")|(,\s*)(?=]|})/g; +var JSONC = { + parse: (text) => { + text = String(text); + try { + return JSON.parse(text); + } catch (e) { + return JSON.parse(text.replace(stringOrCommentRe, "$1").replace(stringOrTrailingCommaRe, "$1")); + } + } +}; +var dist_default = JSONC; + +// src/patchers/patcher.ts +function invoke(fn, thisArg, ...args) { + return fn.call(thisArg, ...args); +} +var Patcher = class _Patcher { + constructor(plugin) { + this.plugin = plugin; + void this.patch(); + } + static async waitForMapValueLookup(map, viewType, patch) { + return new Promise((resolve) => { + const uninstaller = around(map, { + [viewType]: (next) => function(...args) { + const view = invoke(next, this, ...args); + patch(view); + const patchedView = invoke(next, this, ...args); + uninstaller(); + resolve(patchedView); + return patchedView; + } + }); + }); + } + static async waitForViewRequest(plugin, viewType, patch) { + return this.waitForMapValueLookup(plugin.app.viewRegistry.viewByType, viewType, patch); + } + static OverrideExisting(fn) { + return Object.assign(fn, { __overrideExisting: true }); + } + static patchThisAndPrototype(plugin, object, patches, uninstallers) { + _Patcher.patch(plugin, object, patches, false, uninstallers); + return _Patcher.patchPrototype(plugin, object, patches, uninstallers); + } + static patchPrototype(plugin, target, patches, uninstallers) { + return _Patcher.patch(plugin, target, patches, true, uninstallers); + } + static patch(plugin, object, patches, prototype = false, uninstallers) { + if (!object) return null; + const target = prototype ? object.constructor.prototype : object; + for (const key of Object.keys(patches)) { + const patch = patches[key]; + if (patch == null ? void 0 : patch.__overrideExisting) { + if (typeof target[key] !== "function") + throw new Error(`Method ${String(key)} does not exist on target`); + } + } + const uninstaller = around( + target, + patches + ); + if (uninstallers) uninstallers.push(uninstaller); + plugin.register(uninstaller); + return object; + } + static async patchOnce(plugin, object, patches) { + const uninstallers = []; + const value = await new Promise( + (resolve) => this.patch(plugin, object, patches(resolve), false, uninstallers) + ); + for (const uninstall of uninstallers) uninstall(); + return value; + } + static tryPatchWorkspacePrototype(plugin, getTarget, patches, uninstallers) { + return new Promise((resolve) => { + const result = _Patcher.patchPrototype(plugin, getTarget(), patches, uninstallers); + if (result) { + resolve(result); + return; + } + const listener = plugin.app.workspace.on("layout-change", () => { + const result2 = _Patcher.patchPrototype(plugin, getTarget(), patches, uninstallers); + if (result2) { + plugin.app.workspace.offref(listener); + resolve(result2); + } + }); + plugin.registerEvent(listener); + }); + } +}; + +// src/patchers/canvas-patcher.ts +var CanvasPatcher = class extends Patcher { + constructor() { + super(...arguments); + // Uninstall patches when an element gets removed from the canvas + this.elementUninstallers = /* @__PURE__ */ new Map(); + } + async patch() { + const loadedCanvasViewLeafs = this.plugin.app.workspace.getLeavesOfType("canvas").filter((leaf) => !(0, import_obsidian5.requireApiVersion)("1.7.2") || !leaf.isDeferred); + if (loadedCanvasViewLeafs.length > 0) { + console.debug(`Patching and reloading loaded canvas views (Count: ${loadedCanvasViewLeafs.length})`); + this.patchCanvas(loadedCanvasViewLeafs.first().view); + for (const leaf of loadedCanvasViewLeafs) void leaf.rebuildView(); + } else { + await Patcher.waitForViewRequest(this.plugin, "canvas", (view) => this.patchCanvas(view)); + console.debug(`Patched canvas view on first request`); + } + } + patchCanvas(view) { + const that = this; + Patcher.patchPrototype(this.plugin, view, { + setEphemeralState: Patcher.OverrideExisting((next) => function(state) { + var _a, _b, _c; + const s = state; + if (s == null ? void 0 : s.subpath) { + const nodeId = s.subpath.replace(/^#/, ""); + const node = this.canvas.nodes.get(nodeId); + if (node) { + this.canvas.selectOnly(node); + this.canvas.zoomToSelection(); + return; + } + } + if (((_b = (_a = s.match) == null ? void 0 : _a.matches) == null ? void 0 : _b[0]) && !((_c = s.match) == null ? void 0 : _c.nodeId)) { + const match = s.match.matches[0]; + const elementType = match[0] === 0 ? "nodes" : "edges"; + const elementIndex = match[1]; + const element = elementType === "nodes" ? Array.from(this.canvas.nodes.values())[elementIndex] : Array.from(this.canvas.edges.values())[elementIndex]; + if (element) { + this.canvas.selectOnly(element); + this.canvas.zoomToSelection(); + return; + } + } + return invoke(next, this, state); + }), + setViewData: Patcher.OverrideExisting((next) => function(...args) { + let [json, ...rest] = args; + json = json !== "" ? json : '{"nodes": [], "edges": []}'; + try { + const canvasData = dist_default.parse(json); + if (MigrationHelper.needsMigration(canvasData)) { + if (this.file) that.plugin.createFileSnapshot(this.file.path, json); + json = JSON.stringify(MigrationHelper.migrate(canvasData)); + } + } catch (e) { + console.error("Failed to migrate canvas data:", e); + } + let result; + try { + result = invoke(next, this, json, ...rest); + } catch (e) { + console.error("Invalid JSON, repairing through Advanced Canvas:", e); + if (this.file) that.plugin.createFileSnapshot(this.file.path, json); + json = JSON.stringify(dist_default.parse(json), null, 2); + result = invoke(next, this, json, ...rest); + } + that.plugin.app.workspace.trigger("advanced-canvas:canvas-changed", this.canvas); + return result; + }), + close: Patcher.OverrideExisting((next) => function(...args) { + that.plugin.app.workspace.trigger("advanced-canvas:canvas-view-unloaded:before", this); + return invoke(next, this, ...args); + }) + }); + Patcher.patchPrototype(this.plugin, view.canvas, { + markViewportChanged: Patcher.OverrideExisting((next) => function(...args) { + that.plugin.app.workspace.trigger("advanced-canvas:viewport-changed:before", this); + const result = invoke(next, this, ...args); + that.plugin.app.workspace.trigger("advanced-canvas:viewport-changed:after", this); + return result; + }), + markMoved: Patcher.OverrideExisting((next) => function(node) { + const result = invoke(next, this, node); + if (!this.viewportChanged) { + if (node.prevX !== node.x || node.prevY !== node.y) + that.plugin.app.workspace.trigger("advanced-canvas:node-moved", this, node, !this.isDragging); + if (node.prevWidth !== node.width || node.prevHeight !== node.height) + that.plugin.app.workspace.trigger("advanced-canvas:node-resized", this, node); + } + node.prevX = node.x; + node.prevY = node.y; + node.prevWidth = node.width; + node.prevHeight = node.height; + return result; + }), + onDoubleClick: Patcher.OverrideExisting((next) => function(event) { + const preventDefault = { value: false }; + that.plugin.app.workspace.trigger("advanced-canvas:double-click", this, event, preventDefault); + if (!preventDefault.value) invoke(next, this, event); + }), + setDragging: Patcher.OverrideExisting((next) => function(dragging) { + const result = invoke(next, this, dragging); + that.plugin.app.workspace.trigger("advanced-canvas:dragging-state-changed", this, dragging); + return result; + }), + // OBSIDIAN-FIX + cloneData: Patcher.OverrideExisting((next) => function(elements, shift) { + const result = invoke(next, this, elements, shift); + elements.nodes = elements.nodes.map((nodeData) => JSON.parse(JSON.stringify(nodeData))); + elements.edges = elements.edges.map((edgeData) => JSON.parse(JSON.stringify(edgeData))); + return result; + }), + getContainingNodes: Patcher.OverrideExisting((next) => function(bbox) { + const result = invoke(next, this, bbox); + that.plugin.app.workspace.trigger("advanced-canvas:containing-nodes-requested", this, bbox, result); + return result; + }), + updateSelection: Patcher.OverrideExisting((next) => function(update) { + const oldSelection = new Set(this.selection); + const result = invoke(next, this, update); + that.plugin.app.workspace.trigger("advanced-canvas:selection-changed", this, oldSelection, (update2) => invoke(next, this, update2)); + return result; + }), + createTextNode: Patcher.OverrideExisting((next) => function(...args) { + const node = invoke(next, this, ...args); + that.plugin.app.workspace.trigger("advanced-canvas:node-created", this, node); + return node; + }), + createFileNode: Patcher.OverrideExisting((next) => function(...args) { + const node = invoke(next, this, ...args); + that.plugin.app.workspace.trigger("advanced-canvas:node-created", this, node); + return node; + }), + createFileNodes: Patcher.OverrideExisting((next) => function(...args) { + const nodes = invoke(next, this, ...args); + nodes.forEach((node) => that.plugin.app.workspace.trigger("advanced-canvas:node-created", this, node)); + return nodes; + }), + createGroupNode: Patcher.OverrideExisting((next) => function(...args) { + const node = invoke(next, this, ...args); + that.plugin.app.workspace.trigger("advanced-canvas:node-created", this, node); + return node; + }), + createLinkNode: Patcher.OverrideExisting((next) => function(...args) { + const node = invoke(next, this, ...args); + that.plugin.app.workspace.trigger("advanced-canvas:node-created", this, node); + return node; + }), + addNode: Patcher.OverrideExisting((next) => function(node) { + that.patchNode(node); + return invoke(next, this, node); + }), + addEdge: Patcher.OverrideExisting((next) => function(edge) { + that.patchEdge(edge); + if (!this.viewportChanged) that.plugin.app.workspace.trigger("advanced-canvas:edge-created", this, edge); + return invoke(next, this, edge); + }), + removeNode: Patcher.OverrideExisting((next) => function(node) { + that.uninstallNodeElementPatches(node); + const result = invoke(next, this, node); + if (!this.isClearing) that.plugin.app.workspace.trigger("advanced-canvas:node-removed", this, node); + return result; + }), + removeEdge: Patcher.OverrideExisting((next) => function(edge) { + that.uninstallNodeElementPatches(edge); + const result = invoke(next, this, edge); + if (!this.isClearing) that.plugin.app.workspace.trigger("advanced-canvas:edge-removed", this, edge); + return result; + }), + handleCopy: Patcher.OverrideExisting((next) => function(...args) { + this.isCopying = true; + const result = invoke(next, this, ...args); + this.isCopying = false; + return result; + }), + handlePaste: Patcher.OverrideExisting((next) => function(...args) { + this.isPasting = true; + const result = invoke(next, this, ...args); + this.isPasting = false; + return result; + }), + getSelectionData: Patcher.OverrideExisting((next) => function(...args) { + const result = invoke(next, this, ...args); + if (this.isCopying) that.plugin.app.workspace.trigger("advanced-canvas:copy", this, result); + return result; + }), + zoomToBbox: Patcher.OverrideExisting((next) => function(bbox) { + that.plugin.app.workspace.trigger("advanced-canvas:zoom-to-bbox:before", this, bbox); + const result = invoke(next, this, bbox); + that.plugin.app.workspace.trigger("advanced-canvas:zoom-to-bbox:after", this, bbox); + return result; + }), + // Custom + zoomToRealBbox: (_next) => function(bbox) { + if (this.canvasRect.width === 0 || this.canvasRect.height === 0) return; + that.plugin.app.workspace.trigger("advanced-canvas:zoom-to-bbox:before", this, bbox); + const widthZoom = this.canvasRect.width / (bbox.maxX - bbox.minX); + const heightZoom = this.canvasRect.height / (bbox.maxY - bbox.minY); + const zoom = this.screenshotting ? Math.min(widthZoom, heightZoom) : Math.clamp(Math.min(widthZoom, heightZoom), -4, 1); + this.tZoom = Math.log2(zoom); + this.zoomCenter = null; + this.tx = (bbox.minX + bbox.maxX) / 2; + this.ty = (bbox.minY + bbox.maxY) / 2; + this.markViewportChanged(); + that.plugin.app.workspace.trigger("advanced-canvas:zoom-to-bbox:after", this, bbox); + }, + setReadonly: Patcher.OverrideExisting((next) => function(readonly) { + const result = invoke(next, this, readonly); + that.plugin.app.workspace.trigger("advanced-canvas:readonly-changed", this, readonly); + return result; + }), + undo: Patcher.OverrideExisting((next) => function(...args) { + const result = invoke(next, this, ...args); + this.importData(this.getData(), true); + that.plugin.app.workspace.trigger("advanced-canvas:undo", this); + return result; + }), + redo: Patcher.OverrideExisting((next) => function(...args) { + const result = invoke(next, this, ...args); + this.importData(this.getData(), true); + that.plugin.app.workspace.trigger("advanced-canvas:redo", this); + return result; + }), + clear: Patcher.OverrideExisting((next) => function(...args) { + this.isClearing = true; + const result = invoke(next, this, ...args); + this.isClearing = false; + return result; + }), + /*setData: Patcher.OverrideExisting(next => function (...args: any): void { + // + const result = invoke(next, this, ...args) + // + return result + }),*/ + getData: Patcher.OverrideExisting((next) => function(...args) { + const result = invoke(next, this, ...args); + that.plugin.app.workspace.trigger("advanced-canvas:data-requested", this, result); + return result; + }), + importData: Patcher.OverrideExisting((next) => function(data, clearCanvas, silent) { + var _a; + const targetFilePath = (_a = this.view.file) == null ? void 0 : _a.path; + const setData = (data2) => { + if (!this.view.file || this.view.file.path !== targetFilePath) return; + this.importData(data2, true, true); + }; + if (!silent) that.plugin.app.workspace.trigger("advanced-canvas:data-loaded:before", this, data, setData); + const result = invoke(next, this, data, clearCanvas); + if (!silent) that.plugin.app.workspace.trigger("advanced-canvas:data-loaded:after", this, data, setData); + return result; + }), + requestSave: Patcher.OverrideExisting((next) => function(...args) { + that.plugin.app.workspace.trigger("advanced-canvas:canvas-saved:before", this); + const result = invoke(next, this, ...args); + that.plugin.app.workspace.trigger("advanced-canvas:canvas-saved:after", this); + return result; + }) + }); + Patcher.patchPrototype(this.plugin, view.canvas.menu, { + render: Patcher.OverrideExisting((next) => function(...args) { + const result = invoke(next, this, ...args); + that.plugin.app.workspace.trigger("advanced-canvas:popup-menu-created", this.canvas); + invoke(next, this); + return result; + }) + }); + Patcher.patchPrototype(this.plugin, view.canvas.nodeInteractionLayer, { + setTarget: Patcher.OverrideExisting((next) => function(node) { + const result = invoke(next, this, node); + that.plugin.app.workspace.trigger("advanced-canvas:node-interaction", this.canvas, node); + return result; + }) + }); + this.plugin.registerEditorExtension([import_view.EditorView.updateListener.of((update) => { + if (!update.docChanged) return; + let editor; + try { + editor = update.state.field(import_obsidian5.editorInfoField); + } catch (e) { + return; + } + const node = editor.node; + if (!node) return; + that.plugin.app.workspace.trigger("advanced-canvas:node-text-content-changed", node.canvas, node, update); + })]); + } + uninstallNodeElementPatches(element) { + const uninstallers = this.elementUninstallers.get(element); + if (!uninstallers) return; + for (const uninstaller of uninstallers) uninstaller(); + this.elementUninstallers.delete(element); + } + patchNode(node) { + const that = this; + const uninstallers = []; + Patcher.patch(this.plugin, node, { + render: Patcher.OverrideExisting((next) => function(...args) { + const result = invoke(next, this, ...args); + that.plugin.app.workspace.trigger("advanced-canvas:node-rendered", this.canvas, node); + return result; + }), + setData: Patcher.OverrideExisting((next) => function(data, addHistory) { + const unchanged = JSON.stringify(this.getData()) === JSON.stringify(data); + const result = invoke(next, this, data); + let savedData = null; + if (!unchanged) { + if (node.initialized && !node.isDirty) { + node.isDirty = true; + that.plugin.app.workspace.trigger("advanced-canvas:node-changed", this.canvas, node); + delete node.isDirty; + } + if (this.initialized) { + savedData = this.canvas.getData(); + this.canvas.view.requestSave(); + } + } + if (addHistory) this.canvas.pushHistory(savedData != null ? savedData : this.canvas.getData()); + return result; + }), + setZIndex: (_next) => function(value) { + this.setData({ + ...this.getData(), + zIndex: value + }, true); + this.updateZIndex(); + }, + updateZIndex: Patcher.OverrideExisting((next) => function() { + const persistentZIndex = this.getData().zIndex; + if (persistentZIndex === void 0) return invoke(next, this); + this.canvas.zIndexCounter = Math.max(this.canvas.zIndexCounter, persistentZIndex); + this.renderZIndex(); + }), + renderZIndex: Patcher.OverrideExisting((next) => function() { + const persistentZIndex = this.getData().zIndex; + if (persistentZIndex === void 0) return invoke(next, this); + this.zIndex = persistentZIndex; + if (this.canvas.selection.size === 1 && this.canvas.selection.has(this)) + this.zIndex = this.canvas.zIndexCounter + 1; + this.nodeEl.style.zIndex = this.zIndex.toString(); + }), + setIsEditing: Patcher.OverrideExisting((next) => function(...args) { + const result = invoke(next, this, ...args); + const [editing] = args; + that.plugin.app.workspace.trigger("advanced-canvas:node-editing-state-changed", this.canvas, node, editing); + return result; + }), + updateBreakpoint: Patcher.OverrideExisting((next) => function(breakpoint) { + const breakpointRef = { value: breakpoint }; + that.plugin.app.workspace.trigger("advanced-canvas:node-breakpoint-changed", this.canvas, node, breakpointRef); + return invoke(next, this, breakpointRef.value); + }), + getBBox: Patcher.OverrideExisting((next) => function(...args) { + const result = invoke(next, this, ...args); + that.plugin.app.workspace.trigger("advanced-canvas:node-bbox-requested", this.canvas, node, result); + return result; + }), + onConnectionPointerdown: Patcher.OverrideExisting((next) => function(e, side) { + const addEdgeEventRef = that.plugin.app.workspace.on("advanced-canvas:edge-added", (_canvas, edge) => { + that.plugin.app.workspace.trigger("advanced-canvas:edge-connection-dragging:before", this.canvas, edge, e, true, "to"); + that.plugin.app.workspace.offref(addEdgeEventRef); + activeDocument.addEventListener("pointerup", (e2) => { + that.plugin.app.workspace.trigger("advanced-canvas:edge-connection-dragging:after", this.canvas, edge, e2, true, "to"); + }, { once: true }); + }); + const result = invoke(next, this, e, side); + return result; + }), + // File nodes + setFile: (next) => function(...args) { + const result = invoke(next, this, ...args); + that.plugin.app.workspace.trigger("advanced-canvas:node-changed", this.canvas, this); + return result; + }, + setFilePath: (next) => function(...args) { + const result = invoke(next, this, ...args); + that.plugin.app.workspace.trigger("advanced-canvas:node-changed", this.canvas, this); + return result; + } + }, false, uninstallers); + this.elementUninstallers.set(node, uninstallers); + this.runAfterInitialized(node, () => { + this.plugin.app.workspace.trigger("advanced-canvas:node-added", node.canvas, node); + this.plugin.app.workspace.trigger("advanced-canvas:node-changed", node.canvas, node); + }); + } + patchEdge(edge) { + const that = this; + const uninstallers = []; + Patcher.patch(this.plugin, edge, { + setData: Patcher.OverrideExisting((next) => function(data, addHistory) { + const unchanged = JSON.stringify(this.getData()) === JSON.stringify(data); + const result = invoke(next, this, data); + let savedData = null; + if (!unchanged) { + if (this.initialized && !this.isDirty) { + this.isDirty = true; + that.plugin.app.workspace.trigger("advanced-canvas:edge-changed", this.canvas, this); + delete this.isDirty; + } + if (this.initialized) { + savedData = this.canvas.getData(); + this.canvas.view.requestSave(); + } + } + if (addHistory) this.canvas.pushHistory(savedData != null ? savedData : this.canvas.getData()); + return result; + }), + render: Patcher.OverrideExisting((next) => function(...args) { + const result = invoke(next, this, ...args); + that.plugin.app.workspace.trigger("advanced-canvas:edge-changed", this.canvas, this); + return result; + }), + getCenter: Patcher.OverrideExisting((next) => function(...args) { + const result = invoke(next, this, ...args); + that.plugin.app.workspace.trigger("advanced-canvas:edge-center-requested", this.canvas, this, result); + return result; + }), + onConnectionPointerdown: Patcher.OverrideExisting((next) => function(e) { + const cancelRef = { value: false }; + that.plugin.app.workspace.trigger("advanced-canvas:edge-connection-try-dragging:before", this.canvas, this, e, cancelRef); + if (cancelRef.value) return; + const previousEnds = { from: this.from, to: this.to }; + const result = invoke(next, this, e); + const eventPos = this.canvas.posFromEvt(e); + const fromPos = BBoxHelper.getCenterOfBBoxSide(this.from.node.getBBox(), this.from.side); + const toPos = BBoxHelper.getCenterOfBBoxSide(this.to.node.getBBox(), this.to.side); + const draggingSide = Math.hypot(eventPos.x - fromPos.x, eventPos.y - fromPos.y) > Math.hypot(eventPos.x - toPos.x, eventPos.y - toPos.y) ? "to" : "from"; + that.plugin.app.workspace.trigger("advanced-canvas:edge-connection-dragging:before", this.canvas, this, e, false, draggingSide, previousEnds); + activeDocument.addEventListener("pointerup", (e2) => { + that.plugin.app.workspace.trigger("advanced-canvas:edge-connection-dragging:after", this.canvas, this, e2, false, draggingSide, previousEnds); + }, { once: true }); + return result; + }) + }, false, uninstallers); + this.elementUninstallers.set(edge, uninstallers); + this.runAfterInitialized(edge, () => { + this.plugin.app.workspace.trigger("advanced-canvas:edge-added", edge.canvas, edge); + }); + } + runAfterInitialized(canvasElement, onReady) { + if (canvasElement.initialized) { + onReady(); + return; + } + const that = this; + const uninstall = around(canvasElement, { + initialize: (next) => function(...args) { + const result = invoke(next, this, ...args); + onReady(); + uninstall(); + return result; + } + }); + that.plugin.register(uninstall); + } +}; + +// src/patchers/link-suggestions-patcher.ts +var import_obsidian6 = require("obsidian"); +var LinkSuggestionsPatcher = class extends Patcher { + async patch() { + var _a; + if (!this.plugin.settings.getSetting("enableSingleNodeLinks")) return; + const suggests = this.plugin.app.workspace.editorSuggest.suggests; + const suggestManager = (_a = suggests.find((s) => s.suggestManager)) == null ? void 0 : _a.suggestManager; + if (!suggestManager) return console.warn("LinkSuggestionsPatcher: No suggest manager found."); + Patcher.patchThisAndPrototype(this.plugin, suggestManager, { + getHeadingSuggestions: Patcher.OverrideExisting((next) => async function(context, path, subpath) { + const result = await invoke(next, this, context, path, subpath); + if (!path.endsWith(".canvas")) return result; + const currentFilePath = this.getSourcePath(); + const targetFile = this.app.metadataCache.getFirstLinkpathDest(path, currentFilePath); + if (!targetFile) return result; + if (!(targetFile instanceof import_obsidian6.TFile) || targetFile.extension !== "canvas") + return result; + const fileCache = this.app.metadataCache.getFileCache(targetFile); + if (!fileCache) return result; + const canvasNodeCaches = fileCache.nodes; + if (!canvasNodeCaches) return result; + for (const nodeId of Object.keys(canvasNodeCaches)) { + if (nodeId === subpath) continue; + const suggestion = { + file: targetFile, + heading: nodeId, + level: 1, + matches: [], + path, + subpath: `#${nodeId}`, + score: 0, + type: "heading" + }; + result.push(suggestion); + } + return result; + }) + }); + } +}; + +// src/advanced-canvas-embed.ts +var import_obsidian7 = require("obsidian"); +var AdvancedCanvasEmbed = class extends import_obsidian7.Component { + constructor(context, file, subpath) { + super(); + this.onModifyCallback = (file) => { + if (file.path !== this.file.path) return; + void this.loadFile(); + }; + this.context = context; + this.file = file; + this.subpath = subpath; + if (!subpath) console.warn("AdvancedCanvasEmbed: No subpath provided. This embed will not work as expected."); + } + onload() { + this.context.app.vault.on("modify", this.onModifyCallback); + } + onunload() { + this.context.app.vault.off("modify", this.onModifyCallback); + } + async loadFile() { + if (!this.subpath) return; + const nodeId = this.subpath.replace(/^#/, ""); + const canvasContent = await this.context.app.vault.cachedRead(this.file); + if (!canvasContent) return console.warn("AdvancedCanvasEmbed: No canvas content found."); + const canvasJson = JSON.parse(canvasContent); + const canvasNode = canvasJson.nodes.find((node) => node.id === nodeId); + if (!canvasNode) { + this.context.containerEl.classList.add("mod-empty"); + this.context.containerEl.textContent = "Node not found"; + return; + } + let nodeContent = ""; + if (canvasNode.type === "text") nodeContent = canvasNode.text; + else if (canvasNode.type === "group") nodeContent = `**Group Node:** ${canvasNode.label}`; + else if (canvasNode.type === "file") nodeContent = `**File Node:** ${canvasNode.file}`; + this.context.containerEl.empty(); + this.context.containerEl.classList.add("ac-card-embed"); + if (canvasNode.color !== void 0) { + this.context.containerEl.classList.add("is-themed"); + this.context.containerEl.classList.add(`mod-canvas-color-${canvasNode.color}`); + } + const markdownContainer = this.context.containerEl.createSpan(); + markdownContainer.classList.add("markdown-content"); + await import_obsidian7.MarkdownRenderer.render(this.context.app, nodeContent, markdownContainer, this.file.path, this); + } +}; + +// src/patchers/embed-patcher.ts +var EmbedPatcher = class extends Patcher { + async patch() { + if (!this.plugin.settings.getSetting("enableSingleNodeLinks")) return; + const embedByExtension = this.plugin.app.embedRegistry.embedByExtension; + const originalCanvasEmbed = embedByExtension["canvas"]; + if (!originalCanvasEmbed) return; + embedByExtension["canvas"] = function(context, file, subpath) { + if (subpath) return new AdvancedCanvasEmbed(context, file, subpath); + return invoke(originalCanvasEmbed, this, context, file, subpath); + }; + this.plugin.register(() => { + embedByExtension["canvas"] = originalCanvasEmbed; + }); + } +}; + +// src/patchers/metadata-cache-patcher.ts +var import_obsidian8 = require("obsidian"); + +// src/utils/filepath-helper.ts +var FilepathHelper = class { + static extension(path) { + var _a; + return (path == null ? void 0 : path.includes(".")) ? (_a = path == null ? void 0 : path.split(".")) == null ? void 0 : _a.pop() : void 0; + } +}; + +// src/utils/hash-helper.ts +var HashHelper = class _HashHelper { + static async getBytesHash(bytes) { + const cryptoBytes = await crypto.subtle.digest("SHA-256", new Uint8Array(bytes)); + return _HashHelper.arrayBufferToHexString(cryptoBytes); + } + static arrayBufferToHexString(buffer) { + const uint8Array = new Uint8Array(buffer); + const hexArray = []; + for (const byte of uint8Array) { + hexArray.push((byte >>> 4).toString(16)); + hexArray.push((byte & 15).toString(16)); + } + return hexArray.join(""); + } +}; + +// src/utils/task-queue.ts +var TaskQueue = class { + constructor() { + this.running = false; + this.queue = []; + this.onFinished = () => { + }; + } + async add(task) { + return new Promise((resolve) => { + this.queue.push([resolve, task]); + if (!this.running) void this.run(); + }); + } + setOnFinished(callback) { + this.onFinished = callback; + } + async run() { + var _a; + this.running = true; + while (this.queue.length > 0) { + const [resolver, task] = (_a = this.queue.shift()) != null ? _a : [void 0, void 0]; + await (task == null ? void 0 : task()); + resolver == null ? void 0 : resolver(); + } + this.running = false; + this.onFinished(); + } +}; + +// src/patchers/metadata-cache-patcher.ts +var MetadataCachePatcher = class extends Patcher { + async patch() { + if (!this.plugin.settings.getSetting("canvasMetadataCompatibilityEnabled")) return; + Patcher.patchPrototype(this.plugin, this.plugin.app.metadataCache, { + getCache: Patcher.OverrideExisting((next) => function(filepath, ...args) { + var _a; + if (FilepathHelper.extension(filepath) === "canvas") { + if (!Object.prototype.hasOwnProperty.call(this.fileCache, filepath)) + return null; + const hash = (_a = this.fileCache[filepath]) == null ? void 0 : _a.hash; + return hash && this.metadataCache[hash] || null; + } + return invoke(next, this, filepath, ...args); + }), + computeFileMetadataAsync: Patcher.OverrideExisting((next) => async function(file, ...args) { + if (file instanceof import_obsidian8.TFile && (file == null ? void 0 : file.extension) === "canvas") + return invoke(computeCanvasFileMetadataAsync, this, file); + return invoke(next, this, file, ...args); + }), + resolveLinks: Patcher.OverrideExisting((next) => async function(filepath) { + const result = invoke(next, this, filepath); + if (FilepathHelper.extension(filepath) === "canvas") + await invoke(resolveCanvasLinks, this, filepath); + return result; + }) + }); + } +}; +var metadataQueue = new TaskQueue(); +var linkResolveQueue = new TaskQueue(); +async function computeCanvasFileMetadataAsync(file) { + this.uniqueFileLookup.add(file.name.toLowerCase(), file); + let isStale = true; + const cache2 = this.fileCache[file.path]; + if (!cache2) this.saveFileCache(file.path, { mtime: 0, size: 0, hash: "" }); + else { + const unchanged = cache2.mtime === file.stat.mtime && cache2.size === file.stat.size; + const hasMetadataCache = cache2.hash && Object.prototype.hasOwnProperty.call(this.metadataCache, cache2.hash); + if (unchanged && hasMetadataCache) + isStale = false; + } + if (isStale) { + linkResolveQueue.setOnFinished(() => this.trigger("finished")); + await metadataQueue.add( + () => invoke(updateMetadataCache, this, file) + ); + } + linkResolveQueue.setOnFinished(() => this.trigger("resolved")); + await linkResolveQueue.add( + () => invoke(resolveCanvasLinks, this, file.path) + ); +} +async function updateMetadataCache(file) { + const bytes = await this.vault.readBinary(file); + const data = new TextDecoder().decode(new Uint8Array(bytes)); + const hash = await HashHelper.getBytesHash(bytes); + const cache2 = { + mtime: file.stat.mtime, + size: file.stat.size, + hash + }; + this.saveFileCache(file.path, cache2); + let metadata = this.metadataCache[cache2.hash]; + if (metadata) return this.trigger( + "changed", + file, + data, + metadata + ); + const slowIndexingTimeout = window.setTimeout(() => { + new import_obsidian8.Notice(`Canvas indexing taking a long time for file ${file.path}`); + }, 1e4); + try { + metadata = await invoke(computeCanvasMetadataAsync, this, data); + } finally { + window.clearTimeout(slowIndexingTimeout); + } + if (metadata) { + this.saveMetaCache(hash, metadata); + this.trigger("changed", file, data, metadata); + } else { + console.error("Canvas metadata failed to parse", file); + } +} +async function computeCanvasMetadataAsync(data) { + var _a, _b, _c, _d, _e; + const content = JSON.parse(data || "{}"); + const metadata = { + v: 1 + }; + const frontmatter = (_a = content.metadata) == null ? void 0 : _a.frontmatter; + metadata.frontmatterPosition = { + start: { line: 0, col: 0, offset: 0 }, + end: { line: 0, col: 0, offset: 0 } + }; + metadata.frontmatter = frontmatter; + metadata.frontmatterLinks = []; + for (const [key, value] of Object.entries(frontmatter != null ? frontmatter : {})) { + const getLinks = (value2) => value2.map((v) => { + if (!v.startsWith("[[") || !v.endsWith("]]")) return null; + const [link, ...aliases] = v.slice(2, -2).split("|"); + return { + key, + displayText: aliases.length > 0 ? aliases.join("|") : link, + link: link != null ? link : v, + original: v + }; + }).filter((v) => v !== null); + if (typeof value === "string") (_b = metadata.frontmatterLinks) == null ? void 0 : _b.push(...getLinks([value])); + else if (Array.isArray(value)) (_c = metadata.frontmatterLinks) == null ? void 0 : _c.push(...getLinks(value)); + } + metadata.nodes = {}; + metadata.links = []; + metadata.embeds = []; + await Promise.all(((_d = content.nodes) != null ? _d : []).map(async (node, index) => { + var _a2, _b2; + if (node.type !== "text") return; + const text = node.text; + const buffer = new TextEncoder().encode(text).buffer; + const nodeMetadata = await this.computeMetadataAsync(buffer); + if (!nodeMetadata) return; + metadata.nodes[node.id] = nodeMetadata; + metadata.links.push(...((_a2 = nodeMetadata.links) != null ? _a2 : []).map((link) => ({ + ...link, + position: { + nodeId: node.id, + start: { line: 0, col: 1, offset: 0 }, + end: { line: 0, col: 1, offset: index } + } + }))); + metadata.embeds.push(...((_b2 = nodeMetadata.embeds) != null ? _b2 : []).map((embed2) => ({ + ...embed2, + position: { + nodeId: node.id, + start: { line: 0, col: 1, offset: 0 }, + end: { line: 0, col: 1, offset: index } + } + }))); + })); + for (const [index, node] of ((_e = content.nodes) != null ? _e : []).entries()) { + if (node.type !== "file") continue; + const file = node.file; + if (!file) continue; + metadata.embeds.push({ + link: file, + original: file, + displayText: file, + position: { + start: { line: 0, col: 1, offset: 0 }, + end: { line: 0, col: 1, offset: index } + } + }); + } + return metadata; +} +async function resolveCanvasLinks(filepath) { + var _a, _b, _c, _d, _e; + const file = this.vault.getAbstractFileByPath(filepath); + if (!(file instanceof import_obsidian8.TFile)) return; + const metadata = this.getFileCache(file); + const references = [...(_a = metadata == null ? void 0 : metadata.links) != null ? _a : [], ...(_b = metadata == null ? void 0 : metadata.embeds) != null ? _b : []]; + const referenceLinks = references.map((ref) => ref.link).sort(); + const resolvedLinks = {}; + const unresolvedLinks = {}; + for (const link of referenceLinks) { + const resolved = this.getFirstLinkpathDest(link, filepath); + if (resolved) { + (_d = resolvedLinks[_c = resolved.path]) != null ? _d : resolvedLinks[_c] = 0; + resolvedLinks[resolved.path]++; + } else { + const strippedLink = link.endsWith(".md") ? link.slice(0, -3) : link; + (_e = unresolvedLinks[strippedLink]) != null ? _e : unresolvedLinks[strippedLink] = 0; + unresolvedLinks[strippedLink]++; + } + } + this.resolvedLinks[filepath] = resolvedLinks; + this.unresolvedLinks[filepath] = unresolvedLinks; + await sleep(1); + this.trigger("resolve", file); +} + +// src/patchers/backlinks-patcher.ts +var import_obsidian9 = require("obsidian"); +var BacklinksPatcher = class extends Patcher { + constructor() { + super(...arguments); + this.isRecomputingBacklinks = false; + } + async patch() { + if (!this.plugin.settings.getSetting("canvasMetadataCompatibilityEnabled")) return; + const that = this; + await Patcher.waitForViewRequest(this.plugin, "backlink", (view) => { + Patcher.patchPrototype(this.plugin, view.backlink, { + recomputeBacklink: Patcher.OverrideExisting((next) => function(file) { + that.isRecomputingBacklinks = true; + const result = invoke(next, this, file); + that.isRecomputingBacklinks = false; + return result; + }) + }); + }); + Patcher.patchPrototype(this.plugin, this.plugin.app.vault, { + recurseChildrenAC: (_next) => function(origin, traverse) { + for (let stack = [origin]; stack.length > 0; ) { + const current = stack.pop(); + if (current) { + traverse(current); + if (current instanceof import_obsidian9.TFolder) stack = stack.concat(current.children); + } + } + }, + getMarkdownFiles: Patcher.OverrideExisting((next) => function() { + if (!that.isRecomputingBacklinks) return invoke(next, this); + const files = []; + const root = this.getRoot(); + this.recurseChildrenAC(root, (child) => { + if (child instanceof import_obsidian9.TFile && (child.extension === "md" || child.extension === "canvas")) { + files.push(child); + } + }); + return files; + }) + }); + } +}; + +// src/patchers/outgoing-links-patcher.ts +var OutgoingLinksPatcher = class extends Patcher { + async patch() { + if (!this.plugin.settings.getSetting("canvasMetadataCompatibilityEnabled")) return; + await Patcher.waitForViewRequest(this.plugin, "outgoing-link", (view) => { + Patcher.patchPrototype(this.plugin, view.outgoingLink, { + recomputeLinks: Patcher.OverrideExisting((next) => function(...args) { + var _a; + const isCanvas = ((_a = this.file) == null ? void 0 : _a.extension) === "canvas"; + if (isCanvas) this.file.extension = "md"; + const result = invoke(next, this, ...args); + if (isCanvas) this.file.extension = "canvas"; + return result; + }), + recomputeUnlinked: Patcher.OverrideExisting((next) => function(...args) { + var _a; + const isCanvas = ((_a = this.file) == null ? void 0 : _a.extension) === "canvas"; + if (isCanvas) this.file.extension = "md"; + const result = invoke(next, this, ...args); + if (isCanvas) this.file.extension = "canvas"; + return result; + }) + }); + }); + } +}; + +// src/patchers/file-manager-patcher.ts +var FileManagerPatcher = class extends Patcher { + async patch() { + if (!this.plugin.settings.getSetting("canvasMetadataCompatibilityEnabled")) return; + const that = this; + Patcher.patch(this.plugin, this.plugin.app.fileManager, { + processFrontMatter: Patcher.OverrideExisting((next) => async function(file, fn, options) { + if ((file == null ? void 0 : file.extension) === "canvas") { + that.plugin.app.vault.process(file, (data) => { + const content = JSON.parse(data); + fn(content.metadata.frontmatter); + return JSON.stringify(content, null, 2); + }).catch(() => console.error("Failed to update metadata object in canvas file.")); + return; + } + return invoke(next, this, file, fn, options); + }) + }); + } +}; + +// src/patchers/properties-patcher.ts +var PropertiesPatcher = class extends Patcher { + async patch() { + if (!this.plugin.settings.getSetting("canvasMetadataCompatibilityEnabled")) return; + if (!this.plugin.app.viewRegistry.viewByType["file-properties"]) return; + await Patcher.waitForViewRequest(this.plugin, "file-properties", (view) => { + Patcher.patchPrototype(this.plugin, view, { + isSupportedFile: Patcher.OverrideExisting((next) => function(file) { + if ((file == null ? void 0 : file.extension) === "canvas") return true; + return invoke(next, this, file); + }), + updateFrontmatter: Patcher.OverrideExisting((next) => function(file, content) { + var _a, _b, _c; + if ((file == null ? void 0 : file.extension) === "canvas") { + let frontmatter; + try { + frontmatter = (_c = (_b = (_a = JSON.parse(content)) == null ? void 0 : _a.metadata) == null ? void 0 : _b.frontmatter) != null ? _c : {}; + } catch (e) { + frontmatter = {}; + } + this.rawFrontmatter = JSON.stringify(frontmatter, null, 2); + this.frontmatter = frontmatter; + return frontmatter; + } + return invoke(next, this, file, content); + }), + saveFrontmatter: Patcher.OverrideExisting((next) => function(frontmatter) { + var _a; + if (((_a = this.file) == null ? void 0 : _a.extension) === "canvas") { + if (this.file !== this.modifyingFile) return; + this.app.vault.process(this.file, (data) => { + const content = JSON.parse(data); + if (content == null ? void 0 : content.metadata) content.metadata.frontmatter = frontmatter; + return JSON.stringify(content, null, 2); + }).catch(() => console.error("Failed to update metadata object in canvas file.")); + return; + } + return invoke(next, this, frontmatter); + }) + }); + }); + } +}; + +// src/patchers/search-patcher.ts +var SearchPatcher = class extends Patcher { + async patch() { + if (!this.plugin.settings.getSetting("canvasMetadataCompatibilityEnabled")) return; + const that = this; + await Patcher.waitForViewRequest(this.plugin, "search", (view) => { + const uninstallers = []; + Patcher.patchThisAndPrototype(this.plugin, view, { + startSearch: (next) => function(...args) { + const result = invoke(next, this, ...args); + if (this.searchQuery) { + that.patchSearchQuery(this.searchQuery); + uninstallers.forEach((uninstall) => uninstall()); + } + return result; + } + }, uninstallers); + }); + } + patchSearchQuery(searchQuery) { + Patcher.patchThisAndPrototype(this.plugin, searchQuery, { + _match: Patcher.OverrideExisting((next) => function(data) { + var _a, _b; + const isCanvas = (_b = (_a = data.strings.filepath) == null ? void 0 : _a.endsWith(".canvas")) != null ? _b : false; + if (isCanvas && !data.cache) + data.cache = this.app.metadataCache.getCache(data.strings.filepath); + return invoke(next, this, data); + }) + }); + } +}; + +// src/patchers/search-command-patcher.ts +var import_obsidian10 = require("obsidian"); +var SearchCommandPatcher = class extends Patcher { + async patch() { + if (!this.plugin.settings.getSetting("nativeFileSearchEnabled")) return; + const that = this; + const searchCommand = this.plugin.app.commands.commands["editor:open-search"]; + if (!(searchCommand == null ? void 0 : searchCommand.checkCallback)) return; + const originalCallback = searchCommand.checkCallback; + searchCommand.checkCallback = function(checking) { + if (that.plugin.app.workspace.activeEditor) return invoke(originalCallback, this, checking); + const activeCanvasView = that.plugin.getCurrentCanvasView(); + if (!activeCanvasView) return invoke(originalCallback, this, checking); + if (checking) return true; + if (!activeCanvasView.canvas.searchEl) new CanvasSearchView(activeCanvasView); + return true; + }; + that.plugin.register(() => { + searchCommand.checkCallback = originalCallback; + }); + } +}; +var CanvasSearchView = class { + constructor(view) { + this.debouncing = false; + this.searchMatches = []; + this.matchIndex = 0; + this.view = view; + this.createSearchView(); + } + createSearchView() { + this.containerEl = this.view.canvas.wrapperEl.createDiv(); + this.containerEl.className = "document-search-container"; + const documentSearch = this.containerEl.createDiv(); + documentSearch.className = "document-search"; + const searchInputContainer = documentSearch.createDiv(); + searchInputContainer.className = "search-input-container document-search-input"; + this.searchInput = searchInputContainer.createEl("input"); + this.searchInput.type = "text"; + this.searchInput.placeholder = "Find..."; + this.searchInput.addEventListener("keydown", (e) => this.onKeyDown(e)); + const debouncedOnInput = (0, import_obsidian10.debounce)(() => this.onInput(), 200, true); + this.searchInput.addEventListener("input", debouncedOnInput); + this.searchCount = searchInputContainer.createDiv(); + this.searchCount.className = "document-search-count"; + this.searchCount.toggleClass("is-hidden", true); + this.searchCount.textContent = "0 / 0"; + const documentSearchButtons = documentSearch.createDiv(); + documentSearchButtons.className = "document-search-buttons"; + const previousButton = documentSearchButtons.createEl("button"); + previousButton.className = "clickable-icon document-search-button"; + previousButton.setAttribute("aria-label", "Previous\nShift + F3"); + previousButton.setAttribute("data-tooltip-position", "top"); + (0, import_obsidian10.setIcon)(previousButton, "arrow-up"); + previousButton.addEventListener("click", () => this.changeMatch(this.matchIndex - 1)); + const nextButton = documentSearchButtons.createEl("button"); + nextButton.className = "clickable-icon document-search-button"; + nextButton.setAttribute("aria-label", "Next\nF3"); + nextButton.setAttribute("data-tooltip-position", "top"); + (0, import_obsidian10.setIcon)(nextButton, "arrow-down"); + nextButton.addEventListener("click", () => this.changeMatch(this.matchIndex + 1)); + const closeButton = documentSearch.createEl("button"); + closeButton.className = "clickable-icon document-search-close-button"; + closeButton.setAttribute("aria-label", "Exit search"); + closeButton.setAttribute("data-tooltip-position", "top"); + (0, import_obsidian10.setIcon)(closeButton, "x"); + closeButton.addEventListener("click", () => this.close()); + this.view.canvas.searchEl = this.containerEl; + this.searchInput.focus(); + } + onKeyDown(e) { + if (e.key === "Enter" || e.key === "F3") + this.changeMatch(this.matchIndex + (e.shiftKey ? -1 : 1)); + else if (e.key === "Escape") + this.close(); + else this.debouncing = false; + } + onInput() { + this.debouncing = false; + const hasQuery = this.searchInput.value.length > 0; + this.searchCount.toggleClass("is-hidden", !hasQuery); + if (!hasQuery) { + this.searchMatches = []; + return; + } + const regex = new RegExp(this.searchInput.value, "gi"); + const matchesList = []; + for (const node of this.view.canvas.nodes.values()) { + const nodeData = node.getData(); + let content = void 0; + if (nodeData.type === "text") content = nodeData.text; + else if (nodeData.type === "group") content = nodeData.label; + else if (nodeData.type === "file") content = node.child.data; + if (!content) continue; + regex.lastIndex = 0; + const matches = []; + let match; + while ((match = regex.exec(content)) !== null) + matches.push([match.index, match.index + match[0].length]); + if (matches.length === 0) continue; + matchesList.push({ nodeId: node.id, content, matches }); + } + this.searchMatches = matchesList; + this.changeMatch(0); + } + changeMatch(index) { + if (this.debouncing) this.onInput(); + if (this.searchMatches.length === 0) this.matchIndex = -1; + else { + if (index < 0) index += this.searchMatches.length; + this.matchIndex = index % this.searchMatches.length; + } + const match = this.searchMatches[this.matchIndex]; + if (match) this.goToMatch(match); + this.searchCount.textContent = `${this.matchIndex + 1} / ${this.searchMatches.length}`; + } + goToMatch(match) { + this.view.setEphemeralState({ match }); + } + close() { + this.containerEl.remove(); + this.view.canvas.searchEl = void 0; + } +}; + +// src/canvas-extensions/metadata-canvas-extension.ts +var import_obsidian11 = require("obsidian"); +var MetadataCanvasExtension = class extends CanvasExtension { + constructor() { + super(...arguments); + this.canvasCssclassesCache = /* @__PURE__ */ new Map(); + } + isEnabled() { + return true; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:canvas-changed", + (canvas) => this.onCanvasChanged(canvas) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:canvas-metadata-changed", + (canvas) => this.onMetadataChanged(canvas) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:canvas-view-unloaded:before", + (view) => this.onCanvasViewUnloaded(view) + )); + } + onCanvasChanged(canvas) { + var _a; + const metadata = (_a = canvas.getData()) == null ? void 0 : _a.metadata; + if (!metadata || metadata.version !== CURRENT_SPEC_VERSION) + return void new import_obsidian11.Notice("Metadata node not found or version mismatch. Should have been migrated (but wasn't)."); + const that = this; + const validator = { + get(target, key) { + if (typeof target[key] === "object" && target[key] !== null) + return new Proxy(target[key], validator); + else return target[key]; + }, + set(target, key, value) { + target[key] = value; + that.plugin.app.workspace.trigger("advanced-canvas:canvas-metadata-changed", canvas); + canvas.requestSave(); + return true; + } + }; + canvas.metadata = new Proxy(metadata, validator); + this.plugin.app.workspace.trigger("advanced-canvas:canvas-metadata-changed", canvas); + } + onMetadataChanged(canvas) { + var _a, _b; + const oldCssClasses = this.canvasCssclassesCache.get(canvas.view); + if (oldCssClasses) canvas.wrapperEl.classList.remove(...oldCssClasses); + const rawClasses = (_b = (_a = canvas.metadata) == null ? void 0 : _a.frontmatter) == null ? void 0 : _b.cssclasses; + const currentClasses = Array.isArray(rawClasses) ? rawClasses : typeof rawClasses === "string" ? rawClasses.split(/\s+/).filter((cls) => cls) : []; + this.canvasCssclassesCache.set(canvas.view, currentClasses); + if (currentClasses.length > 0) canvas.wrapperEl.classList.add(...currentClasses); + } + onCanvasViewUnloaded(view) { + this.canvasCssclassesCache.delete(view); + } +}; + +// src/utils/modal-helper.ts +var import_obsidian12 = require("obsidian"); +var AbstractSelectionModal = class extends import_obsidian12.FuzzySuggestModal { + constructor(app, placeholder, suggestions, arbitrary = false) { + super(app); + this.suggestions = suggestions; + this.arbitrary = arbitrary; + this.setPlaceholder(placeholder); + this.setInstructions([{ + command: "\u2191\u2193", + purpose: "to navigate" + }, { + command: "esc", + purpose: "to dismiss" + }]); + } + getItems() { + return this.suggestions; + } + getItemText(item) { + return item; + } + getSuggestions(query) { + const suggestions = super.getSuggestions(query); + if (this.arbitrary && query.length > 0 && !suggestions.some((s) => s.item === query)) + suggestions.splice(0, 0, { item: query, match: { score: 1, matches: [[0, query.length]] } }); + return suggestions; + } + onChooseItem(_item, _evt) { + } + get promise() { + return new Promise((resolve, _reject) => { + this.onChooseItem = (item) => resolve(item); + this.open(); + }); + } +}; +var FileNameModal = class extends import_obsidian12.SuggestModal { + constructor(app, parentPath, fileExtension) { + super(app); + this.parentPath = parentPath.replace(/^\//, "").replace(/\/$/, ""); + this.fileExtension = fileExtension; + } + getSuggestions(query) { + const queryWithoutExtension = query.replace(new RegExp(`\\.${this.fileExtension}$`), ""); + if (queryWithoutExtension === "") return []; + const queryWithExtension = queryWithoutExtension + "." + this.fileExtension; + const suggestions = [queryWithExtension]; + if (this.parentPath.length > 0) suggestions.splice(0, 0, `${this.parentPath}/${queryWithExtension}`); + return suggestions.filter((s) => this.app.vault.getAbstractFileByPath(s) === null); + } + renderSuggestion(text, el) { + el.setText(text); + } + onChooseSuggestion(_text, _evt) { + } + get promise() { + return new Promise((resolve, _reject) => { + this.onChooseSuggestion = (text) => { + resolve(text); + }; + this.open(); + }); + } +}; +var FileSelectModal = class extends import_obsidian12.SuggestModal { + constructor(app, extensionsRegex, suggestNewFile = false) { + super(app); + this.files = this.app.vault.getFiles().filter((file) => { + var _a; + return (_a = file == null ? void 0 : file.extension) == null ? void 0 : _a.match(extensionsRegex != null ? extensionsRegex : /.*/); + }).map((file) => file.path); + this.suggestNewFile = suggestNewFile; + this.setPlaceholder("Type to search..."); + this.setInstructions([{ + command: "\u2191\u2193", + purpose: "to navigate" + }, { + command: "\u21B5", + purpose: "to open" + }, { + command: "shift \u21B5", + purpose: "to create" + }, { + command: "esc", + purpose: "to dismiss" + }]); + this.scope.register(["Shift"], "Enter", (e) => { + this.onChooseSuggestion(this.inputEl.value, e); + this.close(); + }); + } + getSuggestions(query) { + const suggestions = this.files.filter((path) => path.toLowerCase().includes(query.toLowerCase())); + if (suggestions.length === 0 && this.suggestNewFile) suggestions.push(query); + return suggestions; + } + renderSuggestion(path, el) { + const simplifiedPath = path.replace(/\.md$/, ""); + el.setText(simplifiedPath); + } + onChooseSuggestion(_path, _evt) { + } + get promise() { + return new Promise((resolve, _reject) => { + this.onChooseSuggestion = (path, _evt) => { + const file = this.app.vault.getAbstractFileByPath(path); + if (file instanceof import_obsidian12.TFile) + return resolve(file); + if (!this.suggestNewFile) return; + if (FilepathHelper.extension(path) === void 0) path += ".md"; + const newFile = this.app.vault.create(path, ""); + resolve(newFile); + }; + this.open(); + }); + } +}; + +// src/canvas-extensions/node-ratio-canvas-extension.ts +var NodeRatioCanvasExtension = class extends CanvasExtension { + isEnabled() { + return true; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "canvas:node-menu", + (menu, node) => this.onNodeMenu(menu, node) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-resized", + (canvas, node) => this.onNodeResized(canvas, node) + )); + } + onNodeMenu(menu, node) { + if (!this.plugin.settings.getSetting("aspectRatioControlFeatureEnabled")) return; + menu.addItem((item) => { + item.setTitle("Set aspect ratio").setIcon("aspect-ratio").onClick(async () => { + const NO_RATIO = "No ratio enforcement"; + const newRatioString = await new AbstractSelectionModal(this.plugin.app, "Enter aspect ratio (width:height)", ["16:9", "4:3", "3:2", "1:1", NO_RATIO]).promise; + const nodeData = node.getData(); + if (newRatioString === NO_RATIO) { + node.setData({ + ...nodeData, + ratio: void 0 + }); + return; + } + const [width, height] = newRatioString.split(":").map(Number); + if (width && height) { + node.setData({ + ...nodeData, + ratio: width / height + }); + node.setData({ + ...node.getData(), + width: nodeData.height * (width / height) + }); + } + }); + }); + } + onNodeResized(_canvas, node) { + const nodeData = node.getData(); + if (!nodeData.ratio) return; + const nodeSize = { width: node.width, height: node.height }; + const nodeAspectRatio = nodeSize.width / nodeSize.height; + if (nodeAspectRatio < nodeData.ratio) + nodeSize.width = nodeSize.height * nodeData.ratio; + else nodeSize.height = nodeSize.width / nodeData.ratio; + node.setData({ + ...nodeData, + width: nodeSize.width, + height: nodeSize.height + }); + } +}; + +// src/canvas-extensions/group-canvas-extension.ts +var GROUP_NODE_SIZE = { width: 300, height: 300 }; +var GROUP_NODE_PADDING = 20; +var GroupCanvasExtension = class extends CanvasExtension { + isEnabled() { + return true; + } + init() { + this.plugin.addCommand({ + id: "create-group-around-selection", + name: "Group selected nodes", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => canvas.selection.size > 0, + (canvas) => this.createGroupAroundSelection(canvas) + ) + }); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:canvas-changed", + (canvas) => { + CanvasHelper.addCardMenuOption( + canvas, + CanvasHelper.createCardMenuOption( + canvas, + { + id: "create-group", + label: "Drag to add group", + icon: "group" + }, + () => GROUP_NODE_SIZE, + (canvas2, pos) => { + canvas2.createGroupNode({ + pos, + size: GROUP_NODE_SIZE + }); + } + ) + ); + } + )); + } + createGroupAroundSelection(canvas) { + const bbox = BBoxHelper.combineBBoxes( + Array.from(canvas.selection.values()).map((e) => e.getBBox()) + ); + const paddedBBox = BBoxHelper.enlargeBBox(bbox, GROUP_NODE_PADDING); + canvas.createGroupNode({ + pos: { x: paddedBBox.minX, y: paddedBBox.minY }, + size: { + width: paddedBBox.maxX - paddedBBox.minX, + height: paddedBBox.maxY - paddedBBox.minY + } + }); + } +}; + +// src/canvas-extensions/node-templates-canvas-extension.ts +var import_obsidian13 = require("obsidian"); +var TEMPLATE_NODE_BUTTON_ID_PREFIX = "create-template-node-"; +var NodeTemplatesCanvasExtension = class extends CanvasExtension { + isEnabled() { + return true; + } + init() { + this.plugin.addCommand({ + id: "save-node-as-template", + name: "Save node as template", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => canvas.getSelectionData().nodes.length === 1, + (canvas) => void this.saveNodeAsTemplate(canvas) + ) + }); + this.registeredNodeTemplateCommandIds = []; + this.registerNodeTemplateCommands(); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:canvas-changed", + (canvas) => this.onCardMenuCreated(canvas) + )); + } + registerNodeTemplateCommands() { + for (const commandId of this.registeredNodeTemplateCommandIds) + this.plugin.removeCommand(commandId); + this.registeredNodeTemplateCommandIds = []; + const templates = this.plugin.settings.getSetting("nodeTemplates"); + for (let i = 0; i < templates.length; i++) { + const template = templates[i]; + const commandId = `create-template-node-${i}`; + this.plugin.addCommand({ + id: commandId, + name: "Create template node " + (template.label ? `"${template.label}"` : i + 1), + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (_) => true, + (canvas) => { + const center = canvas.posCenter(); + void this.createNodeFromTemplate( + canvas, + template, + { + x: center.x - template.width / 2, + y: center.y - template.height / 2 + } + ); + } + ) + }); + this.registeredNodeTemplateCommandIds.push(commandId); + } + } + onCardMenuCreated(canvas) { + var _a; + const existingButtons = canvas.cardMenuEl.querySelectorAll(`[id^="${TEMPLATE_NODE_BUTTON_ID_PREFIX}"]`); + existingButtons.forEach((button) => button.remove()); + const templates = this.plugin.settings.getSetting("nodeTemplates"); + for (let i = 0; i < templates.length; i++) { + const template = templates[i]; + CanvasHelper.addCardMenuOption( + canvas, + CanvasHelper.createCardMenuOption( + canvas, + { + id: `${TEMPLATE_NODE_BUTTON_ID_PREFIX}${i}`, + label: "Drag to add template node " + (template.label ? `"${template.label}"` : i + 1), + icon: (_a = template.icon) != null ? _a : "book-dashed" + }, + () => ({ width: template.width, height: template.height }), + (canvas2, pos) => void this.createNodeFromTemplate(canvas2, template, pos), + (e) => this.createTemplateContextMenu(e) + ) + ); + } + } + async createNodeFromTemplate(canvas, template, pos) { + var _a; + const creationOptions = { + pos, + size: { + width: template.width, + height: template.height + } + }; + let node; + if (template.type === "text") node = canvas.createTextNode(creationOptions); + else if (template.type === "file") { + let tfile; + if (template.path) { + const abstractFile = this.plugin.app.vault.getAbstractFileByPath(template.path); + if (abstractFile instanceof import_obsidian13.TFile) tfile = abstractFile; + } + tfile != null ? tfile : tfile = await new FileSelectModal(this.plugin.app, void 0, true).promise; + node = canvas.createFileNode({ ...creationOptions, file: tfile }); + } else if (template.type === "group") node = canvas.createGroupNode(creationOptions); + else if (template.type === "link") node = canvas.createLinkNode({ ...creationOptions, url: template.url }); + else throw new Error(`Unknown template type: ${template.type}`); + const data = node.getData(); + node.setData( + { + ...data, + color: (_a = template.color) != null ? _a : data.color, + styleAttributes: { + ...data.styleAttributes, + ...template.styleAttributes + } + }, + false + /* addHistory */ + ); + } + createTemplateContextMenu(e) { + const menu = new import_obsidian13.Menu(); + menu.addItem( + (item) => item.setTitle("Remove").setIcon("trash").onClick(async () => { + const buttonEl = e.target; + const index = parseInt(buttonEl.id.replace(TEMPLATE_NODE_BUTTON_ID_PREFIX, "")); + const templates = this.plugin.settings.getSetting("nodeTemplates"); + templates.splice(index, 1); + await this.plugin.settings.setSetting({ nodeTemplates: templates }); + const canvas = this.plugin.getCurrentCanvas(); + if (canvas) this.onCardMenuCreated(canvas); + }) + ); + menu.showAtMouseEvent(e); + } + async saveNodeAsTemplate(canvas) { + const selectedNodeData = canvas.getSelectionData().nodes[0]; + const icon = await new IconModal(this.plugin.app).promise; + if (!icon) { + new import_obsidian13.Notice("No icon selected, template creation cancelled."); + return; + } + const label = await new AbstractSelectionModal(this.plugin.app, "Set template label (optional)", [], true).promise; + await this.plugin.settings.setSetting({ + nodeTemplates: [ + ...this.plugin.settings.getSetting("nodeTemplates"), + { + icon, + label: label != null ? label : void 0, + type: selectedNodeData.type, + width: selectedNodeData.width, + height: selectedNodeData.height, + color: selectedNodeData.color, + styleAttributes: selectedNodeData.styleAttributes, + path: selectedNodeData.type === "file" ? selectedNodeData.file : void 0, + url: selectedNodeData.type === "link" ? selectedNodeData.url : void 0 + } + ] + }); + this.registerNodeTemplateCommands(); + this.onCardMenuCreated(canvas); + } +}; +var IconModal = class extends import_obsidian13.FuzzySuggestModal { + constructor(app) { + super(app); + this.setPlaceholder("Set template icon"); + } + getItems() { + return (0, import_obsidian13.getIconIds)(); + } + getItemText(item) { + return item; + } + renderSuggestion(item, el) { + el.classList.add("icon-modal-suggestion"); + el.createSpan({ cls: "icon-modal-suggestion-icon" }, (iconEl) => { + (0, import_obsidian13.setIcon)(iconEl, item.item); + }); + el.createSpan({ + text: item.item.replace("lucide-", ""), + cls: "icon-modal-suggestion-id" + }); + } + onChooseItem(_item, _evt) { + } + get promise() { + return new Promise((resolve, _reject) => { + this.onChooseItem = (item, _evt) => { + resolve(item); + }; + this.onClose = () => window.setTimeout(() => { + resolve(null); + }, 10); + this.open(); + }); + } +}; + +// src/canvas-extensions/presentation-canvas-extension.ts +var import_obsidian14 = require("obsidian"); +var START_SLIDE_NAME = "Start Slide"; +var DEFAULT_SLIDE_NAME = "New Slide"; +var ARROW_SIDE_MAPPINGS = { + "ArrowRight": "right", + "ArrowDown": "bottom", + "ArrowLeft": "left", + "ArrowUp": "top" +}; +var PresentationCanvasExtension = class extends CanvasExtension { + constructor() { + super(...arguments); + this.savedViewport = { x: 0, y: 0, zoom: 1 }; + this.isPresentationMode = false; + this.visitedNodeIds = []; + this.traveledEdges = []; + this.fullscreenModalObserver = null; + this.presentationUsesFullscreen = false; + } + isEnabled() { + return "presentationFeatureEnabled"; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "canvas:selection-menu", + (menu, canvas) => { + menu.addItem( + (item) => item.setTitle("Wrap in slide").setIcon("gallery-vertical").onClick(() => this.addSlide( + canvas, + void 0, + BBoxHelper.enlargeBBox(BBoxHelper.combineBBoxes( + [...canvas.selection.values()].map((element) => element.getBBox()) + ), this.plugin.settings.getSetting("wrapInSlidePadding")) + )) + ); + } + )); + this.plugin.addCommand({ + id: "create-new-slide", + name: "Create new slide", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => !canvas.readonly && !this.isPresentationMode, + (canvas) => this.addSlide(canvas) + ) + }); + this.plugin.addCommand({ + id: "set-start-node", + name: "Set start node", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => !canvas.readonly && !this.isPresentationMode && canvas.getSelectionData().nodes.length === 1, + (canvas) => this.setStartNode(canvas, canvas.nodes.get(canvas.getSelectionData().nodes[0].id)) + ) + }); + this.plugin.addCommand({ + id: "start-presentation", + name: "Start presentation", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (_canvas) => !this.isPresentationMode, + (canvas) => void this.startPresentation(canvas) + ) + }); + this.plugin.addCommand({ + id: "continue-presentation", + name: "Continue presentation", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (_canvas) => !this.isPresentationMode, + (canvas) => void this.startPresentation(canvas, true) + ) + }); + this.plugin.addCommand({ + id: "end-presentation", + name: "End presentation", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (_canvas) => this.isPresentationMode, + (canvas) => this.endPresentation(canvas) + ) + }); + this.plugin.addCommand({ + id: "previous-node", + name: "Previous node", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (_canvas) => this.isPresentationMode, + (canvas) => this.previousNode(canvas) + ) + }); + this.plugin.addCommand({ + id: "next-node", + name: "Next node", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (_canvas) => this.isPresentationMode, + (canvas) => this.nextNode(canvas) + ) + }); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:canvas-changed", + (canvas) => this.onCanvasChanged(canvas) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:popup-menu-created", + (canvas) => this.onPopupMenuCreated(canvas) + )); + } + onCanvasChanged(canvas) { + CanvasHelper.addCardMenuOption( + canvas, + CanvasHelper.createCardMenuOption( + canvas, + { + id: "new-slide", + label: "Drag to add slide", + icon: "gallery-vertical" + }, + () => this.getDefaultSlideSize(), + (canvas2, pos) => this.addSlide(canvas2, pos) + ) + ); + } + onPopupMenuCreated(canvas) { + if (!this.plugin.settings.getSetting("showSetStartNodeInPopup")) return; + const selectedNodesData = canvas.getSelectionData().nodes; + if (canvas.readonly || selectedNodesData.length !== 1 || canvas.selection.size > 1) return; + const selectedNode = canvas.nodes.get(selectedNodesData[0].id); + if (!selectedNode) return; + CanvasHelper.addPopupMenuOption( + canvas, + CanvasHelper.createPopupMenuOption({ + id: "start-node", + label: "Set as start slide", + icon: "play", + callback: () => this.setStartNode(canvas, selectedNode) + }) + ); + } + setStartNode(canvas, node) { + if (!node) return; + canvas.metadata["startNode"] = node.getData().id; + } + getDefaultSlideSize() { + const slideSize = this.plugin.settings.getSetting("defaultSlideDimensions"); + return { width: slideSize[0], height: slideSize[1] }; + } + getSlideAspectRatio() { + const slideSize = this.getDefaultSlideSize(); + return slideSize.width / slideSize.height; + } + addSlide(canvas, pos, bbox) { + const isStartNode = canvas.metadata["startNode"] === void 0; + const slideSize = this.getDefaultSlideSize(); + const slideAspectRatio = this.getSlideAspectRatio(); + if (bbox) { + const bboxWidth = bbox.maxX - bbox.minX; + const bboxHeight = bbox.maxY - bbox.minY; + if (bboxWidth / bboxHeight > slideAspectRatio) { + slideSize.width = bboxWidth; + slideSize.height = bboxWidth / slideAspectRatio; + } else { + slideSize.height = bboxHeight; + slideSize.width = bboxHeight * slideAspectRatio; + } + pos = { + x: bbox.minX, + y: bbox.minY + }; + } + if (!pos) pos = CanvasHelper.getCenterCoordinates(canvas, this.getDefaultSlideSize()); + const groupNode = canvas.createGroupNode({ + pos, + size: slideSize, + label: isStartNode ? START_SLIDE_NAME : DEFAULT_SLIDE_NAME, + focus: false + }); + groupNode.setData({ + ...groupNode.getData(), + ratio: slideAspectRatio + }); + if (isStartNode) canvas.metadata["startNode"] = groupNode.getData().id; + } + async animateNodeTransition(canvas, fromNode, toNode) { + const removePadding = this.plugin.settings.getSetting("zoomToSlideWithoutPadding"); + const animationDurationMs = this.plugin.settings.getSetting("slideTransitionAnimationDuration") * 1e3; + const toNodeBBox = CanvasHelper.getSmallestAllowedZoomBBox(canvas, toNode.getBBox()); + const toNodeBBoxPadded = removePadding ? toNodeBBox : BBoxHelper.enlargeBBox(toNodeBBox, 50); + if (animationDurationMs > 0 && fromNode) { + const animationIntensity = this.plugin.settings.getSetting("slideTransitionAnimationIntensity"); + const fromNodeBBox = CanvasHelper.getSmallestAllowedZoomBBox(canvas, fromNode.getBBox()); + const fromNodeBBoxPadded = removePadding ? fromNodeBBox : BBoxHelper.enlargeBBox(fromNodeBBox, 50); + const currentNodeBBoxEnlarged = BBoxHelper.scaleBBox(fromNodeBBoxPadded, animationIntensity); + canvas.zoomToRealBbox(currentNodeBBoxEnlarged); + await sleep(animationDurationMs / 2); + if (fromNode.getData().id !== toNode.getData().id) { + const nextNodeBBoxEnlarged = BBoxHelper.scaleBBox(toNodeBBoxPadded, animationIntensity); + canvas.zoomToRealBbox(nextNodeBBoxEnlarged); + await sleep(animationDurationMs / 2); + } + } + canvas.zoomToRealBbox(toNodeBBoxPadded); + } + async startPresentation(canvas, tryContinue = false) { + if (!tryContinue || this.visitedNodeIds.length === 0) { + const startNode2 = canvas.metadata["startNode"] && canvas.nodes.get(canvas.metadata["startNode"]); + if (!startNode2) { + new import_obsidian14.Notice("No start node found. Please mark a node as a start node through the popup menu."); + return; + } + this.visitedNodeIds = [startNode2.getData().id]; + this.traveledEdges = []; + } + this.savedViewport = { + x: canvas.tx, + y: canvas.ty, + zoom: canvas.tZoom + }; + const shouldEnterFullscreen = this.plugin.settings.getSetting("fullscreenPresentationEnabled"); + this.presentationUsesFullscreen = shouldEnterFullscreen; + canvas.wrapperEl.focus(); + canvas.wrapperEl.classList.add("presentation-mode"); + if (shouldEnterFullscreen) { + try { + await canvas.wrapperEl.requestFullscreen(); + } catch (e) { + this.presentationUsesFullscreen = false; + } + } + canvas.setReadonly(true); + if (this.plugin.settings.getSetting("useUnclampedZoomWhilePresenting")) + canvas.screenshotting = true; + canvas.wrapperEl.onkeydown = (e) => { + if (e.key === "Escape") { + e.preventDefault(); + e.stopPropagation(); + this.endPresentation(canvas); + return; + } + if (this.plugin.settings.getSetting("useArrowKeysToChangeSlides")) { + const direction = ARROW_SIDE_MAPPINGS[e.key]; + if (!direction) return; + this.nextNode(canvas, direction); + } + if (this.plugin.settings.getSetting("usePgUpPgDownKeysToChangeSlides")) { + if (e.key === "PageDown") this.nextNode(canvas); + else if (e.key === "PageUp") this.previousNode(canvas); + } + }; + if (this.presentationUsesFullscreen) { + this.fullscreenModalObserver = new MutationObserver((mutationRecords) => { + mutationRecords.forEach((mutationRecord) => { + mutationRecord.addedNodes.forEach((node) => { + var _a; + activeDocument.body.removeChild(node); + (_a = activeDocument.fullscreenElement) == null ? void 0 : _a.appendChild(node); + }); + }); + const inputField = activeDocument.querySelector(".prompt-input"); + if (inputField) inputField.focus(); + }); + this.fullscreenModalObserver.observe(activeDocument.body, { childList: true }); + canvas.wrapperEl.onfullscreenchange = (_e) => { + if (activeDocument.fullscreenElement) return; + this.endPresentation(canvas); + }; + } + this.isPresentationMode = true; + if (this.presentationUsesFullscreen) + await sleep(500); + const startNodeId = this.visitedNodeIds.first(); + if (!startNodeId) return; + const startNode = canvas.nodes.get(startNodeId); + if (!startNode) return; + void this.animateNodeTransition(canvas, void 0, startNode); + } + endPresentation(canvas) { + var _a; + if (!this.isPresentationMode) return; + if (this.presentationUsesFullscreen) { + (_a = this.fullscreenModalObserver) == null ? void 0 : _a.disconnect(); + this.fullscreenModalObserver = null; + canvas.wrapperEl.onfullscreenchange = null; + if (activeDocument.fullscreenElement) void activeDocument.exitFullscreen(); + } + canvas.wrapperEl.onkeydown = null; + canvas.setReadonly(false); + if (this.plugin.settings.getSetting("useUnclampedZoomWhilePresenting")) + canvas.screenshotting = false; + canvas.wrapperEl.classList.remove("presentation-mode"); + if (this.plugin.settings.getSetting("resetViewportOnPresentationEnd")) + canvas.setViewport(this.savedViewport.x, this.savedViewport.y, this.savedViewport.zoom); + this.isPresentationMode = false; + this.presentationUsesFullscreen = false; + } + getNextUntraveledEdge(edges) { + var _a; + return (_a = edges.filter( + (edge) => !this.traveledEdges.includes(edge.getData().id) + ).first()) != null ? _a : edges.last(); + } + nextNode(canvas, direction) { + var _a, _b, _c, _d; + const directionalNavigationEnabled = this.plugin.settings.getSetting("useDirectionalSlideNavigation"); + if (!directionalNavigationEnabled && direction === "left") + return this.previousNode(canvas); + const fromNodeId = this.visitedNodeIds.last(); + if (!fromNodeId) return; + const fromNode = canvas.nodes.get(fromNodeId); + if (!fromNode) return; + const outgoingEdges = canvas.getEdgesForNode(fromNode).filter((edge) => edge.from.node.getData().id === fromNodeId); + let toNode = (_a = outgoingEdges.first()) == null ? void 0 : _a.to.node; + const sortedOutgoingEdges = outgoingEdges.sort((a, b) => { + if (!a.label) return 1; + if (!b.label) return -1; + return a.label.localeCompare(b.label); + }); + let nextEdge; + if (directionalNavigationEnabled && direction) { + const directionCompliantEdges = sortedOutgoingEdges.filter((edge) => edge.from.side === direction); + nextEdge = this.getNextUntraveledEdge(directionCompliantEdges); + toNode = (_b = nextEdge == null ? void 0 : nextEdge.to) == null ? void 0 : _b.node; + if (!nextEdge) { + const bidirectionalEdges = canvas.getEdgesForNode(fromNode).filter( + (edge) => edge.to.node.getData().id === fromNodeId && edge.to.end === "arrow" && edge.to.side === direction + ); + nextEdge = this.getNextUntraveledEdge(bidirectionalEdges); + toNode = (_c = nextEdge == null ? void 0 : nextEdge.from) == null ? void 0 : _c.node; + } + } + if (!nextEdge && outgoingEdges.length > 1) { + nextEdge != null ? nextEdge : nextEdge = this.getNextUntraveledEdge(sortedOutgoingEdges); + toNode = (_d = nextEdge == null ? void 0 : nextEdge.to) == null ? void 0 : _d.node; + } + if (nextEdge) this.traveledEdges.push(nextEdge.getData().id); + if (toNode) { + this.visitedNodeIds.push(toNode.getData().id); + void this.animateNodeTransition(canvas, fromNode, toNode); + } else { + void this.animateNodeTransition(canvas, fromNode, fromNode); + } + } + previousNode(canvas) { + const fromNodeId = this.visitedNodeIds.pop(); + if (!fromNodeId) return; + this.traveledEdges.pop(); + const fromNode = canvas.nodes.get(fromNodeId); + if (!fromNode) return; + const toNodeId = this.visitedNodeIds.last(); + let toNode = toNodeId ? canvas.nodes.get(toNodeId) : null; + if (!toNode) { + toNode = fromNode; + this.visitedNodeIds.push(fromNodeId); + } + void this.animateNodeTransition(canvas, fromNode, toNode); + } +}; + +// src/canvas-extensions/z-ordering-canvas-extension.ts +var ZOrderingCanvasExtension = class extends CanvasExtension { + isEnabled() { + return "zOrderingControlFeatureEnabled"; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "canvas:node-menu", + (menu, node) => this.nodeContextMenu(node, menu) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "canvas:selection-menu", + (menu, canvas) => this.selectionContextMenu(canvas, menu) + )); + } + nodeContextMenu(node, menu) { + this.addZOrderingContextMenuItems(node.canvas, [node], menu); + } + selectionContextMenu(canvas, menu) { + const selectedNodes = canvas.getSelectionData().nodes.map((nodeData) => canvas.nodes.get(nodeData.id)).filter((node) => node !== void 0); + this.addZOrderingContextMenuItems(canvas, selectedNodes, menu); + } + addZOrderingContextMenuItems(canvas, nodes, menu) { + menu.addSeparator(); + if (this.plugin.settings.getSetting("zOrderingControlShowOneLayerShiftOptions") && nodes.length === 1) { + menu.addItem((item) => { + item.setTitle("Move one layer forward"); + item.setIcon("arrow-up"); + item.onClick(() => this.moveOneLayer(canvas, nodes.first(), true)); + }); + menu.addItem((item) => { + item.setTitle("Move one layer backward"); + item.setIcon("arrow-down"); + item.onClick(() => this.moveOneLayer(canvas, nodes.first(), false)); + }); + } + menu.addItem((item) => { + item.setTitle("Bring to front"); + item.setIcon("bring-to-front"); + item.onClick(() => this.moveMaxLayers(canvas, nodes, true)); + }); + menu.addItem((item) => { + item.setTitle("Send to back"); + item.setIcon("send-to-back"); + item.onClick(() => this.moveMaxLayers(canvas, nodes, false)); + }); + if (nodes.some((node) => node.getData().zIndex !== void 0)) { + menu.addItem((item) => { + item.setTitle("Remove persistent z-index"); + item.setIcon("pin-off"); + item.onClick(() => this.removePersistentZIndexes(canvas, nodes)); + }); + } + menu.addSeparator(); + } + moveOneLayer(canvas, selectedNode, forward) { + const selectedNodeBBox = selectedNode.getBBox(); + const collidingNodes = [...canvas.nodes.values()].filter((node) => BBoxHelper.isColliding(selectedNodeBBox, node.getBBox())).filter((node) => node !== selectedNode); + const nearestZIndexNode = collidingNodes.sort((a, b) => forward ? a.zIndex - b.zIndex : b.zIndex - a.zIndex).filter((node) => forward ? node.zIndex > selectedNode.zIndex : node.zIndex < selectedNode.zIndex).first(); + if (nearestZIndexNode === void 0) return; + const targetZIndex = nearestZIndexNode.zIndex; + this.setNodesZIndex([nearestZIndexNode], selectedNode.zIndex); + this.setNodesZIndex([selectedNode], targetZIndex); + } + moveMaxLayers(canvas, selectedNodes, forward) { + const targetZIndex = forward ? Math.max(...this.getAllZIndexes(canvas)) + 1 : Math.min(...this.getAllZIndexes(canvas)) - selectedNodes.length; + this.setNodesZIndex(selectedNodes, targetZIndex); + } + removePersistentZIndexes(_canvas, nodes) { + for (const node of nodes) node.setZIndex(void 0); + } + setNodesZIndex(nodes, zIndex) { + const sortedNodes = nodes.sort((a, b) => a.zIndex - b.zIndex); + for (let i = 0; i < sortedNodes.length; i++) { + const node = sortedNodes[i]; + const finalZIndex = zIndex + i; + node.setZIndex(finalZIndex); + } + } + getAllZIndexes(canvas) { + return [...canvas.nodes.values()].map((n) => n.zIndex); + } +}; + +// src/canvas-extensions/better-readonly-canvas-extension.ts +var BetterReadonlyCanvasExtension = class extends CanvasExtension { + constructor() { + super(...arguments); + this.isMovingToBBox = false; + } + isEnabled() { + return "betterReadonlyEnabled"; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:popup-menu-created", + (canvas) => this.updatePopupMenu(canvas) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:viewport-changed:before", + (canvas) => this.onBeforeViewPortChanged(canvas) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:zoom-to-bbox:before", + () => this.isMovingToBBox = true + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:readonly-changed", + (canvas, _readonly) => { + this.updatePopupMenu(canvas); + this.updateLockedZoom(canvas); + this.updateLockedPan(canvas); + } + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:canvas-changed", + (canvas) => this.addQuickSettings(canvas) + )); + } + onBeforeViewPortChanged(canvas) { + var _a, _b, _c, _d, _e, _f; + if (this.isMovingToBBox) { + this.isMovingToBBox = false; + this.updateLockedZoom(canvas); + this.updateLockedPan(canvas); + return; + } + if (!canvas.readonly) return; + if (this.plugin.settings.getSetting("disableZoom")) { + canvas.zoom = (_a = canvas.lockedZoom) != null ? _a : canvas.zoom; + canvas.tZoom = (_b = canvas.lockedZoom) != null ? _b : canvas.tZoom; + } + if (this.plugin.settings.getSetting("disablePan")) { + canvas.x = (_c = canvas.lockedX) != null ? _c : canvas.x; + canvas.tx = (_d = canvas.lockedX) != null ? _d : canvas.tx; + canvas.y = (_e = canvas.lockedY) != null ? _e : canvas.y; + canvas.ty = (_f = canvas.lockedY) != null ? _f : canvas.ty; + } + } + addQuickSettings(canvas) { + var _a; + const settingsContainer = (_a = canvas.quickSettingsButton) == null ? void 0 : _a.parentElement; + if (!settingsContainer) return; + CanvasHelper.addControlMenuButton( + settingsContainer, + this.createToggle({ + id: "disable-node-popup", + label: "Disable node popup", + icon: "arrow-up-right-from-circle", + callback: () => this.updatePopupMenu(canvas) + }, "disableNodePopup") + ); + CanvasHelper.addControlMenuButton( + settingsContainer, + this.createToggle({ + id: "disable-zoom", + label: "Disable zoom", + icon: "zoom-in", + callback: () => this.updateLockedZoom(canvas) + }, "disableZoom") + ); + CanvasHelper.addControlMenuButton( + settingsContainer, + this.createToggle({ + id: "disable-pan", + label: "Disable pan", + icon: "move", + callback: () => this.updateLockedPan(canvas) + }, "disablePan") + ); + } + createToggle(menuOption, settingKey) { + const toggle = CanvasHelper.createControlMenuButton({ + ...menuOption, + callback: () => void (async () => { + var _a; + const newValue = !this.plugin.settings.getSetting(settingKey); + await this.plugin.settings.setSetting({ [settingKey]: newValue }); + toggle.dataset.toggled = JSON.stringify(this.plugin.settings.getSetting(settingKey)); + (_a = menuOption.callback) == null ? void 0 : _a.call(this); + })() + }); + toggle.classList.add("show-while-readonly"); + toggle.dataset.toggled = JSON.stringify(this.plugin.settings.getSetting(settingKey)); + return toggle; + } + updatePopupMenu(canvas) { + const hidden = canvas.readonly && this.plugin.settings.getSetting("disableNodePopup"); + canvas.menu.menuEl.style.visibility = hidden ? "hidden" : "visible"; + } + updateLockedZoom(canvas) { + canvas.lockedZoom = canvas.tZoom; + } + updateLockedPan(canvas) { + canvas.lockedX = canvas.tx; + canvas.lockedY = canvas.ty; + } +}; + +// src/canvas-extensions/encapsulate-canvas-extension.ts +var ENCAPSULATED_FILE_NODE_SIZE = { width: 300, height: 300 }; +var EncapsulateCanvasExtension = class extends CanvasExtension { + isEnabled() { + return "canvasEncapsulationEnabled"; + } + init() { + this.plugin.addCommand({ + id: "encapsulate-selection", + name: "Encapsulate selection", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => !canvas.readonly && canvas.selection.size > 0, + (canvas) => void this.encapsulateSelection(canvas) + ) + }); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "canvas:selection-menu", + (menu, canvas) => { + menu.addItem( + (item) => item.setTitle("Encapsulate").setIcon("file-plus").onClick(() => this.encapsulateSelection(canvas)) + ); + } + )); + } + async encapsulateSelection(canvas) { + var _a, _b, _c, _d; + const selection = canvas.getSelectionData(); + const canvasSettings = this.plugin.app.internalPlugins.plugins.canvas.instance.options; + const defaultNewCanvasLocation = canvasSettings.newFileLocation; + let targetFolderPath = this.plugin.app.vault.getRoot().path; + if (defaultNewCanvasLocation === "current") targetFolderPath = (_c = (_b = (_a = canvas.view.file) == null ? void 0 : _a.parent) == null ? void 0 : _b.path) != null ? _c : targetFolderPath; + else if (defaultNewCanvasLocation === "folder") targetFolderPath = (_d = canvasSettings.newFileFolderPath) != null ? _d : targetFolderPath; + const targetFilePath = await new FileNameModal( + this.plugin.app, + targetFolderPath, + "canvas" + ).promise; + const newFileData = { nodes: selection.nodes, edges: selection.edges }; + const file = await this.plugin.app.vault.create(targetFilePath, JSON.stringify(newFileData, null, 2)); + for (const nodeData of selection.nodes) { + const node = canvas.nodes.get(nodeData.id); + if (node) canvas.removeNode(node); + } + canvas.createFileNode({ + pos: { + x: selection.center.x - ENCAPSULATED_FILE_NODE_SIZE.width / 2, + y: selection.center.y - ENCAPSULATED_FILE_NODE_SIZE.height / 2 + }, + size: ENCAPSULATED_FILE_NODE_SIZE, + file + }); + } +}; + +// src/canvas-extensions/commands-canvas-extension.ts +var import_obsidian16 = require("obsidian"); + +// src/canvas-extensions/copy-node-reference-canvas-extension.ts +var import_obsidian15 = require("obsidian"); +var CopyNodeReferenceCanvasExtension = class _CopyNodeReferenceCanvasExtension extends CanvasExtension { + isEnabled() { + return "enableSingleNodePopupReferenceCopy"; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:popup-menu-created", + (canvas) => this.onPopupMenuCreated(canvas) + )); + } + onPopupMenuCreated(canvas) { + var _a; + const popupMenuEl = (_a = canvas == null ? void 0 : canvas.menu) == null ? void 0 : _a.menuEl; + if (!popupMenuEl) return; + const selectionData = canvas.getSelectionData(); + if (selectionData.nodes.length !== 1 && selectionData.edges.length === 0) return; + const menuOption = { + id: "node-popup-menu-option-copy-reference", + label: "Copy wikilink to node", + icon: "link", + callback: () => _CopyNodeReferenceCanvasExtension.copyWikilinkToNode(canvas.view.file, selectionData.nodes[0]) + }; + const popupMenuOption = CanvasHelper.createPopupMenuOption(menuOption); + CanvasHelper.addPopupMenuOption(canvas, popupMenuOption); + } + static copyWikilinkToNode(file, nodeData) { + const nodeTypeString = TextHelper.toTitleCase(nodeData.type); + const wikilink = `[[${file.path}#${nodeData.id}|${file.name} (${nodeTypeString} node)]]`; + navigator.clipboard.writeText(wikilink).then( + () => new import_obsidian15.Notice("Copied wikilink to node to clipboard.", 2e3) + ).catch(() => new import_obsidian15.Notice("Failed to copy wikilink to node to clipboard.", 2e3)); + } +}; + +// src/canvas-extensions/commands-canvas-extension.ts +var DIRECTIONS = ["up", "down", "left", "right"]; +var CommandsCanvasExtension = class extends CanvasExtension { + isEnabled() { + return "commandsFeatureEnabled"; + } + init() { + this.plugin.addCommand({ + id: "toggle-readonly", + name: "Toggle readonly", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (_canvas) => true, + (canvas) => canvas.setReadonly(!canvas.readonly) + ) + }); + this.plugin.addCommand({ + id: "create-text-node", + name: "Create text node", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => !canvas.readonly, + (canvas) => this.createTextNode(canvas) + ) + }); + this.plugin.addCommand({ + id: "create-file-node", + name: "Create file node", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => !canvas.readonly, + (canvas) => void this.createFileNode(canvas) + ) + }); + this.plugin.addCommand({ + id: "select-all-edges", + name: "Select all edges", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (_canvas) => true, + (canvas) => canvas.updateSelection( + () => canvas.selection = new Set(canvas.edges.values()) + ) + ) + }); + this.plugin.addCommand({ + id: "zoom-to-selection", + name: "Zoom to selection", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => canvas.selection.size > 0, + (canvas) => canvas.zoomToSelection() + ) + }); + this.plugin.addCommand({ + id: "zoom-to-fit", + name: "Zoom to fit", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (_canvas) => true, + (canvas) => canvas.zoomToFit() + ) + }); + for (const direction of DIRECTIONS) { + this.plugin.addCommand({ + id: `clone-node-${direction}`, + name: `Clone node ${direction}`, + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => { + var _a; + return !canvas.readonly && canvas.selection.size === 1 && ((_a = [...canvas.selection][0]) == null ? void 0 : _a.getData().type) === "text"; + }, + (canvas) => this.cloneNode(canvas, direction) + ) + }); + this.plugin.addCommand({ + id: `expand-node-${direction}`, + name: `Expand node ${direction}`, + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => !canvas.readonly && canvas.selection.size === 1, + (canvas) => this.expandNode(canvas, direction) + ) + }); + this.plugin.addCommand({ + id: `navigate-${direction}`, + name: `Navigate ${direction}`, + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => canvas.getSelectionData().nodes.length === 1, + (canvas) => this.navigate(canvas, direction) + ) + }); + } + this.plugin.addCommand({ + id: "flip-selection-horizontally", + name: "Flip selection horizontally", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => !canvas.readonly && canvas.selection.size > 0, + (canvas) => this.flipSelection( + canvas, + true + ) + ) + }); + this.plugin.addCommand({ + id: "flip-selection-vertically", + name: "Flip selection vertically", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => !canvas.readonly && canvas.selection.size > 0, + (canvas) => this.flipSelection(canvas, false) + ) + }); + this.plugin.addCommand({ + id: "select-connected-edges", + name: "Select connected edges", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => canvas.selection.size > 0, + (canvas) => CanvasHelper.selectEdgesForNodes(canvas, "connected") + ) + }); + this.plugin.addCommand({ + id: "select-incoming-edges", + name: "Select incoming edges", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => canvas.selection.size > 0, + (canvas) => CanvasHelper.selectEdgesForNodes(canvas, "incoming") + ) + }); + this.plugin.addCommand({ + id: "select-outgoing-edges", + name: "Select outgoing edges", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => canvas.selection.size > 0, + (canvas) => CanvasHelper.selectEdgesForNodes(canvas, "outgoing") + ) + }); + this.plugin.addCommand({ + id: "swap-nodes", + name: "Swap nodes", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => !canvas.readonly && canvas.getSelectionData().nodes.length === 2, + (canvas) => { + const selectedNodes = canvas.getSelectionData().nodes.map((nodeData) => canvas.nodes.get(nodeData.id)).filter((node) => node !== void 0); + if (selectedNodes.length !== 2) return; + const [nodeA, nodeB] = selectedNodes; + const nodeAData = nodeA.getData(); + const nodeBData = nodeB.getData(); + nodeA.setData({ ...nodeAData, x: nodeBData.x, y: nodeBData.y, width: nodeBData.width, height: nodeBData.height }); + nodeB.setData({ ...nodeBData, x: nodeAData.x, y: nodeAData.y, width: nodeAData.width, height: nodeAData.height }); + canvas.pushHistory(canvas.getData()); + } + ) + }); + this.plugin.addCommand({ + id: "copy-wikilink-to-node", + name: "Copy wikilink to node", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => !canvas.readonly && canvas.selection.size === 1, + (canvas) => { + const file = canvas.view.file; + if (!file) return; + const nodeData = canvas.getSelectionData().nodes[0]; + if (!nodeData) return; + CopyNodeReferenceCanvasExtension.copyWikilinkToNode(file, nodeData); + } + ) + }); + this.plugin.addCommand({ + id: "pull-outgoing-links-to-canvas", + name: "Pull outgoing links to canvas", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => !canvas.readonly, + (canvas) => { + var _a, _b, _c; + const canvasFile = canvas.view.file; + if (!canvasFile) return; + let selectedNodeIds = canvas.getSelectionData().nodes.map((node) => node.id); + if (selectedNodeIds.length === 0) selectedNodeIds = [...canvas.nodes.keys()]; + const metadata = this.plugin.app.metadataCache.getFileCache(canvasFile); + if (!metadata) return; + const outgoingLinks = /* @__PURE__ */ new Set(); + for (const nodeId of selectedNodeIds) { + let relativeFile = canvasFile; + let nodeOutgoingLinks = (_b = (_a = metadata.nodes) == null ? void 0 : _a[nodeId]) == null ? void 0 : _b.links; + if (!nodeOutgoingLinks) { + const file = (_c = canvas.nodes.get(nodeId)) == null ? void 0 : _c.file; + if (!file) continue; + const fileMetadata = this.plugin.app.metadataCache.getFileCache(file); + nodeOutgoingLinks = fileMetadata == null ? void 0 : fileMetadata.links; + relativeFile = file; + } + if (!nodeOutgoingLinks) continue; + for (const nodeOutgoingLink of nodeOutgoingLinks) { + const resolvedLink = this.plugin.app.metadataCache.getFirstLinkpathDest(nodeOutgoingLink.link, relativeFile.path); + if (!(resolvedLink instanceof import_obsidian16.TFile)) continue; + outgoingLinks.add(resolvedLink); + } + } + const existingFileNodes = /* @__PURE__ */ new Set([canvas.view.file]); + for (const node of canvas.nodes.values()) { + if (node.getData().type !== "file" || !node.file) continue; + existingFileNodes.add(node.file); + } + for (const outgoingLink of outgoingLinks) { + if (existingFileNodes.has(outgoingLink)) continue; + void this.createFileNode(canvas, outgoingLink); + } + } + ) + }); + this.plugin.addCommand({ + id: "pull-backlinks-to-canvas", + name: "Pull backlinks to canvas", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => !canvas.readonly, + (canvas) => { + const canvasFile = canvas.view.file; + if (!canvasFile) return; + const selectedNodesData = canvas.getSelectionData().nodes.map((node) => node); + const backlinks = /* @__PURE__ */ new Set(); + if (selectedNodesData.length > 0) { + for (const nodeData of selectedNodesData) { + if (nodeData.type !== "file" || !nodeData.file) continue; + const file = this.plugin.app.vault.getFileByPath(nodeData.file); + if (!file) continue; + const nodeBacklinks = this.plugin.app.metadataCache.getBacklinksForFile(file); + if (!nodeBacklinks) continue; + for (const nodeBacklink of nodeBacklinks.data.keys()) { + const resolvedLink = this.plugin.app.metadataCache.getFirstLinkpathDest(nodeBacklink, file.path); + if (!(resolvedLink instanceof import_obsidian16.TFile)) continue; + backlinks.add(resolvedLink); + } + } + } else { + const canvasBacklinks = this.plugin.app.metadataCache.getBacklinksForFile(canvasFile); + if (!canvasBacklinks) return; + for (const canvasBacklink of canvasBacklinks.data.keys()) { + const resolvedLink = this.plugin.app.metadataCache.getFirstLinkpathDest(canvasBacklink, canvasFile.path); + if (!(resolvedLink instanceof import_obsidian16.TFile)) continue; + backlinks.add(resolvedLink); + } + } + const existingFileNodes = /* @__PURE__ */ new Set([canvas.view.file]); + for (const node of canvas.nodes.values()) { + if (node.getData().type !== "file" || !node.file) continue; + existingFileNodes.add(node.file); + } + for (const backlink of backlinks) { + if (existingFileNodes.has(backlink)) continue; + void this.createFileNode(canvas, backlink); + } + } + ) + }); + } + createTextNode(canvas) { + const size = canvas.config.defaultTextNodeDimensions; + const pos = CanvasHelper.getCenterCoordinates(canvas, size); + canvas.createTextNode({ pos, size }); + } + async createFileNode(canvas, file) { + const size = canvas.config.defaultFileNodeDimensions; + const pos = CanvasHelper.getCenterCoordinates(canvas, size); + file != null ? file : file = await new FileSelectModal(this.plugin.app, void 0, true).promise; + canvas.createFileNode({ pos, size, file }); + } + cloneNode(canvas, cloneDirection) { + const sourceNode = [...canvas.selection][0]; + if (!sourceNode) return; + const sourceNodeData = sourceNode.getData(); + const nodeMargin = this.plugin.settings.getSetting("cloneNodeMargin"); + const offset = { + x: (sourceNode.width + nodeMargin) * (cloneDirection === "left" ? -1 : cloneDirection === "right" ? 1 : 0), + y: (sourceNode.height + nodeMargin) * (cloneDirection === "up" ? -1 : cloneDirection === "down" ? 1 : 0) + }; + const clonedNode = canvas.createTextNode({ + pos: { + x: sourceNode.x + offset.x, + y: sourceNode.y + offset.y + }, + size: { + width: sourceNode.width, + height: sourceNode.height + } + }); + clonedNode.setData({ + ...clonedNode.getData(), + color: sourceNodeData.color, + styleAttributes: sourceNodeData.styleAttributes + }); + if (this.plugin.settings.getSetting("zoomToClonedNode")) + canvas.zoomToBbox(clonedNode.getBBox()); + } + expandNode(canvas, expandDirection) { + const node = [...canvas.selection][0]; + if (!node) return; + const expandNodeStepSize = this.plugin.settings.getSetting("expandNodeStepSize"); + const expand = { + x: expandDirection === "left" ? -1 : expandDirection === "right" ? 1 : 0, + y: expandDirection === "up" ? -1 : expandDirection === "down" ? 1 : 0 + }; + node.setData({ + ...node.getData(), + width: node.width + expand.x * expandNodeStepSize, + height: node.height + expand.y * expandNodeStepSize + }); + } + flipSelection(canvas, horizontally) { + const selectionData = canvas.getSelectionData(); + if (selectionData.nodes.length === 0) return; + const nodeIds = /* @__PURE__ */ new Set(); + for (const nodeData of selectionData.nodes) { + nodeIds.add(nodeData.id); + const node = canvas.nodes.get(nodeData.id); + if (!node) continue; + const newX = horizontally ? 2 * selectionData.center.x - nodeData.x - nodeData.width : nodeData.x; + const newY = horizontally ? nodeData.y : 2 * selectionData.center.y - nodeData.y - nodeData.height; + node.setData({ + ...nodeData, + x: newX, + y: newY + }); + } + for (const edge of canvas.edges.values()) { + const edgeData = edge.getData(); + let newFromSide = edgeData.fromSide; + if (nodeIds.has(edgeData.fromNode) && BBoxHelper.isHorizontal(edgeData.fromSide) === horizontally) + newFromSide = BBoxHelper.getOppositeSide(edgeData.fromSide); + let newToSide = edgeData.toSide; + if (nodeIds.has(edgeData.toNode) && BBoxHelper.isHorizontal(edgeData.toSide) === horizontally) + newToSide = BBoxHelper.getOppositeSide(edgeData.toSide); + edge.setData({ + ...edgeData, + fromSide: newFromSide, + toSide: newToSide + }); + } + canvas.pushHistory(canvas.getData()); + } + navigate(canvas, direction) { + const node = this.getNextNode(canvas, direction); + if (!node) return; + canvas.updateSelection(() => { + canvas.selection = /* @__PURE__ */ new Set([node]); + }); + } + getNextNode(canvas, direction) { + var _a; + const selectedNodeData = (_a = canvas.getSelectionData().nodes) == null ? void 0 : _a.first(); + if (!selectedNodeData) return; + const selectedNodeBBox = { + minX: selectedNodeData.x, + minY: selectedNodeData.y, + maxX: selectedNodeData.x + selectedNodeData.width, + maxY: selectedNodeData.y + selectedNodeData.height + }; + const possibleTargetNodes = Array.from(canvas.nodes.values()).filter((node) => { + const nodeData = node.getData(); + return nodeData.id !== selectedNodeData.id && (nodeData.type === "text" || nodeData.type === "file"); + }); + const closestNode = possibleTargetNodes.reduce((closestNode2, node) => { + const nodeBBox = node.getBBox(); + const isInVerticalRange = selectedNodeBBox.minY <= nodeBBox.maxY && selectedNodeBBox.maxY >= nodeBBox.minY; + const isInHorizontalRange = selectedNodeBBox.minX <= nodeBBox.maxX && selectedNodeBBox.maxX >= nodeBBox.minX; + if (["up", "down"].includes(direction) && !isInHorizontalRange) return closestNode2; + if (["left", "right"].includes(direction) && !isInVerticalRange) return closestNode2; + let distance = -1; + switch (direction) { + case "up": + distance = selectedNodeBBox.minY - nodeBBox.maxY; + break; + case "down": + distance = nodeBBox.minY - selectedNodeBBox.maxY; + break; + case "left": + distance = selectedNodeBBox.minX - nodeBBox.maxX; + break; + case "right": + distance = nodeBBox.minX - selectedNodeBBox.maxX; + break; + } + if (distance < 0) return closestNode2; + if (!closestNode2) return { node, distance }; + if (distance < closestNode2.distance) return { node, distance }; + if (distance === closestNode2.distance) { + const selectedNodeCenter = { + x: selectedNodeData.x + selectedNodeData.width / 2, + y: selectedNodeData.y + selectedNodeData.height / 2 + }; + const closestNodeCenter = { + x: closestNode2.node.x + closestNode2.node.width / 2, + y: closestNode2.node.y + closestNode2.node.height / 2 + }; + const nodeCenter = { + x: node.x + node.width / 2, + y: node.y + node.height / 2 + }; + const closestNodeDistance = Math.sqrt( + Math.pow(selectedNodeCenter.x - closestNodeCenter.x, 2) + Math.pow(selectedNodeCenter.y - closestNodeCenter.y, 2) + ); + const nodeDistance = Math.sqrt( + Math.pow(selectedNodeCenter.x - nodeCenter.x, 2) + Math.pow(selectedNodeCenter.y - nodeCenter.y, 2) + ); + if (nodeDistance < closestNodeDistance) return { node, distance }; + } + return closestNode2; + }, null); + return closestNode == null ? void 0 : closestNode.node; + } +}; + +// src/canvas-extensions/auto-resize-node-canvas-extension.ts +var AutoResizeNodeCanvasExtension = class extends CanvasExtension { + isEnabled() { + return "autoResizeNodeFeatureEnabled"; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-created", + (canvas, node) => this.onNodeCreated(canvas, node) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:popup-menu-created", + (canvas) => this.onPopupMenuCreated(canvas) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-editing-state-changed", + (canvas, node, editing) => void this.onNodeEditingStateChanged(canvas, node, editing) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-text-content-changed", + (canvas, node, viewUpdate) => void this.onNodeTextContentChanged(canvas, node, viewUpdate.view.dom) + )); + } + isValidNodeType(nodeData) { + return nodeData.type === "text" || nodeData.type === "file" && nodeData.file.endsWith(".md"); + } + onNodeCreated(_canvas, node) { + const autoResizeNodeEnabledByDefault = this.plugin.settings.getSetting("autoResizeNodeEnabledByDefault"); + if (!autoResizeNodeEnabledByDefault) return; + const nodeData = node.getData(); + if (nodeData.type !== "text" && nodeData.type !== "file") return; + node.setData({ + ...node.getData(), + dynamicHeight: true + }); + } + onPopupMenuCreated(canvas) { + if (canvas.readonly) return; + const selectedNodes = canvas.getSelectionData().nodes.filter((nodeData) => this.isValidNodeType(nodeData)).map((nodeData) => canvas.nodes.get(nodeData.id)).filter((node) => node !== void 0); + if (selectedNodes.length === 0) return; + const autoResizeHeightEnabled = selectedNodes.some((node) => node.getData().dynamicHeight); + CanvasHelper.addPopupMenuOption( + canvas, + CanvasHelper.createPopupMenuOption({ + id: "auto-resize-height", + label: autoResizeHeightEnabled ? "Disable auto-resize" : "Enable auto-resize", + icon: autoResizeHeightEnabled ? "scan-text" : "lock", + callback: () => this.toggleAutoResizeHeightEnabled(canvas, selectedNodes, autoResizeHeightEnabled) + }) + ); + } + toggleAutoResizeHeightEnabled(canvas, nodes, autoResizeHeight) { + nodes.forEach((node) => node.setData({ + ...node.getData(), + dynamicHeight: !autoResizeHeight + })); + this.onPopupMenuCreated(canvas); + } + canBeResized(node) { + const nodeData = node.getData(); + return nodeData.dynamicHeight; + } + async onNodeEditingStateChanged(_canvas, node, editing) { + if (!this.isValidNodeType(node.getData())) return; + if (!this.canBeResized(node)) return; + await sleep(10); + if (editing) { + void this.onNodeTextContentChanged(_canvas, node, node.child.editMode.cm.dom); + return; + } + const renderedMarkdownContainer = node.nodeEl.querySelector(".markdown-preview-view.markdown-rendered"); + if (!renderedMarkdownContainer) return; + renderedMarkdownContainer.setCssStyles({ height: "min-content" }); + const newHeight = renderedMarkdownContainer.clientHeight; + renderedMarkdownContainer.setCssStyles({ height: "" }); + this.setNodeHeight(node, newHeight); + } + async onNodeTextContentChanged(_canvas, node, dom) { + if (!this.isValidNodeType(node.getData())) return; + if (!this.canBeResized(node)) return; + const cmScroller = dom.querySelector(".cm-scroller"); + if (!cmScroller) return; + cmScroller.setCssStyles({ height: "min-content" }); + const newHeight = cmScroller.scrollHeight; + cmScroller.setCssStyles({ height: "" }); + this.setNodeHeight(node, newHeight); + } + setNodeHeight(node, height) { + if (height === 0) return; + const maxHeight = this.plugin.settings.getSetting("autoResizeNodeMaxHeight"); + if (maxHeight != -1 && height > maxHeight) height = maxHeight; + const nodeData = node.getData(); + height = Math.max(height, node.canvas.config.minContainerDimension); + if (this.plugin.settings.getSetting("autoResizeNodeSnapToGrid")) + height = Math.ceil(height / CanvasHelper.GRID_SIZE) * CanvasHelper.GRID_SIZE; + if (height === nodeData.height) return; + node.setData({ + ...nodeData, + height + }); + } +}; + +// src/canvas-extensions/portals-canvas-extension.ts +var import_obsidian17 = require("obsidian"); +var PORTAL_ID_DELIMITER = "||"; +var PORTAL_ID_PREFIX = `acportal${PORTAL_ID_DELIMITER}`; +var PORTAL_PADDING = 50; +var MIN_OPEN_PORTAL_SIZE = { width: 200, height: 200 }; +var PortalsCanvasExtension = class _PortalsCanvasExtension extends CanvasExtension { + isEnabled() { + return "portalsFeatureEnabled"; + } + init() { + this.plugin.registerEvent(this.plugin.app.vault.on("modify", (file) => { + for (const canvas of this.plugin.getCanvases()) + this.onFileModified(canvas, file); + })); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:popup-menu-created", + (canvas) => this.onPopupMenu(canvas) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-removed", + (canvas, node) => this.onNodeRemoved(canvas, node) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-moved", + (canvas, node, _keyboard) => this.onNodeMoved(canvas, node) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-resized", + (canvas, node) => this.onNodeResized(canvas, node) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:dragging-state-changed", + (canvas, startedDragging) => this.onDraggingStateChanged(canvas, startedDragging) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:containing-nodes-requested", + (canvas, bbox, nodes) => this.onContainingNodesRequested(canvas, bbox, nodes) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:edge-connection-try-dragging:before", + (canvas, edge, event, cancelRef) => this.onEdgeConnectionTryDraggingBefore(canvas, edge, event, cancelRef) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:edge-connection-dragging:after", + (canvas, edge, event, newEdge, side, previousEnds) => this.onEdgeConnectionDraggingAfter(canvas, edge, event, newEdge, side, previousEnds) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:selection-changed", + (canvas, oldSelection, updateSelection) => this.onSelectionChanged(canvas, oldSelection, updateSelection) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:data-requested", + (canvas, data) => this.onGetData(canvas, data) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:data-loaded:before", + (canvas, data, setData) => { + this.onSetData(canvas, data).then((newData) => { + if (newData.nodes.length === data.nodes.length && newData.edges.length === data.edges.length) return; + setData(newData); + }).catch((error) => { + console.error("Error loading portal data:", error); + new import_obsidian17.Notice("An error occurred while loading portal data. Please check console for details."); + }); + } + )); + } + onFileModified(canvas, file) { + const isAffected = Object.values(canvas.nodes).filter( + (nodeData) => nodeData.getData().type === "file" && nodeData.currentPortalFile === file.path + ).length > 0; + if (!isAffected) return; + canvas.setData(canvas.getData()); + canvas.history.current--; + canvas.history.data.pop(); + } + onContainingNodesRequested(_canvas, _bbox, nodes) { + const filteredNodes = nodes.filter((node) => !_PortalsCanvasExtension.isPortalElement(node.id)); + nodes.splice(0, nodes.length, ...filteredNodes); + } + onSelectionChanged(canvas, _oldSelection, updateSelection) { + updateSelection(() => { + const updatedSelection = Array.from(canvas.selection).filter((canvasElement) => !_PortalsCanvasExtension.isPortalElement(canvasElement.id)); + canvas.selection = new Set(updatedSelection); + }); + } + onDraggingStateChanged(canvas, startedDragging) { + if (!startedDragging) return; + if (!canvas.getSelectionData().nodes.some((node) => node.type === "file" && node.portal)) return; + const objectSnappingEnabled = canvas.options.snapToObjects; + if (!objectSnappingEnabled) return; + canvas.toggleObjectSnapping(false); + const dragEndEventRef = this.plugin.app.workspace.on( + "advanced-canvas:dragging-state-changed", + (canvas2, startedDragging2) => { + if (startedDragging2) return; + canvas2.toggleObjectSnapping(objectSnappingEnabled); + this.plugin.app.workspace.offref(dragEndEventRef); + } + ); + this.plugin.registerEvent(dragEndEventRef); + } + onNodeMoved(canvas, portalNode) { + const portalNodeData = portalNode.getData(); + if (portalNodeData.type !== "file" || !portalNodeData.isPortalLoaded) return; + const nestedNodes = this.getContainingNodes(canvas, portalNode); + const containingNodesBBox = CanvasHelper.getBBox(nestedNodes); + const portalOffset = { + x: portalNodeData.x - containingNodesBBox.minX + PORTAL_PADDING, + y: portalNodeData.y - containingNodesBBox.minY + PORTAL_PADDING + }; + for (const nestedNode of nestedNodes) { + const nestedNodeData = nestedNode.getData(); + nestedNode.setData({ + ...nestedNodeData, + x: nestedNodeData.x + portalOffset.x, + y: nestedNodeData.y + portalOffset.y + }); + } + } + onNodeResized(_canvas, portalNode) { + const portalNodeData = portalNode.getData(); + if (portalNodeData.type !== "file" || !portalNodeData.isPortalLoaded) return; + portalNode.setData({ + ...portalNodeData, + x: portalNode.prevX ? portalNode.prevX : portalNodeData.x, + y: portalNode.prevY ? portalNode.prevY : portalNodeData.y, + width: portalNode.prevWidth ? portalNode.prevWidth : portalNodeData.width, + height: portalNode.prevHeight ? portalNode.prevHeight : portalNodeData.height + }); + } + onNodeRemoved(canvas, portalNode) { + const portalNodeData = portalNode.getData(); + if (portalNodeData.type !== "file" || !portalNodeData.portal) return; + for (const node of this.getContainingNodes(canvas, portalNode, false)) + canvas.removeNode(node); + for (const edge of this.getContainingEdges(canvas, portalNode, false)) + canvas.removeEdge(edge); + } + onEdgeConnectionTryDraggingBefore(_canvas, edge, _event, cancelRef) { + if (!_PortalsCanvasExtension.isPortalElement(edge.id)) return; + cancelRef.value = true; + new import_obsidian17.Notice("Updating edges from portals is not supported yet."); + } + onEdgeConnectionDraggingAfter(canvas, edge, _event, _newEdge, _side, _previousEnds) { + if (_PortalsCanvasExtension.isPortalElement(edge.id)) return; + if (!_PortalsCanvasExtension.isPortalElement(edge.from.node.id) || !_PortalsCanvasExtension.isPortalElement(edge.to.node.id)) return; + canvas.removeEdge(edge); + new import_obsidian17.Notice("Creating edges with both ends in portals are not supported yet."); + } + onPopupMenu(canvas) { + if (canvas.readonly) return; + const selectedFileNodes = canvas.getSelectionData().nodes.map((nodeData) => { + var _a; + const node = canvas.nodes.get(nodeData.id); + if (!node) return null; + if (nodeData.type !== "file") return null; + if (((_a = node.file) == null ? void 0 : _a.extension) === "canvas") return node; + if (nodeData.portal) this.setPortalOpen(canvas, node, false); + return null; + }).filter((node) => node !== null); + if (selectedFileNodes.length !== 1) return; + const portalNode = selectedFileNodes.first(); + const portalNodeData = portalNode.getData(); + if (portalNodeData.portal && portalNodeData.file !== portalNode.currentPortalFile) + this.setPortalOpen(canvas, portalNode, true); + CanvasHelper.addPopupMenuOption( + canvas, + CanvasHelper.createPopupMenuOption({ + id: "toggle-portal", + label: portalNodeData.portal ? "Close portal" : "Open portal", + icon: portalNodeData.portal ? "door-open" : "door-closed", + callback: () => { + this.setPortalOpen(canvas, portalNode, !portalNodeData.portal); + this.onPopupMenu(canvas); + } + }) + ); + } + setPortalOpen(canvas, portalNode, open) { + const portalNodeData = portalNode.getData(); + portalNode.setData({ + ...portalNodeData, + portal: open + }); + portalNode.currentPortalFile = open ? portalNodeData.file : void 0; + canvas.setData(canvas.getData()); + } + // Remove all edges and nodes from portals + onGetData(_canvas, data) { + data.nodes = data.nodes.filter((nodeData) => !_PortalsCanvasExtension.isPortalElement(nodeData.id)); + for (const nodeData of data.nodes) delete nodeData.isPortalLoaded; + const portalsIdMap = new Map( + data.nodes.filter((nodeData) => nodeData.type === "file").map((nodeData) => [nodeData.id, nodeData]) + ); + data.edges = data.edges.filter((edgeData) => { + var _a; + if (_PortalsCanvasExtension.isPortalElement(edgeData.id)) return false; + const isFromNodeFromPortal = _PortalsCanvasExtension.getNestedIds(edgeData.fromNode).length > 1; + const isToNodeFromPortal = _PortalsCanvasExtension.getNestedIds(edgeData.toNode).length > 1; + if (!isFromNodeFromPortal && !isToNodeFromPortal) return true; + if (isFromNodeFromPortal && isToNodeFromPortal) return false; + const targetPortalId = this.getParentPortalId(isFromNodeFromPortal ? edgeData.fromNode : edgeData.toNode); + const targetPortalData = portalsIdMap.get(targetPortalId); + if (!targetPortalData) return false; + (_a = targetPortalData.interdimensionalEdges) != null ? _a : targetPortalData.interdimensionalEdges = []; + targetPortalData.interdimensionalEdges.push(edgeData); + return false; + }); + } + // Add all edges and nodes from portals + async onSetData(canvas, dataRef) { + if (!(dataRef == null ? void 0 : dataRef.nodes)) return dataRef; + const data = JSON.parse(JSON.stringify(dataRef)); + const addedData = await Promise.all(data.nodes.map((nodeData) => this.tryOpenPortal(canvas, nodeData))); + for (const newData of addedData) { + data.nodes.push(...newData.nodes); + data.edges.push(...newData.edges); + } + for (const nodeData of data.nodes) { + if (nodeData.type !== "file" || !nodeData.isPortalLoaded) continue; + const interdimensionalEdges = nodeData.interdimensionalEdges; + if (!interdimensionalEdges) continue; + for (const edge of interdimensionalEdges) data.edges.push(edge); + delete nodeData.interdimensionalEdges; + } + return data; + } + async tryOpenPortal(canvas, portalNodeData, nestedPortalFiles = /* @__PURE__ */ new Set()) { + const addedData = { nodes: [], edges: [] }; + if (portalNodeData.type !== "file" || !portalNodeData.portal) return addedData; + if (portalNodeData.file === canvas.view.file.path) return addedData; + if (nestedPortalFiles.has(portalNodeData.file)) return addedData; + nestedPortalFiles.add(portalNodeData.file); + const portalFile = this.plugin.app.vault.getAbstractFileByPath(portalNodeData.file); + if (!(portalFile instanceof import_obsidian17.TFile) || portalFile.extension !== "canvas") return addedData; + const portalFileDataString = await this.plugin.app.vault.cachedRead(portalFile); + if (portalFileDataString === "") return addedData; + const portalFileData = JSON.parse(portalFileDataString); + if (!portalFileData) return addedData; + portalNodeData.isPortalLoaded = true; + const sourceMinCoordinates = CanvasHelper.getBBox(portalFileData.nodes); + const portalOffset = { + x: portalNodeData.x - sourceMinCoordinates.minX + PORTAL_PADDING, + y: portalNodeData.y - sourceMinCoordinates.minY + PORTAL_PADDING + }; + for (const nodeDataFromPortal of portalFileData.nodes) { + let newNodeId = `${portalNodeData.id}${PORTAL_ID_DELIMITER}${nodeDataFromPortal.id}`; + if (!newNodeId.startsWith(PORTAL_ID_PREFIX)) + newNodeId = PORTAL_ID_PREFIX + newNodeId; + const addedNode = { + ...nodeDataFromPortal, + id: newNodeId, + x: nodeDataFromPortal.x + portalOffset.x, + y: nodeDataFromPortal.y + portalOffset.y + }; + addedData.nodes.push(addedNode); + const nestedNodes = await this.tryOpenPortal(canvas, addedNode, nestedPortalFiles); + addedData.nodes.push(...nestedNodes.nodes); + addedData.edges.push(...nestedNodes.edges); + } + for (const edgeDataFromPortal of portalFileData.edges) { + let newEdgeId = `${portalNodeData.id}${PORTAL_ID_DELIMITER}${edgeDataFromPortal.id}`; + if (!newEdgeId.startsWith(PORTAL_ID_PREFIX)) + newEdgeId = PORTAL_ID_PREFIX + newEdgeId; + let fromNodeId = `${portalNodeData.id}${PORTAL_ID_DELIMITER}${edgeDataFromPortal.fromNode}`; + if (!fromNodeId.startsWith(PORTAL_ID_PREFIX)) + fromNodeId = PORTAL_ID_PREFIX + fromNodeId; + let toNodeId = `${portalNodeData.id}${PORTAL_ID_DELIMITER}${edgeDataFromPortal.toNode}`; + if (!toNodeId.startsWith(PORTAL_ID_PREFIX)) + toNodeId = PORTAL_ID_PREFIX + toNodeId; + addedData.edges.push({ + ...edgeDataFromPortal, + id: newEdgeId, + fromNode: fromNodeId, + toNode: toNodeId + }); + } + const targetSize = this.getPortalSize(CanvasHelper.getBBox(addedData.nodes)); + portalNodeData.width = targetSize.width; + portalNodeData.height = targetSize.height; + return addedData; + } + // Helper functions + getPortalSize(sourceBBox) { + const sourceSize = { + width: sourceBBox.maxX - sourceBBox.minX, + height: sourceBBox.maxY - sourceBBox.minY + }; + const targetSize = { + width: Math.max(sourceSize.width + PORTAL_PADDING * 2, MIN_OPEN_PORTAL_SIZE.width), + height: Math.max(sourceSize.height + PORTAL_PADDING * 2, MIN_OPEN_PORTAL_SIZE.height) + }; + if (!Number.isFinite(targetSize.width)) targetSize.width = MIN_OPEN_PORTAL_SIZE.width; + if (!Number.isFinite(targetSize.height)) targetSize.height = MIN_OPEN_PORTAL_SIZE.height; + return targetSize; + } + getContainingNodes(canvas, portalNode, directChildren = true) { + return Array.from(canvas.nodes.values()).filter((node) => this.isChildOfPortal(portalNode.getData(), node.getData(), directChildren)); + } + getContainingEdges(canvas, portalNode, directChildren = true) { + return Array.from(canvas.edges.values()).filter((edge) => this.isChildOfPortal(portalNode.getData(), edge.getData(), directChildren)); + } + getParentPortalId(elementId) { + const nestedIds = _PortalsCanvasExtension.getNestedIds(elementId); + if (nestedIds.length < 2) return void 0; + return nestedIds.slice(0, -1).join(PORTAL_ID_DELIMITER); + } + static getNestedIds(id) { + if (!this.isPortalElement(id)) return [id]; + const trimmedId = id.substring(PORTAL_ID_PREFIX.length); + return trimmedId.split(PORTAL_ID_DELIMITER); + } + static isPortalElement(id) { + return id.startsWith(PORTAL_ID_PREFIX); + } + isChildOfPortal(portal, canvasElement, directChild = true) { + const nestedIds = _PortalsCanvasExtension.getNestedIds(canvasElement.id); + if (nestedIds.length < 2) return false; + return canvasElement.id !== portal.id && // Not the portal itself + nestedIds.contains(portal.id) && // Is a child of the portal + (!directChild || nestedIds[nestedIds.length - 2] === portal.id); + } +}; + +// src/canvas-extensions/frontmatter-control-button-canvas-extension.ts +var import_obsidian18 = require("obsidian"); +var FrontmatterControlButtonCanvasExtension = class extends CanvasExtension { + isEnabled() { + return "canvasMetadataCompatibilityEnabled"; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:canvas-changed", + (canvas) => this.addQuickSettings(canvas) + )); + } + addQuickSettings(canvas) { + var _a; + if (!canvas) return; + const settingsContainer = (_a = canvas.quickSettingsButton) == null ? void 0 : _a.parentElement; + if (!settingsContainer) return; + CanvasHelper.addControlMenuButton( + settingsContainer, + CanvasHelper.createControlMenuButton({ + id: "properties-button", + icon: "info", + label: "Properties", + callback: () => { + var _a2; + const propertiesPlugin = this.plugin.app.internalPlugins.plugins["properties"]; + if (!(propertiesPlugin == null ? void 0 : propertiesPlugin._loaded)) { + new import_obsidian18.Notice(`Core plugin "Properties view" was not found or isn't enabled. Enable it and restart Obsidian.`); + return; + } + let propertiesLeaf = (_a2 = this.plugin.app.workspace.getLeavesOfType("file-properties").first()) != null ? _a2 : null; + if (!propertiesLeaf) { + propertiesLeaf = this.plugin.app.workspace.getRightLeaf(false); + void (propertiesLeaf == null ? void 0 : propertiesLeaf.setViewState({ type: "file-properties" })); + } + if (propertiesLeaf) void this.plugin.app.workspace.revealLeaf(propertiesLeaf); + } + }) + ); + } +}; + +// src/canvas-extensions/better-default-settings-canvas-extension.ts +var BetterDefaultSettingsCanvasExtension = class extends CanvasExtension { + isEnabled() { + return true; + } + init() { + this.modifyCanvasSettings(this.plugin.getCurrentCanvas()); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:settings-changed", + () => this.modifyCanvasSettings(this.plugin.getCurrentCanvas()) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:canvas-changed", + (canvas) => this.modifyCanvasSettings(canvas) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:double-click", + (canvas, event, preventDefault) => void this.onDoubleClick(canvas, event, preventDefault) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-created", + (canvas, node) => { + this.enforceNodeGridAlignment(canvas, node); + this.applyDefaultNodeStyles(canvas, node); + } + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:edge-created", + (canvas, edge) => void this.applyDefaultEdgeStyles(canvas, edge) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-resized", + (canvas, node) => this.enforceMaxNodeWidth(canvas, node) + )); + } + modifyCanvasSettings(canvas) { + if (!canvas) return; + const defaultTextNodeDimensionsArray = this.plugin.settings.getSetting("defaultTextNodeDimensions"); + canvas.config.defaultTextNodeDimensions = { + width: defaultTextNodeDimensionsArray[0], + height: defaultTextNodeDimensionsArray[1] + }; + const defaultFileNodeDimensionsArray = this.plugin.settings.getSetting("defaultFileNodeDimensions"); + canvas.config.defaultFileNodeDimensions = { + width: defaultFileNodeDimensionsArray[0], + height: defaultFileNodeDimensionsArray[1] + }; + canvas.config.minContainerDimension = this.plugin.settings.getSetting("minNodeSize"); + } + async onDoubleClick(canvas, event, preventDefault) { + if (event.defaultPrevented || event.target !== canvas.wrapperEl || canvas.isDragging || canvas.readonly) return; + preventDefault.value = true; + const pos = canvas.posFromEvt(event); + switch (this.plugin.settings.getSetting("nodeTypeOnDoubleClick")) { + case "file": { + const file = await new FileSelectModal(this.plugin.app, void 0, true).promise; + canvas.createFileNode({ + pos, + position: "center", + file + }); + break; + } + default: + canvas.createTextNode({ + pos, + position: "center" + }); + break; + } + } + enforceNodeGridAlignment(_canvas, node) { + if (!this.plugin.settings.getSetting("alignNewNodesToGrid")) return; + const nodeData = node.getData(); + node.setData({ + ...nodeData, + x: CanvasHelper.alignToGrid(nodeData.x), + y: CanvasHelper.alignToGrid(nodeData.y) + }); + } + applyDefaultNodeStyles(_canvas, node) { + const nodeData = node.getData(); + if (nodeData.type !== "text") return; + let color = this.plugin.settings.getSetting("defaultTextNodeColor").toString(); + if (color === "0") color = void 0; + node.setData({ + ...nodeData, + color, + styleAttributes: { + ...nodeData.styleAttributes, + ...this.plugin.settings.getSetting("defaultTextNodeStyleAttributes") + } + }); + } + async applyDefaultEdgeStyles(canvas, edge) { + var _a; + const edgeData = edge.getData(); + let color = this.plugin.settings.getSetting("defaultEdgeColor").toString(); + if (this.plugin.settings.getSetting("inheritEdgeColorFromNode")) + color = (_a = edge.from.node.getData().color) != null ? _a : color; + if (color === "0") color = void 0; + edge.setData({ + ...edgeData, + color, + styleAttributes: { + ...edgeData.styleAttributes, + ...this.plugin.settings.getSetting("defaultEdgeStyleAttributes") + } + }); + if (canvas.canvasEl.hasClass("is-connecting")) { + await new Promise((resolve) => { + new MutationObserver(() => { + if (!canvas.canvasEl.hasClass("is-connecting")) resolve(); + }).observe(canvas.canvasEl, { attributes: true, attributeFilter: ["class"] }); + }); + } + const lineDirection = this.plugin.settings.getSetting("defaultEdgeLineDirection"); + edge.setData({ + ...edge.getData(), + fromEnd: lineDirection === "bidirectional" ? "arrow" : "none", + toEnd: lineDirection === "nondirectional" ? "none" : "arrow" + }); + } + enforceMaxNodeWidth(_canvas, node) { + const maxNodeWidth = this.plugin.settings.getSetting("maxNodeWidth"); + if (maxNodeWidth <= 0) return; + const nodeData = node.getData(); + if (nodeData.type !== "text" && nodeData.type !== "file" || nodeData.portal) return; + if (nodeData.width <= maxNodeWidth) return; + node.setData({ + ...nodeData, + x: node.prevX !== void 0 ? node.prevX : nodeData.x, + // Reset the position to the previous value + width: maxNodeWidth + }); + } +}; + +// src/canvas-extensions/color-palette-canvas-extension.ts +var DEFAULT_COLORS_COUNT = 6; +var ColorPaletteCanvasExtension = class extends CanvasExtension { + constructor() { + super(...arguments); + this.observer = null; + } + isEnabled() { + return true; + } + init() { + this.styleSheets = /* @__PURE__ */ new Map(); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "window-open", + (_win, _window) => this.updateCustomColorModStyleClasses() + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "css-change", + () => this.updateCustomColorModStyleClasses() + )); + this.updateCustomColorModStyleClasses(); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:popup-menu-created", + (canvas) => this.patchColorSelection(canvas) + )); + this.plugin.register(() => { + var _a; + (_a = this.observer) == null ? void 0 : _a.disconnect(); + for (const [doc, sheet] of this.styleSheets) { + doc.adoptedStyleSheets = doc.adoptedStyleSheets.filter((s) => s !== sheet); + } + this.styleSheets.clear(); + }); + } + updateCustomColorModStyleClasses() { + const customCss = this.getCustomColors().map( + (colorId) => `.mod-canvas-color-${colorId} { --canvas-color: var(--canvas-color-${colorId}); }` + ).join("\n"); + for (const win of this.plugin.windowsManager.windows) { + const doc = win.activeDocument; + if (!doc.defaultView) continue; + let sheet = this.styleSheets.get(doc); + if (!sheet) { + sheet = new doc.defaultView.CSSStyleSheet(); + doc.adoptedStyleSheets = [...doc.adoptedStyleSheets, sheet]; + this.styleSheets.set(doc, sheet); + } + sheet.replaceSync(customCss); + } + } + patchColorSelection(canvas) { + if (this.observer) this.observer.disconnect(); + this.observer = new MutationObserver((mutations) => { + const colorMenuOpened = mutations.some( + (mutation) => Object.values(mutation.addedNodes).some( + (node) => node.instanceOf(HTMLElement) && node.classList.contains("canvas-submenu") && Object.values(node.childNodes).some( + (node2) => node2.instanceOf(HTMLElement) && node2.classList.contains("canvas-color-picker-item") + ) + ) + ); + if (!colorMenuOpened) return; + const submenu = canvas.menu.menuEl.querySelector(".canvas-submenu"); + if (!submenu) return; + const currentNodeColor = canvas.getSelectionData().nodes.map((node) => node.color).last(); + for (const colorId of this.getCustomColors()) { + const customColorMenuItem = this.createColorMenuItem(canvas, colorId); + if (currentNodeColor === colorId) customColorMenuItem.classList.add("is-active"); + submenu.insertBefore(customColorMenuItem, submenu.lastChild); + } + }); + this.observer.observe(canvas.menu.menuEl, { childList: true }); + } + createColorMenuItem(canvas, colorId) { + const menuItem = activeWindow.createDiv(); + menuItem.classList.add("canvas-color-picker-item"); + menuItem.classList.add(`mod-canvas-color-${colorId}`); + menuItem.addEventListener("click", () => { + menuItem.classList.add("is-active"); + for (const item of canvas.selection) { + item.setColor(colorId); + } + canvas.requestSave(); + }); + return menuItem; + } + getCustomColors() { + const colors = []; + const style = getComputedStyle(activeDocument.body); + let colorIndex = DEFAULT_COLORS_COUNT + 1; + while (style.getPropertyValue(`--canvas-color-${colorIndex}`)) { + colors.push(colorIndex.toString()); + colorIndex++; + } + return colors; + } +}; + +// src/canvas-extensions/collapsible-groups-canvas-extension.ts +var import_obsidian19 = require("obsidian"); +var CollapsibleGroupsCanvasExtension = class extends CanvasExtension { + isEnabled() { + return "collapsibleGroupsFeatureEnabled"; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-changed", + (canvas, node) => this.onNodeChanged(canvas, node) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-bbox-requested", + (canvas, node, bbox) => this.onNodeBBoxRequested(canvas, node, bbox) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:copy", + (canvas, selectionData) => this.onCopy(canvas, selectionData) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:data-requested", + (_canvas, data) => this.expandNodes(data) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:data-loaded:before", + (_canvas, data, _setData) => this.collapseNodes(data) + )); + this.plugin.addCommand({ + id: "toggle-collapse-group", + name: "Toggle collapse group", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => { + var _a; + return canvas.selection.size === 1 && ((_a = [...canvas.selection][0]) == null ? void 0 : _a.getData().type) === "group"; + }, + (canvas) => this.toggleCollapseGroup(canvas, [...canvas.selection][0]) + ) + }); + } + toggleCollapseGroup(canvas, node) { + const data = node.getData(); + this.setCollapsed(node.canvas, node, data.collapsed ? void 0 : true); + canvas.markMoved(node); + } + onNodeChanged(canvas, groupNode) { + var _a, _b; + const groupNodeData = groupNode.getData(); + if (groupNodeData.type !== "group") return; + (_a = groupNode.collapseEl) == null ? void 0 : _a.remove(); + const collapseEl = activeWindow.createDiv(); + collapseEl.className = "collapse-button"; + (0, import_obsidian19.setIcon)(collapseEl, groupNodeData.collapsed ? "plus-circle" : "minus-circle"); + collapseEl.onclick = () => this.toggleCollapseGroup(canvas, groupNode); + groupNode.collapseEl = collapseEl; + (_b = groupNode.labelEl) == null ? void 0 : _b.insertAdjacentElement("afterend", collapseEl); + } + onCopy(_canvas, selectionData) { + for (const collapsedGroupData of selectionData.nodes) { + if (collapsedGroupData.type !== "group" || !collapsedGroupData.collapsed || !collapsedGroupData.collapsedData) continue; + selectionData.nodes.push(...collapsedGroupData.collapsedData.nodes.map((nodeData) => ({ + ...nodeData, + // Restore the relative position of the node to the group + x: nodeData.x + collapsedGroupData.x, + y: nodeData.y + collapsedGroupData.y + }))); + selectionData.edges.push(...collapsedGroupData.collapsedData.edges); + } + } + setCollapsed(canvas, groupNode, collapsed) { + groupNode.setData({ ...groupNode.getData(), collapsed }); + canvas.setData(canvas.getData()); + canvas.history.current--; + canvas.pushHistory(canvas.getData()); + canvas.requestSave(); + } + onNodeBBoxRequested(canvas, node, bbox) { + var _a, _b; + const nodeData = node.getData(); + if (nodeData.type !== "group" || !nodeData.collapsed) return; + const collapseElBBox = (_a = node.collapseEl) == null ? void 0 : _a.getBoundingClientRect(); + if (!collapseElBBox) return; + const labelElBBox = (_b = node.labelEl) == null ? void 0 : _b.getBoundingClientRect(); + if (!labelElBBox) return; + const minPos = canvas.posFromClient({ x: collapseElBBox.left, y: collapseElBBox.top }); + const maxPos = canvas.posFromClient({ x: labelElBBox.right, y: collapseElBBox.bottom }); + bbox.minX = minPos.x; + bbox.minY = minPos.y; + bbox.maxX = maxPos.x; + bbox.maxY = maxPos.y; + } + expandNodes(data) { + var _a; + if (!data) return; + data.nodes = (_a = data.nodes) == null ? void 0 : _a.flatMap((groupNodeData) => { + const collapsedData = groupNodeData.collapsedData; + if (collapsedData === void 0) return [groupNodeData]; + delete groupNodeData.collapsedData; + data.edges.push(...collapsedData.edges); + return [groupNodeData, ...collapsedData.nodes.map((nodeData) => ({ + ...nodeData, + // Restore the relative position of the node to the group + x: nodeData.x + groupNodeData.x, + y: nodeData.y + groupNodeData.y + }))]; + }); + } + collapseNodes(data) { + var _a; + (_a = data == null ? void 0 : data.nodes) == null ? void 0 : _a.forEach((groupNodeData) => { + var _a2, _b, _c, _d; + if (!groupNodeData.collapsed) return; + const groupNodeBBox = CanvasHelper.getBBox([groupNodeData]); + const containedNodesData = data.nodes.filter( + (nodeData) => nodeData.id !== groupNodeData.id && BBoxHelper.insideBBox(CanvasHelper.getBBox([nodeData]), groupNodeBBox, false) + ); + const containedEdgesData = data.edges.filter((edgeData) => { + return containedNodesData.some((nodeData) => nodeData.id === edgeData.fromNode) || containedNodesData.some((nodeData) => nodeData.id === edgeData.toNode); + }); + data.nodes = data.nodes.filter((nodeData) => !containedNodesData.includes(nodeData)); + data.edges = data.edges.filter((edgeData) => !containedEdgesData.includes(edgeData)); + const newContainedNodesData = containedNodesData.filter((nodeData) => { + var _a3, _b2, _c2; + return !((_c2 = (_b2 = (_a3 = groupNodeData.collapsedData) == null ? void 0 : _a3.nodes) == null ? void 0 : _b2.some((e) => e.id === nodeData.id)) != null ? _c2 : false); + }); + const newContainedEdgesData = containedEdgesData.filter((edgeData) => { + var _a3, _b2, _c2; + return !((_c2 = (_b2 = (_a3 = groupNodeData.collapsedData) == null ? void 0 : _a3.edges) == null ? void 0 : _b2.some((n) => n.id === edgeData.id)) != null ? _c2 : false); + }); + groupNodeData.collapsedData = { + nodes: [ + ...(_b = (_a2 = groupNodeData.collapsedData) == null ? void 0 : _a2.nodes) != null ? _b : [], + ...newContainedNodesData.map((nodeData) => ({ + ...nodeData, + // Store the relative position of the node to the group + x: nodeData.x - groupNodeData.x, + y: nodeData.y - groupNodeData.y + })) + ], + edges: [ + ...(_d = (_c = groupNodeData.collapsedData) == null ? void 0 : _c.edges) != null ? _d : [], + ...newContainedEdgesData + ] + }; + }); + } +}; + +// src/canvas-extensions/focus-mode-canvas-extension.ts +var CONTROL_MENU_FOCUS_TOGGLE_ID = "focus-mode-toggle"; +var FocusModeCanvasExtension = class extends CanvasExtension { + isEnabled() { + return "focusModeFeatureEnabled"; + } + init() { + this.plugin.addCommand({ + id: "toggle-focus-mode", + name: "Toggle Focus Mode", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (_canvas) => true, + (canvas) => this.toggleFocusMode(canvas) + ) + }); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:canvas-changed", + (canvas) => this.addControlMenuToggle(canvas) + )); + } + addControlMenuToggle(canvas) { + var _a; + const settingsContainer = (_a = canvas.quickSettingsButton) == null ? void 0 : _a.parentElement; + if (!settingsContainer) return; + const controlMenuFocusToggle = CanvasHelper.createControlMenuButton({ + id: CONTROL_MENU_FOCUS_TOGGLE_ID, + label: "Focus Mode", + icon: "focus", + callback: () => this.toggleFocusMode(canvas) + }); + CanvasHelper.addControlMenuButton(settingsContainer, controlMenuFocusToggle); + } + toggleFocusMode(canvas) { + var _a, _b; + const controlMenuFocusToggle = (_b = (_a = canvas.quickSettingsButton) == null ? void 0 : _a.parentElement) == null ? void 0 : _b.querySelector(`#${CONTROL_MENU_FOCUS_TOGGLE_ID}`); + if (!controlMenuFocusToggle) return; + const newValue = controlMenuFocusToggle.dataset.toggled !== "true"; + canvas.wrapperEl.dataset.focusModeEnabled = newValue.toString(); + controlMenuFocusToggle.dataset.toggled = newValue.toString(); + } +}; + +// src/canvas-extensions/auto-file-node-edges-canvas-extension.ts +var AUTO_EDGE_ID_PREFIX = "afe"; +var AutoFileNodeEdgesCanvasExtension = class extends CanvasExtension { + isEnabled() { + return "autoFileNodeEdgesFeatureEnabled"; + } + init() { + this.plugin.registerEvent(this.plugin.app.metadataCache.on("changed", (file) => { + for (const canvas of this.plugin.getCanvases()) + this.onMetadataChanged(canvas, file); + })); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-added", + (canvas, node) => this.onNodeChanged(canvas, node) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-changed", + (canvas, node) => this.onNodeChanged(canvas, node) + )); + } + onMetadataChanged(canvas, file) { + var _a; + for (const node of canvas.nodes.values()) { + if (node.getData().type !== "file" || ((_a = node.file) == null ? void 0 : _a.path) !== file.path) continue; + this.updateFileNodeEdges(canvas, node); + } + } + onNodeChanged(canvas, node) { + if (node.getData().type !== "file") return; + for (const node2 of canvas.nodes.values()) { + if (node2.getData().type !== "file") continue; + this.updateFileNodeEdges(canvas, node2); + } + } + updateFileNodeEdges(canvas, node) { + const edges = this.getFileNodeEdges(canvas, node); + const newEdges = Array.from(edges.values()).filter((edge) => !canvas.edges.has(edge.id)); + canvas.importData({ nodes: [], edges: newEdges }, false, false); + for (const edge of canvas.edges.values()) { + if (edge.id.startsWith(`${AUTO_EDGE_ID_PREFIX}${node.id}`) && !edges.has(edge.id)) + canvas.removeEdge(edge); + } + } + getFileNodeEdges(canvas, node) { + var _a, _b; + const canvasFile = canvas.view.file; + if (!canvasFile || !node.file) return /* @__PURE__ */ new Map(); + const fileMetadata = this.plugin.app.metadataCache.getFileCache(node.file); + if (!fileMetadata) return /* @__PURE__ */ new Map(); + const linkedFilesFrontmatterKey = this.plugin.settings.getSetting("autoFileNodeEdgesFrontmatterKey"); + const fileLinksToBeLinkedTo = (_b = (_a = fileMetadata.frontmatterLinks) == null ? void 0 : _a.filter((link) => link.key.split(".")[0] === linkedFilesFrontmatterKey)) != null ? _b : []; + const filepathsToBeLinkedTo = fileLinksToBeLinkedTo.map((link) => this.plugin.app.metadataCache.getFirstLinkpathDest(link.link, canvasFile.path)).map((file) => file == null ? void 0 : file.path).filter((path) => path !== null); + const nodesToBeLinkedTo = Array.from(canvas.nodes.values()).filter((otherNode) => { + var _a2; + return otherNode.id !== node.id && filepathsToBeLinkedTo.includes((_a2 = otherNode.file) == null ? void 0 : _a2.path); + }); + const newEdges = /* @__PURE__ */ new Map(); + for (const otherNode of nodesToBeLinkedTo) { + const edgeId = `${AUTO_EDGE_ID_PREFIX}${node.id}${otherNode.id}`; + const bestFromSide = CanvasHelper.getBestSideForFloatingEdge(BBoxHelper.getCenterOfBBoxSide(otherNode.getBBox(), "right"), node); + const bestToSide = CanvasHelper.getBestSideForFloatingEdge(BBoxHelper.getCenterOfBBoxSide(node.getBBox(), "left"), otherNode); + newEdges.set(edgeId, { + id: edgeId, + fromNode: node.id, + fromSide: bestFromSide, + fromFloating: true, + toNode: otherNode.id, + toSide: bestToSide, + toFloating: true + }); + } + return newEdges; + } +}; + +// src/canvas-extensions/flip-edge-canvas-extension.ts +var FlipEdgeCanvasExtension = class extends CanvasExtension { + isEnabled() { + return "flipEdgeFeatureEnabled"; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:popup-menu-created", + (canvas) => this.onPopupMenuCreated(canvas) + )); + } + onPopupMenuCreated(canvas) { + var _a, _b; + const popupMenuEl = (_a = canvas == null ? void 0 : canvas.menu) == null ? void 0 : _a.menuEl; + if (!popupMenuEl) return; + const POSSIBLE_ICONS = ["lucide-arrow-right", "lucide-move-horizontal", "line-horizontal"]; + let edgeDirectionButton = null; + for (const icon of POSSIBLE_ICONS) { + edgeDirectionButton = (_b = popupMenuEl.querySelector(`button:not([id]) > .svg-icon.${icon}`)) == null ? void 0 : _b.parentElement; + if (edgeDirectionButton) break; + } + if (!edgeDirectionButton) return; + edgeDirectionButton.addEventListener("click", () => this.onEdgeDirectionDropdownCreated(canvas)); + } + onEdgeDirectionDropdownCreated(canvas) { + const dropdownScrollerEl = activeDocument.body.querySelector("div.menu .menu-scroll"); + if (!dropdownScrollerEl) return; + const separatorEl = CanvasHelper.createDropdownSeparatorElement(); + dropdownScrollerEl.appendChild(separatorEl); + const groupEl = dropdownScrollerEl.createDiv(); + groupEl.classList.add("menu-group"); + const flipEdgeButton = CanvasHelper.createDropdownOptionElement({ + icon: "flip-horizontal-2", + label: "Flip Edge", + callback: () => this.flipEdge(canvas) + }); + groupEl.appendChild(flipEdgeButton); + } + flipEdge(canvas) { + const selectedEdges = [...canvas.selection].filter( + (item) => item.path !== void 0 + ); + if (selectedEdges.length === 0) return; + for (const edge of selectedEdges) { + edge.update({ + ...edge.from, + node: edge.to.node, + side: edge.to.side + }, { + ...edge.to, + node: edge.from.node, + side: edge.from.side + }); + } + canvas.pushHistory(canvas.getData()); + } +}; + +// src/canvas-extensions/edge-selection-canvas-extension.ts +var DIRECTION_MENU_MAP = { + connected: { + id: "select-connected-edges", + icon: "arrows-selected", + label: "Select Connected Edges" + }, + outgoing: { + id: "select-outgoing-edges", + icon: "arrow-right-selected", + label: "Select Outgoing Edges" + }, + incoming: { + id: "select-incoming-edges", + icon: "arrow-left-selected", + label: "Select Incoming Edges" + } +}; +var EdgeSelectionCanvasExtension = class extends CanvasExtension { + isEnabled() { + return "edgeSelectionEnabled"; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:popup-menu-created", + (canvas) => this.onPopupMenuCreated(canvas) + )); + } + onPopupMenuCreated(canvas) { + var _a; + const popupMenuEl = (_a = canvas == null ? void 0 : canvas.menu) == null ? void 0 : _a.menuEl; + if (!popupMenuEl) return; + const selectionNodeData = canvas.getSelectionData().nodes; + if (canvas.readonly || selectionNodeData.length === 0) return; + const selectEdgeByDirection = this.plugin.settings.getSetting("selectEdgeByDirection"); + const menuDirectionSet = /* @__PURE__ */ new Set(["connected"]); + if (selectionNodeData.length === 1) { + const node = canvas.nodes.get(selectionNodeData[0].id); + if (!node) return; + const edges = canvas.getEdgesForNode(node); + if (edges.length === 0) return; + if (selectEdgeByDirection) { + edges.forEach((edge) => { + if (edge.from.node === node) { + menuDirectionSet.add("outgoing"); + } else if (edge.to.node === node) { + menuDirectionSet.add("incoming"); + } + }); + } + } else if (selectEdgeByDirection) { + menuDirectionSet.add("outgoing"); + menuDirectionSet.add("incoming"); + } + menuDirectionSet.forEach((direction) => { + const config = DIRECTION_MENU_MAP[direction]; + CanvasHelper.addPopupMenuOption(canvas, CanvasHelper.createPopupMenuOption({ + ...config, + callback: () => CanvasHelper.selectEdgesForNodes(canvas, direction) + })); + }); + } +}; + +// node_modules/html-to-image/es/util.js +function resolveUrl(url, baseUrl) { + if (url.match(/^[a-z]+:\/\//i)) { + return url; + } + if (url.match(/^\/\//)) { + return window.location.protocol + url; + } + if (url.match(/^[a-z]+:/i)) { + return url; + } + const doc = document.implementation.createHTMLDocument(); + const base = doc.createElement("base"); + const a = doc.createElement("a"); + doc.head.appendChild(base); + doc.body.appendChild(a); + if (baseUrl) { + base.href = baseUrl; + } + a.href = url; + return a.href; +} +var uuid = /* @__PURE__ */ (() => { + let counter = 0; + const random = () => ( + // eslint-disable-next-line no-bitwise + `0000${(Math.random() * 36 ** 4 << 0).toString(36)}`.slice(-4) + ); + return () => { + counter += 1; + return `u${random()}${counter}`; + }; +})(); +function toArray(arrayLike) { + const arr = []; + for (let i = 0, l = arrayLike.length; i < l; i++) { + arr.push(arrayLike[i]); + } + return arr; +} +function px(node, styleProperty) { + const win = node.ownerDocument.defaultView || window; + const val = win.getComputedStyle(node).getPropertyValue(styleProperty); + return val ? parseFloat(val.replace("px", "")) : 0; +} +function getNodeWidth(node) { + const leftBorder = px(node, "border-left-width"); + const rightBorder = px(node, "border-right-width"); + return node.clientWidth + leftBorder + rightBorder; +} +function getNodeHeight(node) { + const topBorder = px(node, "border-top-width"); + const bottomBorder = px(node, "border-bottom-width"); + return node.clientHeight + topBorder + bottomBorder; +} +function getImageSize(targetNode, options = {}) { + const width = options.width || getNodeWidth(targetNode); + const height = options.height || getNodeHeight(targetNode); + return { width, height }; +} +function getPixelRatio() { + let ratio; + let FINAL_PROCESS; + try { + FINAL_PROCESS = process; + } catch (e) { + } + const val = FINAL_PROCESS && FINAL_PROCESS.env ? FINAL_PROCESS.env.devicePixelRatio : null; + if (val) { + ratio = parseInt(val, 10); + if (Number.isNaN(ratio)) { + ratio = 1; + } + } + return ratio || window.devicePixelRatio || 1; +} +var canvasDimensionLimit = 16384; +function checkCanvasDimensions(canvas) { + if (canvas.width > canvasDimensionLimit || canvas.height > canvasDimensionLimit) { + if (canvas.width > canvasDimensionLimit && canvas.height > canvasDimensionLimit) { + if (canvas.width > canvas.height) { + canvas.height *= canvasDimensionLimit / canvas.width; + canvas.width = canvasDimensionLimit; + } else { + canvas.width *= canvasDimensionLimit / canvas.height; + canvas.height = canvasDimensionLimit; + } + } else if (canvas.width > canvasDimensionLimit) { + canvas.height *= canvasDimensionLimit / canvas.width; + canvas.width = canvasDimensionLimit; + } else { + canvas.width *= canvasDimensionLimit / canvas.height; + canvas.height = canvasDimensionLimit; + } + } +} +function createImage(url) { + return new Promise((resolve, reject) => { + const img = new Image(); + img.decode = () => resolve(img); + img.onload = () => resolve(img); + img.onerror = reject; + img.crossOrigin = "anonymous"; + img.decoding = "async"; + img.src = url; + }); +} +async function svgToDataURL(svg) { + return Promise.resolve().then(() => new XMLSerializer().serializeToString(svg)).then(encodeURIComponent).then((html) => `data:image/svg+xml;charset=utf-8,${html}`); +} +async function nodeToDataURL(node, width, height) { + const xmlns = "http://www.w3.org/2000/svg"; + const svg = document.createElementNS(xmlns, "svg"); + const foreignObject = document.createElementNS(xmlns, "foreignObject"); + svg.setAttribute("width", `${width}`); + svg.setAttribute("height", `${height}`); + svg.setAttribute("viewBox", `0 0 ${width} ${height}`); + foreignObject.setAttribute("width", "100%"); + foreignObject.setAttribute("height", "100%"); + foreignObject.setAttribute("x", "0"); + foreignObject.setAttribute("y", "0"); + foreignObject.setAttribute("externalResourcesRequired", "true"); + svg.appendChild(foreignObject); + foreignObject.appendChild(node); + return svgToDataURL(svg); +} +var isInstanceOfElement = (node, instance) => { + if (node instanceof instance) + return true; + const nodePrototype = Object.getPrototypeOf(node); + if (nodePrototype === null) + return false; + return nodePrototype.constructor.name === instance.name || isInstanceOfElement(nodePrototype, instance); +}; + +// node_modules/html-to-image/es/clone-pseudos.js +function formatCSSText(style) { + const content = style.getPropertyValue("content"); + return `${style.cssText} content: '${content.replace(/'|"/g, "")}';`; +} +function formatCSSProperties(style) { + return toArray(style).map((name) => { + const value = style.getPropertyValue(name); + const priority = style.getPropertyPriority(name); + return `${name}: ${value}${priority ? " !important" : ""};`; + }).join(" "); +} +function getPseudoElementStyle(className, pseudo, style) { + const selector = `.${className}:${pseudo}`; + const cssText = style.cssText ? formatCSSText(style) : formatCSSProperties(style); + return document.createTextNode(`${selector}{${cssText}}`); +} +function clonePseudoElement(nativeNode, clonedNode, pseudo) { + const style = window.getComputedStyle(nativeNode, pseudo); + const content = style.getPropertyValue("content"); + if (content === "" || content === "none") { + return; + } + const className = uuid(); + try { + clonedNode.className = `${clonedNode.className} ${className}`; + } catch (err) { + return; + } + const styleElement = document.createElement("style"); + styleElement.appendChild(getPseudoElementStyle(className, pseudo, style)); + clonedNode.appendChild(styleElement); +} +function clonePseudoElements(nativeNode, clonedNode) { + clonePseudoElement(nativeNode, clonedNode, ":before"); + clonePseudoElement(nativeNode, clonedNode, ":after"); +} + +// node_modules/html-to-image/es/mimes.js +var WOFF = "application/font-woff"; +var JPEG = "image/jpeg"; +var mimes = { + woff: WOFF, + woff2: WOFF, + ttf: "application/font-truetype", + eot: "application/vnd.ms-fontobject", + png: "image/png", + jpg: JPEG, + jpeg: JPEG, + gif: "image/gif", + tiff: "image/tiff", + svg: "image/svg+xml", + webp: "image/webp" +}; +function getExtension(url) { + const match = /\.([^./]*?)$/g.exec(url); + return match ? match[1] : ""; +} +function getMimeType(url) { + const extension = getExtension(url).toLowerCase(); + return mimes[extension] || ""; +} + +// node_modules/html-to-image/es/dataurl.js +function getContentFromDataUrl(dataURL) { + return dataURL.split(/,/)[1]; +} +function isDataUrl(url) { + return url.search(/^(data:)/) !== -1; +} +function makeDataUrl(content, mimeType) { + return `data:${mimeType};base64,${content}`; +} +async function fetchAsDataURL(url, init, process2) { + const res = await fetch(url, init); + if (res.status === 404) { + throw new Error(`Resource "${res.url}" not found`); + } + const blob = await res.blob(); + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onerror = reject; + reader.onloadend = () => { + try { + resolve(process2({ res, result: reader.result })); + } catch (error) { + reject(error); + } + }; + reader.readAsDataURL(blob); + }); +} +var cache = {}; +function getCacheKey(url, contentType, includeQueryParams) { + let key = url.replace(/\?.*/, ""); + if (includeQueryParams) { + key = url; + } + if (/ttf|otf|eot|woff2?/i.test(key)) { + key = key.replace(/.*\//, ""); + } + return contentType ? `[${contentType}]${key}` : key; +} +async function resourceToDataURL(resourceUrl, contentType, options) { + const cacheKey = getCacheKey(resourceUrl, contentType, options.includeQueryParams); + if (cache[cacheKey] != null) { + return cache[cacheKey]; + } + if (options.cacheBust) { + resourceUrl += (/\?/.test(resourceUrl) ? "&" : "?") + (/* @__PURE__ */ new Date()).getTime(); + } + let dataURL; + try { + const content = await fetchAsDataURL(resourceUrl, options.fetchRequestInit, ({ res, result }) => { + if (!contentType) { + contentType = res.headers.get("Content-Type") || ""; + } + return getContentFromDataUrl(result); + }); + dataURL = makeDataUrl(content, contentType); + } catch (error) { + dataURL = options.imagePlaceholder || ""; + let msg = `Failed to fetch resource: ${resourceUrl}`; + if (error) { + msg = typeof error === "string" ? error : error.message; + } + if (msg) { + console.warn(msg); + } + } + cache[cacheKey] = dataURL; + return dataURL; +} + +// node_modules/html-to-image/es/clone-node.js +async function cloneCanvasElement(canvas) { + const dataURL = canvas.toDataURL(); + if (dataURL === "data:,") { + return canvas.cloneNode(false); + } + return createImage(dataURL); +} +async function cloneVideoElement(video, options) { + if (video.currentSrc) { + const canvas = document.createElement("canvas"); + const ctx = canvas.getContext("2d"); + canvas.width = video.clientWidth; + canvas.height = video.clientHeight; + ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(video, 0, 0, canvas.width, canvas.height); + const dataURL2 = canvas.toDataURL(); + return createImage(dataURL2); + } + const poster = video.poster; + const contentType = getMimeType(poster); + const dataURL = await resourceToDataURL(poster, contentType, options); + return createImage(dataURL); +} +async function cloneIFrameElement(iframe) { + var _a; + try { + if ((_a = iframe === null || iframe === void 0 ? void 0 : iframe.contentDocument) === null || _a === void 0 ? void 0 : _a.body) { + return await cloneNode(iframe.contentDocument.body, {}, true); + } + } catch (_b) { + } + return iframe.cloneNode(false); +} +async function cloneSingleNode(node, options) { + if (isInstanceOfElement(node, HTMLCanvasElement)) { + return cloneCanvasElement(node); + } + if (isInstanceOfElement(node, HTMLVideoElement)) { + return cloneVideoElement(node, options); + } + if (isInstanceOfElement(node, HTMLIFrameElement)) { + return cloneIFrameElement(node); + } + return node.cloneNode(false); +} +var isSlotElement = (node) => node.tagName != null && node.tagName.toUpperCase() === "SLOT"; +async function cloneChildren(nativeNode, clonedNode, options) { + var _a, _b; + let children = []; + if (isSlotElement(nativeNode) && nativeNode.assignedNodes) { + children = toArray(nativeNode.assignedNodes()); + } else if (isInstanceOfElement(nativeNode, HTMLIFrameElement) && ((_a = nativeNode.contentDocument) === null || _a === void 0 ? void 0 : _a.body)) { + children = toArray(nativeNode.contentDocument.body.childNodes); + } else { + children = toArray(((_b = nativeNode.shadowRoot) !== null && _b !== void 0 ? _b : nativeNode).childNodes); + } + if (children.length === 0 || isInstanceOfElement(nativeNode, HTMLVideoElement)) { + return clonedNode; + } + await children.reduce((deferred, child) => deferred.then(() => cloneNode(child, options)).then((clonedChild) => { + if (clonedChild) { + clonedNode.appendChild(clonedChild); + } + }), Promise.resolve()); + return clonedNode; +} +function cloneCSSStyle(nativeNode, clonedNode) { + const targetStyle = clonedNode.style; + if (!targetStyle) { + return; + } + const sourceStyle = window.getComputedStyle(nativeNode); + if (sourceStyle.cssText) { + targetStyle.cssText = sourceStyle.cssText; + targetStyle.transformOrigin = sourceStyle.transformOrigin; + } else { + toArray(sourceStyle).forEach((name) => { + let value = sourceStyle.getPropertyValue(name); + if (name === "font-size" && value.endsWith("px")) { + const reducedFont = Math.floor(parseFloat(value.substring(0, value.length - 2))) - 0.1; + value = `${reducedFont}px`; + } + if (isInstanceOfElement(nativeNode, HTMLIFrameElement) && name === "display" && value === "inline") { + value = "block"; + } + if (name === "d" && clonedNode.getAttribute("d")) { + value = `path(${clonedNode.getAttribute("d")})`; + } + targetStyle.setProperty(name, value, sourceStyle.getPropertyPriority(name)); + }); + } +} +function cloneInputValue(nativeNode, clonedNode) { + if (isInstanceOfElement(nativeNode, HTMLTextAreaElement)) { + clonedNode.innerHTML = nativeNode.value; + } + if (isInstanceOfElement(nativeNode, HTMLInputElement)) { + clonedNode.setAttribute("value", nativeNode.value); + } +} +function cloneSelectValue(nativeNode, clonedNode) { + if (isInstanceOfElement(nativeNode, HTMLSelectElement)) { + const clonedSelect = clonedNode; + const selectedOption = Array.from(clonedSelect.children).find((child) => nativeNode.value === child.getAttribute("value")); + if (selectedOption) { + selectedOption.setAttribute("selected", ""); + } + } +} +function decorate(nativeNode, clonedNode) { + if (isInstanceOfElement(clonedNode, Element)) { + cloneCSSStyle(nativeNode, clonedNode); + clonePseudoElements(nativeNode, clonedNode); + cloneInputValue(nativeNode, clonedNode); + cloneSelectValue(nativeNode, clonedNode); + } + return clonedNode; +} +async function ensureSVGSymbols(clone, options) { + const uses = clone.querySelectorAll ? clone.querySelectorAll("use") : []; + if (uses.length === 0) { + return clone; + } + const processedDefs = {}; + for (let i = 0; i < uses.length; i++) { + const use = uses[i]; + const id = use.getAttribute("xlink:href"); + if (id) { + const exist = clone.querySelector(id); + const definition = document.querySelector(id); + if (!exist && definition && !processedDefs[id]) { + processedDefs[id] = await cloneNode(definition, options, true); + } + } + } + const nodes = Object.values(processedDefs); + if (nodes.length) { + const ns = "http://www.w3.org/1999/xhtml"; + const svg = document.createElementNS(ns, "svg"); + svg.setAttribute("xmlns", ns); + svg.style.position = "absolute"; + svg.style.width = "0"; + svg.style.height = "0"; + svg.style.overflow = "hidden"; + svg.style.display = "none"; + const defs = document.createElementNS(ns, "defs"); + svg.appendChild(defs); + for (let i = 0; i < nodes.length; i++) { + defs.appendChild(nodes[i]); + } + clone.appendChild(svg); + } + return clone; +} +async function cloneNode(node, options, isRoot) { + if (!isRoot && options.filter && !options.filter(node)) { + return null; + } + return Promise.resolve(node).then((clonedNode) => cloneSingleNode(clonedNode, options)).then((clonedNode) => cloneChildren(node, clonedNode, options)).then((clonedNode) => decorate(node, clonedNode)).then((clonedNode) => ensureSVGSymbols(clonedNode, options)); +} + +// node_modules/html-to-image/es/embed-resources.js +var URL_REGEX = /url\((['"]?)([^'"]+?)\1\)/g; +var URL_WITH_FORMAT_REGEX = /url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g; +var FONT_SRC_REGEX = /src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g; +function toRegex(url) { + const escaped = url.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1"); + return new RegExp(`(url\\(['"]?)(${escaped})(['"]?\\))`, "g"); +} +function parseURLs(cssText) { + const urls = []; + cssText.replace(URL_REGEX, (raw, quotation, url) => { + urls.push(url); + return raw; + }); + return urls.filter((url) => !isDataUrl(url)); +} +async function embed(cssText, resourceURL, baseURL, options, getContentFromUrl) { + try { + const resolvedURL = baseURL ? resolveUrl(resourceURL, baseURL) : resourceURL; + const contentType = getMimeType(resourceURL); + let dataURL; + if (getContentFromUrl) { + const content = await getContentFromUrl(resolvedURL); + dataURL = makeDataUrl(content, contentType); + } else { + dataURL = await resourceToDataURL(resolvedURL, contentType, options); + } + return cssText.replace(toRegex(resourceURL), `$1${dataURL}$3`); + } catch (error) { + } + return cssText; +} +function filterPreferredFontFormat(str, { preferredFontFormat }) { + return !preferredFontFormat ? str : str.replace(FONT_SRC_REGEX, (match) => { + while (true) { + const [src, , format] = URL_WITH_FORMAT_REGEX.exec(match) || []; + if (!format) { + return ""; + } + if (format === preferredFontFormat) { + return `src: ${src};`; + } + } + }); +} +function shouldEmbed(url) { + return url.search(URL_REGEX) !== -1; +} +async function embedResources(cssText, baseUrl, options) { + if (!shouldEmbed(cssText)) { + return cssText; + } + const filteredCSSText = filterPreferredFontFormat(cssText, options); + const urls = parseURLs(filteredCSSText); + return urls.reduce((deferred, url) => deferred.then((css) => embed(css, url, baseUrl, options)), Promise.resolve(filteredCSSText)); +} + +// node_modules/html-to-image/es/embed-images.js +async function embedProp(propName, node, options) { + var _a; + const propValue = (_a = node.style) === null || _a === void 0 ? void 0 : _a.getPropertyValue(propName); + if (propValue) { + const cssString = await embedResources(propValue, null, options); + node.style.setProperty(propName, cssString, node.style.getPropertyPriority(propName)); + return true; + } + return false; +} +async function embedBackground(clonedNode, options) { + if (!await embedProp("background", clonedNode, options)) { + await embedProp("background-image", clonedNode, options); + } + if (!await embedProp("mask", clonedNode, options)) { + await embedProp("mask-image", clonedNode, options); + } +} +async function embedImageNode(clonedNode, options) { + const isImageElement = isInstanceOfElement(clonedNode, HTMLImageElement); + if (!(isImageElement && !isDataUrl(clonedNode.src)) && !(isInstanceOfElement(clonedNode, SVGImageElement) && !isDataUrl(clonedNode.href.baseVal))) { + return; + } + const url = isImageElement ? clonedNode.src : clonedNode.href.baseVal; + const dataURL = await resourceToDataURL(url, getMimeType(url), options); + await new Promise((resolve, reject) => { + clonedNode.onload = resolve; + clonedNode.onerror = reject; + const image = clonedNode; + if (image.decode) { + image.decode = resolve; + } + if (image.loading === "lazy") { + image.loading = "eager"; + } + if (isImageElement) { + clonedNode.srcset = ""; + clonedNode.src = dataURL; + } else { + clonedNode.href.baseVal = dataURL; + } + }); +} +async function embedChildren(clonedNode, options) { + const children = toArray(clonedNode.childNodes); + const deferreds = children.map((child) => embedImages(child, options)); + await Promise.all(deferreds).then(() => clonedNode); +} +async function embedImages(clonedNode, options) { + if (isInstanceOfElement(clonedNode, Element)) { + await embedBackground(clonedNode, options); + await embedImageNode(clonedNode, options); + await embedChildren(clonedNode, options); + } +} + +// node_modules/html-to-image/es/apply-style.js +function applyStyle(node, options) { + const { style } = node; + if (options.backgroundColor) { + style.backgroundColor = options.backgroundColor; + } + if (options.width) { + style.width = `${options.width}px`; + } + if (options.height) { + style.height = `${options.height}px`; + } + const manual = options.style; + if (manual != null) { + Object.keys(manual).forEach((key) => { + style[key] = manual[key]; + }); + } + return node; +} + +// node_modules/html-to-image/es/embed-webfonts.js +var cssFetchCache = {}; +async function fetchCSS(url) { + let cache2 = cssFetchCache[url]; + if (cache2 != null) { + return cache2; + } + const res = await fetch(url); + const cssText = await res.text(); + cache2 = { url, cssText }; + cssFetchCache[url] = cache2; + return cache2; +} +async function embedFonts(data, options) { + let cssText = data.cssText; + const regexUrl = /url\(["']?([^"')]+)["']?\)/g; + const fontLocs = cssText.match(/url\([^)]+\)/g) || []; + const loadFonts = fontLocs.map(async (loc) => { + let url = loc.replace(regexUrl, "$1"); + if (!url.startsWith("https://")) { + url = new URL(url, data.url).href; + } + return fetchAsDataURL(url, options.fetchRequestInit, ({ result }) => { + cssText = cssText.replace(loc, `url(${result})`); + return [loc, result]; + }); + }); + return Promise.all(loadFonts).then(() => cssText); +} +function parseCSS(source) { + if (source == null) { + return []; + } + const result = []; + const commentsRegex = /(\/\*[\s\S]*?\*\/)/gi; + let cssText = source.replace(commentsRegex, ""); + const keyframesRegex = new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})", "gi"); + while (true) { + const matches = keyframesRegex.exec(cssText); + if (matches === null) { + break; + } + result.push(matches[0]); + } + cssText = cssText.replace(keyframesRegex, ""); + const importRegex = /@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi; + const combinedCSSRegex = "((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})"; + const unifiedRegex = new RegExp(combinedCSSRegex, "gi"); + while (true) { + let matches = importRegex.exec(cssText); + if (matches === null) { + matches = unifiedRegex.exec(cssText); + if (matches === null) { + break; + } else { + importRegex.lastIndex = unifiedRegex.lastIndex; + } + } else { + unifiedRegex.lastIndex = importRegex.lastIndex; + } + result.push(matches[0]); + } + return result; +} +async function getCSSRules(styleSheets, options) { + const ret = []; + const deferreds = []; + styleSheets.forEach((sheet) => { + if ("cssRules" in sheet) { + try { + toArray(sheet.cssRules || []).forEach((item, index) => { + if (item.type === CSSRule.IMPORT_RULE) { + let importIndex = index + 1; + const url = item.href; + const deferred = fetchCSS(url).then((metadata) => embedFonts(metadata, options)).then((cssText) => parseCSS(cssText).forEach((rule) => { + try { + sheet.insertRule(rule, rule.startsWith("@import") ? importIndex += 1 : sheet.cssRules.length); + } catch (error) { + console.error("Error inserting rule from remote css", { + rule, + error + }); + } + })).catch((e) => { + console.error("Error loading remote css", e.toString()); + }); + deferreds.push(deferred); + } + }); + } catch (e) { + const inline = styleSheets.find((a) => a.href == null) || document.styleSheets[0]; + if (sheet.href != null) { + deferreds.push(fetchCSS(sheet.href).then((metadata) => embedFonts(metadata, options)).then((cssText) => parseCSS(cssText).forEach((rule) => { + inline.insertRule(rule, sheet.cssRules.length); + })).catch((err) => { + console.error("Error loading remote stylesheet", err); + })); + } + console.error("Error inlining remote css file", e); + } + } + }); + return Promise.all(deferreds).then(() => { + styleSheets.forEach((sheet) => { + if ("cssRules" in sheet) { + try { + toArray(sheet.cssRules || []).forEach((item) => { + ret.push(item); + }); + } catch (e) { + console.error(`Error while reading CSS rules from ${sheet.href}`, e); + } + } + }); + return ret; + }); +} +function getWebFontRules(cssRules) { + return cssRules.filter((rule) => rule.type === CSSRule.FONT_FACE_RULE).filter((rule) => shouldEmbed(rule.style.getPropertyValue("src"))); +} +async function parseWebFontRules(node, options) { + if (node.ownerDocument == null) { + throw new Error("Provided element is not within a Document"); + } + const styleSheets = toArray(node.ownerDocument.styleSheets); + const cssRules = await getCSSRules(styleSheets, options); + return getWebFontRules(cssRules); +} +async function getWebFontCSS(node, options) { + const rules = await parseWebFontRules(node, options); + const cssTexts = await Promise.all(rules.map((rule) => { + const baseUrl = rule.parentStyleSheet ? rule.parentStyleSheet.href : null; + return embedResources(rule.cssText, baseUrl, options); + })); + return cssTexts.join("\n"); +} +async function embedWebFonts(clonedNode, options) { + const cssText = options.fontEmbedCSS != null ? options.fontEmbedCSS : options.skipFonts ? null : await getWebFontCSS(clonedNode, options); + if (cssText) { + const styleNode = document.createElement("style"); + const sytleContent = document.createTextNode(cssText); + styleNode.appendChild(sytleContent); + if (clonedNode.firstChild) { + clonedNode.insertBefore(styleNode, clonedNode.firstChild); + } else { + clonedNode.appendChild(styleNode); + } + } +} + +// node_modules/html-to-image/es/index.js +async function toSvg(node, options = {}) { + const { width, height } = getImageSize(node, options); + const clonedNode = await cloneNode(node, options, true); + await embedWebFonts(clonedNode, options); + await embedImages(clonedNode, options); + applyStyle(clonedNode, options); + const datauri = await nodeToDataURL(clonedNode, width, height); + return datauri; +} +async function toCanvas(node, options = {}) { + const { width, height } = getImageSize(node, options); + const svg = await toSvg(node, options); + const img = await createImage(svg); + const canvas = document.createElement("canvas"); + const context = canvas.getContext("2d"); + const ratio = options.pixelRatio || getPixelRatio(); + const canvasWidth = options.canvasWidth || width; + const canvasHeight = options.canvasHeight || height; + canvas.width = canvasWidth * ratio; + canvas.height = canvasHeight * ratio; + if (!options.skipAutoScale) { + checkCanvasDimensions(canvas); + } + canvas.style.width = `${canvasWidth}`; + canvas.style.height = `${canvasHeight}`; + if (options.backgroundColor) { + context.fillStyle = options.backgroundColor; + context.fillRect(0, 0, canvas.width, canvas.height); + } + context.drawImage(img, 0, 0, canvas.width, canvas.height); + return canvas; +} +async function toPng(node, options = {}) { + const canvas = await toCanvas(node, options); + return canvas.toDataURL(); +} + +// src/canvas-extensions/export-canvas-extension.ts +var import_obsidian20 = require("obsidian"); +var MAX_ALLOWED_LOADING_TIME = 1e4; +var ExportCanvasExtension = class extends CanvasExtension { + isEnabled() { + return "betterExportFeatureEnabled"; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-breakpoint-changed", + (canvas, node, breakpointRef) => { + if (canvas.screenshotting) breakpointRef.value = true; + } + )); + this.plugin.addCommand({ + id: "export-all-as-image", + name: "Export canvas as image", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => canvas.nodes.size > 0, + (canvas) => void this.showExportImageSettingsModal(canvas, null) + ) + }); + this.plugin.addCommand({ + id: "export-selected-as-image", + name: "Export selected nodes as image", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => canvas.selection.size > 0, + (canvas) => void this.showExportImageSettingsModal( + canvas, + canvas.getSelectionData().nodes.map((nodeData) => canvas.nodes.get(nodeData.id)).filter((node) => node !== void 0) + ) + ) + }); + } + async showExportImageSettingsModal(canvas, nodesToExport) { + const modal = new import_obsidian20.Modal(this.plugin.app); + modal.setTitle("Export image settings"); + let pixelRatioSetting = null; + let noFontExportSetting = null; + let transparentBackgroundSetting = null; + const updateDynamicSettings = () => { + var _a, _b, _c, _d, _e, _f; + if (svg) { + (_a = pixelRatioSetting == null ? void 0 : pixelRatioSetting.settingEl) == null ? void 0 : _a.hide(); + (_b = noFontExportSetting == null ? void 0 : noFontExportSetting.settingEl) == null ? void 0 : _b.show(); + (_c = transparentBackgroundSetting == null ? void 0 : transparentBackgroundSetting.settingEl) == null ? void 0 : _c.hide(); + } else { + (_d = pixelRatioSetting == null ? void 0 : pixelRatioSetting.settingEl) == null ? void 0 : _d.show(); + (_e = noFontExportSetting == null ? void 0 : noFontExportSetting.settingEl) == null ? void 0 : _e.hide(); + (_f = transparentBackgroundSetting == null ? void 0 : transparentBackgroundSetting.settingEl) == null ? void 0 : _f.show(); + } + }; + let svg = false; + new import_obsidian20.Setting(modal.contentEl).setName("Export file format").setDesc("Choose the file format to export the canvas as.").addDropdown( + (dropdown) => dropdown.addOptions({ + png: "PNG", + svg: "SVG" + }).setValue(svg ? "svg" : "png").onChange((value) => { + svg = value === "svg"; + updateDynamicSettings(); + }) + ); + let pixelRatioFactor = 1; + pixelRatioSetting = new import_obsidian20.Setting(modal.contentEl).setName("Pixel ratio").setDesc("Higher pixel ratios result in higher resolution images but also larger file sizes.").addSlider( + (slider) => slider.setLimits(0.2, 5, 0.1).setValue(pixelRatioFactor).onChange((value) => pixelRatioFactor = value) + ); + let noFontExport = true; + noFontExportSetting = new import_obsidian20.Setting(modal.contentEl).setName("Skip font export").setDesc("This will not include the fonts in the exported SVG. This will make the SVG file smaller.").addToggle( + (toggle) => toggle.setValue(noFontExport).onChange((value) => noFontExport = value) + ); + let theme = activeDocument.body.classList.contains("theme-dark") ? "dark" : "light"; + new import_obsidian20.Setting(modal.contentEl).setName("Theme").setDesc("The theme used for the export.").addDropdown( + (dropdown) => dropdown.addOptions({ + light: "Light", + dark: "Dark" + }).setValue(theme).onChange((value) => theme = value) + ); + let watermark = false; + new import_obsidian20.Setting(modal.contentEl).setName("Show logo").setDesc("This will add an Obsidian + Advanced Canvas logo to the bottom left.").addToggle( + (toggle) => toggle.setValue(watermark).onChange((value) => watermark = value) + ); + let garbledText = false; + new import_obsidian20.Setting(modal.contentEl).setName("Privacy mode").setDesc("This will obscure any text on your canvas.").addToggle( + (toggle) => toggle.setValue(garbledText).onChange((value) => garbledText = value) + ); + let transparentBackground = false; + transparentBackgroundSetting = new import_obsidian20.Setting(modal.contentEl).setName("Transparent background").setDesc("This will make the background of the image transparent.").addToggle( + (toggle) => toggle.setValue(transparentBackground).onChange((value) => transparentBackground = value) + ); + new import_obsidian20.Setting(modal.contentEl).addButton( + (button) => button.setButtonText("Save").setCta().onClick(async () => { + modal.close(); + await this.exportImage( + canvas, + nodesToExport, + svg, + svg ? 1 : pixelRatioFactor, + svg ? noFontExport : false, + theme, + watermark, + garbledText, + svg ? true : transparentBackground + ); + }) + ); + updateDynamicSettings(); + modal.open(); + } + async exportImage(canvas, nodesToExport, svg, pixelRatioFactor, noFontExport, theme, watermark, garbledText, transparentBackground) { + var _a, _b, _c; + const cachedTheme = activeDocument.body.classList.contains("theme-dark") ? "dark" : "light"; + if (theme !== cachedTheme) { + activeDocument.body.classList.toggle("theme-dark", theme === "dark"); + activeDocument.body.classList.toggle("theme-light", theme === "light"); + } + const isWholeCanvas = nodesToExport === null; + if (!nodesToExport) nodesToExport = [...canvas.nodes.values()]; + const nodesToExportIds = nodesToExport.map((node) => node.getData().id); + const edgesToExport = [...canvas.edges.values()].filter((edge) => { + const edgeData = edge.getData(); + return nodesToExportIds.includes(edgeData.fromNode) && nodesToExportIds.includes(edgeData.toNode); + }); + const backgroundColor = transparentBackground ? void 0 : window.getComputedStyle(canvas.canvasEl).getPropertyValue("--canvas-background"); + new import_obsidian20.Notice("Exporting the canvas. Please wait..."); + const interactionBlocker = this.getInteractionBlocker(); + activeDocument.body.appendChild(interactionBlocker); + canvas.screenshotting = true; + canvas.canvasEl.classList.add("is-exporting"); + if (garbledText) canvas.wrapperEl.classList.add("is-text-garbled"); + let watermarkEl = null; + const cachedSelection = new Set(canvas.selection); + canvas.deselectAll(); + const cachedViewport = { x: canvas.x, y: canvas.y, zoom: canvas.zoom }; + try { + const targetBoundingBox = CanvasHelper.getBBox([...nodesToExport, ...edgesToExport]); + let enlargedTargetBoundingBox = BBoxHelper.scaleBBox(targetBoundingBox, 1.1); + const enlargedTargetBoundingBoxSize = { width: enlargedTargetBoundingBox.maxX - enlargedTargetBoundingBox.minX, height: enlargedTargetBoundingBox.maxY - enlargedTargetBoundingBox.minY }; + const canvasElSize = { width: canvas.canvasEl.clientWidth, height: canvas.canvasEl.clientHeight }; + const requiredPixelRatio = Math.max(enlargedTargetBoundingBoxSize.width / canvasElSize.width, enlargedTargetBoundingBoxSize.height / canvasElSize.height); + const pixelRatio = svg ? void 0 : Math.round(requiredPixelRatio * pixelRatioFactor); + watermarkEl = watermark ? this.getWatermark(enlargedTargetBoundingBox) : null; + if (watermarkEl) canvas.canvasEl.appendChild(watermarkEl); + const actualAspectRatio = canvas.canvasRect.width / canvas.canvasRect.height; + const targetAspectRatio = (enlargedTargetBoundingBox.maxX - enlargedTargetBoundingBox.minX) / (enlargedTargetBoundingBox.maxY - enlargedTargetBoundingBox.minY); + let adjustedBoundingBox = { ...enlargedTargetBoundingBox }; + if (actualAspectRatio > targetAspectRatio) { + const targetHeight = enlargedTargetBoundingBox.maxY - enlargedTargetBoundingBox.minY; + const actualWidth = targetHeight * actualAspectRatio; + adjustedBoundingBox.maxX = enlargedTargetBoundingBox.minX + actualWidth; + } else { + const targetWidth = enlargedTargetBoundingBox.maxX - enlargedTargetBoundingBox.minX; + const actualHeight = targetWidth / actualAspectRatio; + adjustedBoundingBox.maxY = enlargedTargetBoundingBox.minY + actualHeight; + } + canvas.zoomToRealBbox(adjustedBoundingBox); + canvas.setViewport(canvas.tx, canvas.ty, canvas.tZoom); + await sleep(10); + let canvasScale = parseFloat(((_a = canvas.canvasEl.style.transform.match(/scale\((\d+(\.\d+)?)\)/)) == null ? void 0 : _a[1]) || "1"); + const edgePathsBBox = BBoxHelper.combineBBoxes(edgesToExport.map((edge) => { + const edgeCenter = edge.getCenter(); + const labelWidth = edge.labelElement ? edge.labelElement.wrapperEl.getBoundingClientRect().width / canvasScale : 0; + return { minX: edgeCenter.x - labelWidth / 2, minY: edgeCenter.y, maxX: edgeCenter.x + labelWidth / 2, maxY: edgeCenter.y }; + })); + const enlargedEdgePathsBBox = BBoxHelper.enlargeBBox(edgePathsBBox, 1.1); + enlargedTargetBoundingBox = BBoxHelper.combineBBoxes([enlargedTargetBoundingBox, enlargedEdgePathsBBox]); + adjustedBoundingBox = BBoxHelper.combineBBoxes([adjustedBoundingBox, enlargedEdgePathsBBox]); + canvas.zoomToRealBbox(adjustedBoundingBox); + canvas.setViewport(canvas.tx, canvas.ty, canvas.tZoom); + await sleep(10); + const canvasViewportBBox = canvas.getViewportBBox(); + canvasScale = parseFloat(((_b = canvas.canvasEl.style.transform.match(/scale\((\d+(\.\d+)?)\)/)) == null ? void 0 : _b[1]) || "1"); + let width = (canvasViewportBBox.maxX - canvasViewportBBox.minX) * canvasScale; + let height = (canvasViewportBBox.maxY - canvasViewportBBox.minY) * canvasScale; + if (actualAspectRatio > targetAspectRatio) + width = height * targetAspectRatio; + else height = width / targetAspectRatio; + let unloadedNodes = nodesToExport.filter((node) => node.initialized === false || node.isContentMounted === false); + const startTimestamp = performance.now(); + while (unloadedNodes.length > 0 && performance.now() - startTimestamp < MAX_ALLOWED_LOADING_TIME) { + await sleep(10); + unloadedNodes = nodesToExport.filter((node) => node.initialized === false || node.isContentMounted === false); + } + if (unloadedNodes.length === 0) { + const nodeElements = nodesToExport.map((node) => node.nodeEl); + const edgePathAndArrowElements = edgesToExport.map((edge) => [edge.lineGroupEl, edge.lineEndGroupEl]).flat(); + const edgeLabelElements = edgesToExport.map((edge) => { + var _a2; + return (_a2 = edge.labelElement) == null ? void 0 : _a2.wrapperEl; + }).filter((labelElement) => labelElement !== void 0); + const filter = (element) => { + var _a2, _b2, _c2, _d; + if (((_a2 = element.classList) == null ? void 0 : _a2.contains("canvas-node")) && !nodeElements.includes(element)) + return false; + if (((_c2 = (_b2 = element.parentElement) == null ? void 0 : _b2.classList) == null ? void 0 : _c2.contains("canvas-edges")) && !edgePathAndArrowElements.includes(element)) + return false; + if (((_d = element.classList) == null ? void 0 : _d.contains("canvas-path-label-wrapper")) && !edgeLabelElements.includes(element)) + return false; + return true; + }; + const options = { + pixelRatio, + backgroundColor, + height, + width, + filter + }; + if (noFontExport) options.fontEmbedCSS = ""; + let imageDataUri = svg ? await toSvg(canvas.canvasEl, options) : await toPng(canvas.canvasEl, options); + if (svg) { + const header = ``; + imageDataUri = imageDataUri.replace( + encodeURIComponent(" canvas.selection = cachedSelection); + canvas.setViewport(cachedViewport.x, cachedViewport.y, cachedViewport.zoom); + interactionBlocker.remove(); + if (theme !== cachedTheme) { + activeDocument.body.classList.toggle("theme-dark", cachedTheme === "dark"); + activeDocument.body.classList.toggle("theme-light", cachedTheme === "light"); + } + } + } + getInteractionBlocker() { + const interactionBlocker = activeWindow.createDiv(); + interactionBlocker.classList.add("progress-bar-container"); + const progressBar = interactionBlocker.createDiv(); + progressBar.classList.add("progress-bar"); + const progressBarMessage = progressBar.createDiv(); + progressBarMessage.classList.add("progress-bar-message", "u-center-text"); + progressBarMessage.innerText = "Generating image..."; + const progressBarIndicator = progressBar.createDiv(); + progressBarIndicator.classList.add("progress-bar-indicator"); + const progressBarLine = progressBarIndicator.createDiv(); + progressBarLine.classList.add("progress-bar-line"); + const progressBarSublineIncrease = progressBarIndicator.createDiv(); + progressBarSublineIncrease.classList.add("progress-bar-subline", "mod-increase"); + const progressBarSublineDecrease = progressBarIndicator.createDiv(); + progressBarSublineDecrease.classList.add("progress-bar-subline", "mod-decrease"); + return interactionBlocker; + } + getWatermark(bbox) { + const bboxWidth = bbox.maxX - bbox.minX; + const width = Math.max(200, bboxWidth * 0.3); + const WATERMARK_SIZE = { width: 215, height: 25 }; + const height = WATERMARK_SIZE.height / WATERMARK_SIZE.width * width; + const watermarkPadding = { + x: bboxWidth * 0.02, + y: bboxWidth * 0.014 + }; + bbox.maxY += height + watermarkPadding.y; + const watermarkEl = activeWindow.createSvg("svg"); + watermarkEl.id = "watermark-ac"; + watermarkEl.style.transform = `translate(${bbox.minX + watermarkPadding.x}px, ${bbox.maxY - height - watermarkPadding.y}px)`; + watermarkEl.setAttrs({ + viewBox: `0 0 ${WATERMARK_SIZE.width} ${WATERMARK_SIZE.height}`, + width: width.toString(), + fill: "currentColor" + }); + watermarkEl.innerHTML = ''; + return watermarkEl; + } +}; + +// src/canvas-extensions/floating-edge-canvas-extension.ts +var FloatingEdgeCanvasExtension = class extends CanvasExtension { + isEnabled() { + return "floatingEdgeFeatureEnabled"; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:data-loaded:after", + (canvas, data, setData) => this.onLoadData(canvas, data) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-moved", + (canvas, node) => this.onNodeMoved(canvas, node) + )); + if (this.plugin.settings.getSetting("allowFloatingEdgeCreation")) { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:edge-connection-dragging:before", + (canvas, edge, event, newEdge, side) => this.onEdgeStartedDragging(canvas, edge, event, newEdge, side) + )); + } + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:edge-connection-dragging:after", + (canvas, edge, event, newEdge, side) => this.onEdgeStoppedDragging(canvas, edge, event, newEdge, side) + )); + } + onLoadData(canvas, data) { + for (const edgeData of data.edges) { + const edge = canvas.edges.get(edgeData.id); + if (!edge) return console.warn("Imported edge is not yet loaded :("); + this.updateEdgeConnectionSide(edge); + } + } + onNodeMoved(canvas, node) { + const affectedEdges = canvas.getEdgesForNode(node); + for (const edge of affectedEdges) + this.updateEdgeConnectionSide(edge); + } + updateEdgeConnectionSide(edge) { + const edgeData = edge.getData(); + if (edgeData.fromFloating) { + const fixedNodeConnectionPoint = BBoxHelper.getCenterOfBBoxSide(edge.to.node.getBBox(), edge.to.side); + const bestSide = CanvasHelper.getBestSideForFloatingEdge(fixedNodeConnectionPoint, edge.from.node); + if (bestSide !== edge.from.side) { + edge.setData({ + ...edgeData, + fromSide: bestSide + }); + } + } + if (edgeData.toFloating) { + const fixedNodeConnectionPoint = BBoxHelper.getCenterOfBBoxSide(edge.from.node.getBBox(), edge.from.side); + const bestSide = CanvasHelper.getBestSideForFloatingEdge(fixedNodeConnectionPoint, edge.to.node); + if (bestSide !== edge.to.side) { + edge.setData({ + ...edgeData, + toSide: bestSide + }); + } + } + } + onEdgeStartedDragging(canvas, edge, _event, newEdge, _side) { + if (newEdge && this.plugin.settings.getSetting("newEdgeFromSideFloating")) edge.setData({ + ...edge.getData(), + fromFloating: true + // New edges can only get dragged from the "from" side + }); + let cachedViewportNodes = null; + let hasNaNFloatingEdgeDropZones = false; + this.onPointerMove = (event) => { + if (cachedViewportNodes === null || hasNaNFloatingEdgeDropZones || canvas.viewportChanged) { + hasNaNFloatingEdgeDropZones = false; + cachedViewportNodes = canvas.getViewportNodes().map((node) => { + const nodeFloatingEdgeDropZone = this.getFloatingEdgeDropZoneForNode(node); + if (isNaN(nodeFloatingEdgeDropZone.minX) || isNaN(nodeFloatingEdgeDropZone.minY) || isNaN(nodeFloatingEdgeDropZone.maxX) || isNaN(nodeFloatingEdgeDropZone.maxY)) + hasNaNFloatingEdgeDropZones = true; + return [node, nodeFloatingEdgeDropZone]; + }); + } + for (const [node, nodeFloatingEdgeDropZoneClientRect] of cachedViewportNodes) { + const hovering = BBoxHelper.insideBBox({ x: event.clientX, y: event.clientY }, nodeFloatingEdgeDropZoneClientRect, true); + node.nodeEl.classList.toggle("hovering-floating-edge-zone", hovering); + } + }; + activeDocument.addEventListener("pointermove", this.onPointerMove); + } + onEdgeStoppedDragging(_canvas, edge, event, _newEdge, side) { + activeDocument.removeEventListener("pointermove", this.onPointerMove); + const dropZoneNode = side === "from" ? edge.from.node : edge.to.node; + const floatingEdgeDropZone = this.getFloatingEdgeDropZoneForNode(dropZoneNode); + const wasDroppedInFloatingEdgeDropZone = this.plugin.settings.getSetting("allowFloatingEdgeCreation") ? BBoxHelper.insideBBox({ x: event.clientX, y: event.clientY }, floatingEdgeDropZone, true) : false; + const edgeData = edge.getData(); + if (side === "from" && wasDroppedInFloatingEdgeDropZone == edgeData.fromFloating) return; + if (side === "to" && wasDroppedInFloatingEdgeDropZone == edgeData.toFloating) return; + if (side === "from") edgeData.fromFloating = wasDroppedInFloatingEdgeDropZone; + else edgeData.toFloating = wasDroppedInFloatingEdgeDropZone; + edge.setData(edgeData); + this.updateEdgeConnectionSide(edge); + } + getFloatingEdgeDropZoneForNode(node) { + const nodeElClientBoundingRect = node.nodeEl.getBoundingClientRect(); + const nodeFloatingEdgeDropZoneElStyle = window.getComputedStyle(node.nodeEl, ":after"); + const nodeFloatingEdgeDropZoneSize = { + width: parseFloat(nodeFloatingEdgeDropZoneElStyle.getPropertyValue("width")), + height: parseFloat(nodeFloatingEdgeDropZoneElStyle.getPropertyValue("height")) + }; + return { + minX: nodeElClientBoundingRect.left + (nodeElClientBoundingRect.width - nodeFloatingEdgeDropZoneSize.width) / 2, + minY: nodeElClientBoundingRect.top + (nodeElClientBoundingRect.height - nodeFloatingEdgeDropZoneSize.height) / 2, + maxX: nodeElClientBoundingRect.right - (nodeElClientBoundingRect.width - nodeFloatingEdgeDropZoneSize.width) / 2, + maxY: nodeElClientBoundingRect.bottom - (nodeElClientBoundingRect.height - nodeFloatingEdgeDropZoneSize.height) / 2 + }; + } +}; + +// src/canvas-extensions/edge-highlight-canvas-extension.ts +var EdgeHighlightCanvasExtension = class extends CanvasExtension { + isEnabled() { + return "edgeHighlightEnabled"; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:selection-changed", + (canvas, oldSelection, updateSelection) => this.onSelectionChanged(canvas, oldSelection) + )); + } + onSelectionChanged(canvas, oldSelection) { + var _a, _b, _c, _d, _e; + const connectedEdgesToBeHighlighted = new Set(canvas.getSelectionData().nodes.flatMap((nodeData) => { + var _a2, _b2; + return [ + ...(_a2 = canvas.edgeFrom.get(canvas.nodes.get(nodeData.id))) != null ? _a2 : [], + ...this.plugin.settings.getSetting("highlightIncomingEdges") ? (_b2 = canvas.edgeTo.get(canvas.nodes.get(nodeData.id))) != null ? _b2 : [] : [] + ]; + })); + for (const edge of canvas.edges.values()) { + const isFocused = canvas.selection.has(edge) || connectedEdgesToBeHighlighted.has(edge); + edge.lineGroupEl.classList.toggle("is-focused", isFocused); + (_b = (_a = edge.lineEndGroupEl) == null ? void 0 : _a.classList) == null ? void 0 : _b.toggle("is-focused", isFocused); + (_e = (_d = (_c = edge.labelElement) == null ? void 0 : _c.textareaEl) == null ? void 0 : _d.classList) == null ? void 0 : _e.toggle("is-focused", isFocused); + } + } +}; + +// src/canvas-extensions/reading-mode-fix-canvas-extension.ts +var ReadingModeFixCanvasExtension = class extends CanvasExtension { + constructor() { + super(...arguments); + this.hookedRenderers = /* @__PURE__ */ new WeakSet(); + } + isEnabled() { + return "readingModeFixEnabled"; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-rendered", + (_canvas, node) => this.updateNodeRenderer(node) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-editing-state-changed", + (_canvas, node, isEditing) => { + if (isEditing) return; + this.updateNodeRenderer(node); + } + )); + } + updateNodeRenderer(node) { + var _a, _b; + const renderer = (_b = (_a = node.child) == null ? void 0 : _a.previewMode) == null ? void 0 : _b.renderer; + if (!renderer) return; + if (this.hookedRenderers.has(renderer)) return; + this.hookedRenderers.add(renderer); + renderer.onRendered(() => { + var _a2; + let text = (_a2 = renderer.text) != null ? _a2 : ""; + text = text.replaceAll(' \n', "\n"); + text = text.replaceAll("\n", ' \n'); + renderer.set(text); + }); + } +}; + +// src/canvas-extensions/pdf-annotation-canvas-extension.ts +var import_obsidian21 = require("obsidian"); +var PINNED_PARAM = "pinned=true"; +var PdfAnnotationCanvasExtension = class extends CanvasExtension { + isEnabled() { + return "pdfAnnotationFeatureEnabled"; + } + init() { + this.plugin.register(this.patchPdfEmbed()); + this.plugin.addCommand({ + id: "pin-pdf-page", + name: "Pin PDF page", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => { + const selection = canvas.getSelectionData(); + const nodeData = selection.nodes.first(); + if (!nodeData) return false; + return selection.nodes.length === 1 && nodeData.type === "file" && nodeData.file.endsWith(".pdf") && !this.isSubpathPinned(nodeData.subpath); + }, + (canvas) => { + var _a; + const nodeId = (_a = canvas.getSelectionData().nodes.first()) == null ? void 0 : _a.id; + if (!nodeId) return; + const node = canvas.nodes.get(nodeId); + if (!node) return; + this.pinPdfPage(node); + } + ) + }); + this.plugin.addCommand({ + id: "annotate-pdf", + name: "Insert PDF for annotation", + checkCallback: CanvasHelper.canvasCommand( + this.plugin, + (canvas) => !canvas.readonly, + async (canvas) => { + const file = await new FileSelectModal(this.plugin.app, /^pdf$/).promise; + if (!file) return; + void this.insertPdfPages(canvas, file); + } + ) + }); + } + patchPdfEmbed() { + const embedByExtension = this.plugin.app.embedRegistry.embedByExtension; + const originalPdfEmbed = embedByExtension["pdf"]; + if (!originalPdfEmbed) { + console.error("Failed to patch PDF embed: original embed function not found."); + return () => { + }; + } + const that = this; + embedByExtension["pdf"] = function(context, file, subpath) { + if (that.isSubpathPinned(subpath)) { + const view = context.app.workspace.getActiveFileView(); + return new PdfPageEmbedComponent(that.plugin, view, context, file, subpath); + } + return invoke(originalPdfEmbed, this, context, file, subpath); + }; + return () => { + embedByExtension["pdf"] = originalPdfEmbed; + }; + } + async insertPdfPages(canvas, file) { + if (!window.pdfjsLib) await (0, import_obsidian21.loadPdfJs)(); + const data = await this.plugin.app.vault.readBinary(file); + const pdf = await window.pdfjsLib.getDocument({ data }).promise; + const pdfPageSpacing = this.plugin.settings.getSetting("pdfPagesGap"); + const pdfPageScale = this.plugin.settings.getSetting("pdfPageSizeFactor"); + const pos = CanvasHelper.getCenterCoordinates(canvas, { width: 0, height: 0 }); + let yPos = pos.y; + const minZIndex = Math.min(...[...canvas.nodes.values()].map((n) => n.zIndex)); + const zIndex = Math.abs(minZIndex) !== Infinity ? minZIndex - 1 : -1e3; + const pageNodes = /* @__PURE__ */ new Set(); + for (let pageNumber = 1; pageNumber <= pdf.numPages; pageNumber++) { + const page = await pdf.getPage(pageNumber); + const viewport = page.getViewport({ scale: pdfPageScale }); + const node = canvas.createFileNode({ + pos: { x: pos.x - viewport.width / 2, y: yPos }, + size: { width: viewport.width, height: viewport.height }, + file, + subpath: `#page=${pageNumber}&${PINNED_PARAM}` + }); + pageNodes.add(node); + node.setZIndex(zIndex); + node.setData({ + ...node.getData(), + ratio: viewport.width / viewport.height + }); + yPos += viewport.height + pdfPageSpacing; + } + canvas.updateSelection(() => { + canvas.selection = pageNodes; + }); + } + pinPdfPage(node) { + const nodeData = node.getData(); + if (!nodeData.subpath) return; + if (this.isSubpathPinned(nodeData.subpath)) return; + node.setData({ + ...nodeData, + subpath: nodeData.subpath + "&" + PINNED_PARAM + }); + } + isSubpathPinned(subpath) { + if (!subpath) return false; + return subpath.includes(`#${PINNED_PARAM}`) || subpath.includes(`&${PINNED_PARAM}`); + } +}; +var EmbedComponent = class extends import_obsidian21.Component { +}; +var PdfPageEmbedComponent = class extends EmbedComponent { + constructor(plugin, parent, context, file, subpath) { + super(); + this.plugin = plugin; + this.parent = parent; + this.context = context; + this.file = file; + this.subpath = subpath; + } + onload() { + this.canvas = activeWindow.createEl("canvas"); + this.canvas.classList.add("ac-pinned-pdf-page-embed"); + this.context.containerEl.appendChild(this.canvas); + } + async loadFile() { + var _a, _b, _c, _d; + if (!window.pdfjsLib) await (0, import_obsidian21.loadPdfJs)(); + let promise = (_b = (_a = this.parent) == null ? void 0 : _a.pdfCache) == null ? void 0 : _b.get(this.file.path); + if (!promise) { + promise = this.context.app.vault.readBinary(this.file).then((data) => window.pdfjsLib.getDocument({ data }).promise); + if (this.parent) { + (_d = (_c = this.parent).pdfCache) != null ? _d : _c.pdfCache = /* @__PURE__ */ new Map(); + this.parent.pdfCache.set(this.file.path, promise); + } + } + const pdf = await promise; + const pageNumber = this.getPageNumberFromSubpath(this.subpath); + if (!pageNumber || pageNumber < 1 || pageNumber > pdf.numPages) return; + const page = await pdf.getPage(pageNumber); + const pdfPageResolution = this.plugin.settings.getSetting("pdfPageSizeFactor"); + const viewport = page.getViewport({ scale: pdfPageResolution }); + this.canvas.width = viewport.width; + this.canvas.height = viewport.height; + const context = this.canvas.getContext("2d"); + if (!context) return; + await page.render({ + canvasContext: context, + viewport + }).promise; + } + getPageNumberFromSubpath(subpath) { + if (!subpath) return null; + const match = subpath.match(/page=(\d+)/); + return match ? parseInt(match[1], 10) : null; + } +}; + +// src/canvas-extensions/dataset-exposers/canvas-metadata-exposer.ts +var CanvasMetadataExposerExtension = class extends CanvasExtension { + isEnabled() { + return true; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:canvas-metadata-changed", + (canvas) => this.updateExposedSettings(canvas) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:canvas-changed", + (canvas) => this.updateExposedSettings(canvas) + )); + } + updateExposedSettings(canvas) { + const startNodeId = canvas.metadata["startNode"]; + for (const [nodeId, node] of canvas.nodes) { + if (nodeId === startNodeId) node.nodeEl.dataset.isStartNode = "true"; + else delete node.nodeEl.dataset.isStartNode; + } + } +}; + +// src/canvas-extensions/dataset-exposers/canvas-wrapper-exposer.ts +var EXPOSED_SETTINGS = [ + "disableFontSizeRelativeToZoom", + "hideBackgroundGridWhenInReadonly", + "readingModeFixEnabled", + "collapsibleGroupsFeatureEnabled", + "collapsedGroupPreviewOnDrag", + "allowFloatingEdgeCreation" +]; +var CanvasWrapperExposerExtension = class _CanvasWrapperExposerExtension extends CanvasExtension { + isEnabled() { + return true; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:settings-changed", + () => { + var _a; + return _CanvasWrapperExposerExtension.updateCanvasExposedSettings( + this.plugin, + (_a = this.plugin.getCurrentCanvas()) == null ? void 0 : _a.wrapperEl + ); + } + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:canvas-changed", + (canvas) => _CanvasWrapperExposerExtension.updateCanvasExposedSettings( + this.plugin, + canvas.wrapperEl + ) + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:dragging-state-changed", + (canvas, dragging) => { + if (dragging) canvas.wrapperEl.dataset.isDragging = "true"; + else delete canvas.wrapperEl.dataset.isDragging; + } + )); + } + static updateCanvasExposedSettings(plugin, element) { + if (!element) return; + for (const setting of EXPOSED_SETTINGS) { + const value = plugin.settings.getSetting(setting); + element.dataset[setting] = JSON.stringify(value); + } + } +}; + +// src/canvas-extensions/dataset-exposers/node-exposer.ts +var CANVAS_NODE_IFRAME_BODY_CLASS = "canvas-node-iframe-body"; +function getExposedNodeData(settings) { + const exposedData = []; + if (settings.getSetting("nodeStylingFeatureEnabled")) exposedData.push("styleAttributes"); + if (settings.getSetting("collapsibleGroupsFeatureEnabled")) exposedData.push("collapsed"); + if (settings.getSetting("portalsFeatureEnabled")) exposedData.push("isPortalLoaded"); + return exposedData; +} +var NodeExposerExtension = class extends CanvasExtension { + constructor() { + super(...arguments); + this.iframeObservers = /* @__PURE__ */ new WeakSet(); + } + isEnabled() { + return true; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-changed", + (_canvas, node) => { + var _a, _b, _c; + const nodeData = node == null ? void 0 : node.getData(); + if (!nodeData) return; + this.setDataAttributes(node.nodeEl, nodeData); + let iframeBody = null; + try { + iframeBody = (_c = (_b = (_a = node.nodeEl.querySelector("iframe")) == null ? void 0 : _a.contentDocument) == null ? void 0 : _b.body) != null ? _c : null; + } catch (e) { + iframeBody = null; + } + if (iframeBody) this.setDataAttributes(iframeBody, nodeData); + } + )); + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-editing-state-changed", + (_canvas, node, editing) => { + var _a, _b, _c; + if (!editing) return; + const nodeData = node.getData(); + if (!nodeData) return; + let iframeBody = null; + try { + iframeBody = (_c = (_b = (_a = node.nodeEl.querySelector("iframe")) == null ? void 0 : _a.contentDocument) == null ? void 0 : _b.body) != null ? _c : null; + } catch (e) { + return; + } + if (!iframeBody) return; + if (!this.iframeObservers.has(iframeBody)) { + this.iframeObservers.add(iframeBody); + iframeBody.classList.add(CANVAS_NODE_IFRAME_BODY_CLASS); + new MutationObserver(() => iframeBody.classList.toggle(CANVAS_NODE_IFRAME_BODY_CLASS, true)).observe(iframeBody, { attributes: true, attributeFilter: ["class"] }); + } + this.setDataAttributes(iframeBody, nodeData); + CanvasWrapperExposerExtension.updateCanvasExposedSettings(this.plugin, iframeBody); + } + )); + } + setDataAttributes(element, nodeData) { + for (const exposedDataKey of getExposedNodeData(this.plugin.settings)) { + const datasetPairs = nodeData[exposedDataKey] && typeof nodeData[exposedDataKey] === "object" ? Object.entries(nodeData[exposedDataKey]) : [[exposedDataKey, nodeData[exposedDataKey]]]; + for (const [key, value] of datasetPairs) { + if (!value) delete element.dataset[key]; + else element.dataset[key] = value; + } + } + } +}; + +// src/canvas-extensions/dataset-exposers/node-interaction-exposer.ts +var TARGET_NODE_DATASET_PREFIX = "target"; +var NodeInteractionExposerExtension = class extends CanvasExtension { + isEnabled() { + return true; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:node-interaction", + (canvas, node) => { + const nodeData = node == null ? void 0 : node.getData(); + if (!nodeData) return; + const interactionEl = canvas.nodeInteractionLayer.interactionEl; + if (!interactionEl) return; + for (const exposedDataKey of getExposedNodeData(this.plugin.settings)) { + const datasetPairs = nodeData[exposedDataKey] instanceof Object ? Object.entries(nodeData[exposedDataKey]) : [[exposedDataKey, nodeData[exposedDataKey]]]; + for (const [key, value] of datasetPairs) { + const modifiedKey = TARGET_NODE_DATASET_PREFIX + key.toString().charAt(0).toUpperCase() + key.toString().slice(1); + if (!value) delete interactionEl.dataset[modifiedKey]; + else interactionEl.dataset[modifiedKey] = value; + } + } + if (PortalsCanvasExtension.isPortalElement(node.id)) interactionEl.dataset.isFromPortal = "true"; + else delete interactionEl.dataset.isFromPortal; + } + )); + } +}; + +// src/canvas-extensions/dataset-exposers/edge-exposer.ts +function getExposedEdgeData(settings) { + const exposedData = []; + if (settings.getSetting("edgesStylingFeatureEnabled")) exposedData.push("styleAttributes"); + return exposedData; +} +var EdgeExposerExtension = class extends CanvasExtension { + isEnabled() { + return true; + } + init() { + this.plugin.registerEvent(this.plugin.app.workspace.on( + "advanced-canvas:edge-changed", + (_canvas, edge) => { + var _a, _b, _c, _d; + const edgeData = edge == null ? void 0 : edge.getData(); + if (!edgeData) return; + for (const exposedDataKey of getExposedEdgeData(this.plugin.settings)) { + const datasetPairs = edgeData[exposedDataKey] && typeof edgeData[exposedDataKey] === "object" ? Object.entries(edgeData[exposedDataKey]) : [[exposedDataKey, edgeData[exposedDataKey]]]; + for (const [key, value] of datasetPairs) { + if (!value) { + delete edge.path.display.dataset[key]; + if ((_a = edge.fromLineEnd) == null ? void 0 : _a.el) delete edge.fromLineEnd.el.dataset[key]; + if ((_b = edge.toLineEnd) == null ? void 0 : _b.el) delete edge.toLineEnd.el.dataset[key]; + } else { + edge.path.display.dataset[key] = value; + if ((_c = edge.fromLineEnd) == null ? void 0 : _c.el) edge.fromLineEnd.el.dataset[key] = value; + if ((_d = edge.toLineEnd) == null ? void 0 : _d.el) edge.toLineEnd.el.dataset[key] = value; + } + } + } + } + )); + } +}; + +// src/patchers/bases-table-view-patcher.ts +var BasesTableViewPatcher = class extends Patcher { + async patch() { + if (!this.plugin.settings.getSetting("canvasMetadataCompatibilityEnabled")) return; + const bases = this.plugin.app.internalPlugins.getEnabledPluginById("bases"); + if (!bases) return; + void this.patchViewFactory(bases); + } + async patchViewFactory(bases) { + const that = this; + await Patcher.patchOnce(this.plugin, bases.registrations.table, (resolve) => ({ + factory: Patcher.OverrideExisting((next) => function(...args) { + const view = invoke(next, this, ...args); + void that.patchTableView(view); + resolve(view); + return view; + }) + })); + } + async patchTableView(basesView) { + const that = this; + await Patcher.patchOnce(this.plugin, basesView, (resolve) => ({ + updateVirtualDisplay: Patcher.OverrideExisting((next) => function(...args) { + const result = invoke(next, this, ...args); + if (this.rows.length > 0) { + const row = this.rows.first(); + void that.patchTableRow(row); + resolve(row); + } + return result; + }) + })); + } + async patchTableRow(row) { + const that = this; + await Patcher.patchOnce(this.plugin, row, (resolve) => ({ + render: Patcher.OverrideExisting((next) => function(...args) { + let result = invoke(next, this, ...args); + if (this.cells.length > 0) { + const cell = this.cells.first(); + void that.patchTableCell(cell); + resolve(cell); + result = invoke(next, this, ...args); + } + return result; + }) + })); + } + async patchTableCell(cell) { + Patcher.patchPrototype(this.plugin, cell, { + render: Patcher.OverrideExisting((next) => function(ctx) { + var _a; + const isCanvas = ((_a = ctx.file) == null ? void 0 : _a.extension) === "canvas"; + if (isCanvas) ctx.file.extension = "md"; + const result = invoke(next, this, ctx); + if (isCanvas) ctx.file.extension = "canvas"; + return result; + }) + }); + } +}; + +// src/main.ts +var PATCHERS = [ + // Core canvas patchers + CanvasPatcher, + SearchCommandPatcher, + // Core metadata patchers + MetadataCachePatcher, + FileManagerPatcher, + // Direct metadata dependant patchers + PropertiesPatcher, + !(0, import_obsidian22.requireApiVersion)("1.12.0") && BacklinksPatcher, + OutgoingLinksPatcher, + // Metadata dependant patchers + (0, import_obsidian22.requireApiVersion)("1.9.0") && BasesTableViewPatcher, + LinkSuggestionsPatcher, + EmbedPatcher, + SearchPatcher +]; +var CANVAS_EXTENSIONS = [ + // Advanced JSON Canvas Extensions + MetadataCanvasExtension, + NodeStylesExtension, + EdgeStylesExtension, + NodeRatioCanvasExtension, + FloatingEdgeCanvasExtension, + AutoResizeNodeCanvasExtension, + CollapsibleGroupsCanvasExtension, + ColorPaletteCanvasExtension, + PresentationCanvasExtension, + PortalsCanvasExtension, + PdfAnnotationCanvasExtension, + // UI Extensions (Non-savable data) + CanvasMetadataExposerExtension, + CanvasWrapperExposerExtension, + NodeExposerExtension, + EdgeExposerExtension, + NodeInteractionExposerExtension, + FrontmatterControlButtonCanvasExtension, + BetterDefaultSettingsCanvasExtension, + CommandsCanvasExtension, + BetterReadonlyCanvasExtension, + ReadingModeFixCanvasExtension, + GroupCanvasExtension, + NodeTemplatesCanvasExtension, + VariableBreakpointCanvasExtension, + EdgeHighlightCanvasExtension, + AutoFileNodeEdgesCanvasExtension, + FlipEdgeCanvasExtension, + ZOrderingCanvasExtension, + ExportCanvasExtension, + FocusModeCanvasExtension, + EncapsulateCanvasExtension, + EdgeSelectionCanvasExtension, + CopyNodeReferenceCanvasExtension +]; +var AdvancedCanvasPlugin = class extends import_obsidian22.Plugin { + async onload() { + IconsHelper.addIcons(); + this.settings = new SettingsManager(this); + await this.settings.loadSettings(); + this.settings.addSettingsTab(); + this.windowsManager = new WindowsManager(this); + this.patchers = PATCHERS.map((PatcherClass) => { + if (!PatcherClass) return void 0; + try { + return new PatcherClass(this); + } catch (e) { + console.error(`Error initializing patcher ${PatcherClass.name}:`, e); + return void 0; + } + }).filter((p) => p !== void 0); + this.canvasExtensions = CANVAS_EXTENSIONS.map((ExtensionClass) => { + try { + return new ExtensionClass(this); + } catch (e) { + console.error(`Error initializing ac-extension ${ExtensionClass.name}:`, e); + return void 0; + } + }).filter((e) => e !== void 0); + } + onunload() { + } + getCanvases() { + return this.app.workspace.getLeavesOfType("canvas").map((leaf) => { + var _a; + return (_a = leaf.view) == null ? void 0 : _a.canvas; + }).filter((canvas) => canvas); + } + getCurrentCanvasView() { + const canvasView = this.app.workspace.getActiveViewOfType(import_obsidian22.TextFileView); + if ((canvasView == null ? void 0 : canvasView.getViewType()) !== "canvas") return null; + return canvasView; + } + getCurrentCanvas() { + var _a; + return ((_a = this.getCurrentCanvasView()) == null ? void 0 : _a.canvas) || null; + } + createFileSnapshot(path, content) { + var _a; + const fileRecoveryPlugin = (_a = this.app.internalPlugins.plugins["file-recovery"]) == null ? void 0 : _a.instance; + if (!fileRecoveryPlugin) return; + fileRecoveryPlugin.forceAdd(path, content); + } + // this.app.plugins.plugins["advanced-canvas"].enableDebugMode() + enableDebugMode() { + if (this.debugHelper) return; + this.debugHelper = new DebugHelper(this); + } +}; + +/* nosourcemap */ \ No newline at end of file diff --git a/.obsidian/plugins/advanced-canvas/manifest.json b/.obsidian/plugins/advanced-canvas/manifest.json new file mode 100644 index 0000000..f0c6f97 --- /dev/null +++ b/.obsidian/plugins/advanced-canvas/manifest.json @@ -0,0 +1,11 @@ +{ + "id": "advanced-canvas", + "name": "Advanced Canvas", + "version": "7.0.1", + "minAppVersion": "1.13.0", + "description": "Supercharge your canvas experience! Create presentations, flowcharts and more!", + "author": "Developer-Mike", + "authorUrl": "https://github.com/Developer-Mike", + "fundingUrl": "https://ko-fi.com/X8X27IA08", + "isDesktopOnly": false +} diff --git a/.obsidian/plugins/advanced-canvas/styles.css b/.obsidian/plugins/advanced-canvas/styles.css new file mode 100644 index 0000000..56b8a03 --- /dev/null +++ b/.obsidian/plugins/advanced-canvas/styles.css @@ -0,0 +1,538 @@ +/* src/styles.scss */ +.canvas-wrapper > .document-search-container { + transform: translateZ(0); + margin: 0; +} +.document-search-count.is-hidden { + display: none; +} +.canvas-wrapper:not(.mod-readonly) .show-while-readonly { + display: none; +} +.canvas-control-item[data-toggled=true] { + background-color: var(--color-accent); +} +.canvas-control-item[data-toggled=true] svg { + stroke: var(--text-on-accent); +} +.reactive-node, +.canvas-node[data-shape=database], +.canvas-node[data-shape=document], +.canvas-node[data-shape=predefined-process], +.canvas-node[data-shape=diamond] { + --border-color: var(--canvas-color); + --border-width: 3px; + --box-shadow: none; +} +.reactive-node.is-focused, +.is-focused.canvas-node[data-shape=database], +.is-focused.canvas-node[data-shape=document], +.is-focused.canvas-node[data-shape=predefined-process], +.is-focused.canvas-node[data-shape=diamond], +.reactive-node.is-selected, +.is-selected.canvas-node[data-shape=database], +.is-selected.canvas-node[data-shape=document], +.is-selected.canvas-node[data-shape=predefined-process], +.is-selected.canvas-node[data-shape=diamond] { + --border-color: var(--color-accent); + --border-width: 5px; + --box-shadow: var(--shadow-border-accent); +} +.reactive-node.is-themed, +.is-themed.canvas-node[data-shape=database], +.is-themed.canvas-node[data-shape=document], +.is-themed.canvas-node[data-shape=predefined-process], +.is-themed.canvas-node[data-shape=diamond] { + --border-color: rgb(from var(--canvas-color) r g b / 0.7); +} +.reactive-node.is-themed.is-focused, +.is-themed.is-focused.canvas-node[data-shape=database], +.is-themed.is-focused.canvas-node[data-shape=document], +.is-themed.is-focused.canvas-node[data-shape=predefined-process], +.is-themed.is-focused.canvas-node[data-shape=diamond], +.reactive-node.is-themed.is-selected, +.is-themed.is-selected.canvas-node[data-shape=database], +.is-themed.is-selected.canvas-node[data-shape=document], +.is-themed.is-selected.canvas-node[data-shape=predefined-process], +.is-themed.is-selected.canvas-node[data-shape=diamond] { + --border-color: var(--canvas-color); + --box-shadow: var(--shadow-border-themed); +} +.canvas-node[data-text-align=center] .markdown-preview-view { + scrollbar-gutter: auto; +} +.canvas-node[data-text-align=center] .markdown-preview-view .markdown-preview-section { + display: flex; + flex-direction: column; + justify-content: center; + text-align: center; + vertical-align: middle; +} +.canvas-node[data-text-align=right] { + text-align: right; +} +.canvas-node[data-shape] .canvas-node-container .markdown-preview-view.markdown-rendered { + transform: unset; +} +.canvas-node[data-shape=pill] .canvas-node-container { + border-radius: 5000px; +} +.canvas-node[data-shape=diamond] { +} +.canvas-node[data-shape=diamond].is-focused, +.canvas-node[data-shape=diamond].is-selected { + border-radius: var(--radius-m); + outline: 2px solid var(--color-accent); + outline-offset: 5px; +} +.canvas-node[data-shape=diamond] .canvas-node-container { + border: none; + box-shadow: none !important; +} +.canvas-node[data-shape=diamond] .canvas-node-container:not(:has(.embed-iframe)) { + mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 141.42135624 141.42135624' preserveAspectRatio='none'%3E%3Cstyle%3E rect %7B transform-origin: center; transform: rotate(45deg) scale(1.05); %7D %3C/style%3E%3Crect rx='8' x='20.71067812' y='20.71067812' width='100' height='100' /%3E%3C/svg%3E"); + -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 141.42135624 141.42135624' preserveAspectRatio='none'%3E%3Cstyle%3E rect %7B transform-origin: center; transform: rotate(45deg) scale(1.05); %7D %3C/style%3E%3Crect rx='8' x='20.71067812' y='20.71067812' width='100' height='100' /%3E%3C/svg%3E"); + mask-repeat: no-repeat; + -webkit-mask-repeat: no-repeat; + mask-size: 100%; + -webkit-mask-size: 100%; +} +.canvas-node[data-shape=diamond] .canvas-node-container .canvas-node-placeholder::after { + mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 141.42135624 141.42135624' preserveAspectRatio='none'%3E%3Cstyle%3E rect %7B transform-origin: center; transform: rotate(45deg) scale(1.05); %7D %3C/style%3E%3Crect rx='8' x='20.71067812' y='20.71067812' width='100' height='100' /%3E%3C/svg%3E"); + -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 141.42135624 141.42135624' preserveAspectRatio='none'%3E%3Cstyle%3E rect %7B transform-origin: center; transform: rotate(45deg) scale(1.05); %7D %3C/style%3E%3Crect rx='8' x='20.71067812' y='20.71067812' width='100' height='100' /%3E%3C/svg%3E"); + mask-repeat: no-repeat; + -webkit-mask-repeat: no-repeat; + mask-size: 100%; + -webkit-mask-size: 100%; +} +.canvas-node[data-shape=diamond]::before { + mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 141.42135624 141.42135624' preserveAspectRatio='none'%3E%3Cstyle%3E rect %7B transform-origin: center; transform: rotate(45deg) scale(1.05); %7D %3C/style%3E%3Crect rx='8' x='20.71067812' y='20.71067812' width='100' height='100' /%3E%3C/svg%3E"); + -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 141.42135624 141.42135624' preserveAspectRatio='none'%3E%3Cstyle%3E rect %7B transform-origin: center; transform: rotate(45deg) scale(1.05); %7D %3C/style%3E%3Crect rx='8' x='20.71067812' y='20.71067812' width='100' height='100' /%3E%3C/svg%3E"); + mask-repeat: no-repeat; + -webkit-mask-repeat: no-repeat; + mask-size: 100%; + -webkit-mask-size: 100%; + content: ""; + position: absolute; + top: calc(var(--border-width) * -1); + left: calc(var(--border-width) * -1); + width: calc(100% + var(--border-width) * 2); + height: calc(100% + var(--border-width) * 2); + background-color: var(--border-color); +} +.canvas-node[data-shape=parallelogram] .canvas-node-container { + transform: skewX(-20deg); + backface-visibility: hidden; +} +.canvas-node[data-shape=parallelogram] .canvas-node-container .canvas-node-content > .markdown-embed-content { + transform: skewX(20deg); +} +.canvas-node[data-shape=circle] .canvas-node-container { + border-radius: 50%; +} +.canvas-node[data-shape=circle] .canvas-node-container .markdown-preview-view { + overflow-y: initial; +} +.canvas-node[data-shape=predefined-process] .canvas-node-container .canvas-node-content { + padding: 0 10px; +} +.canvas-node[data-shape=predefined-process] .canvas-node-container::before, +.canvas-node[data-shape=predefined-process] .canvas-node-container::after { + content: ""; + z-index: 1; + position: absolute; + top: 0; + width: 0; + height: 100%; + border-left: var(--border-width) solid var(--border-color); +} +.canvas-node[data-shape=predefined-process] .canvas-node-container::before { + left: calc(10px - var(--border-width)); +} +.canvas-node[data-shape=predefined-process] .canvas-node-container::after { + right: calc(10px - var(--border-width)); +} +.canvas-node[data-shape=document] { + --border-width: 2.5px; + filter: drop-shadow(0 var(--border-width) 0 var(--border-color)) drop-shadow(0 calc(var(--border-width) * -1) 0 var(--border-color)); +} +.canvas-node[data-shape=document] .canvas-node-container { + mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 75 45' preserveAspectRatio='none'%3E%3Cpath d='M75 0 75 39.375Q56.25 29.25 37.5 39.375 18.75 49.5 0 39.375L0 0Z' /%3E%3C/svg%3E"); + -webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 75 45' preserveAspectRatio='none'%3E%3Cpath d='M75 0 75 39.375Q56.25 29.25 37.5 39.375 18.75 49.5 0 39.375L0 0Z' /%3E%3C/svg%3E"); + mask-repeat: no-repeat; + -webkit-mask-repeat: no-repeat; + mask-size: 100%; + -webkit-mask-size: 100%; + border: var(--border-width) solid var(--border-color); + border-top: none; + border-bottom: none; +} +.canvas-node[data-shape=document].is-focused, +.canvas-node[data-shape=document].is-selected { + --border-width: 4px; +} +.canvas-node[data-shape=database] { +} +.canvas-node[data-shape=database] .canvas-node-container { + border: var(--border-width) solid var(--border-color); + border-bottom: 0; + border-top: 0; + border-radius: 0; + box-shadow: none !important; +} +.canvas-node[data-shape=database] .canvas-node-container .canvas-node-placeholder { + transform: translateY(25px); +} +.canvas-node[data-shape=database]::before, +.canvas-node[data-shape=database]::after { + content: ""; + position: absolute; + left: 0; + box-sizing: border-box; + width: 100%; + height: 50px; + border-radius: 50%; + border: var(--border-width) solid var(--border-color); + background-color: var(--background-primary); +} +.canvas-node[data-shape=database]::after { + top: -25px; +} +.canvas-node[data-shape=database]::before { + bottom: -25px; +} +.canvas-node[data-shape=database].is-themed .canvas-node-content { + background-color: transparent; +} +.canvas-node[data-shape=database].is-themed:not(:has(.embed-iframe)) .canvas-node-container, +.canvas-node[data-shape=database].is-themed:not(:has(.embed-iframe))::after, +.canvas-node[data-shape=database].is-themed:not(:has(.embed-iframe))::before { + box-shadow: inset 0 0 0 1000px rgb(from var(--canvas-color) r g b/0.07) !important; +} +.canvas-node[data-shape=database] .canvas-node-content:not(:has(.embed-iframe)) { + transform: translateY(20px); +} +.canvas-node[data-shape=database]:has(.embed-iframe)::after { + z-index: -1; +} +.canvas-node[data-border=dashed] .canvas-node-container { + box-shadow: none; + border-style: dashed; +} +.canvas-node[data-border=dotted] .canvas-node-container { + box-shadow: none; + border-style: dotted; +} +.canvas-node[data-border=invisible] { + box-shadow: none; +} +.canvas-node[data-border=invisible]:not(.is-focused):not(.is-selected) .canvas-node-container { + border-color: transparent !important; +} +.canvas-node[data-border=invisible] .canvas-node-label { + display: none; +} +.canvas-node[data-border=invisible] .canvas-node-container { + background-color: transparent; + box-shadow: none; +} +.canvas-node[data-border][data-shape=predefined-process] { + --border-width: 2px; +} +.canvas-node[data-border][data-shape=predefined-process] .is-focused, +.canvas-node[data-border][data-shape=predefined-process] .is-selected { + --border-width: 2px; +} +.canvas-node[data-border=dashed][data-shape=predefined-process] .canvas-node-container::before, +.canvas-node[data-border=dashed][data-shape=predefined-process] .canvas-node-container::after { + border-left: var(--border-width) dashed var(--border-color); +} +.canvas-node[data-border=dotted][data-shape=predefined-process] .canvas-node-container::before, +.canvas-node[data-border=dotted][data-shape=predefined-process] .canvas-node-container::after { + border-left: var(--border-width) dotted var(--border-color); +} +.canvas-node[data-border][data-shape=document] .canvas-node-container { + border-top: none; + border-bottom: none; +} +.canvas-edges path[data-path=dotted] { + stroke-dasharray: calc(3px * var(--zoom-multiplier)); +} +.canvas-edges path[data-path=short-dashed] { + stroke-dasharray: 9px; +} +.canvas-edges path[data-path=long-dashed] { + stroke-dasharray: 18px; +} +.canvas-edges [data-arrow=triangle-outline] polygon, +.canvas-edges [data-arrow=diamond-outline] polygon, +.canvas-edges [data-arrow=circle-outline] polygon { + fill: var(--canvas-background); + stroke: var(--canvas-color); + stroke-width: calc(3px * var(--zoom-multiplier)); +} +.canvas-edges [data-arrow=thin-triangle] polygon { + fill: transparent; + stroke: var(--canvas-color); + stroke-width: calc(4px * var(--zoom-multiplier)); +} +.icon-modal-suggestion { + display: flex; + align-items: center; + gap: var(--size-4-4); +} +.icon-modal-suggestion .icon-modal-suggestion-icon { + line-height: 0; +} +.icon-modal-suggestion .icon-modal-suggestion-id { + font-size: var(--font-ui-smaller); + color: var(--text-muted); +} +.ac-pinned-pdf-page-embed { + height: 100%; +} +.canvas.is-exporting { + --zoom-multiplier: 1; +} +.canvas.is-exporting * { + pointer-events: none !important; + transition: none !important; +} +.canvas.is-exporting .collapse-button { + display: none; +} +.canvas.is-exporting #watermark-ac { + z-index: 9999999; + position: absolute; +} +.canvas-wrapper[data-collapsible-groups-feature-enabled=true] .canvas.is-exporting .canvas-node .canvas-group-label { + left: 0; +} +.progress-bar-modal-ac { + margin-top: 0.75em; +} +.progress-bar-modal-ac.error .setting-progress-bar { + color: var(--color-error); +} +.canvas-wrapper[data-disable-font-size-relative-to-zoom=true] { + --zoom-multiplier: 1 !important; +} +.canvas-wrapper.mod-readonly .canvas-controls .canvas-control-group:nth-child(3), +.canvas-wrapper.mod-readonly .canvas-card-menu { + display: none; +} +.canvas-wrapper.mod-readonly[data-hide-background-grid-when-in-readonly=true] .canvas-background { + visibility: hidden; +} +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas { +} +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas .el-p > p:has(> span.vertical-space) { + margin-top: 0px; +} +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas .el-p > p { + margin-top: 0px; + margin-bottom: 0px; +} +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas :is(.el-ul, .el-ol) + .el-p > p:has(> span.vertical-space:first-child) { + margin-top: 24px; +} +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas ol::before { + margin-left: -2px; +} +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas ol { + margin-top: 0px; + margin-bottom: 0px; +} +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas ul > li > ol > li { + margin-left: 36px; +} +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas ul::before { + margin-left: -2px; +} +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas ul { + margin-top: 0px; + margin-bottom: 0px; +} +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas .el-ul > ul > li { + margin-top: 0px; + margin-bottom: 0px; +} +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas ol > li > ul > li { + margin-left: 36px; +} +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas ul > li > .list-bullet { + margin-top: 2px; +} +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas .has-list-bullet .list-bullet::after { + margin-left: -4px; + margin-top: -3px; +} +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas .el-h1 > h1, +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas .el-h2 > h2, +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas .el-h3 > h3, +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas .el-h4 > h4, +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas .el-h5 > h5, +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas .el-h6 > h6 { + margin-top: 0px !important; + margin-bottom: 0px !important; +} +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas .markdown-preview-section > .markdown-preview-pusher + :is(.el-h2) > :is(h2), +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas .markdown-preview-section > .markdown-preview-pusher + :is(.el-h3) > :is(h3) { + margin-top: 0px !important; +} +.canvas-wrapper[data-reading-mode-fix-enabled=true] .canvas .el-table { + margin-top: 24px; +} +.canvas-node-iframe-body[data-reading-mode-fix-enabled=true] { +} +.canvas-node-iframe-body[data-reading-mode-fix-enabled=true] .markdown-source-view .cm-contentContainer > .cm-content.cm-lineWrapping > .cm-line { + margin-right: -2px !important; +} +.canvas-node-iframe-body[data-reading-mode-fix-enabled=true] .mod-inside-iframe .HyperMD-header { + padding-top: 0px !important; +} +.canvas-node-iframe-body[data-reading-mode-fix-enabled=true] .cm-formatting-list.cm-formatting-list-ul { + margin-right: 7px; +} +.collapse-button { + position: absolute; + left: 0; + top: calc(-1 * var(--size-4-1) * var(--zoom-multiplier)); + padding: var(--size-4-1) var(--size-4-2); + transform-origin: bottom left; + transform: translate(0, -100%) scale(var(--zoom-multiplier)); + border-radius: var(--radius-s); + color: var(--text-muted); + background-color: rgb(from var(--canvas-color) r g b/0.1); + font-size: 1.5em; + line-height: 1; + pointer-events: initial; + cursor: pointer; + transition: transform 500ms cubic-bezier(0.16, 1, 0.3, 1); +} +.canvas-wrapper[data-collapsible-groups-feature-enabled=true] .canvas-node .canvas-group-label { + left: calc(40px * var(--zoom-multiplier)); +} +.canvas-node[data-collapsed] .canvas-node-container { + display: none; +} +.canvas-node[data-collapsed] .canvas-group-label { + max-width: initial; +} +.canvas-wrapper[data-collapsed-group-preview-on-drag=true][data-is-dragging] .canvas-node[data-collapsed] .canvas-node-container { + display: block; + opacity: 0.5; + border-style: dashed; +} +.canvas-wrapper[data-collapsed-group-preview-on-drag=true][data-is-dragging] .canvas-node[data-collapsed] .canvas-node-container .canvas-node-content { + background-color: transparent; +} +.canvas-node-interaction-layer[data-target-collapsed] .canvas-node-resizer { + pointer-events: none; + cursor: inherit; +} +.canvas-node-interaction-layer[data-target-collapsed] .canvas-node-resizer .canvas-node-connection-point { + display: none; + pointer-events: none; +} +.canvas-wrapper[data-allow-floating-edge-creation=true] .canvas.is-connecting .canvas-node:not(.canvas-node-group)::after { + all: unset; + content: ""; + z-index: 100; + position: absolute; + top: 50%; + left: 50%; + width: max(10px, 100% - 50px * var(--zoom-multiplier) * 2); + height: max(10px, 100% - 50px * var(--zoom-multiplier) * 2); + transform: translate(-50%, -50%); + border-radius: var(--radius-m); + outline: calc(4px * var(--zoom-multiplier)) dashed hsla(var(--color-accent-hsl), 0.5); +} +.canvas-wrapper[data-allow-floating-edge-creation=true] .canvas.is-connecting .canvas-node:not(.canvas-node-group).hovering-floating-edge-zone::after { + outline-color: var(--color-accent); + outline-style: solid; + background-color: hsla(var(--color-accent-hsl), 0.1); +} +.canvas-wrapper[data-focus-mode-enabled=true] .canvas:has(.canvas-node.is-focused) .canvas-node:not(.is-focused) { + filter: blur(5px); +} +.canvas-wrapper[data-focus-mode-enabled=true] .canvas:has(.canvas-node.is-focused) .canvas-edges > g:not(.is-focused) { + filter: blur(5px); +} +.canvas-wrapper[data-focus-mode-enabled=true] .canvas:has(.canvas-node.is-focused) .canvas-path-label-wrapper > .canvas-path-label:not(.is-focused) { + filter: blur(5px); +} +.canvas-wrapper.presentation-mode .canvas-controls { + visibility: hidden; +} +.canvas-wrapper.presentation-mode .canvas-card-menu { + visibility: hidden; +} +.canvas-wrapper:not(.presentation-mode) .canvas-node[data-is-start-node=true]::before { + content: "Start"; + position: absolute; + top: calc(-1 * var(--size-4-1) * var(--zoom-multiplier)); + right: 0; + transform: translate(0, -100%) scale(var(--zoom-multiplier)); + transform-origin: bottom right; + max-width: calc(100% / var(--zoom-multiplier)); + padding: var(--size-4-1) var(--size-4-2); + font-size: 1em; + border-radius: var(--radius-s); + color: var(--color-green); + background-color: rgba(var(--color-green-rgb), 0.1); +} +.canvas-node[data-is-portal-loaded=true] { + pointer-events: all; +} +.canvas-node[data-is-portal-loaded=true]:not(.is-focused) { + pointer-events: none; +} +.canvas-node[data-is-portal-loaded=true]:not(.is-focused) .canvas-node-label { + pointer-events: all; +} +.canvas-node[data-is-portal-loaded=true] .canvas-node-container { + background-color: transparent; + border-style: dashed; +} +.canvas-node[data-is-portal-loaded=true] .canvas-node-container .canvas-node-content { + display: none; +} +.canvas-node-interaction-layer[data-is-from-portal=true] .canvas-node-resizer { + pointer-events: none; + cursor: inherit; +} +.canvas-node-interaction-layer[data-is-from-portal=true] .canvas-node-resizer .canvas-node-connection-point { + pointer-events: all; +} +.ac-card-embed { + display: flex; + flex-direction: column; + overflow: hidden; + background-color: var(--background-primary); + border: 1px solid var(--canvas-color); + border-radius: var(--radius-m); + box-shadow: var(--shadow-stationary); +} +.ac-card-embed.is-themed { + background-color: rgb(from var(--canvas-color) r g b/0.07); + border-color: rgb(from var(--canvas-color) r g b/0.7); + box-shadow: inset 0 0 0 1px rgb(from var(--canvas-color) r g b/0.7), var(--shadow-stationary); +} +.ac-card-embed > .markdown-content { + position: relative; + overflow-y: auto; + overflow-wrap: break-word; + display: flex; + flex-direction: column; + width: 100%; + height: 100%; + padding: 0 var(--size-4-4); + font-size: var(--font-text-size); + font-family: var(--font-text); + line-height: var(--line-height-normal); + color: var(--text-normal); + user-select: text; + -webkit-user-select: text; + scrollbar-gutter: stable; +} diff --git a/.obsidian/plugins/obsidian-git/data.json b/.obsidian/plugins/obsidian-git/data.json new file mode 100644 index 0000000..50963bb --- /dev/null +++ b/.obsidian/plugins/obsidian-git/data.json @@ -0,0 +1,70 @@ +{ + "commitMessage": "vault backup: {{date}}", + "autoCommitMessage": "vault backup: {{date}}", + "commitMessageScript": "", + "commitDateFormat": "YYYY-MM-DD HH:mm:ss", + "autoSaveInterval": 0, + "autoPushInterval": 0, + "autoPullInterval": 0, + "autoPullOnBoot": false, + "autoCommitOnlyStaged": false, + "disablePush": false, + "pullBeforePush": true, + "squashCommitsBeforePush": false, + "disablePopups": false, + "showErrorNotices": true, + "disablePopupsForNoChanges": false, + "listChangedFilesInMessageBody": false, + "showStatusBar": true, + "updateSubmodules": false, + "syncMethod": "merge", + "mergeStrategy": "none", + "customMessageOnAutoBackup": false, + "autoBackupAfterFileChange": false, + "treeStructure": false, + "refreshSourceControl": true, + "basePath": "", + "differentIntervalCommitAndPush": false, + "changedFilesInStatusBar": false, + "showedMobileNotice": true, + "refreshSourceControlTimer": 7000, + "showBranchStatusBar": true, + "setLastSaveToLastCommit": false, + "submoduleRecurseCheckout": false, + "gitDir": "", + "showFileMenu": true, + "authorInHistoryView": "hide", + "dateInHistoryView": false, + "diffStyle": "split", + "diffTimeout": 50, + "autoStageOnEmptyIndex": true, + "hunks": { + "showSigns": false, + "hunkCommands": false, + "statusBar": "disabled" + }, + "lineAuthor": { + "show": false, + "followMovement": "inactive", + "authorDisplay": "initials", + "showCommitHash": false, + "dateTimeFormatOptions": "date", + "dateTimeFormatCustomString": "YYYY-MM-DD HH:mm", + "dateTimeTimezone": "viewer-local", + "coloringMaxAge": "1y", + "colorNew": { + "r": 255, + "g": 150, + "b": 150 + }, + "colorOld": { + "r": 120, + "g": 160, + "b": 255 + }, + "textColorCss": "var(--text-muted)", + "ignoreWhitespace": false, + "lastShownAuthorDisplay": "initials", + "lastShownDateTimeFormatOptions": "date" + } +} \ No newline at end of file diff --git a/.obsidian/plugins/obsidian-git/main.js b/.obsidian/plugins/obsidian-git/main.js new file mode 100644 index 0000000..376ef66 --- /dev/null +++ b/.obsidian/plugins/obsidian-git/main.js @@ -0,0 +1,427 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ESBUILD +if you want to view the source visit the plugins github repository (https://github.com/denolehov/obsidian-git) +*/ + +"use strict";var j$=Object.create;var _c=Object.defineProperty;var V$=Object.getOwnPropertyDescriptor;var z$=Object.getOwnPropertyNames;var W$=Object.getPrototypeOf,q$=Object.prototype.hasOwnProperty;var Bb=t=>{throw TypeError(t)};var Y$=(t,e,r)=>e in t?_c(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Z$=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(i){throw r=[i],i}};var H=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},K$=(t,e)=>{for(var r in e)_c(t,r,{get:e[r],enumerable:!0})},Hb=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of z$(e))!q$.call(t,n)&&n!==r&&_c(t,n,{get:()=>e[n],enumerable:!(i=V$(e,n))||i.enumerable});return t};var mt=(t,e,r)=>(r=t!=null?j$(W$(t)):{},Hb(e||!t||!t.__esModule?_c(r,"default",{value:t,enumerable:!0}):r,t)),X$=t=>Hb(_c({},"__esModule",{value:!0}),t);var Ue=(t,e,r)=>Y$(t,typeof e!="symbol"?e+"":e,r),dm=(t,e,r)=>e.has(t)||Bb("Cannot "+r);var $=(t,e,r)=>(dm(t,e,"read from private field"),r?r.call(t):e.get(t)),ge=(t,e,r)=>e.has(t)?Bb("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),de=(t,e,r,i)=>(dm(t,e,"write to private field"),i?i.call(t,r):e.set(t,r),r),Se=(t,e,r)=>(dm(t,e,"access private method"),r);var jb=H(Lf=>{"use strict";m();Lf.byteLength=J$;Lf.toByteArray=tF;Lf.fromByteArray=nF;var dn=[],bi=[],Q$=typeof Uint8Array!="undefined"?Uint8Array:Array,hm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(ca=0,Ub=hm.length;ca0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var i=r===e?0:4-r%4;return[r,i]}function J$(t){var e=Gb(t),r=e[0],i=e[1];return(r+i)*3/4-i}function eF(t,e,r){return(e+r)*3/4-r}function tF(t){var e,r=Gb(t),i=r[0],n=r[1],s=new Q$(eF(t,i,n)),a=0,o=n>0?i-4:i,l;for(l=0;l>16&255,s[a++]=e>>8&255,s[a++]=e&255;return n===2&&(e=bi[t.charCodeAt(l)]<<2|bi[t.charCodeAt(l+1)]>>4,s[a++]=e&255),n===1&&(e=bi[t.charCodeAt(l)]<<10|bi[t.charCodeAt(l+1)]<<4|bi[t.charCodeAt(l+2)]>>2,s[a++]=e>>8&255,s[a++]=e&255),s}function rF(t){return dn[t>>18&63]+dn[t>>12&63]+dn[t>>6&63]+dn[t&63]}function iF(t,e,r){for(var i,n=[],s=e;so?o:a+s));return i===1?(e=t[r-1],n.push(dn[e>>2]+dn[e<<4&63]+"==")):i===2&&(e=(t[r-2]<<8)+t[r-1],n.push(dn[e>>10]+dn[e>>4&63]+dn[e<<2&63]+"=")),n.join("")}});var Vb=H(pm=>{m();pm.read=function(t,e,r,i,n){var s,a,o=n*8-i-1,l=(1<>1,u=-7,f=r?n-1:0,d=r?-1:1,h=t[e+f];for(f+=d,s=h&(1<<-u)-1,h>>=-u,u+=o;u>0;s=s*256+t[e+f],f+=d,u-=8);for(a=s&(1<<-u)-1,s>>=-u,u+=i;u>0;a=a*256+t[e+f],f+=d,u-=8);if(s===0)s=1-c;else{if(s===l)return a?NaN:(h?-1:1)*(1/0);a=a+Math.pow(2,i),s=s-c}return(h?-1:1)*a*Math.pow(2,s-i)};pm.write=function(t,e,r,i,n,s){var a,o,l,c=s*8-n-1,u=(1<>1,d=n===23?Math.pow(2,-24)-Math.pow(2,-77):0,h=i?0:s-1,p=i?1:-1,g=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(o=isNaN(e)?1:0,a=u):(a=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-a))<1&&(a--,l*=2),a+f>=1?e+=d/l:e+=d*Math.pow(2,1-f),e*l>=2&&(a++,l/=2),a+f>=u?(o=0,a=u):a+f>=1?(o=(e*l-1)*Math.pow(2,n),a=a+f):(o=e*Math.pow(2,f-1)*Math.pow(2,n),a=0));n>=8;t[r+h]=o&255,h+=p,o/=256,n-=8);for(a=a<0;t[r+h]=a&255,h+=p,a/=256,c-=8);t[r+h-p]|=g*128}});var Em=H(Ao=>{"use strict";m();var mm=jb(),ko=Vb(),zb=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Ao.Buffer=D;Ao.SlowBuffer=uF;Ao.INSPECT_MAX_BYTES=50;var Nf=2147483647;Ao.kMaxLength=Nf;D.TYPED_ARRAY_SUPPORT=sF();!D.TYPED_ARRAY_SUPPORT&&typeof console!="undefined"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function sF(){try{let t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch(t){return!1}}Object.defineProperty(D.prototype,"parent",{enumerable:!0,get:function(){if(D.isBuffer(this))return this.buffer}});Object.defineProperty(D.prototype,"offset",{enumerable:!0,get:function(){if(D.isBuffer(this))return this.byteOffset}});function Wn(t){if(t>Nf)throw new RangeError('The value "'+t+'" is invalid for option "size"');let e=new Uint8Array(t);return Object.setPrototypeOf(e,D.prototype),e}function D(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return bm(t)}return Zb(t,e,r)}D.poolSize=8192;function Zb(t,e,r){if(typeof t=="string")return oF(t,e);if(ArrayBuffer.isView(t))return lF(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(hn(t,ArrayBuffer)||t&&hn(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer!="undefined"&&(hn(t,SharedArrayBuffer)||t&&hn(t.buffer,SharedArrayBuffer)))return vm(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let i=t.valueOf&&t.valueOf();if(i!=null&&i!==t)return D.from(i,e,r);let n=cF(t);if(n)return n;if(typeof Symbol!="undefined"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return D.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}D.from=function(t,e,r){return Zb(t,e,r)};Object.setPrototypeOf(D.prototype,Uint8Array.prototype);Object.setPrototypeOf(D,Uint8Array);function Kb(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function aF(t,e,r){return Kb(t),t<=0?Wn(t):e!==void 0?typeof r=="string"?Wn(t).fill(e,r):Wn(t).fill(e):Wn(t)}D.alloc=function(t,e,r){return aF(t,e,r)};function bm(t){return Kb(t),Wn(t<0?0:_m(t)|0)}D.allocUnsafe=function(t){return bm(t)};D.allocUnsafeSlow=function(t){return bm(t)};function oF(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!D.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let r=Xb(t,e)|0,i=Wn(r),n=i.write(t,e);return n!==r&&(i=i.slice(0,n)),i}function gm(t){let e=t.length<0?0:_m(t.length)|0,r=Wn(e);for(let i=0;i=Nf)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Nf.toString(16)+" bytes");return t|0}function uF(t){return+t!=t&&(t=0),D.alloc(+t)}D.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==D.prototype};D.compare=function(e,r){if(hn(e,Uint8Array)&&(e=D.from(e,e.offset,e.byteLength)),hn(r,Uint8Array)&&(r=D.from(r,r.offset,r.byteLength)),!D.isBuffer(e)||!D.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;let i=e.length,n=r.length;for(let s=0,a=Math.min(i,n);sn.length?(D.isBuffer(a)||(a=D.from(a)),a.copy(n,s)):Uint8Array.prototype.set.call(n,a,s);else if(D.isBuffer(a))a.copy(n,s);else throw new TypeError('"list" argument must be an Array of Buffers');s+=a.length}return n};function Xb(t,e){if(D.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||hn(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);let r=t.length,i=arguments.length>2&&arguments[2]===!0;if(!i&&r===0)return 0;let n=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return wm(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return a_(t).length;default:if(n)return i?-1:wm(t).length;e=(""+e).toLowerCase(),n=!0}}D.byteLength=Xb;function fF(t,e,r){let i=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return yF(this,e,r);case"utf8":case"utf-8":return Jb(this,e,r);case"ascii":return bF(this,e,r);case"latin1":case"binary":return _F(this,e,r);case"base64":return vF(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return xF(this,e,r);default:if(i)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),i=!0}}D.prototype._isBuffer=!0;function ua(t,e,r){let i=t[e];t[e]=t[r],t[r]=i}D.prototype.swap16=function(){let e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let r=0;rr&&(e+=" ... "),""};zb&&(D.prototype[zb]=D.prototype.inspect);D.prototype.compare=function(e,r,i,n,s){if(hn(e,Uint8Array)&&(e=D.from(e,e.offset,e.byteLength)),!D.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),i===void 0&&(i=e?e.length:0),n===void 0&&(n=0),s===void 0&&(s=this.length),r<0||i>e.length||n<0||s>this.length)throw new RangeError("out of range index");if(n>=s&&r>=i)return 0;if(n>=s)return-1;if(r>=i)return 1;if(r>>>=0,i>>>=0,n>>>=0,s>>>=0,this===e)return 0;let a=s-n,o=i-r,l=Math.min(a,o),c=this.slice(n,s),u=e.slice(r,i);for(let f=0;f2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,xm(r)&&(r=n?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(n)return-1;r=t.length-1}else if(r<0)if(n)r=0;else return-1;if(typeof e=="string"&&(e=D.from(e,i)),D.isBuffer(e))return e.length===0?-1:Wb(t,e,r,i,n);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?n?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):Wb(t,[e],r,i,n);throw new TypeError("val must be string, number or Buffer")}function Wb(t,e,r,i,n){let s=1,a=t.length,o=e.length;if(i!==void 0&&(i=String(i).toLowerCase(),i==="ucs2"||i==="ucs-2"||i==="utf16le"||i==="utf-16le")){if(t.length<2||e.length<2)return-1;s=2,a/=2,o/=2,r/=2}function l(u,f){return s===1?u[f]:u.readUInt16BE(f*s)}let c;if(n){let u=-1;for(c=r;ca&&(r=a-o),c=r;c>=0;c--){let u=!0;for(let f=0;fn&&(i=n)):i=n;let s=e.length;i>s/2&&(i=s/2);let a;for(a=0;a>>0,isFinite(i)?(i=i>>>0,n===void 0&&(n="utf8")):(n=i,i=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let s=this.length-r;if((i===void 0||i>s)&&(i=s),e.length>0&&(i<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let a=!1;for(;;)switch(n){case"hex":return dF(this,e,r,i);case"utf8":case"utf-8":return hF(this,e,r,i);case"ascii":case"latin1":case"binary":return pF(this,e,r,i);case"base64":return mF(this,e,r,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return gF(this,e,r,i);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}};D.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function vF(t,e,r){return e===0&&r===t.length?mm.fromByteArray(t):mm.fromByteArray(t.slice(e,r))}function Jb(t,e,r){r=Math.min(t.length,r);let i=[],n=e;for(;n239?4:s>223?3:s>191?2:1;if(n+o<=r){let l,c,u,f;switch(o){case 1:s<128&&(a=s);break;case 2:l=t[n+1],(l&192)===128&&(f=(s&31)<<6|l&63,f>127&&(a=f));break;case 3:l=t[n+1],c=t[n+2],(l&192)===128&&(c&192)===128&&(f=(s&15)<<12|(l&63)<<6|c&63,f>2047&&(f<55296||f>57343)&&(a=f));break;case 4:l=t[n+1],c=t[n+2],u=t[n+3],(l&192)===128&&(c&192)===128&&(u&192)===128&&(f=(s&15)<<18|(l&63)<<12|(c&63)<<6|u&63,f>65535&&f<1114112&&(a=f))}}a===null?(a=65533,o=1):a>65535&&(a-=65536,i.push(a>>>10&1023|55296),a=56320|a&1023),i.push(a),n+=o}return wF(i)}var qb=4096;function wF(t){let e=t.length;if(e<=qb)return String.fromCharCode.apply(String,t);let r="",i=0;for(;ii)&&(r=i);let n="";for(let s=e;si&&(e=i),r<0?(r+=i,r<0&&(r=0)):r>i&&(r=i),rr)throw new RangeError("Trying to access beyond buffer length")}D.prototype.readUintLE=D.prototype.readUIntLE=function(e,r,i){e=e>>>0,r=r>>>0,i||Vt(e,r,this.length);let n=this[e],s=1,a=0;for(;++a>>0,r=r>>>0,i||Vt(e,r,this.length);let n=this[e+--r],s=1;for(;r>0&&(s*=256);)n+=this[e+--r]*s;return n};D.prototype.readUint8=D.prototype.readUInt8=function(e,r){return e=e>>>0,r||Vt(e,1,this.length),this[e]};D.prototype.readUint16LE=D.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||Vt(e,2,this.length),this[e]|this[e+1]<<8};D.prototype.readUint16BE=D.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||Vt(e,2,this.length),this[e]<<8|this[e+1]};D.prototype.readUint32LE=D.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||Vt(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};D.prototype.readUint32BE=D.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||Vt(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};D.prototype.readBigUInt64LE=ks(function(e){e=e>>>0,Co(e,"offset");let r=this[e],i=this[e+7];(r===void 0||i===void 0)&&yc(e,this.length-8);let n=r+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,s=this[++e]+this[++e]*2**8+this[++e]*2**16+i*2**24;return BigInt(n)+(BigInt(s)<>>0,Co(e,"offset");let r=this[e],i=this[e+7];(r===void 0||i===void 0)&&yc(e,this.length-8);let n=r*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],s=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+i;return(BigInt(n)<>>0,r=r>>>0,i||Vt(e,r,this.length);let n=this[e],s=1,a=0;for(;++a=s&&(n-=Math.pow(2,8*r)),n};D.prototype.readIntBE=function(e,r,i){e=e>>>0,r=r>>>0,i||Vt(e,r,this.length);let n=r,s=1,a=this[e+--n];for(;n>0&&(s*=256);)a+=this[e+--n]*s;return s*=128,a>=s&&(a-=Math.pow(2,8*r)),a};D.prototype.readInt8=function(e,r){return e=e>>>0,r||Vt(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};D.prototype.readInt16LE=function(e,r){e=e>>>0,r||Vt(e,2,this.length);let i=this[e]|this[e+1]<<8;return i&32768?i|4294901760:i};D.prototype.readInt16BE=function(e,r){e=e>>>0,r||Vt(e,2,this.length);let i=this[e+1]|this[e]<<8;return i&32768?i|4294901760:i};D.prototype.readInt32LE=function(e,r){return e=e>>>0,r||Vt(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};D.prototype.readInt32BE=function(e,r){return e=e>>>0,r||Vt(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};D.prototype.readBigInt64LE=ks(function(e){e=e>>>0,Co(e,"offset");let r=this[e],i=this[e+7];(r===void 0||i===void 0)&&yc(e,this.length-8);let n=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(i<<24);return(BigInt(n)<>>0,Co(e,"offset");let r=this[e],i=this[e+7];(r===void 0||i===void 0)&&yc(e,this.length-8);let n=(r<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(n)<>>0,r||Vt(e,4,this.length),ko.read(this,e,!0,23,4)};D.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Vt(e,4,this.length),ko.read(this,e,!1,23,4)};D.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Vt(e,8,this.length),ko.read(this,e,!0,52,8)};D.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Vt(e,8,this.length),ko.read(this,e,!1,52,8)};function Ir(t,e,r,i,n,s){if(!D.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>n||et.length)throw new RangeError("Index out of range")}D.prototype.writeUintLE=D.prototype.writeUIntLE=function(e,r,i,n){if(e=+e,r=r>>>0,i=i>>>0,!n){let o=Math.pow(2,8*i)-1;Ir(this,e,r,i,o,0)}let s=1,a=0;for(this[r]=e&255;++a>>0,i=i>>>0,!n){let o=Math.pow(2,8*i)-1;Ir(this,e,r,i,o,0)}let s=i-1,a=1;for(this[r+s]=e&255;--s>=0&&(a*=256);)this[r+s]=e/a&255;return r+i};D.prototype.writeUint8=D.prototype.writeUInt8=function(e,r,i){return e=+e,r=r>>>0,i||Ir(this,e,r,1,255,0),this[r]=e&255,r+1};D.prototype.writeUint16LE=D.prototype.writeUInt16LE=function(e,r,i){return e=+e,r=r>>>0,i||Ir(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};D.prototype.writeUint16BE=D.prototype.writeUInt16BE=function(e,r,i){return e=+e,r=r>>>0,i||Ir(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};D.prototype.writeUint32LE=D.prototype.writeUInt32LE=function(e,r,i){return e=+e,r=r>>>0,i||Ir(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};D.prototype.writeUint32BE=D.prototype.writeUInt32BE=function(e,r,i){return e=+e,r=r>>>0,i||Ir(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function e_(t,e,r,i,n){s_(e,i,n,t,r,7);let s=Number(e&BigInt(4294967295));t[r++]=s,s=s>>8,t[r++]=s,s=s>>8,t[r++]=s,s=s>>8,t[r++]=s;let a=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=a,a=a>>8,t[r++]=a,a=a>>8,t[r++]=a,a=a>>8,t[r++]=a,r}function t_(t,e,r,i,n){s_(e,i,n,t,r,7);let s=Number(e&BigInt(4294967295));t[r+7]=s,s=s>>8,t[r+6]=s,s=s>>8,t[r+5]=s,s=s>>8,t[r+4]=s;let a=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=a,a=a>>8,t[r+2]=a,a=a>>8,t[r+1]=a,a=a>>8,t[r]=a,r+8}D.prototype.writeBigUInt64LE=ks(function(e,r=0){return e_(this,e,r,BigInt(0),BigInt("0xffffffffffffffff"))});D.prototype.writeBigUInt64BE=ks(function(e,r=0){return t_(this,e,r,BigInt(0),BigInt("0xffffffffffffffff"))});D.prototype.writeIntLE=function(e,r,i,n){if(e=+e,r=r>>>0,!n){let l=Math.pow(2,8*i-1);Ir(this,e,r,i,l-1,-l)}let s=0,a=1,o=0;for(this[r]=e&255;++s>0)-o&255;return r+i};D.prototype.writeIntBE=function(e,r,i,n){if(e=+e,r=r>>>0,!n){let l=Math.pow(2,8*i-1);Ir(this,e,r,i,l-1,-l)}let s=i-1,a=1,o=0;for(this[r+s]=e&255;--s>=0&&(a*=256);)e<0&&o===0&&this[r+s+1]!==0&&(o=1),this[r+s]=(e/a>>0)-o&255;return r+i};D.prototype.writeInt8=function(e,r,i){return e=+e,r=r>>>0,i||Ir(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};D.prototype.writeInt16LE=function(e,r,i){return e=+e,r=r>>>0,i||Ir(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};D.prototype.writeInt16BE=function(e,r,i){return e=+e,r=r>>>0,i||Ir(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};D.prototype.writeInt32LE=function(e,r,i){return e=+e,r=r>>>0,i||Ir(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};D.prototype.writeInt32BE=function(e,r,i){return e=+e,r=r>>>0,i||Ir(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};D.prototype.writeBigInt64LE=ks(function(e,r=0){return e_(this,e,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});D.prototype.writeBigInt64BE=ks(function(e,r=0){return t_(this,e,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function r_(t,e,r,i,n,s){if(r+i>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function i_(t,e,r,i,n){return e=+e,r=r>>>0,n||r_(t,e,r,4,34028234663852886e22,-34028234663852886e22),ko.write(t,e,r,i,23,4),r+4}D.prototype.writeFloatLE=function(e,r,i){return i_(this,e,r,!0,i)};D.prototype.writeFloatBE=function(e,r,i){return i_(this,e,r,!1,i)};function n_(t,e,r,i,n){return e=+e,r=r>>>0,n||r_(t,e,r,8,17976931348623157e292,-17976931348623157e292),ko.write(t,e,r,i,52,8),r+8}D.prototype.writeDoubleLE=function(e,r,i){return n_(this,e,r,!0,i)};D.prototype.writeDoubleBE=function(e,r,i){return n_(this,e,r,!1,i)};D.prototype.copy=function(e,r,i,n){if(!D.isBuffer(e))throw new TypeError("argument should be a Buffer");if(i||(i=0),!n&&n!==0&&(n=this.length),r>=e.length&&(r=e.length),r||(r=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-r>>0,i=i===void 0?this.length:i>>>0,e||(e=0);let s;if(typeof e=="number")for(s=r;s2**32?n=Yb(String(r)):typeof r=="bigint"&&(n=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(n=Yb(n)),n+="n"),i+=` It must be ${e}. Received ${n}`,i},RangeError);function Yb(t){let e="",r=t.length,i=t[0]==="-"?1:0;for(;r>=i+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function EF(t,e,r){Co(e,"offset"),(t[e]===void 0||t[e+r]===void 0)&&yc(e,t.length-(r+1))}function s_(t,e,r,i,n,s){if(t>r||t3?e===0||e===BigInt(0)?o=`>= 0${a} and < 2${a} ** ${(s+1)*8}${a}`:o=`>= -(2${a} ** ${(s+1)*8-1}${a}) and < 2 ** ${(s+1)*8-1}${a}`:o=`>= ${e}${a} and <= ${r}${a}`,new So.ERR_OUT_OF_RANGE("value",o,t)}EF(i,n,s)}function Co(t,e){if(typeof t!="number")throw new So.ERR_INVALID_ARG_TYPE(e,"number",t)}function yc(t,e,r){throw Math.floor(t)!==t?(Co(t,r),new So.ERR_OUT_OF_RANGE(r||"offset","an integer",t)):e<0?new So.ERR_BUFFER_OUT_OF_BOUNDS:new So.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${e}`,t)}var SF=/[^+/0-9A-Za-z-_]/g;function kF(t){if(t=t.split("=")[0],t=t.trim().replace(SF,""),t.length<2)return"";for(;t.length%4!==0;)t=t+"=";return t}function wm(t,e){e=e||1/0;let r,i=t.length,n=null,s=[];for(let a=0;a55295&&r<57344){if(!n){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(a+1===i){(e-=3)>-1&&s.push(239,191,189);continue}n=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),n=r;continue}r=(n-55296<<10|r-56320)+65536}else n&&(e-=3)>-1&&s.push(239,191,189);if(n=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return s}function CF(t){let e=[];for(let r=0;r>8,n=r%256,s.push(n),s.push(i);return s}function a_(t){return mm.toByteArray(kF(t))}function Bf(t,e,r,i){let n;for(n=0;n=e.length||n>=t.length);++n)e[n+r]=t[n];return n}function hn(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function xm(t){return t!==t}var TF=(function(){let t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){let i=r*16;for(let n=0;n<16;++n)e[i+n]=t[r]+t[n]}return e})();function ks(t){return typeof BigInt=="undefined"?PF:t}function PF(){throw new Error("BigInt not supported")}});var o_,Sm,k,m=Z$(()=>{"use strict";o_=require("obsidian");o_.Platform.isMobileApp?Sm=Em().Buffer:Sm=global.Buffer;k=Sm});var c_=H((nj,l_)=>{"use strict";m();var ri=function(t){if(t=t||{},this.Promise=t.Promise||Promise,this.queues=Object.create(null),this.domainReentrant=t.domainReentrant||!1,this.domainReentrant){if(typeof process=="undefined"||typeof process.domain=="undefined")throw new Error("Domain-reentrant locks require `process.domain` to exist. Please flip `opts.domainReentrant = false`, use a NodeJS version that still implements Domain, or install a browser polyfill.");this.domains=Object.create(null)}this.timeout=t.timeout||ri.DEFAULT_TIMEOUT,this.maxOccupationTime=t.maxOccupationTime||ri.DEFAULT_MAX_OCCUPATION_TIME,this.maxExecutionTime=t.maxExecutionTime||ri.DEFAULT_MAX_EXECUTION_TIME,t.maxPending===1/0||Number.isInteger(t.maxPending)&&t.maxPending>=0?this.maxPending=t.maxPending:this.maxPending=ri.DEFAULT_MAX_PENDING};ri.DEFAULT_TIMEOUT=0;ri.DEFAULT_MAX_OCCUPATION_TIME=0;ri.DEFAULT_MAX_EXECUTION_TIME=0;ri.DEFAULT_MAX_PENDING=1e3;ri.prototype.acquire=function(t,e,r,i){if(Array.isArray(t))return this._acquireBatch(t,e,r,i);if(typeof e!="function")throw new Error("You must pass a function to execute");var n=null,s=null,a=null;typeof r!="function"&&(i=r,r=null,a=new this.Promise(function(_,C){n=_,s=C})),i=i||{};var o=!1,l=null,c=null,u=null,f=this,d=function(_,C,x){c&&(clearTimeout(c),c=null),u&&(clearTimeout(u),u=null),_&&(f.queues[t]&&f.queues[t].length===0&&delete f.queues[t],f.domainReentrant&&delete f.domains[t]),o||(a?C?s(C):n(x):typeof r=="function"&&r(C,x),o=!0),_&&f.queues[t]&&f.queues[t].length>0&&f.queues[t].shift()()},h=function(_){if(o)return d(_);l&&(clearTimeout(l),l=null),f.domainReentrant&&_&&(f.domains[t]=process.domain);var C=i.maxExecutionTime||f.maxExecutionTime;if(C&&(u=setTimeout(function(){f.queues[t]&&d(_,new Error("Maximum execution time is exceeded "+t))},C)),e.length===1){var x=!1;try{e(function(E,A){x||(x=!0,d(_,E,A))})}catch(E){x||(x=!0,d(_,E))}}else f._promiseTry(function(){return e()}).then(function(E){d(_,void 0,E)},function(E){d(_,E)})};f.domainReentrant&&process.domain&&(h=process.domain.bind(h));var p=i.maxPending||f.maxPending;if(!f.queues[t])f.queues[t]=[],h(!0);else if(f.domainReentrant&&process.domain&&process.domain===f.domains[t])h(!1);else if(f.queues[t].length>=p)d(!1,new Error("Too many pending tasks in queue "+t));else{var g=function(){h(!0)};i.skipQueue?f.queues[t].unshift(g):f.queues[t].push(g);var v=i.timeout||f.timeout;v&&(l=setTimeout(function(){l=null,d(!1,new Error("async-lock timed out in queue "+t))},v))}var b=i.maxOccupationTime||f.maxOccupationTime;if(b&&(c=setTimeout(function(){f.queues[t]&&d(!1,new Error("Maximum occupation time is exceeded in queue "+t))},b)),a)return a};ri.prototype._acquireBatch=function(t,e,r,i){typeof r!="function"&&(i=r,r=null);var n=this,s=function(o,l){return function(c){n.acquire(o,l,c,i)}},a=t.reduceRight(function(o,l){return s(l,o)},e);if(typeof r=="function")a(r);else return new this.Promise(function(o,l){a.length===1?a(function(c,u){c?l(c):o(u)}):o(a())})};ri.prototype.isBusy=function(t){return t?!!this.queues[t]:Object.keys(this.queues).length>0};ri.prototype._promiseTry=function(t){try{return this.Promise.resolve(t())}catch(e){return this.Promise.reject(e)}};l_.exports=ri});var f_=H((aj,u_)=>{"use strict";m();u_.exports=c_()});var d_=H((lj,km)=>{m();typeof Object.create=="function"?km.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:km.exports=function(e,r){if(r){e.super_=r;var i=function(){};i.prototype=r.prototype,e.prototype=new i,e.prototype.constructor=e}}});var Uf=H((Cm,p_)=>{m();var Hf=Em(),pn=Hf.Buffer;function h_(t,e){for(var r in t)e[r]=t[r]}pn.from&&pn.alloc&&pn.allocUnsafe&&pn.allocUnsafeSlow?p_.exports=Hf:(h_(Hf,Cm),Cm.Buffer=fa);function fa(t,e,r){return pn(t,e,r)}fa.prototype=Object.create(pn.prototype);h_(pn,fa);fa.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return pn(t,e,r)};fa.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var i=pn(t);return e!==void 0?typeof r=="string"?i.fill(e,r):i.fill(e):i.fill(0),i};fa.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return pn(t)};fa.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Hf.SlowBuffer(t)}});var g_=H((fj,m_)=>{m();var RF={}.toString;m_.exports=Array.isArray||function(t){return RF.call(t)=="[object Array]"}});var To=H((hj,v_)=>{"use strict";m();v_.exports=TypeError});var Am=H((mj,w_)=>{"use strict";m();w_.exports=Object});var __=H((vj,b_)=>{"use strict";m();b_.exports=Error});var x_=H((bj,y_)=>{"use strict";m();y_.exports=EvalError});var S_=H((yj,E_)=>{"use strict";m();E_.exports=RangeError});var C_=H((Ej,k_)=>{"use strict";m();k_.exports=ReferenceError});var Tm=H((kj,A_)=>{"use strict";m();A_.exports=SyntaxError});var P_=H((Aj,T_)=>{"use strict";m();T_.exports=URIError});var $_=H((Pj,R_)=>{"use strict";m();R_.exports=Math.abs});var I_=H(($j,F_)=>{"use strict";m();F_.exports=Math.floor});var D_=H((Ij,M_)=>{"use strict";m();M_.exports=Math.max});var L_=H((Dj,O_)=>{"use strict";m();O_.exports=Math.min});var B_=H((Lj,N_)=>{"use strict";m();N_.exports=Math.pow});var U_=H((Bj,H_)=>{"use strict";m();H_.exports=Math.round});var j_=H((Uj,G_)=>{"use strict";m();G_.exports=Number.isNaN||function(e){return e!==e}});var z_=H((jj,V_)=>{"use strict";m();var $F=j_();V_.exports=function(e){return $F(e)||e===0?e:e<0?-1:1}});var q_=H((zj,W_)=>{"use strict";m();W_.exports=Object.getOwnPropertyDescriptor});var Po=H((qj,Y_)=>{"use strict";m();var Gf=q_();if(Gf)try{Gf([],"length")}catch(t){Gf=null}Y_.exports=Gf});var xc=H((Zj,Z_)=>{"use strict";m();var jf=Object.defineProperty||!1;if(jf)try{jf({},"a",{value:1})}catch(t){jf=!1}Z_.exports=jf});var Pm=H((Xj,K_)=>{"use strict";m();K_.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),i=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(i)!=="[object Symbol]")return!1;var n=42;e[r]=n;for(var s in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var a=Object.getOwnPropertySymbols(e);if(a.length!==1||a[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var o=Object.getOwnPropertyDescriptor(e,r);if(o.value!==n||o.enumerable!==!0)return!1}return!0}});var J_=H((Jj,Q_)=>{"use strict";m();var X_=typeof Symbol!="undefined"&&Symbol,FF=Pm();Q_.exports=function(){return typeof X_!="function"||typeof Symbol!="function"||typeof X_("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:FF()}});var Rm=H((tV,ey)=>{"use strict";m();ey.exports=typeof Reflect!="undefined"&&Reflect.getPrototypeOf||null});var $m=H((iV,ty)=>{"use strict";m();var IF=Am();ty.exports=IF.getPrototypeOf||null});var ny=H((sV,iy)=>{"use strict";m();var MF="Function.prototype.bind called on incompatible ",DF=Object.prototype.toString,OF=Math.max,LF="[object Function]",ry=function(e,r){for(var i=[],n=0;n{"use strict";m();var HF=ny();sy.exports=Function.prototype.bind||HF});var Vf=H((cV,ay)=>{"use strict";m();ay.exports=Function.prototype.call});var zf=H((fV,oy)=>{"use strict";m();oy.exports=Function.prototype.apply});var cy=H((hV,ly)=>{"use strict";m();ly.exports=typeof Reflect!="undefined"&&Reflect&&Reflect.apply});var Fm=H((mV,uy)=>{"use strict";m();var UF=Ro(),GF=zf(),jF=Vf(),VF=cy();uy.exports=VF||UF.call(jF,GF)});var Wf=H((vV,fy)=>{"use strict";m();var zF=Ro(),WF=To(),qF=Vf(),YF=Fm();fy.exports=function(e){if(e.length<1||typeof e[0]!="function")throw new WF("a function is required");return YF(zF,qF,e)}});var vy=H((bV,gy)=>{"use strict";m();var ZF=Wf(),dy=Po(),py;try{py=[].__proto__===Array.prototype}catch(t){if(!t||typeof t!="object"||!("code"in t)||t.code!=="ERR_PROTO_ACCESS")throw t}var Im=!!py&&dy&&dy(Object.prototype,"__proto__"),my=Object,hy=my.getPrototypeOf;gy.exports=Im&&typeof Im.get=="function"?ZF([Im.get]):typeof hy=="function"?function(e){return hy(e==null?e:my(e))}:!1});var Mm=H((yV,yy)=>{"use strict";m();var wy=Rm(),by=$m(),_y=vy();yy.exports=wy?function(e){return wy(e)}:by?function(e){if(!e||typeof e!="object"&&typeof e!="function")throw new TypeError("getProto: not an object");return by(e)}:_y?function(e){return _y(e)}:null});var Ey=H((EV,xy)=>{"use strict";m();var KF=Function.prototype.call,XF=Object.prototype.hasOwnProperty,QF=Ro();xy.exports=QF.call(KF,XF)});var Lm=H((kV,Py)=>{"use strict";m();var Te,JF=Am(),eI=__(),tI=x_(),rI=S_(),iI=C_(),Mo=Tm(),Io=To(),nI=P_(),sI=$_(),aI=I_(),oI=D_(),lI=L_(),cI=B_(),uI=U_(),fI=z_(),Ay=Function,Dm=function(t){try{return Ay('"use strict"; return ('+t+").constructor;")()}catch(e){}},Ec=Po(),dI=xc(),Om=function(){throw new Io},hI=Ec?(function(){try{return arguments.callee,Om}catch(t){try{return Ec(arguments,"callee").get}catch(e){return Om}}})():Om,$o=J_()(),zt=Mm(),pI=$m(),mI=Rm(),Ty=zf(),Sc=Vf(),Fo={},gI=typeof Uint8Array=="undefined"||!zt?Te:zt(Uint8Array),da={__proto__:null,"%AggregateError%":typeof AggregateError=="undefined"?Te:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer=="undefined"?Te:ArrayBuffer,"%ArrayIteratorPrototype%":$o&&zt?zt([][Symbol.iterator]()):Te,"%AsyncFromSyncIteratorPrototype%":Te,"%AsyncFunction%":Fo,"%AsyncGenerator%":Fo,"%AsyncGeneratorFunction%":Fo,"%AsyncIteratorPrototype%":Fo,"%Atomics%":typeof Atomics=="undefined"?Te:Atomics,"%BigInt%":typeof BigInt=="undefined"?Te:BigInt,"%BigInt64Array%":typeof BigInt64Array=="undefined"?Te:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array=="undefined"?Te:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView=="undefined"?Te:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":eI,"%eval%":eval,"%EvalError%":tI,"%Float16Array%":typeof Float16Array=="undefined"?Te:Float16Array,"%Float32Array%":typeof Float32Array=="undefined"?Te:Float32Array,"%Float64Array%":typeof Float64Array=="undefined"?Te:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry=="undefined"?Te:FinalizationRegistry,"%Function%":Ay,"%GeneratorFunction%":Fo,"%Int8Array%":typeof Int8Array=="undefined"?Te:Int8Array,"%Int16Array%":typeof Int16Array=="undefined"?Te:Int16Array,"%Int32Array%":typeof Int32Array=="undefined"?Te:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":$o&&zt?zt(zt([][Symbol.iterator]())):Te,"%JSON%":typeof JSON=="object"?JSON:Te,"%Map%":typeof Map=="undefined"?Te:Map,"%MapIteratorPrototype%":typeof Map=="undefined"||!$o||!zt?Te:zt(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":JF,"%Object.getOwnPropertyDescriptor%":Ec,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise=="undefined"?Te:Promise,"%Proxy%":typeof Proxy=="undefined"?Te:Proxy,"%RangeError%":rI,"%ReferenceError%":iI,"%Reflect%":typeof Reflect=="undefined"?Te:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set=="undefined"?Te:Set,"%SetIteratorPrototype%":typeof Set=="undefined"||!$o||!zt?Te:zt(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer=="undefined"?Te:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":$o&&zt?zt(""[Symbol.iterator]()):Te,"%Symbol%":$o?Symbol:Te,"%SyntaxError%":Mo,"%ThrowTypeError%":hI,"%TypedArray%":gI,"%TypeError%":Io,"%Uint8Array%":typeof Uint8Array=="undefined"?Te:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray=="undefined"?Te:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array=="undefined"?Te:Uint16Array,"%Uint32Array%":typeof Uint32Array=="undefined"?Te:Uint32Array,"%URIError%":nI,"%WeakMap%":typeof WeakMap=="undefined"?Te:WeakMap,"%WeakRef%":typeof WeakRef=="undefined"?Te:WeakRef,"%WeakSet%":typeof WeakSet=="undefined"?Te:WeakSet,"%Function.prototype.call%":Sc,"%Function.prototype.apply%":Ty,"%Object.defineProperty%":dI,"%Object.getPrototypeOf%":pI,"%Math.abs%":sI,"%Math.floor%":aI,"%Math.max%":oI,"%Math.min%":lI,"%Math.pow%":cI,"%Math.round%":uI,"%Math.sign%":fI,"%Reflect.getPrototypeOf%":mI};if(zt)try{null.error}catch(t){Sy=zt(zt(t)),da["%Error.prototype%"]=Sy}var Sy,vI=function t(e){var r;if(e==="%AsyncFunction%")r=Dm("async function () {}");else if(e==="%GeneratorFunction%")r=Dm("function* () {}");else if(e==="%AsyncGeneratorFunction%")r=Dm("async function* () {}");else if(e==="%AsyncGenerator%"){var i=t("%AsyncGeneratorFunction%");i&&(r=i.prototype)}else if(e==="%AsyncIteratorPrototype%"){var n=t("%AsyncGenerator%");n&&zt&&(r=zt(n.prototype))}return da[e]=r,r},ky={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},kc=Ro(),qf=Ey(),wI=kc.call(Sc,Array.prototype.concat),bI=kc.call(Ty,Array.prototype.splice),Cy=kc.call(Sc,String.prototype.replace),Yf=kc.call(Sc,String.prototype.slice),_I=kc.call(Sc,RegExp.prototype.exec),yI=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,xI=/\\(\\)?/g,EI=function(e){var r=Yf(e,0,1),i=Yf(e,-1);if(r==="%"&&i!=="%")throw new Mo("invalid intrinsic syntax, expected closing `%`");if(i==="%"&&r!=="%")throw new Mo("invalid intrinsic syntax, expected opening `%`");var n=[];return Cy(e,yI,function(s,a,o,l){n[n.length]=o?Cy(l,xI,"$1"):a||s}),n},SI=function(e,r){var i=e,n;if(qf(ky,i)&&(n=ky[i],i="%"+n[0]+"%"),qf(da,i)){var s=da[i];if(s===Fo&&(s=vI(i)),typeof s=="undefined"&&!r)throw new Io("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:n,name:i,value:s}}throw new Mo("intrinsic "+e+" does not exist!")};Py.exports=function(e,r){if(typeof e!="string"||e.length===0)throw new Io("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new Io('"allowMissing" argument must be a boolean');if(_I(/^%?[^%]*%?$/,e)===null)throw new Mo("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var i=EI(e),n=i.length>0?i[0]:"",s=SI("%"+n+"%",r),a=s.name,o=s.value,l=!1,c=s.alias;c&&(n=c[0],bI(i,wI([0,1],c)));for(var u=1,f=!0;u=i.length){var g=Ec(o,d);f=!!g,f&&"get"in g&&!("originalValue"in g.get)?o=g.get:o=o[d]}else f=qf(o,d),o=o[d];f&&!l&&(da[a]=o)}}return o}});var Nm=H((AV,Fy)=>{"use strict";m();var Ry=Lm(),$y=Wf(),kI=$y([Ry("%String.prototype.indexOf%")]);Fy.exports=function(e,r){var i=Ry(e,!!r);return typeof i=="function"&&kI(e,".prototype.")>-1?$y([i]):i}});var Oy=H((PV,Dy)=>{"use strict";m();var My=Function.prototype.toString,Do=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,Hm,Zf;if(typeof Do=="function"&&typeof Object.defineProperty=="function")try{Hm=Object.defineProperty({},"length",{get:function(){throw Zf}}),Zf={},Do(function(){throw 42},null,Hm)}catch(t){t!==Zf&&(Do=null)}else Do=null;var CI=/^\s*class\b/,Um=function(e){try{var r=My.call(e);return CI.test(r)}catch(i){return!1}},Bm=function(e){try{return Um(e)?!1:(My.call(e),!0)}catch(r){return!1}},Kf=Object.prototype.toString,AI="[object Object]",TI="[object Function]",PI="[object GeneratorFunction]",RI="[object HTMLAllCollection]",$I="[object HTML document.all class]",FI="[object HTMLCollection]",II=typeof Symbol=="function"&&!!Symbol.toStringTag,MI=!(0 in[,]),Gm=function(){return!1};typeof document=="object"&&(Iy=document.all,Kf.call(Iy)===Kf.call(document.all)&&(Gm=function(e){if((MI||!e)&&(typeof e=="undefined"||typeof e=="object"))try{var r=Kf.call(e);return(r===RI||r===$I||r===FI||r===AI)&&e("")==null}catch(i){}return!1}));var Iy;Dy.exports=Do?function(e){if(Gm(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;try{Do(e,null,Hm)}catch(r){if(r!==Zf)return!1}return!Um(e)&&Bm(e)}:function(e){if(Gm(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;if(II)return Bm(e);if(Um(e))return!1;var r=Kf.call(e);return r!==TI&&r!==PI&&!/^\[object HTML/.test(r)?!1:Bm(e)}});var By=H(($V,Ny)=>{"use strict";m();var DI=Oy(),OI=Object.prototype.toString,Ly=Object.prototype.hasOwnProperty,LI=function(e,r,i){for(var n=0,s=e.length;n=3&&(n=i),HI(e)?LI(e,r,n):typeof e=="string"?NI(e,r,n):BI(e,r,n)}});var Uy=H((IV,Hy)=>{"use strict";m();Hy.exports=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]});var jy=H((DV,Gy)=>{"use strict";m();var jm=Uy(),UI=typeof globalThis=="undefined"?global:globalThis;Gy.exports=function(){for(var e=[],r=0;r{"use strict";m();var Vy=xc(),GI=Tm(),Oo=To(),zy=Po();Wy.exports=function(e,r,i){if(!e||typeof e!="object"&&typeof e!="function")throw new Oo("`obj` must be an object or a function`");if(typeof r!="string"&&typeof r!="symbol")throw new Oo("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new Oo("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new Oo("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new Oo("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new Oo("`loose`, if provided, must be a boolean");var n=arguments.length>3?arguments[3]:null,s=arguments.length>4?arguments[4]:null,a=arguments.length>5?arguments[5]:null,o=arguments.length>6?arguments[6]:!1,l=!!zy&&zy(e,r);if(Vy)Vy(e,r,{configurable:a===null&&l?l.configurable:!a,enumerable:n===null&&l?l.enumerable:!n,value:i,writable:s===null&&l?l.writable:!s});else if(o||!n&&!s&&!a)e[r]=i;else throw new GI("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")}});var Ky=H((BV,Zy)=>{"use strict";m();var Vm=xc(),Yy=function(){return!!Vm};Yy.hasArrayLengthDefineBug=function(){if(!Vm)return null;try{return Vm([],"length",{value:1}).length!==1}catch(e){return!0}};Zy.exports=Yy});var tx=H((UV,ex)=>{"use strict";m();var jI=Lm(),Xy=qy(),VI=Ky()(),Qy=Po(),Jy=To(),zI=jI("%Math.floor%");ex.exports=function(e,r){if(typeof e!="function")throw new Jy("`fn` is not a function");if(typeof r!="number"||r<0||r>4294967295||zI(r)!==r)throw new Jy("`length` must be a positive 32-bit integer");var i=arguments.length>2&&!!arguments[2],n=!0,s=!0;if("length"in e&&Qy){var a=Qy(e,"length");a&&!a.configurable&&(n=!1),a&&!a.writable&&(s=!1)}return(n||s||!i)&&(VI?Xy(e,"length",r,!0,!0):Xy(e,"length",r)),e}});var ix=H((jV,rx)=>{"use strict";m();var WI=Ro(),qI=zf(),YI=Fm();rx.exports=function(){return YI(WI,qI,arguments)}});var ax=H((zV,Xf)=>{"use strict";m();var ZI=tx(),nx=xc(),KI=Wf(),sx=ix();Xf.exports=function(e){var r=KI(arguments),i=1+e.length-(arguments.length-1);return ZI(r,i>0?i:0,!0)};nx?nx(Xf.exports,"apply",{value:sx}):Xf.exports.apply=sx});var lx=H((qV,ox)=>{"use strict";m();var XI=Pm();ox.exports=function(){return XI()&&!!Symbol.toStringTag}});var hx=H((ZV,dx)=>{"use strict";m();var td=By(),QI=jy(),cx=ax(),Wm=Nm(),Jf=Po(),Qf=Mm(),JI=Wm("Object.prototype.toString"),fx=lx()(),ux=typeof globalThis=="undefined"?global:globalThis,zm=QI(),qm=Wm("String.prototype.slice"),eM=Wm("Array.prototype.indexOf",!0)||function(e,r){for(var i=0;i-1}dx.exports=function(e){if(!e||typeof e!="object")return!1;if(!fx){var r=qm(JI(e),8,-1);return iM(r)?r:r!=="Object"?!1:rM(e)}return Jf?tM(e):null}});var mx=H((XV,px)=>{"use strict";m();var nM=hx();px.exports=function(e){return!!nM(e)}});var vx=H((JV,gx)=>{"use strict";m();var sM=To(),aM=Nm(),oM=aM("TypedArray.prototype.buffer",!0),lM=mx();gx.exports=oM||function(e){if(!lM(e))throw new sM("Not a Typed Array");return e.buffer}});var _x=H((tz,bx)=>{"use strict";m();var Gi=Uf().Buffer,cM=g_(),uM=vx(),fM=ArrayBuffer.isView||function(e){try{return uM(e),!0}catch(r){return!1}},dM=typeof Uint8Array!="undefined",wx=typeof ArrayBuffer!="undefined"&&typeof Uint8Array!="undefined",hM=wx&&(Gi.prototype instanceof Uint8Array||Gi.TYPED_ARRAY_SUPPORT);bx.exports=function(e,r){if(Gi.isBuffer(e))return e.constructor&&!("isBuffer"in e)?Gi.from(e):e;if(typeof e=="string")return Gi.from(e,r);if(wx&&fM(e)){if(e.byteLength===0)return Gi.alloc(0);if(hM){var i=Gi.from(e.buffer,e.byteOffset,e.byteLength);if(i.byteLength===e.byteLength)return i}var n=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=Gi.from(n);if(s.length===e.byteLength)return s}if(dM&&e instanceof Uint8Array)return Gi.from(e);var a=cM(e);if(a)for(var o=0;o255||~~l!==l)throw new RangeError("Array items must be numbers in the range 0-255.")}if(a||Gi.isBuffer(e)&&e.constructor&&typeof e.constructor.isBuffer=="function"&&e.constructor.isBuffer(e))return Gi.from(e);throw new TypeError('The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.')}});var xx=H((iz,yx)=>{"use strict";m();var pM=Uf().Buffer,mM=_x();function id(t,e){this._block=pM.alloc(t),this._finalSize=e,this._blockSize=t,this._len=0}id.prototype.update=function(t,e){t=mM(t,e||"utf8");for(var r=this._block,i=this._blockSize,n=t.length,s=this._len,a=0;a=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=this._len*8;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var i=(r&4294967295)>>>0,n=(r-i)/4294967296;this._block.writeUInt32BE(n,this._blockSize-8),this._block.writeUInt32BE(i,this._blockSize-4)}this._update(this._block);var s=this._hash();return t?s.toString(t):s};id.prototype._update=function(){throw new Error("_update must be implemented by subclass")};yx.exports=id});var kx=H((sz,Sx)=>{"use strict";m();var gM=d_(),Ex=xx(),vM=Uf().Buffer,wM=[1518500249,1859775393,-1894007588,-899497514],bM=new Array(80);function Cc(){this.init(),this._w=bM,Ex.call(this,64,56)}gM(Cc,Ex);Cc.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function _M(t){return t<<1|t>>>31}function yM(t){return t<<5|t>>>27}function xM(t){return t<<30|t>>>2}function EM(t,e,r,i){return t===0?e&r|~e&i:t===2?e&r|e&i|r&i:e^r^i}Cc.prototype._update=function(t){for(var e=this._w,r=this._a|0,i=this._b|0,n=this._c|0,s=this._d|0,a=this._e|0,o=0;o<16;++o)e[o]=t.readInt32BE(o*4);for(;o<80;++o)e[o]=_M(e[o-3]^e[o-8]^e[o-14]^e[o-16]);for(var l=0;l<80;++l){var c=~~(l/20),u=yM(r)+EM(c,i,n,s)+a+e[l]+wM[c]|0;a=s,s=n,n=xM(i),i=r,r=u}this._a=r+this._a|0,this._b=i+this._b|0,this._c=n+this._c|0,this._d=s+this._d|0,this._e=a+this._e|0};Cc.prototype._hash=function(){var t=vM.allocUnsafe(20);return t.writeInt32BE(this._a|0,0),t.writeInt32BE(this._b|0,4),t.writeInt32BE(this._c|0,8),t.writeInt32BE(this._d|0,12),t.writeInt32BE(this._e|0,16),t};Sx.exports=Cc});var Ax=H(Ym=>{m();var Cx;(function(t){typeof DO_NOT_EXPORT_CRC=="undefined"?typeof Ym=="object"?t(Ym):typeof define=="function"&&define.amd?define(function(){var e={};return t(e),e}):t(Cx={}):t(Cx={})})(function(t){t.version="1.2.2";function e(){for(var w=0,S=new Array(256),y=0;y!=256;++y)w=y,w=w&1?-306674912^w>>>1:w>>>1,w=w&1?-306674912^w>>>1:w>>>1,w=w&1?-306674912^w>>>1:w>>>1,w=w&1?-306674912^w>>>1:w>>>1,w=w&1?-306674912^w>>>1:w>>>1,w=w&1?-306674912^w>>>1:w>>>1,w=w&1?-306674912^w>>>1:w>>>1,w=w&1?-306674912^w>>>1:w>>>1,S[y]=w;return typeof Int32Array!="undefined"?new Int32Array(S):S}var r=e();function i(w){var S=0,y=0,P=0,T=typeof Int32Array!="undefined"?new Int32Array(4096):new Array(4096);for(P=0;P!=256;++P)T[P]=w[P];for(P=0;P!=256;++P)for(y=w[P],S=256+P;S<4096;S+=256)y=T[S]=y>>>8^w[y&255];var I=[];for(P=1;P!=16;++P)I[P-1]=typeof Int32Array!="undefined"?T.subarray(P*256,P*256+256):T.slice(P*256,P*256+256);return I}var n=i(r),s=n[0],a=n[1],o=n[2],l=n[3],c=n[4],u=n[5],f=n[6],d=n[7],h=n[8],p=n[9],g=n[10],v=n[11],b=n[12],_=n[13],C=n[14];function x(w,S){for(var y=S^-1,P=0,T=w.length;P>>8^r[(y^w.charCodeAt(P++))&255];return~y}function E(w,S){for(var y=S^-1,P=w.length-15,T=0;T>8&255]^b[w[T++]^y>>16&255]^v[w[T++]^y>>>24]^g[w[T++]]^p[w[T++]]^h[w[T++]]^d[w[T++]]^f[w[T++]]^u[w[T++]]^c[w[T++]]^l[w[T++]]^o[w[T++]]^a[w[T++]]^s[w[T++]]^r[w[T++]];for(P+=15;T>>8^r[(y^w[T++])&255];return~y}function A(w,S){for(var y=S^-1,P=0,T=w.length,I=0,M=0;P>>8^r[(y^I)&255]:I<2048?(y=y>>>8^r[(y^(192|I>>6&31))&255],y=y>>>8^r[(y^(128|I&63))&255]):I>=55296&&I<57344?(I=(I&1023)+64,M=w.charCodeAt(P++)&1023,y=y>>>8^r[(y^(240|I>>8&7))&255],y=y>>>8^r[(y^(128|I>>2&63))&255],y=y>>>8^r[(y^(128|M>>6&15|(I&3)<<4))&255],y=y>>>8^r[(y^(128|M&63))&255]):(y=y>>>8^r[(y^(224|I>>12&15))&255],y=y>>>8^r[(y^(128|I>>6&63))&255],y=y>>>8^r[(y^(128|I&63))&255]);return~y}t.table=r,t.bstr=x,t.buf=E,t.str=A})});var qn=H(_r=>{"use strict";m();var SM=typeof Uint8Array!="undefined"&&typeof Uint16Array!="undefined"&&typeof Int32Array!="undefined";function kM(t,e){return Object.prototype.hasOwnProperty.call(t,e)}_r.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var r=e.shift();if(r){if(typeof r!="object")throw new TypeError(r+"must be non-object");for(var i in r)kM(r,i)&&(t[i]=r[i])}}return t};_r.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var CM={arraySet:function(t,e,r,i,n){if(e.subarray&&t.subarray){t.set(e.subarray(r,r+i),n);return}for(var s=0;s{"use strict";m();var TM=qn(),PM=4,Tx=0,Px=1,RM=2;function No(t){for(var e=t.length;--e>=0;)t[e]=0}var $M=0,Dx=1,FM=2,IM=3,MM=258,tg=29,Fc=256,Tc=Fc+1+tg,Lo=30,rg=19,Ox=2*Tc+1,ha=15,Zm=16,DM=7,ig=256,Lx=16,Nx=17,Bx=18,Jm=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],nd=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],OM=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],Hx=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],LM=512,Yn=new Array((Tc+2)*2);No(Yn);var Ac=new Array(Lo*2);No(Ac);var Pc=new Array(LM);No(Pc);var Rc=new Array(MM-IM+1);No(Rc);var ng=new Array(tg);No(ng);var sd=new Array(Lo);No(sd);function Km(t,e,r,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=r,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}var Ux,Gx,jx;function Xm(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function Vx(t){return t<256?Pc[t]:Pc[256+(t>>>7)]}function $c(t,e){t.pending_buf[t.pending++]=e&255,t.pending_buf[t.pending++]=e>>>8&255}function Mr(t,e,r){t.bi_valid>Zm-r?(t.bi_buf|=e<>Zm-t.bi_valid,t.bi_valid+=r-Zm):(t.bi_buf|=e<>>=1,r<<=1;while(--e>0);return r>>>1}function NM(t){t.bi_valid===16?($c(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=t.bi_buf&255,t.bi_buf>>=8,t.bi_valid-=8)}function BM(t,e){var r=e.dyn_tree,i=e.max_code,n=e.stat_desc.static_tree,s=e.stat_desc.has_stree,a=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,l=e.stat_desc.max_length,c,u,f,d,h,p,g=0;for(d=0;d<=ha;d++)t.bl_count[d]=0;for(r[t.heap[t.heap_max]*2+1]=0,c=t.heap_max+1;cl&&(d=l,g++),r[u*2+1]=d,!(u>i)&&(t.bl_count[d]++,h=0,u>=o&&(h=a[u-o]),p=r[u*2],t.opt_len+=p*(d+h),s&&(t.static_len+=p*(n[u*2+1]+h)));if(g!==0){do{for(d=l-1;t.bl_count[d]===0;)d--;t.bl_count[d]--,t.bl_count[d+1]+=2,t.bl_count[l]--,g-=2}while(g>0);for(d=l;d!==0;d--)for(u=t.bl_count[d];u!==0;)f=t.heap[--c],!(f>i)&&(r[f*2+1]!==d&&(t.opt_len+=(d-r[f*2+1])*r[f*2],r[f*2+1]=d),u--)}}function Wx(t,e,r){var i=new Array(ha+1),n=0,s,a;for(s=1;s<=ha;s++)i[s]=n=n+r[s-1]<<1;for(a=0;a<=e;a++){var o=t[a*2+1];o!==0&&(t[a*2]=zx(i[o]++,o))}}function HM(){var t,e,r,i,n,s=new Array(ha+1);for(r=0,i=0;i>=7;i8?$c(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function UM(t,e,r,i){Yx(t),i&&($c(t,r),$c(t,~r)),TM.arraySet(t.pending_buf,t.window,e,r,t.pending),t.pending+=r}function Rx(t,e,r,i){var n=e*2,s=r*2;return t[n]>1;a>=1;a--)Qm(t,r,a);c=s;do a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],Qm(t,r,1),o=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=o,r[c*2]=r[a*2]+r[o*2],t.depth[c]=(t.depth[a]>=t.depth[o]?t.depth[a]:t.depth[o])+1,r[a*2+1]=r[o*2+1]=c,t.heap[1]=c++,Qm(t,r,1);while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],BM(t,e),Wx(r,l,t.bl_count)}function Fx(t,e,r){var i,n=-1,s,a=e[1],o=0,l=7,c=4;for(a===0&&(l=138,c=3),e[(r+1)*2+1]=65535,i=0;i<=r;i++)s=a,a=e[(i+1)*2+1],!(++o=3&&t.bl_tree[Hx[e]*2+1]===0;e--);return t.opt_len+=3*(e+1)+5+5+4,e}function jM(t,e,r,i){var n;for(Mr(t,e-257,5),Mr(t,r-1,5),Mr(t,i-4,4),n=0;n>>=1)if(e&1&&t.dyn_ltree[r*2]!==0)return Tx;if(t.dyn_ltree[18]!==0||t.dyn_ltree[20]!==0||t.dyn_ltree[26]!==0)return Px;for(r=32;r0?(t.strm.data_type===RM&&(t.strm.data_type=VM(t)),eg(t,t.l_desc),eg(t,t.d_desc),a=GM(t),n=t.opt_len+3+7>>>3,s=t.static_len+3+7>>>3,s<=n&&(n=s)):n=s=r+5,r+4<=n&&e!==-1?Zx(t,e,r,i):t.strategy===PM||s===n?(Mr(t,(Dx<<1)+(i?1:0),3),$x(t,Yn,Ac)):(Mr(t,(FM<<1)+(i?1:0),3),jM(t,t.l_desc.max_code+1,t.d_desc.max_code+1,a+1),$x(t,t.dyn_ltree,t.dyn_dtree)),qx(t),i&&Yx(t)}function YM(t,e,r){return t.pending_buf[t.d_buf+t.last_lit*2]=e>>>8&255,t.pending_buf[t.d_buf+t.last_lit*2+1]=e&255,t.pending_buf[t.l_buf+t.last_lit]=r&255,t.last_lit++,e===0?t.dyn_ltree[r*2]++:(t.matches++,e--,t.dyn_ltree[(Rc[r]+Fc+1)*2]++,t.dyn_dtree[Vx(e)*2]++),t.last_lit===t.lit_bufsize-1}Bo._tr_init=zM;Bo._tr_stored_block=Zx;Bo._tr_flush_block=qM;Bo._tr_tally=YM;Bo._tr_align=WM});var sg=H((hz,Xx)=>{"use strict";m();function ZM(t,e,r,i){for(var n=t&65535|0,s=t>>>16&65535|0,a=0;r!==0;){a=r>2e3?2e3:r,r-=a;do n=n+e[i++]|0,s=s+n|0;while(--a);n%=65521,s%=65521}return n|s<<16|0}Xx.exports=ZM});var ag=H((mz,Qx)=>{"use strict";m();function KM(){for(var t,e=[],r=0;r<256;r++){t=r;for(var i=0;i<8;i++)t=t&1?3988292384^t>>>1:t>>>1;e[r]=t}return e}var XM=KM();function QM(t,e,r,i){var n=XM,s=i+r;t^=-1;for(var a=i;a>>8^n[(t^e[a])&255];return t^-1}Qx.exports=QM});var ad=H((vz,Jx)=>{"use strict";m();Jx.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}});var l1=H(wn=>{"use strict";m();var yr=qn(),_i=Kx(),i1=sg(),Cs=ag(),JM=ad(),va=0,eD=1,tD=3,$s=4,e1=5,vn=0,t1=1,yi=-2,rD=-3,og=-5,iD=-1,nD=1,od=2,sD=3,aD=4,oD=0,lD=2,fd=8,cD=9,uD=15,fD=8,dD=29,hD=256,cg=hD+1+dD,pD=30,mD=19,gD=2*cg+1,vD=15,Re=3,Ps=258,ji=Ps+Re+1,wD=32,dd=42,ug=69,ld=73,cd=91,ud=103,pa=113,Mc=666,Ot=1,Dc=2,ma=3,Go=4,bD=3;function Rs(t,e){return t.msg=JM[e],e}function r1(t){return(t<<1)-(t>4?9:0)}function Ts(t){for(var e=t.length;--e>=0;)t[e]=0}function As(t){var e=t.state,r=e.pending;r>t.avail_out&&(r=t.avail_out),r!==0&&(yr.arraySet(t.output,e.pending_buf,e.pending_out,r,t.next_out),t.next_out+=r,e.pending_out+=r,t.total_out+=r,t.avail_out-=r,e.pending-=r,e.pending===0&&(e.pending_out=0))}function Qt(t,e){_i._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,As(t.strm)}function Me(t,e){t.pending_buf[t.pending++]=e}function Ic(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=e&255}function _D(t,e,r,i){var n=t.avail_in;return n>i&&(n=i),n===0?0:(t.avail_in-=n,yr.arraySet(e,t.input,t.next_in,n,r),t.state.wrap===1?t.adler=i1(t.adler,e,n,r):t.state.wrap===2&&(t.adler=Cs(t.adler,e,n,r)),t.next_in+=n,t.total_in+=n,n)}function n1(t,e){var r=t.max_chain_length,i=t.strstart,n,s,a=t.prev_length,o=t.nice_match,l=t.strstart>t.w_size-ji?t.strstart-(t.w_size-ji):0,c=t.window,u=t.w_mask,f=t.prev,d=t.strstart+Ps,h=c[i+a-1],p=c[i+a];t.prev_length>=t.good_match&&(r>>=2),o>t.lookahead&&(o=t.lookahead);do if(n=e,!(c[n+a]!==p||c[n+a-1]!==h||c[n]!==c[i]||c[++n]!==c[i+1])){i+=2,n++;do;while(c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&c[++i]===c[++n]&&ia){if(t.match_start=e,a=s,s>=o)break;h=c[i+a-1],p=c[i+a]}}while((e=f[e&u])>l&&--r!==0);return a<=t.lookahead?a:t.lookahead}function ga(t){var e=t.w_size,r,i,n,s,a;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-ji)){yr.arraySet(t.window,t.window,e,e,0),t.match_start-=e,t.strstart-=e,t.block_start-=e,i=t.hash_size,r=i;do n=t.head[--r],t.head[r]=n>=e?n-e:0;while(--i);i=e,r=i;do n=t.prev[--r],t.prev[r]=n>=e?n-e:0;while(--i);s+=e}if(t.strm.avail_in===0)break;if(i=_D(t.strm,t.window,t.strstart+t.lookahead,s),t.lookahead+=i,t.lookahead+t.insert>=Re)for(a=t.strstart-t.insert,t.ins_h=t.window[a],t.ins_h=(t.ins_h<t.pending_buf_size-5&&(r=t.pending_buf_size-5);;){if(t.lookahead<=1){if(ga(t),t.lookahead===0&&e===va)return Ot;if(t.lookahead===0)break}t.strstart+=t.lookahead,t.lookahead=0;var i=t.block_start+r;if((t.strstart===0||t.strstart>=i)&&(t.lookahead=t.strstart-i,t.strstart=i,Qt(t,!1),t.strm.avail_out===0)||t.strstart-t.block_start>=t.w_size-ji&&(Qt(t,!1),t.strm.avail_out===0))return Ot}return t.insert=0,e===$s?(Qt(t,!0),t.strm.avail_out===0?ma:Go):(t.strstart>t.block_start&&(Qt(t,!1),t.strm.avail_out===0),Ot)}function lg(t,e){for(var r,i;;){if(t.lookahead=Re&&(t.ins_h=(t.ins_h<=Re)if(i=_i._tr_tally(t,t.strstart-t.match_start,t.match_length-Re),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=Re){t.match_length--;do t.strstart++,t.ins_h=(t.ins_h<=Re&&(t.ins_h=(t.ins_h<4096)&&(t.match_length=Re-1)),t.prev_length>=Re&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-Re,i=_i._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-Re),t.lookahead-=t.prev_length-1,t.prev_length-=2;do++t.strstart<=n&&(t.ins_h=(t.ins_h<=Re&&t.strstart>0&&(n=t.strstart-1,i=a[n],i===a[++n]&&i===a[++n]&&i===a[++n])){s=t.strstart+Ps;do;while(i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&i===a[++n]&&nt.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=Re?(r=_i._tr_tally(t,1,t.match_length-Re),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(r=_i._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),r&&(Qt(t,!1),t.strm.avail_out===0))return Ot}return t.insert=0,e===$s?(Qt(t,!0),t.strm.avail_out===0?ma:Go):t.last_lit&&(Qt(t,!1),t.strm.avail_out===0)?Ot:Dc}function ED(t,e){for(var r;;){if(t.lookahead===0&&(ga(t),t.lookahead===0)){if(e===va)return Ot;break}if(t.match_length=0,r=_i._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,r&&(Qt(t,!1),t.strm.avail_out===0))return Ot}return t.insert=0,e===$s?(Qt(t,!0),t.strm.avail_out===0?ma:Go):t.last_lit&&(Qt(t,!1),t.strm.avail_out===0)?Ot:Dc}function gn(t,e,r,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=r,this.max_chain=i,this.func=n}var Uo;Uo=[new gn(0,0,0,0,yD),new gn(4,4,8,4,lg),new gn(4,5,16,8,lg),new gn(4,6,32,32,lg),new gn(4,4,16,16,Ho),new gn(8,16,32,32,Ho),new gn(8,16,128,128,Ho),new gn(8,32,128,256,Ho),new gn(32,128,258,1024,Ho),new gn(32,258,258,4096,Ho)];function SD(t){t.window_size=2*t.w_size,Ts(t.head),t.max_lazy_match=Uo[t.level].max_lazy,t.good_match=Uo[t.level].good_length,t.nice_match=Uo[t.level].nice_length,t.max_chain_length=Uo[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=Re-1,t.match_available=0,t.ins_h=0}function kD(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=fd,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new yr.Buf16(gD*2),this.dyn_dtree=new yr.Buf16((2*pD+1)*2),this.bl_tree=new yr.Buf16((2*mD+1)*2),Ts(this.dyn_ltree),Ts(this.dyn_dtree),Ts(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new yr.Buf16(vD+1),this.heap=new yr.Buf16(2*cg+1),Ts(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new yr.Buf16(2*cg+1),Ts(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function s1(t){var e;return!t||!t.state?Rs(t,yi):(t.total_in=t.total_out=0,t.data_type=lD,e=t.state,e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?dd:pa,t.adler=e.wrap===2?0:1,e.last_flush=va,_i._tr_init(e),vn)}function a1(t){var e=s1(t);return e===vn&&SD(t.state),e}function CD(t,e){return!t||!t.state||t.state.wrap!==2?yi:(t.state.gzhead=e,vn)}function o1(t,e,r,i,n,s){if(!t)return yi;var a=1;if(e===iD&&(e=6),i<0?(a=0,i=-i):i>15&&(a=2,i-=16),n<1||n>cD||r!==fd||i<8||i>15||e<0||e>9||s<0||s>aD)return Rs(t,yi);i===8&&(i=9);var o=new kD;return t.state=o,o.strm=t,o.wrap=a,o.gzhead=null,o.w_bits=i,o.w_size=1<e1||e<0)return t?Rs(t,yi):yi;if(i=t.state,!t.output||!t.input&&t.avail_in!==0||i.status===Mc&&e!==$s)return Rs(t,t.avail_out===0?og:yi);if(i.strm=t,r=i.last_flush,i.last_flush=e,i.status===dd)if(i.wrap===2)t.adler=0,Me(i,31),Me(i,139),Me(i,8),i.gzhead?(Me(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),Me(i,i.gzhead.time&255),Me(i,i.gzhead.time>>8&255),Me(i,i.gzhead.time>>16&255),Me(i,i.gzhead.time>>24&255),Me(i,i.level===9?2:i.strategy>=od||i.level<2?4:0),Me(i,i.gzhead.os&255),i.gzhead.extra&&i.gzhead.extra.length&&(Me(i,i.gzhead.extra.length&255),Me(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=Cs(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=ug):(Me(i,0),Me(i,0),Me(i,0),Me(i,0),Me(i,0),Me(i,i.level===9?2:i.strategy>=od||i.level<2?4:0),Me(i,bD),i.status=pa);else{var a=fd+(i.w_bits-8<<4)<<8,o=-1;i.strategy>=od||i.level<2?o=0:i.level<6?o=1:i.level===6?o=2:o=3,a|=o<<6,i.strstart!==0&&(a|=wD),a+=31-a%31,i.status=pa,Ic(i,a),i.strstart!==0&&(Ic(i,t.adler>>>16),Ic(i,t.adler&65535)),t.adler=1}if(i.status===ug)if(i.gzhead.extra){for(n=i.pending;i.gzindex<(i.gzhead.extra.length&65535)&&!(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(t.adler=Cs(t.adler,i.pending_buf,i.pending-n,n)),As(t),n=i.pending,i.pending===i.pending_buf_size));)Me(i,i.gzhead.extra[i.gzindex]&255),i.gzindex++;i.gzhead.hcrc&&i.pending>n&&(t.adler=Cs(t.adler,i.pending_buf,i.pending-n,n)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=ld)}else i.status=ld;if(i.status===ld)if(i.gzhead.name){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(t.adler=Cs(t.adler,i.pending_buf,i.pending-n,n)),As(t),n=i.pending,i.pending===i.pending_buf_size)){s=1;break}i.gzindexn&&(t.adler=Cs(t.adler,i.pending_buf,i.pending-n,n)),s===0&&(i.gzindex=0,i.status=cd)}else i.status=cd;if(i.status===cd)if(i.gzhead.comment){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(t.adler=Cs(t.adler,i.pending_buf,i.pending-n,n)),As(t),n=i.pending,i.pending===i.pending_buf_size)){s=1;break}i.gzindexn&&(t.adler=Cs(t.adler,i.pending_buf,i.pending-n,n)),s===0&&(i.status=ud)}else i.status=ud;if(i.status===ud&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&As(t),i.pending+2<=i.pending_buf_size&&(Me(i,t.adler&255),Me(i,t.adler>>8&255),t.adler=0,i.status=pa)):i.status=pa),i.pending!==0){if(As(t),t.avail_out===0)return i.last_flush=-1,vn}else if(t.avail_in===0&&r1(e)<=r1(r)&&e!==$s)return Rs(t,og);if(i.status===Mc&&t.avail_in!==0)return Rs(t,og);if(t.avail_in!==0||i.lookahead!==0||e!==va&&i.status!==Mc){var l=i.strategy===od?ED(i,e):i.strategy===sD?xD(i,e):Uo[i.level].func(i,e);if((l===ma||l===Go)&&(i.status=Mc),l===Ot||l===ma)return t.avail_out===0&&(i.last_flush=-1),vn;if(l===Dc&&(e===eD?_i._tr_align(i):e!==e1&&(_i._tr_stored_block(i,0,0,!1),e===tD&&(Ts(i.head),i.lookahead===0&&(i.strstart=0,i.block_start=0,i.insert=0))),As(t),t.avail_out===0))return i.last_flush=-1,vn}return e!==$s?vn:i.wrap<=0?t1:(i.wrap===2?(Me(i,t.adler&255),Me(i,t.adler>>8&255),Me(i,t.adler>>16&255),Me(i,t.adler>>24&255),Me(i,t.total_in&255),Me(i,t.total_in>>8&255),Me(i,t.total_in>>16&255),Me(i,t.total_in>>24&255)):(Ic(i,t.adler>>>16),Ic(i,t.adler&65535)),As(t),i.wrap>0&&(i.wrap=-i.wrap),i.pending!==0?vn:t1)}function PD(t){var e;return!t||!t.state?yi:(e=t.state.status,e!==dd&&e!==ug&&e!==ld&&e!==cd&&e!==ud&&e!==pa&&e!==Mc?Rs(t,yi):(t.state=null,e===pa?Rs(t,rD):vn))}function RD(t,e){var r=e.length,i,n,s,a,o,l,c,u;if(!t||!t.state||(i=t.state,a=i.wrap,a===2||a===1&&i.status!==dd||i.lookahead))return yi;for(a===1&&(t.adler=i1(t.adler,e,r,0)),i.wrap=0,r>=i.w_size&&(a===0&&(Ts(i.head),i.strstart=0,i.block_start=0,i.insert=0),u=new yr.Buf8(i.w_size),yr.arraySet(u,e,r-i.w_size,i.w_size,0),e=u,r=i.w_size),o=t.avail_in,l=t.next_in,c=t.input,t.avail_in=r,t.next_in=0,t.input=e,ga(i);i.lookahead>=Re;){n=i.strstart,s=i.lookahead-(Re-1);do i.ins_h=(i.ins_h<{"use strict";m();var hd=qn(),c1=!0,u1=!0;try{String.fromCharCode.apply(null,[0])}catch(t){c1=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){u1=!1}var Oc=new hd.Buf8(256);for(Zn=0;Zn<256;Zn++)Oc[Zn]=Zn>=252?6:Zn>=248?5:Zn>=240?4:Zn>=224?3:Zn>=192?2:1;var Zn;Oc[254]=Oc[254]=1;jo.string2buf=function(t){var e,r,i,n,s,a=t.length,o=0;for(n=0;n>>6,e[s++]=128|r&63):r<65536?(e[s++]=224|r>>>12,e[s++]=128|r>>>6&63,e[s++]=128|r&63):(e[s++]=240|r>>>18,e[s++]=128|r>>>12&63,e[s++]=128|r>>>6&63,e[s++]=128|r&63);return e};function f1(t,e){if(e<65534&&(t.subarray&&u1||!t.subarray&&c1))return String.fromCharCode.apply(null,hd.shrinkBuf(t,e));for(var r="",i=0;i4){o[i++]=65533,r+=s-1;continue}for(n&=s===2?31:s===3?15:7;s>1&&r1){o[i++]=65533;continue}n<65536?o[i++]=n:(n-=65536,o[i++]=55296|n>>10&1023,o[i++]=56320|n&1023)}return f1(o,i)};jo.utf8border=function(t,e){var r;for(e=e||t.length,e>t.length&&(e=t.length),r=e-1;r>=0&&(t[r]&192)===128;)r--;return r<0||r===0?e:r+Oc[t[r]]>e?r:e}});var dg=H((Ez,d1)=>{"use strict";m();function $D(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}d1.exports=$D});var g1=H(Bc=>{"use strict";m();var Lc=l1(),Nc=qn(),pg=fg(),mg=ad(),FD=dg(),m1=Object.prototype.toString,ID=0,hg=4,Vo=0,h1=1,p1=2,MD=-1,DD=0,OD=8;function wa(t){if(!(this instanceof wa))return new wa(t);this.options=Nc.assign({level:MD,method:OD,chunkSize:16384,windowBits:15,memLevel:8,strategy:DD,to:""},t||{});var e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new FD,this.strm.avail_out=0;var r=Lc.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(r!==Vo)throw new Error(mg[r]);if(e.header&&Lc.deflateSetHeader(this.strm,e.header),e.dictionary){var i;if(typeof e.dictionary=="string"?i=pg.string2buf(e.dictionary):m1.call(e.dictionary)==="[object ArrayBuffer]"?i=new Uint8Array(e.dictionary):i=e.dictionary,r=Lc.deflateSetDictionary(this.strm,i),r!==Vo)throw new Error(mg[r]);this._dict_set=!0}}wa.prototype.push=function(t,e){var r=this.strm,i=this.options.chunkSize,n,s;if(this.ended)return!1;s=e===~~e?e:e===!0?hg:ID,typeof t=="string"?r.input=pg.string2buf(t):m1.call(t)==="[object ArrayBuffer]"?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;do{if(r.avail_out===0&&(r.output=new Nc.Buf8(i),r.next_out=0,r.avail_out=i),n=Lc.deflate(r,s),n!==h1&&n!==Vo)return this.onEnd(n),this.ended=!0,!1;(r.avail_out===0||r.avail_in===0&&(s===hg||s===p1))&&(this.options.to==="string"?this.onData(pg.buf2binstring(Nc.shrinkBuf(r.output,r.next_out))):this.onData(Nc.shrinkBuf(r.output,r.next_out)))}while((r.avail_in>0||r.avail_out===0)&&n!==h1);return s===hg?(n=Lc.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===Vo):(s===p1&&(this.onEnd(Vo),r.avail_out=0),!0)};wa.prototype.onData=function(t){this.chunks.push(t)};wa.prototype.onEnd=function(t){t===Vo&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Nc.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function gg(t,e){var r=new wa(e);if(r.push(t,!0),r.err)throw r.msg||mg[r.err];return r.result}function LD(t,e){return e=e||{},e.raw=!0,gg(t,e)}function ND(t,e){return e=e||{},e.gzip=!0,gg(t,e)}Bc.Deflate=wa;Bc.deflate=gg;Bc.deflateRaw=LD;Bc.gzip=ND});var w1=H((Az,v1)=>{"use strict";m();var pd=30,BD=12;v1.exports=function(e,r){var i,n,s,a,o,l,c,u,f,d,h,p,g,v,b,_,C,x,E,A,w,S,y,P,T;i=e.state,n=e.next_in,P=e.input,s=n+(e.avail_in-5),a=e.next_out,T=e.output,o=a-(r-e.avail_out),l=a+(e.avail_out-257),c=i.dmax,u=i.wsize,f=i.whave,d=i.wnext,h=i.window,p=i.hold,g=i.bits,v=i.lencode,b=i.distcode,_=(1<>>24,p>>>=E,g-=E,E=x>>>16&255,E===0)T[a++]=x&65535;else if(E&16){A=x&65535,E&=15,E&&(g>>=E,g-=E),g<15&&(p+=P[n++]<>>24,p>>>=E,g-=E,E=x>>>16&255,E&16){if(w=x&65535,E&=15,gc){e.msg="invalid distance too far back",i.mode=pd;break e}if(p>>>=E,g-=E,E=a-o,w>E){if(E=w-E,E>f&&i.sane){e.msg="invalid distance too far back",i.mode=pd;break e}if(S=0,y=h,d===0){if(S+=u-E,E2;)T[a++]=y[S++],T[a++]=y[S++],T[a++]=y[S++],A-=3;A&&(T[a++]=y[S++],A>1&&(T[a++]=y[S++]))}else{S=a-w;do T[a++]=T[S++],T[a++]=T[S++],T[a++]=T[S++],A-=3;while(A>2);A&&(T[a++]=T[S++],A>1&&(T[a++]=T[S++]))}}else if((E&64)===0){x=b[(x&65535)+(p&(1<>3,n-=A,g-=A<<3,p&=(1<{"use strict";m();var b1=qn(),zo=15,_1=852,y1=592,x1=0,vg=1,E1=2,HD=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],UD=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],GD=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],jD=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];S1.exports=function(e,r,i,n,s,a,o,l){var c=l.bits,u=0,f=0,d=0,h=0,p=0,g=0,v=0,b=0,_=0,C=0,x,E,A,w,S,y=null,P=0,T,I=new b1.Buf16(zo+1),M=new b1.Buf16(zo+1),B=null,re=0,Ae,K,Q;for(u=0;u<=zo;u++)I[u]=0;for(f=0;f=1&&I[h]===0;h--);if(p>h&&(p=h),h===0)return s[a++]=1<<24|64<<16|0,s[a++]=1<<24|64<<16|0,l.bits=1,0;for(d=1;d0&&(e===x1||h!==1))return-1;for(M[1]=0,u=1;u_1||e===E1&&_>y1)return 1;for(;;){Ae=u-v,o[f]T?(K=B[re+o[f]],Q=y[P+o[f]]):(K=96,Q=0),x=1<>v)+E]=Ae<<24|K<<16|Q|0;while(E!==0);for(x=1<>=1;if(x!==0?(C&=x-1,C+=x):C=0,f++,--I[u]===0){if(u===h)break;u=r[i+o[f]]}if(u>p&&(C&w)!==A){for(v===0&&(v=p),S+=d,g=u-v,b=1<_1||e===E1&&_>y1)return 1;A=C&w,s[A]=p<<24|g<<16|S-a|0}}return C!==0&&(s[S+C]=u-v<<24|64<<16|0),l.bits=p,0}});var aE=H(Vi=>{"use strict";m();var ii=qn(),Eg=sg(),bn=ag(),VD=w1(),Hc=k1(),zD=0,X1=1,Q1=2,C1=4,WD=5,md=6,ba=0,qD=1,YD=2,xi=-2,J1=-3,Sg=-4,ZD=-5,A1=8,eE=1,T1=2,P1=3,R1=4,$1=5,F1=6,I1=7,M1=8,D1=9,O1=10,wd=11,Kn=12,wg=13,L1=14,bg=15,N1=16,B1=17,H1=18,U1=19,gd=20,vd=21,G1=22,j1=23,V1=24,z1=25,W1=26,_g=27,q1=28,Y1=29,lt=30,kg=31,KD=32,XD=852,QD=592,JD=15,eO=JD;function Z1(t){return(t>>>24&255)+(t>>>8&65280)+((t&65280)<<8)+((t&255)<<24)}function tO(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new ii.Buf16(320),this.work=new ii.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function tE(t){var e;return!t||!t.state?xi:(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=e.wrap&1),e.mode=eE,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new ii.Buf32(XD),e.distcode=e.distdyn=new ii.Buf32(QD),e.sane=1,e.back=-1,ba)}function rE(t){var e;return!t||!t.state?xi:(e=t.state,e.wsize=0,e.whave=0,e.wnext=0,tE(t))}function iE(t,e){var r,i;return!t||!t.state||(i=t.state,e<0?(r=0,e=-e):(r=(e>>4)+1,e<48&&(e&=15)),e&&(e<8||e>15))?xi:(i.window!==null&&i.wbits!==e&&(i.window=null),i.wrap=r,i.wbits=e,rE(t))}function nE(t,e){var r,i;return t?(i=new tO,t.state=i,i.window=null,r=iE(t,e),r!==ba&&(t.state=null),r):xi}function rO(t){return nE(t,eO)}var K1=!0,yg,xg;function iO(t){if(K1){var e;for(yg=new ii.Buf32(512),xg=new ii.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(Hc(X1,t.lens,0,288,yg,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;Hc(Q1,t.lens,0,32,xg,0,t.work,{bits:5}),K1=!1}t.lencode=yg,t.lenbits=9,t.distcode=xg,t.distbits=5}function sE(t,e,r,i){var n,s=t.state;return s.window===null&&(s.wsize=1<=s.wsize?(ii.arraySet(s.window,e,r-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):(n=s.wsize-s.wnext,n>i&&(n=i),ii.arraySet(s.window,e,r-i,n,s.wnext),i-=n,i?(ii.arraySet(s.window,e,r-i,i,0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whave>>8&255,r.check=bn(r.check,y,2,0),c=0,u=0,r.mode=T1;break}if(r.flags=0,r.head&&(r.head.done=!1),!(r.wrap&1)||(((c&255)<<8)+(c>>8))%31){t.msg="incorrect header check",r.mode=lt;break}if((c&15)!==A1){t.msg="unknown compression method",r.mode=lt;break}if(c>>>=4,u-=4,w=(c&15)+8,r.wbits===0)r.wbits=w;else if(w>r.wbits){t.msg="invalid window size",r.mode=lt;break}r.dmax=1<>8&1),r.flags&512&&(y[0]=c&255,y[1]=c>>>8&255,r.check=bn(r.check,y,2,0)),c=0,u=0,r.mode=P1;case P1:for(;u<32;){if(o===0)break e;o--,c+=i[s++]<>>8&255,y[2]=c>>>16&255,y[3]=c>>>24&255,r.check=bn(r.check,y,4,0)),c=0,u=0,r.mode=R1;case R1:for(;u<16;){if(o===0)break e;o--,c+=i[s++]<>8),r.flags&512&&(y[0]=c&255,y[1]=c>>>8&255,r.check=bn(r.check,y,2,0)),c=0,u=0,r.mode=$1;case $1:if(r.flags&1024){for(;u<16;){if(o===0)break e;o--,c+=i[s++]<>>8&255,r.check=bn(r.check,y,2,0)),c=0,u=0}else r.head&&(r.head.extra=null);r.mode=F1;case F1:if(r.flags&1024&&(h=r.length,h>o&&(h=o),h&&(r.head&&(w=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),ii.arraySet(r.head.extra,i,s,h,w)),r.flags&512&&(r.check=bn(r.check,i,h,s)),o-=h,s+=h,r.length-=h),r.length))break e;r.length=0,r.mode=I1;case I1:if(r.flags&2048){if(o===0)break e;h=0;do w=i[s+h++],r.head&&w&&r.length<65536&&(r.head.name+=String.fromCharCode(w));while(w&&h>9&1,r.head.done=!0),t.adler=r.check=0,r.mode=Kn;break;case O1:for(;u<32;){if(o===0)break e;o--,c+=i[s++]<>>=u&7,u-=u&7,r.mode=_g;break}for(;u<3;){if(o===0)break e;o--,c+=i[s++]<>>=1,u-=1,c&3){case 0:r.mode=L1;break;case 1:if(iO(r),r.mode=gd,e===md){c>>>=2,u-=2;break e}break;case 2:r.mode=B1;break;case 3:t.msg="invalid block type",r.mode=lt}c>>>=2,u-=2;break;case L1:for(c>>>=u&7,u-=u&7;u<32;){if(o===0)break e;o--,c+=i[s++]<>>16^65535)){t.msg="invalid stored block lengths",r.mode=lt;break}if(r.length=c&65535,c=0,u=0,r.mode=bg,e===md)break e;case bg:r.mode=N1;case N1:if(h=r.length,h){if(h>o&&(h=o),h>l&&(h=l),h===0)break e;ii.arraySet(n,i,s,h,a),o-=h,s+=h,l-=h,a+=h,r.length-=h;break}r.mode=Kn;break;case B1:for(;u<14;){if(o===0)break e;o--,c+=i[s++]<>>=5,u-=5,r.ndist=(c&31)+1,c>>>=5,u-=5,r.ncode=(c&15)+4,c>>>=4,u-=4,r.nlen>286||r.ndist>30){t.msg="too many length or distance symbols",r.mode=lt;break}r.have=0,r.mode=H1;case H1:for(;r.have>>=3,u-=3}for(;r.have<19;)r.lens[I[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,P={bits:r.lenbits},S=Hc(zD,r.lens,0,19,r.lencode,0,r.work,P),r.lenbits=P.bits,S){t.msg="invalid code lengths set",r.mode=lt;break}r.have=0,r.mode=U1;case U1:for(;r.have>>24,_=v>>>16&255,C=v&65535,!(b<=u);){if(o===0)break e;o--,c+=i[s++]<>>=b,u-=b,r.lens[r.have++]=C;else{if(C===16){for(T=b+2;u>>=b,u-=b,r.have===0){t.msg="invalid bit length repeat",r.mode=lt;break}w=r.lens[r.have-1],h=3+(c&3),c>>>=2,u-=2}else if(C===17){for(T=b+3;u>>=b,u-=b,w=0,h=3+(c&7),c>>>=3,u-=3}else{for(T=b+7;u>>=b,u-=b,w=0,h=11+(c&127),c>>>=7,u-=7}if(r.have+h>r.nlen+r.ndist){t.msg="invalid bit length repeat",r.mode=lt;break}for(;h--;)r.lens[r.have++]=w}}if(r.mode===lt)break;if(r.lens[256]===0){t.msg="invalid code -- missing end-of-block",r.mode=lt;break}if(r.lenbits=9,P={bits:r.lenbits},S=Hc(X1,r.lens,0,r.nlen,r.lencode,0,r.work,P),r.lenbits=P.bits,S){t.msg="invalid literal/lengths set",r.mode=lt;break}if(r.distbits=6,r.distcode=r.distdyn,P={bits:r.distbits},S=Hc(Q1,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,P),r.distbits=P.bits,S){t.msg="invalid distances set",r.mode=lt;break}if(r.mode=gd,e===md)break e;case gd:r.mode=vd;case vd:if(o>=6&&l>=258){t.next_out=a,t.avail_out=l,t.next_in=s,t.avail_in=o,r.hold=c,r.bits=u,VD(t,d),a=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,c=r.hold,u=r.bits,r.mode===Kn&&(r.back=-1);break}for(r.back=0;v=r.lencode[c&(1<>>24,_=v>>>16&255,C=v&65535,!(b<=u);){if(o===0)break e;o--,c+=i[s++]<>x)],b=v>>>24,_=v>>>16&255,C=v&65535,!(x+b<=u);){if(o===0)break e;o--,c+=i[s++]<>>=x,u-=x,r.back+=x}if(c>>>=b,u-=b,r.back+=b,r.length=C,_===0){r.mode=W1;break}if(_&32){r.back=-1,r.mode=Kn;break}if(_&64){t.msg="invalid literal/length code",r.mode=lt;break}r.extra=_&15,r.mode=G1;case G1:if(r.extra){for(T=r.extra;u>>=r.extra,u-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=j1;case j1:for(;v=r.distcode[c&(1<>>24,_=v>>>16&255,C=v&65535,!(b<=u);){if(o===0)break e;o--,c+=i[s++]<>x)],b=v>>>24,_=v>>>16&255,C=v&65535,!(x+b<=u);){if(o===0)break e;o--,c+=i[s++]<>>=x,u-=x,r.back+=x}if(c>>>=b,u-=b,r.back+=b,_&64){t.msg="invalid distance code",r.mode=lt;break}r.offset=C,r.extra=_&15,r.mode=V1;case V1:if(r.extra){for(T=r.extra;u>>=r.extra,u-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){t.msg="invalid distance too far back",r.mode=lt;break}r.mode=z1;case z1:if(l===0)break e;if(h=d-l,r.offset>h){if(h=r.offset-h,h>r.whave&&r.sane){t.msg="invalid distance too far back",r.mode=lt;break}h>r.wnext?(h-=r.wnext,p=r.wsize-h):p=r.wnext-h,h>r.length&&(h=r.length),g=r.window}else g=n,p=a-r.offset,h=r.length;h>l&&(h=l),l-=h,r.length-=h;do n[a++]=g[p++];while(--h);r.length===0&&(r.mode=vd);break;case W1:if(l===0)break e;n[a++]=r.length,l--,r.mode=vd;break;case _g:if(r.wrap){for(;u<32;){if(o===0)break e;o--,c|=i[s++]<{"use strict";m();oE.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}});var cE=H((Dz,lE)=>{"use strict";m();function lO(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}lE.exports=lO});var fE=H(Gc=>{"use strict";m();var Wo=aE(),Uc=qn(),bd=fg(),xt=Cg(),Ag=ad(),cO=dg(),uO=cE(),uE=Object.prototype.toString;function _a(t){if(!(this instanceof _a))return new _a(t);this.options=Uc.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),e.windowBits>=0&&e.windowBits<16&&!(t&&t.windowBits)&&(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(e.windowBits&15)===0&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new cO,this.strm.avail_out=0;var r=Wo.inflateInit2(this.strm,e.windowBits);if(r!==xt.Z_OK)throw new Error(Ag[r]);if(this.header=new uO,Wo.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=bd.string2buf(e.dictionary):uE.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(r=Wo.inflateSetDictionary(this.strm,e.dictionary),r!==xt.Z_OK)))throw new Error(Ag[r])}_a.prototype.push=function(t,e){var r=this.strm,i=this.options.chunkSize,n=this.options.dictionary,s,a,o,l,c,u=!1;if(this.ended)return!1;a=e===~~e?e:e===!0?xt.Z_FINISH:xt.Z_NO_FLUSH,typeof t=="string"?r.input=bd.binstring2buf(t):uE.call(t)==="[object ArrayBuffer]"?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;do{if(r.avail_out===0&&(r.output=new Uc.Buf8(i),r.next_out=0,r.avail_out=i),s=Wo.inflate(r,xt.Z_NO_FLUSH),s===xt.Z_NEED_DICT&&n&&(s=Wo.inflateSetDictionary(this.strm,n)),s===xt.Z_BUF_ERROR&&u===!0&&(s=xt.Z_OK,u=!1),s!==xt.Z_STREAM_END&&s!==xt.Z_OK)return this.onEnd(s),this.ended=!0,!1;r.next_out&&(r.avail_out===0||s===xt.Z_STREAM_END||r.avail_in===0&&(a===xt.Z_FINISH||a===xt.Z_SYNC_FLUSH))&&(this.options.to==="string"?(o=bd.utf8border(r.output,r.next_out),l=r.next_out-o,c=bd.buf2string(r.output,o),r.next_out=l,r.avail_out=i-l,l&&Uc.arraySet(r.output,r.output,o,l,0),this.onData(c)):this.onData(Uc.shrinkBuf(r.output,r.next_out))),r.avail_in===0&&r.avail_out===0&&(u=!0)}while((r.avail_in>0||r.avail_out===0)&&s!==xt.Z_STREAM_END);return s===xt.Z_STREAM_END&&(a=xt.Z_FINISH),a===xt.Z_FINISH?(s=Wo.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===xt.Z_OK):(a===xt.Z_SYNC_FLUSH&&(this.onEnd(xt.Z_OK),r.avail_out=0),!0)};_a.prototype.onData=function(t){this.chunks.push(t)};_a.prototype.onEnd=function(t){t===xt.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Uc.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function Tg(t,e){var r=new _a(e);if(r.push(t,!0),r.err)throw r.msg||Ag[r.err];return r.result}function fO(t,e){return e=e||{},e.raw=!0,Tg(t,e)}Gc.Inflate=_a;Gc.inflate=Tg;Gc.inflateRaw=fO;Gc.ungzip=Tg});var pE=H((Bz,hE)=>{"use strict";m();var dO=qn().assign,hO=g1(),pO=fE(),mO=Cg(),dE={};dO(dE,hO,pO,mO);hE.exports=dE});var vE=H((Uz,gE)=>{"use strict";m();var mE=(t,e)=>function(...r){let i=e.promiseModule;return new i((n,s)=>{e.multiArgs?r.push((...a)=>{e.errorFirst?a[0]?s(a):(a.shift(),n(a)):n(a)}):e.errorFirst?r.push((a,o)=>{a?s(a):n(o)}):r.push(n),t.apply(this,r)})};gE.exports=(t,e)=>{e=Object.assign({exclude:[/.+(Sync|Stream)$/],errorFirst:!0,promiseModule:Promise},e);let r=typeof t;if(!(t!==null&&(r==="object"||r==="function")))throw new TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${t===null?"null":r}\``);let i=s=>{let a=o=>typeof o=="string"?s===o:o.test(s);return e.include?e.include.some(a):!e.exclude.some(a)},n;r==="function"?n=function(...s){return e.excludeMain?t(...s):mE(t,e).apply(this,s)}:n=Object.create(Object.getPrototypeOf(t));for(let s in t){let a=t[s];n[s]=typeof a=="function"&&i(s)?mE(a,e):a}return n}});var CE=H((jz,kE)=>{m();function wE(t){return Array.isArray(t)?t:[t]}var $g="",bE=" ",Pg="\\",gO=/^\s+$/,vO=/(?:[^\\]|^)\\$/,wO=/^\\!/,bO=/^\\#/,_O=/\r?\n/g,yO=/^\.*\/|^\.+$/,Rg="/",xE="node-ignore";typeof Symbol!="undefined"&&(xE=Symbol.for("node-ignore"));var _E=xE,xO=(t,e,r)=>Object.defineProperty(t,e,{value:r}),EO=/([0-z])-([0-z])/g,EE=()=>!1,SO=t=>t.replace(EO,(e,r,i)=>r.charCodeAt(0)<=i.charCodeAt(0)?e:$g),kO=t=>{let{length:e}=t;return t.slice(0,e-e%2)},CO=[[/^\uFEFF/,()=>$g],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,r)=>e+(r.indexOf("\\")===0?bE:$g)],[/(\\+?)\s/g,(t,e)=>{let{length:r}=e;return e.slice(0,r-r%2)+bE}],[/[\\$.|*+(){^]/g,t=>`\\${t}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(t,e,r)=>e+6{let i=r.replace(/\\\*/g,"[^\\/]*");return e+i}],[/\\\\\\(?=[$.|*+(){^])/g,()=>Pg],[/\\\\/g,()=>Pg],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,r,i,n)=>e===Pg?`\\[${r}${kO(i)}${n}`:n==="]"&&i.length%2===0?`[${SO(r)}${i}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(t,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],yE=Object.create(null),AO=(t,e)=>{let r=yE[t];return r||(r=CO.reduce((i,[n,s])=>i.replace(n,s.bind(t)),t),yE[t]=r),e?new RegExp(r,"i"):new RegExp(r)},Mg=t=>typeof t=="string",TO=t=>t&&Mg(t)&&!gO.test(t)&&!vO.test(t)&&t.indexOf("#")!==0,PO=t=>t.split(_O),Fg=class{constructor(e,r,i,n){this.origin=e,this.pattern=r,this.negative=i,this.regex=n}},RO=(t,e)=>{let r=t,i=!1;t.indexOf("!")===0&&(i=!0,t=t.substr(1)),t=t.replace(wO,"!").replace(bO,"#");let n=AO(t,e);return new Fg(r,t,i,n)},$O=(t,e)=>{throw new e(t)},Xn=(t,e,r)=>Mg(t)?t?Xn.isNotRelative(t)?r(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:r("path must not be empty",TypeError):r(`path must be a string, but got \`${e}\``,TypeError),SE=t=>yO.test(t);Xn.isNotRelative=SE;Xn.convert=t=>t;var Ig=class{constructor({ignorecase:e=!0,ignoreCase:r=e,allowRelativePaths:i=!1}={}){xO(this,_E,!0),this._rules=[],this._ignoreCase=r,this._allowRelativePaths=i,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[_E]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if(TO(e)){let r=RO(e,this._ignoreCase);this._added=!0,this._rules.push(r)}}add(e){return this._added=!1,wE(Mg(e)?PO(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,r){let i=!1,n=!1;return this._rules.forEach(s=>{let{negative:a}=s;if(n===a&&i!==n||a&&!i&&!n&&!r)return;s.regex.test(e)&&(i=!a,n=a)}),{ignored:i,unignored:n}}_test(e,r,i,n){let s=e&&Xn.convert(e);return Xn(s,e,this._allowRelativePaths?EE:$O),this._t(s,r,i,n)}_t(e,r,i,n){if(e in r)return r[e];if(n||(n=e.split(Rg)),n.pop(),!n.length)return r[e]=this._testOne(e,i);let s=this._t(n.join(Rg)+Rg,r,i,n);return r[e]=s.ignored?s:this._testOne(e,i)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return wE(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},_d=t=>new Ig(t),FO=t=>Xn(t&&Xn.convert(t),t,EE);_d.isPathValid=FO;_d.default=_d;kE.exports=_d;if(typeof process!="undefined"&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform==="win32")){let t=r=>/^\\\\\?\\/.test(r)||/["<>|\u0000-\u001F]+/u.test(r)?r:r.replace(/\\/g,"/");Xn.convert=t;let e=/^[a-z]:\//i;Xn.isNotRelative=r=>e.test(r)||SE(r)}});var TE=H((zz,AE)=>{"use strict";m();function IO(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _n(t,e,r){return e=e instanceof RegExp?e:new RegExp(IO(e),"g"),t.replace(e,r)}var MO={clean:function(e){if(typeof e!="string")throw new Error("Expected a string, received: "+e);return e=_n(e,"./","/"),e=_n(e,"..","."),e=_n(e," ","-"),e=_n(e,/^[~^:?*\\\-]/g,""),e=_n(e,/[~^:?*\\]/g,"-"),e=_n(e,/[~^:?*\\\-]$/g,""),e=_n(e,"@{","-"),e=_n(e,/\.$/g,""),e=_n(e,/\/$/g,""),e=_n(e,/\.lock$/g,""),e}};AE.exports=MO});var RE=H((qz,PE)=>{m();PE.exports=function(t,e){var r=t,i=e,n=r.length,s=i.length,a=!1,o=null,l=n+1,c=[],u=[],f=[],d="",h=-1,p=0,g=1,v,b,_=function(){n>=s&&(v=r,b=n,r=i,i=v,n=s,s=b,a=!0,l=n+1)},C=function(w,S,y){return{x:w,y:S,k:y}},x=function(w,S){return{elem:w,t:S}},E=function(w,S,y){var P,T,I;for(S>y?P=c[w-1+l]:P=c[w+1+l],I=Math.max(S,y),T=I-w;T=0;--I)for(;PT-P?(a?f[f.length]=new x(i[T],h):f[f.length]=new x(i[T],g),++y,++T):w[I].y-w[I].x=w+1;--B)y[B+l]=E(B,y[B-1+l]+1,y[B+1+l]);y[w+l]=E(w,y[w-1+l]+1,y[w+1+l])}while(y[w+l]!==s);for(o=w+2*P,T=c[w+l],I=[];T!==-1;)I[I.length]=new C(u[T].x,u[T].y,null),T=u[T].k;A(I)}}}});var IE=H((Zz,FE)=>{m();var DO=RE();function OO(t,e){var r=new DO(t,e);r.compose();for(var i=r.getses(),n,s,a=t.length-1,o=e.length-1,l=i.length-1;l>=0;--l)i[l].t===r.SES_COMMON?(s?(s.chain={file1index:a,file2index:o,chain:null},s=s.chain):(n={file1index:a,file2index:o,chain:null},s=n),a--,o--):i[l].t===r.SES_DELETE?a--:i[l].t===r.SES_ADD&&o--;var c={file1index:-1,file2index:-1,chain:null};return s?(s.chain=c,n):c}function $E(t,e){for(var r=[],i=t.length,n=e.length,s=OO(t,e);s!==null;s=s.chain){var a=i-s.file1index-1,o=n-s.file2index-1;i=s.file1index,n=s.file2index,(a||o)&&r.push({file1:[i+1,a],file2:[n+1,o]})}return r.reverse(),r}function LO(t,e,r){var i,n=$E(e,t),s=$E(e,r),a=[];function o(M,B){a.push([M.file1[0],B,M.file1[1],M.file2[0],M.file2[1]])}for(i=0;ic&&(l.push([1,c,M-c]),c=M)}for(var f=0;fg)break;g=Math.max(g,b+v[2]),f++}if(u(p),d==f)h[4]>0&&l.push([h[1],h[3],h[4]]);else{var _={0:[t.length,-1,e.length,-1],2:[r.length,-1,e.length,-1]};for(i=d;i<=f;i++){h=a[i];var C=h[1],x=_[C],E=h[0],A=E+h[2],w=h[3],S=w+h[4];x[0]=Math.min(w,x[0]),x[1]=Math.max(S,x[1]),x[2]=Math.min(E,x[2]),x[3]=Math.max(A,x[3])}var y=_[0][0]+(p-_[0][2]),P=_[0][1]+(g-_[0][3]),T=_[2][0]+(p-_[2][2]),I=_[2][1]+(g-_[2][3]);l.push([-1,y,P-y,p,g-p,T,I-T])}c=g}return u(e.length),l}function NO(t,e,r){var i=[],n=[t,e,r],s=LO(t,e,r),a=[];function o(){a.length&&i.push({ok:a}),a=[]}function l(h){for(var p=0;p{"use strict";m();JS.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var rk=H((A9,tk)=>{m();var gv={px:{px:1,cm:37.79527559055118,mm:3.7795275590551185,in:96,pt:1.3333333333333333,pc:16},cm:{px:.026458333333333334,cm:1,mm:.1,in:2.54,pt:.035277777777777776,pc:.42333333333333334},mm:{px:.26458333333333334,cm:10,mm:1,in:25.4,pt:.35277777777777775,pc:4.233333333333333},in:{px:.010416666666666666,cm:.39370078740157477,mm:.03937007874015748,in:1,pt:.013888888888888888,pc:.16666666666666666},pt:{px:.75,cm:28.346456692913385,mm:2.834645669291339,in:72,pt:1,pc:12},pc:{px:.0625,cm:2.3622047244094486,mm:.2362204724409449,in:6,pt:.08333333333333333,pc:1},deg:{deg:1,grad:.9,rad:180/Math.PI,turn:360},grad:{deg:1.1111111111111112,grad:1,rad:200/Math.PI,turn:400},rad:{deg:Math.PI/180,grad:Math.PI/200,rad:1,turn:Math.PI*2},turn:{deg:.002777777777777778,grad:.0025,rad:.5/Math.PI,turn:1},s:{s:1,ms:.001},ms:{s:1e3,ms:1},Hz:{Hz:1,kHz:1e3},kHz:{Hz:.001,kHz:1},dpi:{dpi:1,dpcm:.39370078740157477,dppx:.010416666666666666},dpcm:{dpi:2.54,dpcm:1,dppx:.026458333333333334},dppx:{dpi:96,dpcm:37.79527559055118,dppx:1}};tk.exports=function(t,e,r,i){if(!gv.hasOwnProperty(r))throw new Error("Cannot convert to "+r);if(!gv[r].hasOwnProperty(e))throw new Error("Cannot convert from "+e+" to "+r);var n=gv[r][e]*t;return i!==!1?(i=Math.pow(10,parseInt(i)||5),Math.round(n*i)/i):n}});var gk=H(es=>{"use strict";m();Object.defineProperty(es,"__esModule",{value:!0});es.fromRgba=cl;es.fromRgb=vv;es.fromHsla=Vd;es.fromHsl=pk;es.fromString=mk;es.default=void 0;var ik=ak(ek()),a3=ak(rk());function ak(t){return t&&t.__esModule?t:{default:t}}function o3(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function nk(t,e){for(var r=0;rt.length)&&(e=t.length);for(var r=0,i=new Array(e);r-1}function h3(t,e,r){var i=t/255,n=e/255,s=r/255,a=Math.max(i,n,s),o=Math.min(i,n,s),l=a-o,c=(a+o)/2;if(l===0)return[0,0,c*100];var u=l/(1-Math.abs(2*c-1)),f=(function(){switch(a){case i:return(n-s)/l%6;case n:return(s-i)/l+2;default:return(i-n)/l+4}})();return[f*60,u*100,c*100]}function p3(t,e,r){var i=t/60,n=e/100,s=r/100,a=(1-Math.abs(2*s-1))*n,o=a*(1-Math.abs(i%2-1)),l=s-a/2,c=(function(){return i<1?[a,o,0]:i<2?[o,a,0]:i<3?[0,a,o]:i<4?[0,o,a]:i<5?[o,0,a]:[a,0,o]})(),u=Er(c,3),f=u[0],d=u[1],h=u[2];return[(f+l)*255,(d+l)*255,(h+l)*255]}var m3=(function(){function t(e){var r=Er(e,4),i=r[0],n=r[1],s=r[2],a=r[3];o3(this,t),this.values=[Math.max(Math.min(parseInt(i,10),255),0),Math.max(Math.min(parseInt(n,10),255),0),Math.max(Math.min(parseInt(s,10),255),0),a==null?1:Math.max(Math.min(parseFloat(a),255),0)]}return l3(t,[{key:"toRgbString",value:function(){var r=Er(this.values,4),i=r[0],n=r[1],s=r[2],a=r[3];return a===1?"rgb(".concat(i,", ").concat(n,", ").concat(s,")"):"rgba(".concat(i,", ").concat(n,", ").concat(s,", ").concat(a,")")}},{key:"toHslString",value:function(){var r=this.toHslaArray(),i=Er(r,4),n=i[0],s=i[1],a=i[2],o=i[3];return o===1?"hsl(".concat(n,", ").concat(s,"%, ").concat(a,"%)"):"hsla(".concat(n,", ").concat(s,"%, ").concat(a,"%, ").concat(o,")")}},{key:"toHexString",value:function(){var r=Er(this.values,4),i=r[0],n=r[1],s=r[2],a=r[3];return i=Number(i).toString(16).padStart(2,"0"),n=Number(n).toString(16).padStart(2,"0"),s=Number(s).toString(16).padStart(2,"0"),a=a<1?parseInt(a*255,10).toString(16).padStart(2,"0"):"","#".concat(i).concat(n).concat(s).concat(a)}},{key:"toRgbaArray",value:function(){return this.values}},{key:"toHslaArray",value:function(){var r=Er(this.values,4),i=r[0],n=r[1],s=r[2],a=r[3],o=h3(i,n,s),l=Er(o,3),c=l[0],u=l[1],f=l[2];return[c,u,f,a]}}]),t})();function cl(t){var e=Er(t,4),r=e[0],i=e[1],n=e[2],s=e[3];return new m3([r,i,n,s])}function vv(t){var e=Er(t,3),r=e[0],i=e[1],n=e[2];return cl([r,i,n,1])}function Vd(t){var e=Er(t,4),r=e[0],i=e[1],n=e[2],s=e[3],a=p3(r,i,n),o=Er(a,3),l=o[0],c=o[1],u=o[2];return cl([l,c,u,s])}function pk(t){var e=Er(t,3),r=e[0],i=e[1],n=e[2];return Vd([r,i,n,1])}function g3(t){var e=ok.exec(t)||lk.exec(t),r=Er(e,5),i=r[1],n=r[2],s=r[3],a=r[4];return i=parseInt(i.length<2?i.repeat(2):i,16),n=parseInt(n.length<2?n.repeat(2):n,16),s=parseInt(s.length<2?s.repeat(2):s,16),a=a&&(parseInt(a.length<2?a.repeat(2):a,16)/255).toPrecision(1)||1,cl([i,n,s,a])}function v3(t){var e=ck.exec(t)||fk.exec(t)||uk.exec(t)||dk.exec(t),r=Er(e,5),i=r[1],n=r[2],s=r[3],a=r[4];return i=yu(i,"%")?parseInt(i,10)*255/100:parseInt(i,10),n=yu(n,"%")?parseInt(n,10)*255/100:parseInt(n,10),s=yu(s,"%")>0?parseInt(s,10)*255/100:parseInt(s,10),a=a===void 0?1:parseFloat(a)/(yu(a,"%")?100:1),cl([i,n,s,a])}function w3(t){var e=hk.exec(t),r=Er(e,6),i=r[1],n=r[2],s=r[3],a=r[4],o=r[5];return n=n||"deg",i=(0,a3.default)(parseFloat(i),n,"deg"),s=parseFloat(s),a=parseFloat(a),o=o===void 0?1:parseFloat(o)/(yu(o,"%")?100:1),Vd([i,s,a,o])}function mk(t){return ik.default[t]?vv(ik.default[t]):ok.test(t)||lk.test(t)?g3(t):ck.test(t)||fk.test(t)||uk.test(t)||dk.test(t)?v3(t):hk.test(t)?w3(t):null}var b3={fromString:mk,fromRgb:vv,fromRgba:cl,fromHsl:pk,fromHsla:Vd};es.default=b3});var Tk=H((B9,Ak)=>{m();Ak.exports=function(t,e){var r=t,i=e,n=r.length,s=i.length,a=!1,o=n+1,l=[],c=[],u,f,d=function(){n>=s&&(u=r,f=n,r=i,i=u,n=s,s=f,a=!0,o=n+1)},h=function(g,v,b,_,C){return{startX:g,startY:v,endX:b,endY:_,r:C}},p=function(g,v,b){var _,C,x,E,A;for(v>b?_=l[g-1+o]:_=l[g+1+o],A=x=Math.max(v,b),E=C=x-g;C=g+1;--E)b[E+o]=p(E,b[E-1+o]+1,b[E+1+o]);b[g+o]=p(g,b[g-1+o]+1,b[g+1+o])}while(b[g+o]!==s);for(ed=g+2*_,C=l[g+o],A=n,w=s,S=[];C!==-1;){let y=c[C];(n!=y.endX||s!=y.endY)&&S.push({file1:[a?y.endY:y.endX,a?w-y.endY:A-y.endX],file2:[a?y.endX:y.endY,a?A-y.endX:w-y.endY]}),A=y.startX,w=y.startY,C=c[C].r}return(A!=0||w!=0)&&S.push({file1:[0,a?w:A],file2:[0,a?A:w]}),S.reverse(),S}}}});var $k=H((U9,Rk)=>{m();var Pk=Tk();function x3(t,e,r){var i,n=new Pk(e,t).compose(),s=new Pk(e,r).compose(),a=[];function o(M,B){a.push([M.file1[0],B,M.file1[1],M.file2[0],M.file2[1]])}for(i=0;ic&&(l.push([1,c,M-c]),c=M)}for(var f=0;fg)break;g=Math.max(g,b+v[2]),f++}if(u(p),d==f)h[4]>0&&l.push([h[1],h[3],h[4]]);else{var _={0:[t.length,-1,e.length,-1],2:[r.length,-1,e.length,-1]};for(i=d;i<=f;i++){h=a[i];var C=h[1],x=_[C],E=h[0],A=E+h[2],w=h[3],S=w+h[4];x[0]=Math.min(w,x[0]),x[1]=Math.max(S,x[1]),x[2]=Math.min(E,x[2]),x[3]=Math.max(A,x[3])}var y=_[0][0]+(p-_[0][2]),P=_[0][1]+(g-_[0][3]),T=_[2][0]+(p-_[2][2]),I=_[2][1]+(g-_[2][3]);l.push([-1,y,P-y,p,g-p,T,I-T])}c=g}return u(e.length),l}function E3(t,e,r){var i=[],n=[t,e,r],s=x3(t,e,r),a=[];function o(){a.length&&i.push({ok:a}),a=[]}function l(h){for(var p=0;p{m();var pl=1e3,ml=pl*60,gl=ml*60,Fa=gl*24,A3=Fa*7,T3=Fa*365.25;Ik.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return P3(t);if(r==="number"&&isFinite(t))return e.long?$3(t):R3(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function P3(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var r=parseFloat(e[1]),i=(e[2]||"ms").toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return r*T3;case"weeks":case"week":case"w":return r*A3;case"days":case"day":case"d":return r*Fa;case"hours":case"hour":case"hrs":case"hr":case"h":return r*gl;case"minutes":case"minute":case"mins":case"min":case"m":return r*ml;case"seconds":case"second":case"secs":case"sec":case"s":return r*pl;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function R3(t){var e=Math.abs(t);return e>=Fa?Math.round(t/Fa)+"d":e>=gl?Math.round(t/gl)+"h":e>=ml?Math.round(t/ml)+"m":e>=pl?Math.round(t/pl)+"s":t+"ms"}function $3(t){var e=Math.abs(t);return e>=Fa?Kd(t,e,Fa,"day"):e>=gl?Kd(t,e,gl,"hour"):e>=ml?Kd(t,e,ml,"minute"):e>=pl?Kd(t,e,pl,"second"):t+" ms"}function Kd(t,e,r,i){var n=e>=r*1.5;return Math.round(t/r)+" "+i+(n?"s":"")}});var Ok=H((eW,Dk)=>{m();function F3(t){r.debug=r,r.default=r,r.coerce=l,r.disable=a,r.enable=n,r.enabled=o,r.humanize=Mk(),r.destroy=c,Object.keys(t).forEach(u=>{r[u]=t[u]}),r.names=[],r.skips=[],r.formatters={};function e(u){let f=0;for(let d=0;d{if(A==="%%")return"%";x++;let S=r.formatters[w];if(typeof S=="function"){let y=v[x];A=S.call(b,y),v.splice(x,1),x--}return A}),r.formatArgs.call(b,v),(b.log||r.log).apply(b,v)}return g.namespace=u,g.useColors=r.useColors(),g.color=r.selectColor(u),g.extend=i,g.destroy=r.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==r.namespaces&&(h=r.namespaces,p=r.enabled(u)),p),set:v=>{d=v}}),typeof r.init=="function"&&r.init(g),g}function i(u,f){let d=r(this.namespace+(typeof f=="undefined"?":":f)+u);return d.log=this.log,d}function n(u){r.save(u),r.namespaces=u,r.names=[],r.skips=[];let f=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let d of f)d[0]==="-"?r.skips.push(d.slice(1)):r.names.push(d)}function s(u,f){let d=0,h=0,p=-1,g=0;for(;d"-"+f)].join(",");return r.enable(""),u}function o(u){for(let f of r.skips)if(s(u,f))return!1;for(let f of r.names)if(s(u,f))return!0;return!1}function l(u){return u instanceof Error?u.stack||u.message:u}function c(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}Dk.exports=F3});var Qd=H((Ur,Xd)=>{m();Ur.formatArgs=M3;Ur.save=D3;Ur.load=O3;Ur.useColors=I3;Ur.storage=L3();Ur.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Ur.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function I3(){if(typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function M3(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Xd.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,i=0;t[0].replace(/%[a-zA-Z%]/g,n=>{n!=="%%"&&(r++,n==="%c"&&(i=r))}),t.splice(i,0,e)}Ur.log=console.debug||console.log||(()=>{});function D3(t){try{t?Ur.storage.setItem("debug",t):Ur.storage.removeItem("debug")}catch(e){}}function O3(){let t;try{t=Ur.storage.getItem("debug")||Ur.storage.getItem("DEBUG")}catch(e){}return!t&&typeof process!="undefined"&&"env"in process&&(t=process.env.DEBUG),t}function L3(){try{return localStorage}catch(t){}}Xd.exports=Ok()(Ur);var{formatters:N3}=Xd.exports;N3.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Lk=H(si=>{"use strict";m();var B3=si&&si.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(si,"__esModule",{value:!0});var H3=require("fs"),U3=B3(Qd()),vl=U3.default("@kwsites/file-exists");function G3(t,e,r){vl("checking %s",t);try{let i=H3.statSync(t);return i.isFile()&&e?(vl("[OK] path represents a file"),!0):i.isDirectory()&&r?(vl("[OK] path represents a directory"),!0):(vl("[FAIL] path represents something other than a file or directory"),!1)}catch(i){if(i.code==="ENOENT")return vl("[FAIL] path is not accessible: %o",i),!1;throw vl("[FATAL] %o",i),i}}function j3(t,e=si.READABLE){return G3(t,(e&si.FILE)>0,(e&si.FOLDER)>0)}si.exists=j3;si.FILE=1;si.FOLDER=2;si.READABLE=si.FILE+si.FOLDER});var Nk=H(Jd=>{"use strict";m();function V3(t){for(var e in t)Jd.hasOwnProperty(e)||(Jd[e]=t[e])}Object.defineProperty(Jd,"__esModule",{value:!0});V3(Lk())});var kv=H(Ia=>{"use strict";m();Object.defineProperty(Ia,"__esModule",{value:!0});Ia.createDeferred=Ia.deferred=void 0;function Sv(){let t,e,r="pending";return{promise:new Promise((n,s)=>{t=n,e=s}),done(n){r==="pending"&&(r="resolved",t(n))},fail(n){r==="pending"&&(r="rejected",e(n))},get fulfilled(){return r!=="pending"},get status(){return r}}}Ia.deferred=Sv;Ia.createDeferred=Sv;Ia.default=Sv});var uP=H(r0=>{m();(function(t){var e=/\S/,r=/\"/g,i=/\n/g,n=/\r/g,s=/\\/g,a=/\u2028/,o=/\u2029/;t.tags={"#":1,"^":2,"<":3,$:4,"/":5,"!":6,">":7,"=":8,_v:9,"{":10,"&":11,_t:12},t.scan=function(S,y){var P=S.length,T=0,I=1,M=2,B=T,re=null,Ae=null,K="",Q=[],fe=!1,ce=0,z=0,X="{{",j="}}";function Ze(){K.length>0&&(Q.push({tag:"_t",text:new String(K)}),K="")}function $r(){for(var yt=!0,Tt=z;Tt"&&(J.indent=Q[Ke].text.toString()),Q.splice(Ke,1));else Tt||Q.push({tag:` +`});fe=!1,z=Q.length}function Ie(yt,Tt){var Ke="="+j,J=yt.indexOf(Ke,Tt),L=c(yt.substring(yt.indexOf("=",Tt)+1,J)).split(" ");return X=L[0],j=L[L.length-1],J+Ke.length-1}for(y&&(y=y.split(" "),X=y[0],j=y[1]),ce=0;ce0;){if(B=w.shift(),M&&M.tag=="<"&&!(B.tag in f))throw new Error("Illegal content in < super tag.");if(t.tags[B.tag]<=t.tags.$||h(B,P))y.push(B),B.nodes=d(w,B.tag,y,P);else if(B.tag=="/"){if(y.length===0)throw new Error("Closing tag without opener: /"+B.n);if(I=y.pop(),B.n!=I.n&&!p(B.n,I.n,P))throw new Error("Nesting error: "+I.n+" vs. "+B.n);return I.end=B.i,T}else B.tag==` +`&&(B.last=w.length==0||w[0].tag==` +`);T.push(B)}if(y.length>0)throw new Error("missing closing tag: "+y.pop().n);return T}function h(w,S){for(var y=0,P=S.length;y":x,"<":function(w,S){var y={partials:{},code:"",subs:{},inPartial:!0};t.walk(w.nodes,y);var P=S.partials[x(w,S)];P.subs=y.subs,P.partials=y.partials},$:function(w,S){var y={subs:{},code:"",partials:S.partials,prefix:w.n};t.walk(w.nodes,y),S.subs[w.n]=y.code,S.inPartial||(S.code+='t.sub("'+_(w.n)+'",c,p,i);')},"\n":function(w,S){S.code+=A('"\\n"'+(w.last?"":" + i"))},_v:function(w,S){S.code+="t.b(t.v(t."+C(w.n)+'("'+_(w.n)+'",c,p,0)));'},_t:function(w,S){S.code+=A('"'+_(w.text)+'"')},"{":E,"&":E};function E(w,S){S.code+="t.b(t.t(t."+C(w.n)+'("'+_(w.n)+'",c,p,0)));'}function A(w){return"t.b("+w+");"}t.walk=function(w,S){for(var y,P=0,T=w.length;P{m();var B4={};(function(t){t.Template=function(d,h,p,g){d=d||{},this.r=d.code||this.r,this.c=p,this.options=g||{},this.text=h||"",this.partials=d.partials||{},this.subs=d.subs||{},this.buf=""},t.Template.prototype={r:function(d,h,p){return""},v:u,t:c,render:function(h,p,g){return this.ri([h],p||{},g)},ri:function(d,h,p){return this.r(d,h,p)},ep:function(d,h){var p=this.partials[d],g=h[p.name];if(p.instance&&p.base==g)return p.instance;if(typeof g=="string"){if(!this.c)throw new Error("No compiler available.");g=this.c.compile(g,this.options)}if(!g)return null;if(this.partials[d].base=g,p.subs){h.stackText||(h.stackText={});for(key in p.subs)h.stackText[key]||(h.stackText[key]=this.activeSub!==void 0&&h.stackText[this.activeSub]?h.stackText[this.activeSub]:this.text);g=r(g,p.subs,p.partials,this.stackSubs,this.stackPartials,h.stackText)}return this.partials[d].instance=g,g},rp:function(d,h,p,g){var v=this.ep(d,p);return v?v.ri(h,p,g):""},rs:function(d,h,p){var g=d[d.length-1];if(!f(g)){p(d,h,this);return}for(var v=0;v=0;x--)if(b=h[x],v=e(d,b,C),v!==void 0){_=!0;break}return _?(!g&&typeof v=="function"&&(v=this.mv(v,h,p)),v):g?!1:""},ls:function(d,h,p,g,v,b){var _=this.options.delimiters;return this.options.delimiters=b,this.b(this.ct(c(d.call(h,v,p)),h,g)),this.options.delimiters=_,!1},ct:function(d,h,p){if(this.options.disableLambda)throw new Error("Lambda features disabled.");return this.c.compile(d,this.options).render(h,p)},b:function(d){this.buf+=d},fl:function(){var d=this.buf;return this.buf="",d},ms:function(d,h,p,g,v,b,_){var C,x=h[h.length-1],E=d.call(x);return typeof E=="function"?g?!0:(C=this.activeSub&&this.subsText&&this.subsText[this.activeSub]?this.subsText[this.activeSub]:this.text,this.ls(E,x,h,p,C.substring(v,b),_)):E},mv:function(d,h,p){var g=h[h.length-1],v=d.call(g);return typeof v=="function"?this.ct(c(v.call(g)),g,p):v},sub:function(d,h,p,g){var v=this.subs[d];v&&(this.activeSub=d,v(h,p,this,g),this.activeSub=!1)}};function e(d,h,p){var g;return h&&typeof h=="object"&&(h[d]!==void 0?g=h[d]:p&&h.get&&typeof h.get=="function"&&(g=h.get(d))),g}function r(d,h,p,g,v,b){function _(){}_.prototype=d;function C(){}C.prototype=d.subs;var x,E=new _;E.subs=new C,E.subsText={},E.buf="",g=g||{},E.stackSubs=g,E.subsText=b;for(x in h)g[x]||(g[x]=h[x]);for(x in g)E.subs[x]=g[x];v=v||{},E.stackPartials=v;for(x in p)v[x]||(v[x]=p[x]);for(x in v)E.partials[x]=v[x];return E}var i=/&/g,n=//g,a=/\'/g,o=/\"/g,l=/[&<>\"\']/;function c(d){return String(d==null?"":d)}function u(d){return d=c(d),l.test(d)?d.replace(i,"&").replace(n,"<").replace(s,">").replace(a,"'").replace(o,"""):d}var f=Array.isArray||function(d){return Object.prototype.toString.call(d)==="[object Array]"}})(typeof i0!="undefined"?i0:B4)});var n0=H((zY,dP)=>{m();var Qh=uP();Qh.Template=fP().Template;Qh.template=Qh.Template;dP.exports=Qh});var mP=H($i=>{"use strict";m();Object.defineProperty($i,"__esModule",{value:!0});$i.ColorSchemeType=$i.DiffStyleType=$i.LineMatchingType=$i.OutputFormatType=$i.LineType=void 0;var hP;(function(t){t.INSERT="insert",t.DELETE="delete",t.CONTEXT="context"})(hP||($i.LineType=hP={}));$i.OutputFormatType={LINE_BY_LINE:"line-by-line",SIDE_BY_SIDE:"side-by-side"};$i.LineMatchingType={LINES:"lines",WORDS:"words",NONE:"none"};$i.DiffStyleType={WORD:"word",CHAR:"char"};var pP;(function(t){t.AUTO="auto",t.DARK="dark",t.LIGHT="light"})(pP||($i.ColorSchemeType=pP={}))});var YG={};K$(YG,{default:()=>sm});module.exports=X$(YG);m();m();var Yo=mt(f_(),1),sv=mt(kx(),1),iS=mt(Ax(),1),Md=mt(pE(),1),Vc=mt(vE(),1),nS=mt(CE(),1),Zo=mt(TE(),1),sS=mt(IE(),1),Pe=class t extends Error{constructor(e){super(e),this.caller=""}toJSON(){return{code:this.code,data:this.data,caller:this.caller,message:this.message,stack:this.stack}}fromJSON(e){let r=new t(e.message);return r.code=e.code,r.data=e.data,r.caller=e.caller,r.stack=e.stack,r}get isIsomorphicGitError(){return!0}},zc=class t extends Pe{constructor(e){super(`Modifying the index is not possible because you have unmerged files: ${e.toString}. Fix them up in the work tree, and then use 'git add/rm as appropriate to mark resolution and make a commit.`),this.code=this.name=t.code,this.data={filepaths:e}}};zc.code="UnmergedPathsError";var he=class t extends Pe{constructor(e){super(`An internal error caused this command to fail. + +If you're using an application that depends on isomorphic-git, please report this error to that application's developers. + +If you're a developer and you believe this is a bug in isomorphic-git, please file an issue at https://github.com/isomorphic-git/isomorphic-git/issues with a minimal reproduction, version and environment details, and this error message: ${e}`),this.code=this.name=t.code,this.data={message:e}}};he.code="InternalError";var Ea=class t extends Pe{constructor(e){super(`The filepath "${e}" contains unsafe character sequences`),this.code=this.name=t.code,this.data={filepath:e}}};Ea.code="UnsafeFilepathError";var zi=class{constructor(e){this.buffer=e,this._start=0}eof(){return this._start>=this.buffer.length}tell(){return this._start}seek(e){this._start=e}slice(e){let r=this.buffer.slice(this._start,this._start+e);return this._start+=e,r}toString(e,r){let i=this.buffer.toString(e,this._start,this._start+r);return this._start+=r,i}write(e,r,i){let n=this.buffer.write(e,this._start,r,i);return this._start+=r,n}copy(e,r,i){let n=e.copy(this.buffer,this._start,r,i);return this._start+=n,n}readUInt8(){let e=this.buffer.readUInt8(this._start);return this._start+=1,e}writeUInt8(e){let r=this.buffer.writeUInt8(e,this._start);return this._start+=1,r}readUInt16BE(){let e=this.buffer.readUInt16BE(this._start);return this._start+=2,e}writeUInt16BE(e){let r=this.buffer.writeUInt16BE(e,this._start);return this._start+=2,r}readUInt32BE(){let e=this.buffer.readUInt32BE(this._start);return this._start+=4,e}writeUInt32BE(e){let r=this.buffer.writeUInt32BE(e,this._start);return this._start+=4,r}};function Dd(t,e){return-(te)}function aS(t,e){return Dd(t.path,e.path)}function oS(t){let e=t>0?t>>12:0;e!==4&&e!==8&&e!==10&&e!==14&&(e=8);let r=t&511;return r&73?r=493:r=420,e!==8&&(r=0),(e<<12)+r}var yn=2**32;function ME(t,e,r,i){if(t!==void 0&&e!==void 0)return[t,e];r===void 0&&(r=i.valueOf());let n=Math.floor(r/1e3),s=(r-n*1e3)*1e6;return[n,s]}function Ko(t){let[e,r]=ME(t.ctimeSeconds,t.ctimeNanoseconds,t.ctimeMs,t.ctime),[i,n]=ME(t.mtimeSeconds,t.mtimeNanoseconds,t.mtimeMs,t.mtime);return{ctimeSeconds:e%yn,ctimeNanoseconds:r%yn,mtimeSeconds:i%yn,mtimeNanoseconds:n%yn,dev:t.dev%yn,ino:t.ino%yn,mode:oS(t.mode%yn),uid:t.uid%yn,gid:t.gid%yn,size:t.size>-1?t.size%yn:0}}function BO(t){let e="";for(let r of new Uint8Array(t))r<16&&(e+="0"),e+=r.toString(16);return e}var Dg=null;async function En(t){return Dg===null&&(Dg=await UO()),Dg?lS(t):HO(t)}function HO(t){return new sv.default().update(t).digest("hex")}async function lS(t){let e=await crypto.subtle.digest("SHA-1",t);return BO(e)}async function UO(){try{return await lS(new Uint8Array([]))==="da39a3ee5e6b4b0d3255bfef95601890afd80709"}catch(t){}return!1}function GO(t){return{assumeValid:!!(t&32768),extended:!!(t&16384),stage:(t&12288)>>12,nameLength:t&4095}}function jO(t){let e=t.flags;return e.extended=!1,e.nameLength=Math.min(k.from(t.path).length,4095),(e.assumeValid?32768:0)+(e.extended?16384:0)+((e.stage&3)<<12)+(e.nameLength&4095)}var qg=class t{constructor(e,r){this._dirty=!1,this._unmergedPaths=r||new Set,this._entries=e||new Map}_addEntry(e){if(e.flags.stage===0)e.stages=[e],this._entries.set(e.path,e),this._unmergedPaths.delete(e.path);else{let r=this._entries.get(e.path);r||(this._entries.set(e.path,e),r=e),r.stages[e.flags.stage]=e,this._unmergedPaths.add(e.path)}}static async from(e){if(k.isBuffer(e))return t.fromBuffer(e);if(e===null)return new t(null);throw new he("invalid type passed to GitIndex.from")}static async fromBuffer(e){if(e.length===0)throw new he("Index file is empty (.git/index)");let r=new t,i=new zi(e),n=i.toString("utf8",4);if(n!=="DIRC")throw new he(`Invalid dircache magic file number: ${n}`);let s=await En(e.slice(0,-20)),a=e.slice(-20).toString("hex");if(a!==s)throw new he(`Invalid checksum in GitIndex buffer: expected ${a} but saw ${s}`);let o=i.readUInt32BE();if(o!==2)throw new he(`Unsupported dircache version: ${o}`);let l=i.readUInt32BE(),c=0;for(;!i.eof()&&ce.stages.length>1?e.stages.filter(r=>r):e)}*[Symbol.iterator](){for(let e of this.entries)yield e}insert({filepath:e,stats:r,oid:i,stage:n=0}){r||(r={ctimeSeconds:0,ctimeNanoseconds:0,mtimeSeconds:0,mtimeNanoseconds:0,dev:0,ino:0,mode:0,uid:0,gid:0,size:0}),r=Ko(r);let s=k.from(e),a={ctimeSeconds:r.ctimeSeconds,ctimeNanoseconds:r.ctimeNanoseconds,mtimeSeconds:r.mtimeSeconds,mtimeNanoseconds:r.mtimeNanoseconds,dev:r.dev,ino:r.ino,mode:r.mode||33188,uid:r.uid,gid:r.gid,size:r.size,path:e,oid:i,flags:{assumeValid:!1,extended:!1,stage:n,nameLength:s.length<4095?s.length:4095},stages:[]};this._addEntry(a),this._dirty=!0}delete({filepath:e}){if(this._entries.has(e))this._entries.delete(e);else for(let r of this._entries.keys())r.startsWith(e+"/")&&this._entries.delete(r);this._unmergedPaths.has(e)&&this._unmergedPaths.delete(e),this._dirty=!0}clear(){this._entries.clear(),this._dirty=!0}has({filepath:e}){return this._entries.has(e)}render(){return this.entries.map(e=>`${e.mode.toString(8)} ${e.oid} ${e.path}`).join(` +`)}static async _entryToBuffer(e){let r=k.from(e.path),i=Math.ceil((62+r.length+1)/8)*8,n=k.alloc(i),s=new zi(n),a=Ko(e);return s.writeUInt32BE(a.ctimeSeconds),s.writeUInt32BE(a.ctimeNanoseconds),s.writeUInt32BE(a.mtimeSeconds),s.writeUInt32BE(a.mtimeNanoseconds),s.writeUInt32BE(a.dev),s.writeUInt32BE(a.ino),s.writeUInt32BE(a.mode),s.writeUInt32BE(a.uid),s.writeUInt32BE(a.gid),s.writeUInt32BE(a.size),s.write(e.oid,20,"hex"),s.writeUInt16BE(jO(e)),s.write(e.path,r.length,"utf8"),n}async toObject(){let e=k.alloc(12),r=new zi(e);r.write("DIRC",4,"utf8"),r.writeUInt32BE(2),r.writeUInt32BE(this.entriesFlat.length);let i=[];for(let o of this.entries)if(i.push(t._entryToBuffer(o)),o.stages.length>1)for(let l of o.stages)l&&l!==o&&i.push(t._entryToBuffer(l));i=await Promise.all(i);let n=k.concat(i),s=k.concat([e,n]),a=await En(s);return k.concat([s,k.from(a,"hex")])}};function Ed(t,e,r=!0,i=!0){let n=Ko(t),s=Ko(e);return r&&n.mode!==s.mode||n.mtimeSeconds!==s.mtimeSeconds||n.ctimeSeconds!==s.ctimeSeconds||n.uid!==s.uid||n.gid!==s.gid||i&&n.ino!==s.ino||n.size!==s.size}var Og=null,Lg=Symbol("IndexCache");function VO(){return{map:new Map,stats:new Map}}async function zO(t,e,r){let[i,n]=await Promise.all([t.lstat(e),t.read(e)]),s=await qg.from(n);r.map.set(e,s),r.stats.set(e,i)}async function WO(t,e,r){let i=r.stats.get(e);if(i===void 0)return!0;if(i===null)return!1;let n=await t.lstat(e);return n===null?!1:Ed(i,n)}var gt=class{static async acquire({fs:e,gitdir:r,cache:i,allowUnmerged:n=!0},s){i[Lg]||(i[Lg]=VO());let a=`${r}/index`;Og===null&&(Og=new Yo.default({maxPending:1/0}));let o,l=[];return await Og.acquire(a,async()=>{let c=i[Lg];await WO(e,a,c)&&await zO(e,a,c);let u=c.map.get(a);if(l=u.unmergedPaths,l.length&&!n)throw new zc(l);if(o=await s(u),u._dirty){let f=await u.toObject();await e.write(a,f),c.stats.set(a,await e.lstat(a)),u._dirty=!1}}),o}};function Sd(t){let e=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return e>-1&&(t=t.slice(e+1)),t}function Sa(t){let e=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return e===-1?".":e===0?"/":t.slice(0,e)}function cS(t){let e=new Map,r=function(n){if(!e.has(n)){let s={type:"tree",fullpath:n,basename:Sd(n),metadata:{},children:[]};e.set(n,s),s.parent=r(Sa(n)),s.parent&&s.parent!==s&&s.parent.children.push(s)}return e.get(n)},i=function(n,s){if(!e.has(n)){let a={type:"blob",fullpath:n,basename:Sd(n),metadata:s,parent:r(Sa(n)),children:[]};a.parent&&a.parent.children.push(a),e.set(n,a)}return e.get(n)};r(".");for(let n of t)i(n.path,n);return e}function qO(t){switch(t){case 16384:return"tree";case 33188:return"blob";case 33261:return"blob";case 40960:return"blob";case 57344:return"commit"}throw new he(`Unexpected GitTree entry mode: ${t.toString(8)}`)}var Yg=class{constructor({fs:e,gitdir:r,cache:i}){this.treePromise=gt.acquire({fs:e,gitdir:r,cache:i},async function(s){return cS(s.entries)});let n=this;this.ConstructEntry=class{constructor(a){this._fullpath=a,this._type=!1,this._mode=!1,this._stat=!1,this._oid=!1}async type(){return n.type(this)}async mode(){return n.mode(this)}async stat(){return n.stat(this)}async content(){return n.content(this)}async oid(){return n.oid(this)}}}async readdir(e){let r=e._fullpath,n=(await this.treePromise).get(r);if(!n||n.type==="blob")return null;if(n.type!=="tree")throw new Error(`ENOTDIR: not a directory, scandir '${r}'`);let s=n.children.map(a=>a.fullpath);return s.sort(Dd),s}async type(e){return e._type===!1&&await e.stat(),e._type}async mode(e){return e._mode===!1&&await e.stat(),e._mode}async stat(e){if(e._stat===!1){let i=(await this.treePromise).get(e._fullpath);if(!i)throw new Error(`ENOENT: no such file or directory, lstat '${e._fullpath}'`);let n=i.type==="tree"?{}:Ko(i.metadata);e._type=i.type==="tree"?"tree":qO(n.mode),e._mode=n.mode,i.type==="tree"?e._stat=void 0:e._stat=n}return e._stat}async content(e){}async oid(e){if(e._oid===!1){let i=(await this.treePromise).get(e._fullpath);e._oid=i.metadata.oid}return e._oid}},Od=Symbol("GitWalkSymbol");function sl(){let t=Object.create(null);return Object.defineProperty(t,Od,{value:function({fs:e,gitdir:r,cache:i}){return new Yg({fs:e,gitdir:r,cache:i})}}),Object.freeze(t),t}var ze=class t extends Pe{constructor(e){super(`Could not find ${e}.`),this.code=this.name=t.code,this.data={what:e}}};ze.code="NotFoundError";var xr=class t extends Pe{constructor(e,r,i,n){super(`Object ${e} ${n?`at ${n}`:""}was anticipated to be a ${i} but it is a ${r}.`),this.code=this.name=t.code,this.data={oid:e,actual:r,expected:i,filepath:n}}};xr.code="ObjectTypeError";var Ms=class t extends Pe{constructor(e){super(`Expected a 40-char hex object id but saw "${e}".`),this.code=this.name=t.code,this.data={value:e}}};Ms.code="InvalidOidError";var Wc=class t extends Pe{constructor(e){super(`Could not find a fetch refspec for remote "${e}". Make sure the config file has an entry like the following: +[remote "${e}"] + fetch = +refs/heads/*:refs/remotes/origin/* +`),this.code=this.name=t.code,this.data={remote:e}}};Wc.code="NoRefspecError";var kd=class t{constructor(e){if(this.refs=new Map,this.parsedConfig=[],e){let r=null;this.parsedConfig=e.trim().split(` +`).map(i=>{if(/^\s*#/.test(i))return{line:i,comment:!0};let n=i.indexOf(" ");if(i.startsWith("^")){let s=i.slice(1);return this.refs.set(r+"^{}",s),{line:i,ref:r,peeled:s}}else{let s=i.slice(0,n);return r=i.slice(n+1),this.refs.set(r,s),{line:i,ref:r,oid:s}}})}return this}static from(e){return new t(e)}delete(e){this.parsedConfig=this.parsedConfig.filter(r=>r.ref!==e),this.refs.delete(e)}toString(){return this.parsedConfig.map(({line:e})=>e).join(` +`)+` +`}},Cd=class t{constructor({remotePath:e,localPath:r,force:i,matchPrefix:n}){Object.assign(this,{remotePath:e,localPath:r,force:i,matchPrefix:n})}static from(e){let[r,i,n,s,a]=e.match(/^(\+?)(.*?)(\*?):(.*?)(\*?)$/).slice(1),o=r==="+",l=n==="*";if(l!==(a==="*"))throw new he("Invalid refspec");return new t({remotePath:i,localPath:s,force:o,matchPrefix:l})}translate(e){if(this.matchPrefix){if(e.startsWith(this.remotePath))return this.localPath+e.replace(this.remotePath,"")}else if(e===this.remotePath)return this.localPath;return null}reverseTranslate(e){if(this.matchPrefix){if(e.startsWith(this.localPath))return this.remotePath+e.replace(this.localPath,"")}else if(e===this.localPath)return this.remotePath;return null}},Zg=class t{constructor(e=[]){this.rules=e}static from(e){let r=[];for(let i of e)r.push(Cd.from(i));return new t(r)}add(e){let r=Cd.from(e);this.rules.push(r)}translate(e){let r=[];for(let i of this.rules)for(let n of e){let s=i.translate(n);s&&r.push([n,s])}return r}translateOne(e){let r=null;for(let i of this.rules){let n=i.translate(e);n&&(r=n)}return r}localNamespaces(){return this.rules.filter(e=>e.matchPrefix).map(e=>e.localPath.replace(/\/$/,""))}};function YO(t,e){let r=t.replace(/\^\{\}$/,""),i=e.replace(/\^\{\}$/,""),n=-(ri);return n===0?t.endsWith("^{}")?1:-1:n}function ZO(t,e){let r="",i=0,n=-1,s=0,a="\0";for(let o=0;o<=t.length;++o){if(o2){let l=r.lastIndexOf("/");l===-1?(r="",i=0):(r=r.slice(0,l),i=r.length-1-r.lastIndexOf("/")),n=o,s=0;continue}else if(r.length!==0){r="",i=0,n=o,s=0;continue}}e&&(r+=r.length>0?"/..":"..",i=2)}else r.length>0?r+="/"+t.slice(n+1,o):r=t.slice(n+1,o),i=o-n-1;n=o,s=0}else a==="."&&s!==-1?++s:s=-1}return r}function KO(t){return t.length>=2&&/^[a-zA-Z]:/.test(t)?t.slice(0,2):null}function XO(t){if(!t.length)return".";t=t.replace(/\\/g,"/");let e=KO(t),r=t[0]==="/"||e!==null&&t[2]==="/",i=t.at(-1)==="/",n=e?t.slice(2):t,s=ZO(n,!r);if(!s.length){let a=e?r?e+"/":e:r?"/":".";return i&&!r?a+"/":a}return i&&(s+="/"),e?r?`${e}/${s}`:`${e}${s}`:r?`/${s}`:s}function N(...t){if(t.length===0)return".";let e;for(let r=0;r{if(typeof t=="number")return t;t=t.toLowerCase();let e=parseInt(t);return t.endsWith("k")&&(e*=1024),t.endsWith("m")&&(e*=1024*1024),t.endsWith("g")&&(e*=1024*1024*1024),e},jc=t=>{if(typeof t=="boolean")return t;if(t=t.trim().toLowerCase(),t==="true"||t==="yes"||t==="on")return!0;if(t==="false"||t==="no"||t==="off")return!1;throw Error(`Expected 'true', 'false', 'yes', 'no', 'on', or 'off', but got ${t}`)},DE={core:{filemode:jc,bare:jc,logallrefupdates:jc,symlinks:jc,ignorecase:jc,bigFileThreshold:QO}},JO=/^\[([A-Za-z0-9-.]+)(?: "(.*)")?\]$/,eL=/^[A-Za-z0-9-.]+$/,tL=/^([A-Za-z][A-Za-z-]*)(?: *= *(.*))?$/,rL=/^[A-Za-z][A-Za-z-]*$/,iL=/^(.*?)( *[#;].*)$/,nL=t=>{let e=JO.exec(t);if(e!=null){let[r,i]=e.slice(1);return[r,i]}return null},sL=t=>{let e=tL.exec(t);if(e!=null){let[r,i="true"]=e.slice(1),n=aL(i),s=oL(n);return[r,s]}return null},aL=t=>{let e=iL.exec(t);if(e==null)return t;let[r,i]=e.slice(1);return OE(r)&&OE(i)?`${r}${i}`:r},OE=t=>(t.match(/(?:^|[^\\])"/g)||[]).length%2!==0,oL=t=>t.split("").reduce((e,r,i,n)=>{let s=r==='"'&&n[i-1]!=="\\",a=r==="\\"&&n[i+1]==='"';return s||a?e:e+r},""),LE=t=>t!=null?t.toLowerCase():null,Kg=(t,e,r)=>[LE(t),e,LE(r)].filter(i=>i!=null).join("."),NE=t=>{let e=t.split("."),r=e.shift(),i=e.pop(),n=e.length?e.join("."):void 0;return{section:r,subsection:n,name:i,path:Kg(r,n,i),sectionPath:Kg(r,n,null),isSection:!!r}},lL=(t,e)=>t.reduce((r,i,n)=>e(i)?n:r,-1),Xg=class t{constructor(e){let r=null,i=null;this.parsedConfig=e?e.split(` +`).map(n=>{let s=null,a=null,o=n.trim(),l=nL(o),c=l!=null;if(c)[r,i]=l;else{let f=sL(o);f!=null&&([s,a]=f)}let u=Kg(r,i,s);return{line:n,isSection:c,section:r,subsection:i,name:s,value:a,path:u}}):[]}static from(e){return new t(e)}async get(e,r=!1){let i=NE(e).path,n=this.parsedConfig.filter(s=>s.path===i).map(({section:s,name:a,value:o})=>{let l=DE[s]&&DE[s][a];return l?l(o):o});return r?n:n.pop()}async getall(e){return this.get(e,!0)}async getSubsections(e){return this.parsedConfig.filter(r=>r.isSection&&r.section===e).map(r=>r.subsection)}async deleteSection(e,r){this.parsedConfig=this.parsedConfig.filter(i=>!(i.section===e&&i.subsection===r))}async append(e,r){return this.set(e,r,!0)}async set(e,r,i=!1){let{section:n,subsection:s,name:a,path:o,sectionPath:l,isSection:c}=NE(e),u=lL(this.parsedConfig,f=>f.path===o);if(r==null)u!==-1&&this.parsedConfig.splice(u,1);else if(u!==-1){let f=this.parsedConfig[u],d=Object.assign({},f,{name:a,value:r,modified:!0});i?this.parsedConfig.splice(u+1,0,d):this.parsedConfig[u]=d}else{let f=this.parsedConfig.findIndex(h=>h.path===l),d={section:n,subsection:s,name:a,value:r,modified:!0,path:o};if(eL.test(n)&&rL.test(a))if(f>=0)this.parsedConfig.splice(f+1,0,d);else{let h={isSection:c,section:n,subsection:s,modified:!0,path:l};this.parsedConfig.push(h,d)}}}toString(){return this.parsedConfig.map(({line:e,section:r,subsection:i,name:n,value:s,modified:a=!1})=>a?n!=null&&s!=null?typeof s=="string"&&/[#;]/.test(s)?` ${n} = "${s}"`:` ${n} = ${s}`:i!=null?`[${r} "${i}"]`:`[${r}]`:e).join(` +`)}},vt=class{static async get({fs:e,gitdir:r}){let i=await e.read(`${r}/config`,{encoding:"utf8"});return Xg.from(i)}static async save({fs:e,gitdir:r,config:i}){await e.write(`${r}/config`,i.toString(),{encoding:"utf8"})}},yd=t=>[`${t}`,`refs/${t}`,`refs/tags/${t}`,`refs/heads/${t}`,`refs/remotes/${t}`,`refs/remotes/${t}/HEAD`],cL=["config","description","index","shallow","commondir"],Ng;async function Fs(t,e){return Ng===void 0&&(Ng=new Yo.default),Ng.acquire(t,e)}var q=class t{static async updateRemoteRefs({fs:e,gitdir:r,remote:i,refs:n,symrefs:s,tags:a,refspecs:o=void 0,prune:l=!1,pruneTags:c=!1}){for(let v of n.values())if(!v.match(/[0-9a-f]{40}/))throw new Ms(v);let u=await vt.get({fs:e,gitdir:r});if(!o){if(o=await u.getall(`remote.${i}.fetch`),o.length===0)throw new Wc(i);o.unshift(`+HEAD:refs/remotes/${i}/HEAD`)}let f=Zg.from(o),d=new Map;if(c){let v=await t.listRefs({fs:e,gitdir:r,filepath:"refs/tags"});await t.deleteRefs({fs:e,gitdir:r,refs:v.map(b=>`refs/tags/${b}`)})}if(a){for(let v of n.keys())if(v.startsWith("refs/tags")&&!v.endsWith("^{}")&&!await t.exists({fs:e,gitdir:r,ref:v})){let b=n.get(v);d.set(v,b)}}let h=f.translate([...n.keys()]);for(let[v,b]of h){let _=n.get(v);d.set(b,_)}let p=f.translate([...s.keys()]);for(let[v,b]of p){let _=s.get(v),C=f.translateOne(_);C&&d.set(b,`ref: ${C}`)}let g=[];if(l){for(let v of f.localNamespaces()){let b=(await t.listRefs({fs:e,gitdir:r,filepath:v})).map(_=>`${v}/${_}`);for(let _ of b)d.has(_)||g.push(_)}g.length>0&&await t.deleteRefs({fs:e,gitdir:r,refs:g})}for(let[v,b]of d)await Fs(v,async()=>e.write(N(r,v),`${b.trim()} +`,"utf8"));return{pruned:g}}static async writeRef({fs:e,gitdir:r,ref:i,value:n}){if(!n.match(/[0-9a-f]{40}/))throw new Ms(n);await Fs(i,async()=>e.write(N(r,i),`${n.trim()} +`,"utf8"))}static async writeSymbolicRef({fs:e,gitdir:r,ref:i,value:n}){await Fs(i,async()=>e.write(N(r,i),`ref: ${n.trim()} +`,"utf8"))}static async deleteRef({fs:e,gitdir:r,ref:i}){return t.deleteRefs({fs:e,gitdir:r,refs:[i]})}static async deleteRefs({fs:e,gitdir:r,refs:i}){await Promise.all(i.map(o=>e.rm(N(r,o))));let n=await Fs("packed-refs",async()=>e.read(`${r}/packed-refs`,{encoding:"utf8"})),s=kd.from(n),a=s.refs.size;for(let o of i)s.refs.has(o)&&s.delete(o);s.refs.sizee.write(`${r}/packed-refs`,n,{encoding:"utf8"})))}static async resolve({fs:e,gitdir:r,ref:i,depth:n=void 0,visited:s=new Set}){if(n!==void 0&&(n--,n===-1))return i;if(i.startsWith("ref: "))return i=i.slice(5),t.resolve({fs:e,gitdir:r,ref:i,depth:n,visited:s});if(i.length===40&&/[0-9a-f]{40}/.test(i))return i;let a=await t.packedRefs({fs:e,gitdir:r}),o=yd(i).filter(l=>!cL.includes(l));for(let l of o){let c=await Fs(l,async()=>await e.read(`${r}/${l}`,{encoding:"utf8"})||a.get(l));if(c){if(s.has(l))throw new he(`Circular reference detected while resolving ref "${l}"`);return s.add(l),t.resolve({fs:e,gitdir:r,ref:c.trim(),depth:n,visited:s})}}throw new ze(i)}static async exists({fs:e,gitdir:r,ref:i}){try{return await t.expand({fs:e,gitdir:r,ref:i}),!0}catch(n){return!1}}static async expand({fs:e,gitdir:r,ref:i}){if(i.length===40&&/[0-9a-f]{40}/.test(i))return i;let n=await t.packedRefs({fs:e,gitdir:r}),s=yd(i);for(let a of s)if(await Fs(a,async()=>e.exists(`${r}/${a}`))||n.has(a))return a;throw new ze(i)}static async expandAgainstMap({ref:e,map:r}){let i=yd(e);for(let n of i)if(await r.has(n))return n;throw new ze(e)}static resolveAgainstMap({ref:e,fullref:r=e,depth:i=void 0,map:n}){if(i!==void 0&&(i--,i===-1))return{fullref:r,oid:e};if(e.startsWith("ref: "))return e=e.slice(5),t.resolveAgainstMap({ref:e,fullref:r,depth:i,map:n});if(e.length===40&&/[0-9a-f]{40}/.test(e))return{fullref:r,oid:e};let s=yd(e);for(let a of s){let o=n.get(a);if(o)return t.resolveAgainstMap({ref:o.trim(),fullref:a,depth:i,map:n})}throw new ze(e)}static async packedRefs({fs:e,gitdir:r}){let i=await Fs("packed-refs",async()=>e.read(`${r}/packed-refs`,{encoding:"utf8"}));return kd.from(i).refs}static async listRefs({fs:e,gitdir:r,filepath:i}){let n=t.packedRefs({fs:e,gitdir:r}),s=null;try{s=await e.readdirDeep(`${r}/${i}`),s=s.map(a=>a.replace(`${r}/${i}/`,""))}catch(a){s=[]}for(let a of(await n).keys())a.startsWith(i)&&(a=a.replace(i+"/",""),s.includes(a)||s.push(a));return s.sort(YO),s}static async listBranches({fs:e,gitdir:r,remote:i}){return i?t.listRefs({fs:e,gitdir:r,filepath:`refs/remotes/${i}`}):t.listRefs({fs:e,gitdir:r,filepath:"refs/heads"})}static async listTags({fs:e,gitdir:r}){return(await t.listRefs({fs:e,gitdir:r,filepath:"refs/tags"})).filter(n=>!n.endsWith("^{}"))}};function uL(t,e){return Dd(BE(t),BE(e))}function BE(t){return t.mode==="040000"?t.path+"/":t.path}function uS(t){switch(t){case"040000":return"tree";case"100644":return"blob";case"100755":return"blob";case"120000":return"blob";case"160000":return"commit"}throw new he(`Unexpected GitTree entry mode: ${t}`)}function fL(t){let e=[],r=0;for(;r`${e.mode} ${e.type} ${e.oid} ${e.path}`).join(` +`)}toObject(){let e=[...this._entries];return e.sort(uL),k.concat(e.map(r=>{let i=k.from(r.mode.replace(/^0/,"")),n=k.from(" "),s=k.from(r.path,"utf8"),a=k.from([0]),o=k.from(r.oid,"hex");return k.concat([i,n,s,a,o])}))}entries(){return this._entries}*[Symbol.iterator](){for(let e of this._entries)yield e}},Ds=class{static wrap({type:e,object:r}){let i=`${e} ${r.length}\0`,n=i.length,s=n+r.length,a=new Uint8Array(s);for(let o=0;o>=1,n+=8;return i}function GE(t,e){let r=t.readUInt8(),i=128,n=15,s=112;if(r&i){let a=UE(t,r&n,4),o=UE(t,(r&s)>>4,3);return o===0&&(o=65536),e.slice(a,a+o)}else return t.slice(r)}function mL(t){let e=[t];return{next(){return Promise.resolve({done:e.length===0,value:e.pop()})},return(){return e=[],{}},[Symbol.asyncIterator](){return this}}}function dS(t){return t[Symbol.asyncIterator]?t[Symbol.asyncIterator]():t[Symbol.iterator]?t[Symbol.iterator]():t.next?t:mL(t)}var Ad=class{constructor(e){if(typeof k=="undefined")throw new Error("Missing Buffer dependency");this.stream=dS(e),this.buffer=null,this.cursor=0,this.undoCursor=0,this.started=!1,this._ended=!1,this._discardedBytes=0}eof(){return this._ended&&this.cursor===this.buffer.length}tell(){return this._discardedBytes+this.cursor}async byte(){if(!this.eof()&&(this.started||await this._init(),!(this.cursor===this.buffer.length&&(await this._loadnext(),this._ended))))return this._moveCursor(1),this.buffer[this.undoCursor]}async chunk(){if(!this.eof()&&(this.started||await this._init(),!(this.cursor===this.buffer.length&&(await this._loadnext(),this._ended))))return this._moveCursor(this.buffer.length),this.buffer.slice(this.undoCursor,this.cursor)}async read(e){if(!this.eof())return this.started||await this._init(),this.cursor+e>this.buffer.length&&(this._trim(),await this._accumulate(e)),this._moveCursor(e),this.buffer.slice(this.undoCursor,this.cursor)}async skip(e){this.eof()||(this.started||await this._init(),this.cursor+e>this.buffer.length&&(this._trim(),await this._accumulate(e)),this._moveCursor(e))}async undo(){this.cursor=this.undoCursor}async _next(){this.started=!0;let{done:e,value:r}=await this.stream.next();return e&&(this._ended=!0,!r)?k.alloc(0):(r&&(r=k.from(r)),r)}_trim(){this.buffer=this.buffer.slice(this.undoCursor),this.cursor-=this.undoCursor,this._discardedBytes+=this.undoCursor,this.undoCursor=0}_moveCursor(e){this.undoCursor=this.cursor,this.cursor+=e,this.cursor>this.buffer.length&&(this.cursor=this.buffer.length)}async _accumulate(e){if(this._ended)return;let r=[this.buffer];for(;this.cursor+e>gL(r);){let i=await this._next();if(this._ended)break;r.push(i)}this.buffer=k.concat(r)}async _loadnext(){this._discardedBytes+=this.buffer.length,this.undoCursor=0,this.cursor=0,this.buffer=await this._next()}async _init(){this.buffer=await this._next()}};function gL(t){return t.reduce((e,r)=>e+r.length,0)}async function vL(t,e){let r=new Ad(t),i=await r.read(4);if(i=i.toString("utf8"),i!=="PACK")throw new he(`Invalid PACK header '${i}'`);let n=await r.read(4);if(n=n.readUInt32BE(0),n!==2)throw new he(`Invalid packfile version: ${n}`);let s=await r.read(4);if(s=s.readUInt32BE(0),!(s<1))for(;!r.eof()&&s--;){let a=r.tell(),{type:o,length:l,ofs:c,reference:u}=await wL(r),f=new Md.default.Inflate;for(;!f.result;){let d=await r.chunk();if(!d)break;if(f.push(d,!1),f.err)throw new he(`Pako error: ${f.msg}`);if(f.result){if(f.result.length!==l)throw new he("Inflated object size is different from that stated in packfile.");await r.undo(),await r.read(d.length-f.strm.avail_in);let h=r.tell();await e({data:f.result,type:o,num:s,offset:a,end:h,reference:u,ofs:c})}}}}async function wL(t){let e=await t.byte(),r=e>>4&7,i=e&15;if(e&128){let a=4;do e=await t.byte(),i|=(e&127)<n+1<<7|s,-1)}function xL(t,e){let r=e,i=4,n=null;do n=t.readUInt8(),r|=(n&127)<2048*1024*1024)throw new he("To keep implementation simple, I haven't implemented the layer 5 feature needed to support packfiles > 2GB in size.");i.seek(i.tell()+1020);let a=i.readUInt32BE(),o=[];for(let u=0;u{u===null&&(u=x);let E=Math.floor((u-x)*100/u);E!==f&&i&&await i({phase:"Receiving objects",loaded:u-x,total:u}),f=E,b=n[b],["commit","tree","blob","tag"].includes(b)?s[C]={type:b,offset:C}:b==="ofs-delta"?s[C]={type:b,offset:C}:b==="ref-delta"&&(s[C]={type:b,offset:C})});let d=Object.keys(s).map(Number);for(let[v,b]of d.entries()){let _=v+1===d.length?e.byteLength-20:d[v+1],C=s[b],x=iS.default.buf(e.slice(b,_))>>>0;C.end=_,C.crc=x}let h=new t({pack:Promise.resolve(e),packfileSha:a,crcs:l,hashes:o,offsets:c,getExternalRefDelta:r});f=null;let p=0,g=[0,0,0,0,0,0,0,0,0,0,0,0];for(let v in s){v=Number(v);let b=Math.floor(p*100/u);b!==f&&i&&await i({phase:"Resolving deltas",loaded:p,total:u}),p++,f=b;let _=s[v];if(!_.oid)try{h.readDepth=0,h.externalReadDepth=0;let{type:C,object:x}=await h.readSlice({start:v});g[h.readDepth]+=1;let E=await En(Ds.wrap({type:C,object:x}));_.oid=E,o.push(E),c.set(E,v),l[E]=_.crc}catch(C){continue}}return o.sort(),h}async toBuffer(){let e=[],r=(c,u)=>{e.push(k.from(c,u))};r("ff744f63","hex"),r("00000002","hex");let i=new zi(k.alloc(256*4));for(let c=0;c<256;c++){let u=0;for(let f of this.hashes)parseInt(f.slice(0,2),16)<=c&&u++;i.writeUInt32BE(u)}e.push(i.buffer);for(let c of this.hashes)r(c,"hex");let n=new zi(k.alloc(this.hashes.length*4));for(let c of this.hashes)n.writeUInt32BE(this.crcs[c]);e.push(n.buffer);let s=new zi(k.alloc(this.hashes.length*4));for(let c of this.hashes)s.writeUInt32BE(this.offsets.get(c));e.push(s.buffer),r(this.packfileSha,"hex");let a=k.concat(e),o=await En(a),l=k.alloc(20);return l.write(o,"hex"),k.concat([a,l])}async load({pack:e}){this.pack=e}async unload(){this.pack=null}async read({oid:e}){if(!this.offsets.get(e)){if(this.getExternalRefDelta)return this.externalReadDepth++,this.getExternalRefDelta(e);throw new he(`Could not read object ${e} from packfile`)}let r=this.offsets.get(e);return this.readSlice({start:r})}async readSlice({start:e}){if(this.offsetCache[e])return Object.assign({},this.offsetCache[e]);this.readDepth++;let r={16:"commit",32:"tree",48:"blob",64:"tag",96:"ofs_delta",112:"ref_delta"},i=await this.pack;if(!i)throw new he("Could not read packfile data. The packfile may be missing, corrupted, or too large to read into memory.");let n=i.slice(e),s=new zi(n),a=s.readUInt8(),o=a&112,l=r[o];if(l===void 0)throw new he("Unrecognized type: 0b"+o.toString(2));let c=a&15,u=c;a&128&&(u=xL(s,c));let d=null,h=null;if(l==="ofs_delta"){let g=yL(s),v=e-g;({object:d,type:l}=await this.readSlice({start:v}))}if(l==="ref_delta"){let g=s.slice(20).toString("hex");({object:d,type:l}=await this.read({oid:g}))}let p=n.slice(s.tell());if(h=k.from(await hS(p)),h.byteLength!==u)throw new he(`Packfile told us object would have length ${u} but it had length ${h.byteLength}`);return d&&(h=k.from(pL(h,d))),this.readDepth>3&&(this.offsetCache[e]={type:l,object:h}),{type:l,format:"content",object:h}}},xd=Symbol("PackfileCache");async function EL({fs:t,filename:e,getExternalRefDelta:r,emitter:i,emitterPrefix:n}){let s=await t.read(e);return qc.fromIdx({idx:s,getExternalRefDelta:r})}function av({fs:t,cache:e,filename:r,getExternalRefDelta:i,emitter:n,emitterPrefix:s}){e[xd]||(e[xd]=new Map);let a=e[xd].get(r);return a||(a=EL({fs:t,filename:r,getExternalRefDelta:i,emitter:n,emitterPrefix:s}),e[xd].set(r,a)),a}async function SL(t,{start:e=0,end:r=t.length}={}){return En(t.subarray(e,r))}async function kL({fs:t,cache:e,gitdir:r,oid:i,format:n="content",getExternalRefDelta:s}){let a=await t.readdir(N(r,"objects/pack"));a=a.filter(o=>o.endsWith(".idx"));for(let o of a){let l=`${r}/objects/pack/${o}`,c=await av({fs:t,cache:e,filename:l,getExternalRefDelta:s});if(c.error)throw new he(c.error);if(c.offsets.has(i)){let u=l.replace(/idx$/,"pack");c.pack||(c.pack=t.read(u));let f=await c.pack;if(!f)throw c.pack=null,new he(`Could not read packfile at ${u}. The file may be missing, corrupted, or too large to read into memory.`);if(!c._checksumVerified){let h=c.packfileSha,p=f.subarray(-20),g=Array.from(p).map(b=>b.toString(16).padStart(2,"0")).join("");if(g!==h)throw new he(`Packfile trailer mismatch: expected ${h}, got ${g}. The packfile may be corrupted.`);let v=await SL(f,{start:0,end:f.length-20});if(v!==h)throw new he(`Packfile payload corrupted: calculated ${v} but expected ${h}. The packfile may have been tampered with.`);c._checksumVerified=!0}let d=await c.read({oid:i,getExternalRefDelta:s});return d.format="content",d.source=`objects/pack/${o.replace(/idx$/,"pack")}`,d}}return null}async function st({fs:t,cache:e,gitdir:r,oid:i,format:n="content"}){let s=u=>st({fs:t,cache:e,gitdir:r,oid:u}),a;if(i==="4b825dc642cb6eb9a060e54bf8d69288fbee4904"&&(a={format:"wrapped",object:k.from("tree 0\0")}),a||(a=await fS({fs:t,gitdir:r,oid:i})),!a){if(a=await kL({fs:t,cache:e,gitdir:r,oid:i,getExternalRefDelta:s}),!a)throw new ze(i);return a}if(n==="deflated"||(a.format==="deflated"&&(a.object=k.from(await hS(a.object)),a.format="wrapped"),n==="wrapped"))return a;let o=await En(a.object);if(o!==i)throw new he(`SHA check failed! Expected ${i}, computed ${o}`);let{object:l,type:c}=Ds.unwrap(a.object);if(a.type=c,a.object=l,a.format="content",n==="content")return a;throw new he(`invalid requested format "${n}"`)}var Wi=class t extends Pe{constructor(e,r,i=!0){super(`Failed to create ${e} at ${r} because it already exists.${i?` (Hint: use 'force: true' parameter to overwrite existing ${e}.)`:""}`),this.code=this.name=t.code,this.data={noun:e,where:r,canForce:i}}};Wi.code="AlreadyExistsError";var Yc=class t extends Pe{constructor(e,r,i){super(`Found multiple ${e} matching "${r}" (${i.join(", ")}). Use a longer abbreviation length to disambiguate them.`),this.code=this.name=t.code,this.data={nouns:e,short:r,matches:i}}};Yc.code="AmbiguousError";var Zc=class t extends Pe{constructor(e){super(`Your local changes to the following files would be overwritten by checkout: ${e.join(", ")}`),this.code=this.name=t.code,this.data={filepaths:e}}};Zc.code="CheckoutConflictError";var Kc=class t extends Pe{constructor(e,r){super(`Cannot cherry-pick merge commit ${e}. Merge commits have ${r} parents and require specifying which parent to use as the base.`),this.code=this.name=t.code,this.data={oid:e,parentCount:r}}};Kc.code="CherryPickMergeCommitError";var Xc=class t extends Pe{constructor(e){super(`Cannot cherry-pick root commit ${e}. Root commits have no parents.`),this.code=this.name=t.code,this.data={oid:e}}};Xc.code="CherryPickRootCommitError";var Qc=class t extends Pe{constructor(e,r){super(`Failed to checkout "${e}" because commit ${r} is not available locally. Do a git fetch to make the branch available locally.`),this.code=this.name=t.code,this.data={ref:e,oid:r}}};Qc.code="CommitNotFetchedError";var Jc=class t extends Pe{constructor(){super("Cannot create an empty commit when disallowEmpty is true."),this.code=this.name=t.code,this.data={}}};Jc.code="EmptyCommitError";var eu=class t extends Pe{constructor(){super("Empty response from git server."),this.code=this.name=t.code,this.data={}}};eu.code="EmptyServerResponseError";var tu=class t extends Pe{constructor(){super("A simple fast-forward merge was not possible."),this.code=this.name=t.code,this.data={}}};tu.code="FastForwardError";var ru=class t extends Pe{constructor(e,r){super(`One or more branches were not updated: ${e}`),this.code=this.name=t.code,this.data={prettyDetails:e,result:r}}};ru.code="GitPushError";var Xo=class t extends Pe{constructor(e,r,i){super(`HTTP Error: ${e} ${r}`),this.code=this.name=t.code,this.data={statusCode:e,statusMessage:r,response:i}}};Xo.code="HttpError";var Os=class t extends Pe{constructor(e){let r="invalid filepath";e==="leading-slash"||e==="trailing-slash"?r='"filepath" parameter should not include leading or trailing directory separators because these can cause problems on some platforms.':e==="directory"&&(r='"filepath" should not be a directory.'),super(r),this.code=this.name=t.code,this.data={reason:e}}};Os.code="InvalidFilepathError";var qi=class t extends Pe{constructor(e,r){super(`"${e}" would be an invalid git reference. (Hint: a valid alternative would be "${r}".)`),this.code=this.name=t.code,this.data={ref:e,suggestion:r}}};qi.code="InvalidRefNameError";var iu=class t extends Pe{constructor(e){super(`Maximum search depth of ${e} exceeded.`),this.code=this.name=t.code,this.data={depth:e}}};iu.code="MaxDepthError";var Qo=class t extends Pe{constructor(){super("Merges with conflicts are not supported yet."),this.code=this.name=t.code,this.data={}}};Qo.code="MergeNotSupportedError";var ka=class t extends Pe{constructor(e,r,i,n){super(`Automatic merge failed with one or more merge conflicts in the following files: ${e.toString()}. Fix conflicts then commit the result.`),this.code=this.name=t.code,this.data={filepaths:e,bothModified:r,deleteByUs:i,deleteByTheirs:n}}};ka.code="MergeConflictError";var Jt=class t extends Pe{constructor(e){super(`No name was provided for ${e} in the argument or in the .git/config file.`),this.code=this.name=t.code,this.data={role:e}}};Jt.code="MissingNameError";var Or=class t extends Pe{constructor(e){super(`The function requires a "${e}" parameter but none was provided.`),this.code=this.name=t.code,this.data={parameter:e}}};Or.code="MissingParameterError";var Ca=class t extends Pe{constructor(e){super('There are multiple errors that were thrown by the method. Please refer to the "errors" property to see more'),this.code=this.name=t.code,this.data={errors:e},this.errors=e}};Ca.code="MultipleGitError";var Aa=class t extends Pe{constructor(e,r){super(`Expected "${e}" but received "${r}".`),this.code=this.name=t.code,this.data={expected:e,actual:r}}};Aa.code="ParseError";var Jo=class t extends Pe{constructor(e){let r="";e==="not-fast-forward"?r=" because it was not a simple fast-forward":e==="tag-exists"&&(r=" because tag already exists"),super(`Push rejected${r}. Use "force: true" to override.`),this.code=this.name=t.code,this.data={reason:e}}};Jo.code="PushRejectedError";var Is=class t extends Pe{constructor(e,r){super(`Remote does not support the "${e}" so the "${r}" parameter cannot be used.`),this.code=this.name=t.code,this.data={capability:e,parameter:r}}};Is.code="RemoteCapabilityError";var nu=class t extends Pe{constructor(e,r){super(`Remote did not reply using the "smart" HTTP protocol. Expected "001e# service=git-upload-pack" but received: ${e}`),this.code=this.name=t.code,this.data={preview:e,response:r}}};nu.code="SmartHttpError";var su=class t extends Pe{constructor(e,r,i){super(`Git remote "${e}" uses an unrecognized transport protocol: "${r}"`),this.code=this.name=t.code,this.data={url:e,transport:r,suggestion:i}}};su.code="UnknownTransportError";var au=class t extends Pe{constructor(e){super(`Cannot parse remote URL: "${e}"`),this.code=this.name=t.code,this.data={url:e}}};au.code="UrlParseError";var el=class t extends Pe{constructor(){super("The operation was canceled."),this.code=this.name=t.code,this.data={}}};el.code="UserCanceledError";var ou=class t extends Pe{constructor(e){super(`Could not merge index: Entry for '${e}' is not up to date. Either reset the index entry to HEAD, or stage your unstaged changes.`),this.code=this.name=t.code,this.data={filepath:e}}};ou.code="IndexResetError";var lu=class t extends Pe{constructor(e){super(`"${e}" does not point to any commit. You're maybe working on a repository with no commits yet. `),this.code=this.name=t.code,this.data={ref:e}}};lu.code="NoCommitError";var du=Object.freeze({__proto__:null,AlreadyExistsError:Wi,AmbiguousError:Yc,CheckoutConflictError:Zc,CherryPickMergeCommitError:Kc,CherryPickRootCommitError:Xc,CommitNotFetchedError:Qc,EmptyCommitError:Jc,EmptyServerResponseError:eu,FastForwardError:tu,GitPushError:ru,HttpError:Xo,InternalError:he,InvalidFilepathError:Os,InvalidOidError:Ms,InvalidRefNameError:qi,MaxDepthError:iu,MergeNotSupportedError:Qo,MergeConflictError:ka,MissingNameError:Jt,MissingParameterError:Or,MultipleGitError:Ca,NoRefspecError:Wc,NotFoundError:ze,ObjectTypeError:xr,ParseError:Aa,PushRejectedError:Jo,RemoteCapabilityError:Is,SmartHttpError:nu,UnknownTransportError:su,UnsafeFilepathError:Ea,UrlParseError:au,UserCanceledError:el,UnmergedPathsError:zc,IndexResetError:ou,NoCommitError:lu});function Qg({name:t,email:e,timestamp:r,timezoneOffset:i}){return i=CL(i),`${t} <${e}> ${r} ${i}`}function CL(t){let e=AL(TL(t));t=Math.abs(t);let r=Math.floor(t/60);t-=r*60;let i=String(r),n=String(t);return i.length<2&&(i="0"+i),n.length<2&&(n="0"+n),(e===-1?"-":"+")+i+n}function AL(t){return Math.sign(t)||(Object.is(t,-0)?-1:1)}function TL(t){return t===0?t:-t}function Qn(t){return t=t.replace(/\r/g,""),t=t.replace(/^\n+/,""),t=t.replace(/\n+$/,"")+` +`,t}function Td(t){let[,e,r,i,n]=t.match(/^(.*) <(.*)> (.*) (.*)$/);return{name:e,email:r,timestamp:Number(i),timezoneOffset:PL(n)}}function PL(t){let[,e,r,i]=t.match(/(\+|-)(\d\d)(\d\d)/);return i=(e==="+"?1:-1)*(Number(r)*60+Number(i)),RL(i)}function RL(t){return t===0?t:-t}var ni=class t{constructor(e){if(typeof e=="string")this._tag=e;else if(k.isBuffer(e))this._tag=e.toString("utf8");else if(typeof e=="object")this._tag=t.render(e);else throw new he("invalid type passed to GitAnnotatedTag constructor")}static from(e){return new t(e)}static render(e){return`object ${e.object} +type ${e.type} +tag ${e.tag} +tagger ${Qg(e.tagger)} + +${e.message} +${e.gpgsig?e.gpgsig:""}`}justHeaders(){return this._tag.slice(0,this._tag.indexOf(` + +`))}message(){let e=this.withoutSignature();return e.slice(e.indexOf(` + +`)+2)}parse(){return Object.assign(this.headers(),{message:this.message(),gpgsig:this.gpgsig()})}render(){return this._tag}headers(){let e=this.justHeaders().split(` +`),r=[];for(let n of e)n[0]===" "?r[r.length-1]+=` +`+n.slice(1):r.push(n);let i={};for(let n of r){let s=n.slice(0,n.indexOf(" ")),a=n.slice(n.indexOf(" ")+1);Array.isArray(i[s])?i[s].push(a):i[s]=a}return i.tagger&&(i.tagger=Td(i.tagger)),i.committer&&(i.committer=Td(i.committer)),i}withoutSignature(){let e=Qn(this._tag);return e.indexOf(` +-----BEGIN PGP SIGNATURE-----`)===-1?e:e.slice(0,e.lastIndexOf(` +-----BEGIN PGP SIGNATURE-----`))}gpgsig(){if(this._tag.indexOf(` +-----BEGIN PGP SIGNATURE-----`)===-1)return;let e=this._tag.slice(this._tag.indexOf("-----BEGIN PGP SIGNATURE-----"),this._tag.indexOf("-----END PGP SIGNATURE-----")+27);return Qn(e)}payload(){return this.withoutSignature()+` +`}toObject(){return k.from(this._tag,"utf8")}static async sign(e,r,i){let n=e.payload(),{signature:s}=await r({payload:n,secretKey:i});s=Qn(s);let a=n+s;return t.from(a)}};function Hg(t){return t.trim().split(` +`).map(e=>" "+e).join(` +`)+` +`}function $L(t){return t.split(` +`).map(e=>e.replace(/^ /,"")).join(` +`)}var Nr=class t{constructor(e){if(typeof e=="string")this._commit=e;else if(k.isBuffer(e))this._commit=e.toString("utf8");else if(typeof e=="object")this._commit=t.render(e);else throw new he("invalid type passed to GitCommit constructor")}static fromPayloadSignature({payload:e,signature:r}){let i=t.justHeaders(e),n=t.justMessage(e),s=Qn(i+` +gpgsig`+Hg(r)+` +`+n);return new t(s)}static from(e){return new t(e)}toObject(){return k.from(this._commit,"utf8")}headers(){return this.parseHeaders()}message(){return t.justMessage(this._commit)}parse(){return Object.assign({message:this.message()},this.headers())}static justMessage(e){return Qn(e.slice(e.indexOf(` + +`)+2))}static justHeaders(e){return e.slice(0,e.indexOf(` + +`))}parseHeaders(){let e=t.justHeaders(this._commit).split(` +`),r=[];for(let n of e)n[0]===" "?r[r.length-1]+=` +`+n.slice(1):r.push(n);let i={parent:[]};for(let n of r){let s=n.slice(0,n.indexOf(" ")),a=n.slice(n.indexOf(" ")+1);Array.isArray(i[s])?i[s].push(a):i[s]=a}return i.author&&(i.author=Td(i.author)),i.committer&&(i.committer=Td(i.committer)),i}static renderHeaders(e){let r="";if(e.tree?r+=`tree ${e.tree} +`:r+=`tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904 +`,e.parent){if(e.parent.length===void 0)throw new he("commit 'parent' property should be an array");for(let s of e.parent)r+=`parent ${s} +`}let i=e.author;r+=`author ${Qg(i)} +`;let n=e.committer||e.author;return r+=`committer ${Qg(n)} +`,e.gpgsig&&(r+="gpgsig"+Hg(e.gpgsig)),r}static render(e){return t.renderHeaders(e)+` +`+Qn(e.message)}render(){return this._commit}withoutSignature(){let e=Qn(this._commit);if(e.indexOf(` +gpgsig`)===-1)return e;let r=e.slice(0,e.indexOf(` +gpgsig`)),i=e.slice(e.indexOf(`-----END PGP SIGNATURE----- +`)+28);return Qn(r+` +`+i)}isolateSignature(){let e=this._commit.slice(this._commit.indexOf("-----BEGIN PGP SIGNATURE-----"),this._commit.indexOf("-----END PGP SIGNATURE-----")+27);return $L(e)}static async sign(e,r,i){let n=e.withoutSignature(),s=t.justMessage(e._commit),{signature:a}=await r({payload:n,secretKey:i});a=Qn(a);let l=t.justHeaders(e._commit)+` +gpgsig`+Hg(a)+` +`+s;return t.from(l)}};async function tl({fs:t,cache:e,gitdir:r,oid:i}){if(i==="4b825dc642cb6eb9a060e54bf8d69288fbee4904")return{tree:Lr.from([]),oid:i};let{type:n,object:s}=await st({fs:t,cache:e,gitdir:r,oid:i});if(n==="tag")return i=ni.from(s).parse().object,tl({fs:t,cache:e,gitdir:r,oid:i});if(n==="commit")return i=Nr.from(s).parse().tree,tl({fs:t,cache:e,gitdir:r,oid:i});if(n!=="tree")throw new xr(i,n,"tree");return{tree:Lr.from(s),oid:i}}var Jg=class{constructor({fs:e,gitdir:r,ref:i,cache:n}){this.fs=e,this.cache=n,this.gitdir=r,this.mapPromise=(async()=>{let a=new Map,o;try{o=await q.resolve({fs:e,gitdir:r,ref:i})}catch(c){c instanceof ze&&(o="4b825dc642cb6eb9a060e54bf8d69288fbee4904")}let l=await tl({fs:e,cache:this.cache,gitdir:r,oid:o});return l.type="tree",l.mode="40000",a.set(".",l),a})();let s=this;this.ConstructEntry=class{constructor(o){this._fullpath=o,this._type=!1,this._mode=!1,this._stat=!1,this._content=!1,this._oid=!1}async type(){return s.type(this)}async mode(){return s.mode(this)}async stat(){return s.stat(this)}async content(){return s.content(this)}async oid(){return s.oid(this)}}}async readdir(e){let r=e._fullpath,{fs:i,cache:n,gitdir:s}=this,a=await this.mapPromise,o=a.get(r);if(!o)throw new Error(`No obj for ${r}`);let l=o.oid;if(!l)throw new Error(`No oid for obj ${JSON.stringify(o)}`);if(o.type!=="tree")return null;let{type:c,object:u}=await st({fs:i,cache:n,gitdir:s,oid:l});if(c!==o.type)throw new xr(l,c,o.type);let f=Lr.from(u);for(let d of f)a.set(N(r,d.path),d);return f.entries().map(d=>N(r,d.path))}async type(e){if(e._type===!1){let r=await this.mapPromise,{type:i}=r.get(e._fullpath);e._type=i}return e._type}async mode(e){if(e._mode===!1){let r=await this.mapPromise,{mode:i}=r.get(e._fullpath);e._mode=oS(parseInt(i,8))}return e._mode}async stat(e){}async content(e){if(e._content===!1){let r=await this.mapPromise,{fs:i,cache:n,gitdir:s}=this,o=r.get(e._fullpath).oid,{type:l,object:c}=await st({fs:i,cache:n,gitdir:s,oid:o});l!=="blob"?e._content=void 0:e._content=new Uint8Array(c)}return e._content}async oid(e){if(e._oid===!1){let i=(await this.mapPromise).get(e._fullpath);e._oid=i.oid}return e._oid}};function Dr({ref:t="HEAD"}={}){let e=Object.create(null);return Object.defineProperty(e,Od,{value:function({fs:r,gitdir:i,cache:n}){return new Jg({fs:r,gitdir:i,ref:t,cache:n})}}),Object.freeze(e),e}var ev=class{constructor({fs:e,dir:r,gitdir:i,cache:n,refresh:s=!0}){this.fs=e,this.cache=n,this.dir=r,this.gitdir=i,this.refresh=s,this.config=null;let a=this;this.ConstructEntry=class{constructor(l){this._fullpath=l,this._type=!1,this._mode=!1,this._stat=!1,this._content=!1,this._oid=!1}async type(){return a.type(this)}async mode(){return a.mode(this)}async stat(){return a.stat(this)}async content(){return a.content(this)}async oid(){return a.oid(this)}}}async readdir(e){if(await e.type()!=="tree")return null;let r=e._fullpath,{fs:i,dir:n}=this,s=await i.readdir(N(n,r));return s===null?null:s.map(a=>N(r,a))}async type(e){return e._type===!1&&await e.stat(),e._type}async mode(e){return e._mode===!1&&await e.stat(),e._mode}async stat(e){if(e._stat===!1){let{fs:r,dir:i}=this,n=await r.lstat(`${i}/${e._fullpath}`);if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${e._fullpath}'`);let s=n.isDirectory()?"tree":"blob";s==="blob"&&!n.isFile()&&!n.isSymbolicLink()&&(s="special"),e._type=s,n=Ko(n),e._mode=n.mode,n.size===-1&&e._actualSize&&(n.size=e._actualSize),e._stat=n}return e._stat}async content(e){if(e._content===!1){let{fs:r,dir:i,gitdir:n}=this;if(await e.type()==="tree")e._content=void 0;else{let s;if(await e.mode()>>12===10)s=await r.readlink(`${i}/${e._fullpath}`);else{let o=await(await this._getGitConfig(r,n)).get("core.autocrlf");s=await r.read(`${i}/${e._fullpath}`,{autocrlf:o})}e._actualSize=s.length,e._stat&&e._stat.size===-1&&(e._stat.size=e._actualSize),e._content=new Uint8Array(s)}}return e._content}async oid(e){if(e._oid===!1){let r=this,{fs:i,gitdir:n,cache:s}=this,a;await gt.acquire({fs:i,gitdir:n,cache:s},async function(o){let l=o.entriesMap.get(e._fullpath),c=await e.stat(),f=await(await r._getGitConfig(i,n)).get("core.filemode"),d=typeof process!="undefined"?process.platform!=="win32":!0;if(!l||Ed(c,l,f,d)){let h=await e.content();h===void 0?a=void 0:(a=await En(Ds.wrap({type:"blob",object:h})),r.refresh&&l&&a===l.oid&&(!f||c.mode===l.mode)&&Ed(c,l,f,d)&&o.insert({filepath:e._fullpath,stats:c,oid:a}))}else a=l.oid}),e._oid=a}return e._oid}async _getGitConfig(e,r){return this.config?this.config:(this.config=await vt.get({fs:e,gitdir:r}),this.config)}};function hu({refresh:t=!0}={}){let e=Object.create(null);return Object.defineProperty(e,Od,{value:function({fs:r,dir:i,gitdir:n,cache:s}){return new ev({fs:r,dir:i,gitdir:n,cache:s,refresh:t})}}),Object.freeze(e),e}function FL(t,e){let r=e-t;return Array.from({length:r},(i,n)=>t+n)}var pS=typeof Array.prototype.flat=="undefined"?t=>t.reduce((e,r)=>e.concat(r),[]):t=>t.flat(),tv=class{constructor(){this.value=null}consider(e){e!=null&&(this.value===null?this.value=e:ec,reduce:a=async(l,c)=>{let u=pS(c);return l!==void 0&&u.unshift(l),u},iterate:o=(l,c)=>Promise.all([...c].map(l))}){let l=n.map(h=>h[Od]({fs:t,dir:r,gitdir:i,cache:e})),c=new Array(l.length).fill("."),u=FL(0,l.length),f=async h=>{u.forEach(v=>{let b=h[v];h[v]=b&&new l[v].ConstructEntry(b)});let g=(await Promise.all(u.map(v=>{let b=h[v];return b?l[v].readdir(b):[]}))).map(v=>(v===null?[]:v)[Symbol.iterator]());return{entries:h,children:IL(g)}},d=async h=>{let{entries:p,children:g}=await f(h),v=p.find(_=>_&&_._fullpath)._fullpath,b=await s(v,p);if(b!==null){let _=await o(d,g);return _=_.filter(C=>C!==void 0),a(b,_)}};return d(c)}async function rv(t,e){let r=await t.readdir(e);r==null?await t.rm(e):r.length?await Promise.all(r.map(i=>{let n=N(e,i);return t.lstat(n).then(s=>{if(s)return s.isDirectory()?rv(t,n):t.rm(n)})})).then(()=>t.rmdir(e)):await t.rmdir(e)}function ML(t){return DL(t)&&jE(t.then)&&jE(t.catch)}function DL(t){return t&&typeof t=="object"}function jE(t){return typeof t=="function"}function VE(t){return ML((r=>{try{return r.readFile().catch(i=>i)}catch(i){return i}})(t))}var zE=["readFile","writeFile","mkdir","rmdir","unlink","stat","lstat","readdir","readlink","symlink"];function WE(t,e){if(VE(e))for(let r of zE)t[`_${r}`]=e[r].bind(e);else for(let r of zE)t[`_${r}`]=(0,Vc.default)(e[r].bind(e));VE(e)?(e.cp&&(t._cp=e.cp.bind(e)),e.rm?t._rm=e.rm.bind(e):e.rmdir.length>1?t._rm=e.rmdir.bind(e):t._rm=rv.bind(null,t)):(e.cp&&(t._cp=(0,Vc.default)(e.cp.bind(e))),e.rm?t._rm=(0,Vc.default)(e.rm.bind(e)):e.rmdir.length>2?t._rm=(0,Vc.default)(e.rmdir.bind(e)):t._rm=rv.bind(null,t))}var te=class{constructor(e){if(typeof e._original_unwrapped_fs!="undefined")return e;let r=Object.getOwnPropertyDescriptor(e,"promises");r&&r.enumerable?WE(this,e.promises):WE(this,e),this._original_unwrapped_fs=e}async exists(e,r={}){try{return await this._stat(e),!0}catch(i){if(i.code==="ENOENT"||i.code==="ENOTDIR"||(i.code||"").includes("ENS"))return!1;throw console.log('Unhandled error in "FileSystem.exists()" function',i),i}}async read(e,r={}){try{let i=await this._readFile(e,r);if(r.autocrlf==="true")try{i=new TextDecoder("utf8",{fatal:!0}).decode(i),i=i.replace(/\r\n/g,` +`),i=new TextEncoder().encode(i)}catch(n){}return typeof i!="string"&&(i=k.from(i)),i}catch(i){return null}}async write(e,r,i={}){try{await this._writeFile(e,r,i)}catch(n){await this.mkdir(Sa(e)),await this._writeFile(e,r,i)}}async mkdir(e,r=!1){try{await this._mkdir(e)}catch(i){if(i===null||i.code==="EEXIST")return;if(r)throw i;if(i.code==="ENOENT"){let n=Sa(e);if(n==="."||n==="/"||n===e)throw i;await this.mkdir(n),await this.mkdir(e,!0)}}}async rm(e){try{await this._unlink(e)}catch(r){if(r.code!=="ENOENT")throw r}}async rmdir(e,r){try{r&&r.recursive?await this._rm(e,r):await this._rmdir(e)}catch(i){if(i.code!=="ENOENT")throw i}}async readdir(e){try{let r=await this._readdir(e);return r.sort(Dd),r}catch(r){return r.code==="ENOTDIR"?null:[]}}async readdirDeep(e){let r=await this._readdir(e);return(await Promise.all(r.map(async n=>{let s=e+"/"+n;return(await this._stat(s)).isDirectory()?this.readdirDeep(s):s}))).reduce((n,s)=>n.concat(s),[])}async lstat(e){try{return await this._lstat(e)}catch(r){if(r.code==="ENOENT"||(r.code||"").includes("ENS"))return null;throw r}}async readlink(e,r={encoding:"buffer"}){try{let i=await this._readlink(e,r);return k.isBuffer(i)?i:k.from(i)}catch(i){if(i.code==="ENOENT"||(i.code||"").includes("ENS"))return null;throw i}}async writelink(e,r){return this._symlink(r.toString("utf8"),e)}};function R(t,e){if(e===void 0)throw new Or(t)}function OL(t){return t.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(t)}async function ie({fsp:t,dotgit:e}){R("fsp",t),R("dotgit",e);let r=await t._stat(e).catch(()=>({isFile:()=>!1,isDirectory:()=>!1}));return r.isDirectory()?e:r.isFile()?t._readFile(e,"utf8").then(i=>i.trimRight().substr(8)).then(i=>OL(i)?i:N(Sa(e),i)):e}async function Pd(t,e){return!t&&!e?!1:t&&!e||!t&&e?!0:!(await t.type()==="tree"&&await e.type()==="tree"||await t.type()===await e.type()&&await t.mode()===await e.mode()&&await t.oid()===await e.oid())}async function LL({fs:t,dir:e,gitdir:r=N(e,".git"),commit:i="HEAD",cache:n={}}){try{R("fs",t),R("dir",e),R("gitdir",r);let s=new te(t),a=[Dr({ref:i}),hu(),sl()],o=[],l=await ie({fsp:s,dotgit:r});await gt.acquire({fs:s,gitdir:l,cache:n},async function(u){o=u.unmergedPaths});let c=await Jn({fs:s,cache:n,dir:e,gitdir:l,trees:a,map:async function(u,[f,d,h]){let p=!await Pd(d,h),g=o.includes(u),v=!await Pd(h,f);if(p||g)return f?{path:u,mode:await f.mode(),oid:await f.oid(),type:await f.type(),content:await f.content()}:void 0;if(v)return!1;throw new ou(u)}});await gt.acquire({fs:s,gitdir:l,cache:n},async function(u){for(let f of c)if(f!==!1){if(!f){await s.rmdir(`${e}/${f.path}`,{recursive:!0}),u.delete({filepath:f.path});continue}if(f.type==="blob"){let d=new TextDecoder().decode(f.content);await s.write(`${e}/${f.path}`,d,{mode:f.mode}),u.insert({filepath:f.path,oid:f.oid,stage:0})}}})}catch(s){throw s.caller="git.abortMerge",s}}var Ls=class{static async isIgnored({fs:e,dir:r,gitdir:i=N(r,".git"),filepath:n}){if(Sd(n)===".git")return!0;if(n===".")return!1;let s="",a=N(i,"info","exclude");await e.exists(a)&&(s=await e.read(a,"utf8"));let o=[{gitignore:N(r,".gitignore"),filepath:n}],l=n.split("/").filter(Boolean);for(let u=1;u{let f=await(await vt.get({fs:o,gitdir:l})).get("core.autocrlf");return iv({dir:e,gitdir:l,fs:o,filepath:i,index:c,force:s,parallel:a,autocrlf:f})})}catch(o){throw o.caller="git.add",o}}async function iv({dir:t,gitdir:e,fs:r,filepath:i,index:n,force:s,parallel:a,autocrlf:o}){i=Array.isArray(i)?i:[i];let l=i.map(async d=>{if(!s&&await Ls.isIgnored({fs:r,dir:t,gitdir:e,filepath:d}))return;let h=await r.lstat(N(t,d));if(!h)throw new ze(d);if(h.isDirectory()){let p=await r.readdir(N(t,d));if(a){let g=p.map(v=>iv({dir:t,gitdir:e,fs:r,filepath:[N(d,v)],index:n,force:s,parallel:a,autocrlf:o}));await Promise.all(g)}else for(let g of p)await iv({dir:t,gitdir:e,fs:r,filepath:[N(d,g)],index:n,force:s,parallel:a,autocrlf:o})}else{let p=h.isSymbolicLink()?await r.readlink(N(t,d)).then(gS):await r.read(N(t,d),{autocrlf:o});if(p===null)throw new ze(d);let g=await Br({fs:r,gitdir:e,type:"blob",object:p});n.insert({filepath:d,stats:h,oid:g})}}),c=await Promise.allSettled(l),u=c.filter(d=>d.status==="rejected").map(d=>d.reason);if(u.length>1)throw new Ca(u);if(u.length===1)throw u[0];return c.filter(d=>d.status==="fulfilled"&&d.value).map(d=>d.value)}async function cu({fs:t,gitdir:e,path:r}){return(await vt.get({fs:t,gitdir:e})).get(r)}function vS(t,...e){for(let r of e)if(r)for(let i of Object.keys(r)){let n=r[i];n!==void 0&&(t[i]=n)}return t}async function Ns({fs:t,gitdir:e,author:r,commit:i}){let n=Math.floor(Date.now()/1e3),s={name:await cu({fs:t,gitdir:e,path:"user.name"}),email:await cu({fs:t,gitdir:e,path:"user.email"})||"",timestamp:n,timezoneOffset:new Date(n*1e3).getTimezoneOffset()},a=vS({},s,i?i.author:void 0,r);if(a.name!==void 0)return a}async function Ta({fs:t,gitdir:e,author:r,committer:i,commit:n}){let s=Math.floor(Date.now()/1e3),a={name:await cu({fs:t,gitdir:e,path:"user.name"}),email:await cu({fs:t,gitdir:e,path:"user.email"})||"",timestamp:s,timezoneOffset:new Date(s*1e3).getTimezoneOffset()},o=vS({},a,n?n.committer:void 0,r,i);if(o.name!==void 0)return o}async function wS({fs:t,cache:e,gitdir:r,oid:i}){let{type:n,object:s}=await st({fs:t,cache:e,gitdir:r,oid:i});if(n==="tag")return i=ni.from(s).parse().object,wS({fs:t,cache:e,gitdir:r,oid:i});if(n!=="commit")throw new xr(i,n,"commit");return{commit:Nr.from(s),oid:i}}async function xn({fs:t,cache:e,gitdir:r,oid:i}){let{commit:n,oid:s}=await wS({fs:t,cache:e,gitdir:r,oid:i});return{oid:s,commit:n.parse(),payload:n.withoutSignature()}}var GL="4b825dc642cb6eb9a060e54bf8d69288fbee4904";async function pu({fs:t,cache:e,onSign:r,gitdir:i,message:n,author:s,committer:a,signingKey:o,amend:l=!1,dryRun:c=!1,noUpdateBranch:u=!1,disallowEmpty:f=!1,ref:d,parent:h,tree:p}){let g=!1,v=!1;d||(v=!(await t.read(`${i}/HEAD`,{encoding:"utf8"})).startsWith("ref:"),d=await q.resolve({fs:t,gitdir:i,ref:"HEAD",depth:2}));let b,_;try{b=await q.resolve({fs:t,gitdir:i,ref:d}),_=await xn({fs:t,gitdir:i,oid:b,cache:{}})}catch(E){g=!0}if(l&&g)throw new lu(d);let C=l?await Ns({fs:t,gitdir:i,author:s,commit:_.commit}):await Ns({fs:t,gitdir:i,author:s});if(!C)throw new Jt("author");let x=l?await Ta({fs:t,gitdir:i,author:C,committer:a,commit:_.commit}):await Ta({fs:t,gitdir:i,author:C,committer:a});if(!x)throw new Jt("committer");return gt.acquire({fs:t,gitdir:i,cache:e,allowUnmerged:!1},async function(E){let w=cS(E.entries).get(".");if(p||(p=await bS({fs:t,gitdir:i,inode:w,dryRun:c})),h?h=await Promise.all(h.map(P=>q.resolve({fs:t,gitdir:i,ref:P}))):l?h=_.commit.parent:h=b?[b]:[],f&&!l&&(g&&p===GL||!g&&p===_.commit.tree))throw new Jc;if(!n)if(l)n=_.commit.message;else throw new Or("message");let S=Nr.from({tree:p,parent:h,author:C,committer:x,message:n});o&&(S=await Nr.sign(S,r,o));let y=await Br({fs:t,gitdir:i,type:"commit",object:S.toObject(),dryRun:c});return!u&&!c&&await q.writeRef({fs:t,gitdir:i,ref:v?"HEAD":d,value:y}),y})}async function bS({fs:t,gitdir:e,inode:r,dryRun:i}){let n=r.children;for(let l of n)l.type==="tree"&&(l.metadata.mode="040000",l.metadata.oid=await bS({fs:t,gitdir:e,inode:l,dryRun:i}));let s=n.map(l=>({mode:l.metadata.mode,path:l.basename,oid:l.metadata.oid,type:l.type})),a=Lr.from(s);return await Br({fs:t,gitdir:e,type:"tree",object:a.toObject(),dryRun:i})}async function mu({fs:t,cache:e,gitdir:r,oid:i,filepath:n}){if(n.startsWith("/"))throw new Os("leading-slash");if(n.endsWith("/"))throw new Os("trailing-slash");let s=i,a=await tl({fs:t,cache:e,gitdir:r,oid:i}),o=a.tree;if(n==="")i=a.oid;else{let l=n.split("/");i=await _S({fs:t,cache:e,gitdir:r,tree:o,pathArray:l,oid:s,filepath:n})}return i}async function _S({fs:t,cache:e,gitdir:r,tree:i,pathArray:n,oid:s,filepath:a}){let o=n.shift();for(let l of i)if(l.path===o){if(n.length===0)return l.oid;{let{type:c,object:u}=await st({fs:t,cache:e,gitdir:r,oid:l.oid});if(c!=="tree")throw new xr(s,c,"tree",a);return i=Lr.from(u),_S({fs:t,cache:e,gitdir:r,tree:i,pathArray:n,oid:s,filepath:a})}}throw new ze(`file or directory found at "${s}:${a}"`)}async function al({fs:t,cache:e,gitdir:r,oid:i,filepath:n=void 0}){n!==void 0&&(i=await mu({fs:t,cache:e,gitdir:r,oid:i,filepath:n}));let{tree:s,oid:a}=await tl({fs:t,cache:e,gitdir:r,oid:i});return{oid:a,tree:s.entries()}}async function gu({fs:t,gitdir:e,tree:r}){let i=Lr.from(r).toObject();return await Br({fs:t,gitdir:e,type:"tree",object:i,format:"content"})}async function jL({fs:t,cache:e,onSign:r,gitdir:i,ref:n,oid:s,note:a,force:o,author:l,committer:c,signingKey:u}){let f;try{f=await q.resolve({gitdir:i,fs:t,ref:n})}catch(b){if(!(b instanceof ze))throw b}let h=(await al({fs:t,cache:e,gitdir:i,oid:f||"4b825dc642cb6eb9a060e54bf8d69288fbee4904"})).tree;if(o)h=h.filter(b=>b.path!==s);else for(let b of h)if(b.path===s)throw new Wi("note",s);typeof a=="string"&&(a=k.from(a,"utf8"));let p=await Br({fs:t,gitdir:i,type:"blob",object:a,format:"content"});h.push({mode:"100644",path:s,oid:p,type:"blob"});let g=await gu({fs:t,gitdir:i,tree:h});return await pu({fs:t,cache:e,onSign:r,gitdir:i,ref:n,tree:g,parent:f&&[f],message:`Note added by 'isomorphic-git addNote' +`,author:l,committer:c,signingKey:u})}async function VL({fs:t,onSign:e,dir:r,gitdir:i=N(r,".git"),ref:n="refs/notes/commits",oid:s,note:a,force:o,author:l,committer:c,signingKey:u,cache:f={}}){try{R("fs",t),R("gitdir",i),R("oid",s),R("note",a),u&&R("onSign",e);let d=new te(t),h=await Ns({fs:d,gitdir:i,author:l});if(!h)throw new Jt("author");let p=await Ta({fs:d,gitdir:i,author:h,committer:c});if(!p)throw new Jt("committer");let g=await ie({fsp:d,dotgit:i});return await jL({fs:d,cache:f,onSign:e,gitdir:g,ref:n,oid:s,note:a,force:o,author:h,committer:p,signingKey:u})}catch(d){throw d.caller="git.addNote",d}}var zL=/(^|[/.])([/.]|$)|^@$|@{|[\x00-\x20\x7f~^:?*[\\]|\.lock(\/|$)/;function uu(t,e){if(typeof t!="string")throw new TypeError("Reference name must be a string");return!zL.test(t)&&(!!e||t.includes("/"))}async function yS({fs:t,gitdir:e,remote:r,url:i,force:n}){if(!uu(r,!0))throw new qi(r,Zo.default.clean(r));let s=await vt.get({fs:t,gitdir:e});if(!n&&(await s.getSubsections("remote")).includes(r)&&i!==await s.get(`remote.${r}.url`))throw new Wi("remote",r);await s.set(`remote.${r}.url`,i),await s.set(`remote.${r}.fetch`,`+refs/heads/*:refs/remotes/${r}/*`),await vt.save({fs:t,gitdir:e,config:s})}async function WL({fs:t,dir:e,gitdir:r=N(e,".git"),remote:i,url:n,force:s=!1}){try{R("fs",t),R("gitdir",r),R("remote",i),R("url",n);let a=new te(t),o=await ie({fsp:a,dotgit:r});return await yS({fs:a,gitdir:o,remote:i,url:n,force:s})}catch(a){throw a.caller="git.addRemote",a}}async function qL({fs:t,cache:e,onSign:r,gitdir:i,ref:n,tagger:s,message:a=n,gpgsig:o,object:l,signingKey:c,force:u=!1}){if(n=n.startsWith("refs/tags/")?n:`refs/tags/${n}`,!u&&await q.exists({fs:t,gitdir:i,ref:n}))throw new Wi("tag",n);let f=await q.resolve({fs:t,gitdir:i,ref:l||"HEAD"}),{type:d}=await st({fs:t,cache:e,gitdir:i,oid:f}),h=ni.from({object:f,type:d,tag:n.replace("refs/tags/",""),tagger:s,message:a,gpgsig:o});c&&(h=await ni.sign(h,r,c));let p=await Br({fs:t,gitdir:i,type:"tag",object:h.toObject()});await q.writeRef({fs:t,gitdir:i,ref:n,value:p})}async function YL({fs:t,onSign:e,dir:r,gitdir:i=N(r,".git"),ref:n,tagger:s,message:a=n,gpgsig:o,object:l,signingKey:c,force:u=!1,cache:f={}}){try{R("fs",t),R("gitdir",i),R("ref",n),c&&R("onSign",e);let d=new te(t),h=await ie({fsp:d,dotgit:i}),p=await Ns({fs:d,gitdir:h,author:s});if(!p)throw new Jt("tagger");return await qL({fs:d,cache:f,onSign:e,gitdir:h,ref:n,tagger:p,message:a,gpgsig:o,object:l,signingKey:c,force:u})}catch(d){throw d.caller="git.annotatedTag",d}}async function ZL({fs:t,gitdir:e,ref:r,object:i,checkout:n=!1,force:s=!1}){if(!uu(r,!0))throw new qi(r,Zo.default.clean(r));let a=`refs/heads/${r}`;if(!s&&await q.exists({fs:t,gitdir:e,ref:a}))throw new Wi("branch",r,!1);let o;try{o=await q.resolve({fs:t,gitdir:e,ref:i||"HEAD"})}catch(l){}o&&await q.writeRef({fs:t,gitdir:e,ref:a,value:o}),n&&await q.writeSymbolicRef({fs:t,gitdir:e,ref:"HEAD",value:a})}async function KL({fs:t,dir:e,gitdir:r=N(e,".git"),ref:i,object:n,checkout:s=!1,force:a=!1}){try{R("fs",t),R("gitdir",r),R("ref",i);let o=new te(t),l=await ie({fsp:o,dotgit:r});return await ZL({fs:o,gitdir:l,ref:i,object:n,checkout:s,force:a})}catch(o){throw o.caller="git.branch",o}}async function fu(t,e,r){let i=r.split("/");i.pop();let n=e;for(let s of i){if(s===""||s===".")continue;n=`${n}/${s}`;let a=await t.lstat(n);if(a&&a.isSymbolicLink())throw new Ea(r)}}var xS=(t,e)=>t==="."||e==null||e.length===0||e==="."?!0:e.length>=t.length?e.startsWith(t):t.startsWith(e);async function ov({fs:t,cache:e,onProgress:r,onPostCheckout:i,dir:n,gitdir:s,remote:a,ref:o,filepaths:l,noCheckout:c,noUpdateHead:u,dryRun:f,force:d,track:h=!0,nonBlocking:p=!1,batchSize:g=100}){let v;if(i)try{v=await q.resolve({fs:t,gitdir:s,ref:"HEAD"})}catch(_){v="0000000000000000000000000000000000000000"}let b;try{b=await q.resolve({fs:t,gitdir:s,ref:o})}catch(_){if(o==="HEAD")throw _;let C=`${a}/${o}`;if(b=await q.resolve({fs:t,gitdir:s,ref:C}),h){let x=await vt.get({fs:t,gitdir:s});await x.set(`branch.${o}.remote`,a),await x.set(`branch.${o}.merge`,`refs/heads/${o}`),await vt.save({fs:t,gitdir:s,config:x})}await q.writeRef({fs:t,gitdir:s,ref:`refs/heads/${o}`,value:b})}if(!c){let _;try{_=await XL({fs:t,cache:e,onProgress:r,dir:n,gitdir:s,ref:o,force:d,filepaths:l})}catch(w){throw w instanceof ze&&w.data.what===b?new Qc(o,b):w}let C=_.filter(([w])=>w==="conflict").map(([w,S])=>S);if(C.length>0)throw new Zc(C);let x=_.filter(([w])=>w==="error").map(([w,S])=>S);if(x.length>0)throw new he(x.join(", "));if(f){i&&await i({previousHead:v,newHead:b,type:l!=null&&l.length>0?"file":"branch"});return}let E=0,A=_.length;if(await gt.acquire({fs:t,gitdir:s,cache:e},async function(w){await Promise.all(_.filter(([S])=>S==="delete"||S==="delete-index").map(async function([S,y]){let P=`${n}/${y}`;S==="delete"&&await t.rm(P),w.delete({filepath:y}),r&&await r({phase:"Updating workdir",loaded:++E,total:A})}))}),await gt.acquire({fs:t,gitdir:s,cache:e},async function(w){for(let[S,y]of _)if(S==="rmdir"||S==="rmdir-index"){let P=`${n}/${y}`;try{S==="rmdir"&&await t.rmdir(P),w.delete({filepath:y}),r&&await r({phase:"Updating workdir",loaded:++E,total:A})}catch(T){if(T.code==="ENOTEMPTY")console.log(`Did not delete ${y} because directory is not empty`);else throw T}}}),await Promise.all(_.filter(([w])=>w==="mkdir"||w==="mkdir-index").map(async function([w,S]){let y=`${n}/${S}`;await fu(t,n,S),await t.mkdir(y),r&&await r({phase:"Updating workdir",loaded:++E,total:A})})),p){let w=_.filter(([y])=>y==="create"||y==="create-index"||y==="update"||y==="mkdir-index"),S=await qE("Update Working Dir",w.map(([y,P,T,I,M])=>()=>JL({fs:t,cache:e,gitdir:s,dir:n},[y,P,T,I,M])),r,g);await gt.acquire({fs:t,gitdir:s,cache:e,allowUnmerged:!0},async function(y){await qE("Update Index",S.map(([P,T,I])=>()=>QL({index:y,fullpath:P,oid:T,stats:I})),r,g)})}else await gt.acquire({fs:t,gitdir:s,cache:e,allowUnmerged:!0},async function(w){var P,T;let S=await Promise.allSettled(_.filter(([I])=>I==="create"||I==="create-index"||I==="update"||I==="mkdir-index").map(async function([I,M,B,re,Ae]){let K=`${n}/${M}`;if(I!=="create-index"&&I!=="mkdir-index"){await fu(t,n,M);let{object:fe}=await st({fs:t,cache:e,gitdir:s,oid:B});if(Ae&&await t.rm(K),re===33188)await t.write(K,fe);else if(re===33261)await t.write(K,fe,{mode:511});else if(re===40960)await t.writelink(K,fe);else throw new he(`Invalid mode 0o${re.toString(8)} detected in blob ${B}`)}let Q=await t.lstat(K);re===33261&&(Q.mode=493),I==="mkdir-index"&&(Q.mode=57344),w.insert({filepath:M,stats:Q,oid:B}),r&&await r({phase:"Updating workdir",loaded:++E,total:A})})),y=[];for(let I of S)I.status==="rejected"&&(y.push(I.reason),console.error("[isomorphic-git checkout] task rejected:",(T=(P=I.reason)==null?void 0:P.stack)!=null?T:I.reason));if(y.length>0)throw new Ca(y)});i&&await i({previousHead:v,newHead:b,type:l!=null&&l.length>0?"file":"branch"})}if(!u){let _=await q.expand({fs:t,gitdir:s,ref:o});_.startsWith("refs/heads")?await q.writeSymbolicRef({fs:t,gitdir:s,ref:"HEAD",value:_}):await q.writeRef({fs:t,gitdir:s,ref:"HEAD",value:b})}}async function XL({fs:t,cache:e,onProgress:r,dir:i,gitdir:n,ref:s,force:a,filepaths:o}){let l=0;return Jn({fs:t,cache:e,dir:i,gitdir:n,trees:[Dr({ref:s}),hu(),sl()],map:async function(c,[u,f,d]){if(c===".")return;if(o&&!o.some(p=>xS(c,p)))return null;switch(r&&await r({phase:"Analyzing workdir",loaded:++l}),[!!d,!!u,!!f].map(Number).join("")){case"000":return;case"001":return a&&o&&o.includes(c)?["delete",c]:void 0;case"010":switch(await u.type()){case"tree":return["mkdir",c];case"blob":return["create",c,await u.oid(),await u.mode()];case"commit":return["mkdir-index",c,await u.oid(),await u.mode()];default:return["error",`new entry Unhandled type ${await u.type()}`]}case"011":switch(`${await u.type()}-${await f.type()}`){case"tree-tree":return;case"tree-blob":case"blob-tree":return["conflict",c];case"blob-blob":return await u.oid()!==await f.oid()?a?["update",c,await u.oid(),await u.mode(),await u.mode()!==await f.mode()]:["conflict",c]:await u.mode()!==await f.mode()?a?["update",c,await u.oid(),await u.mode(),!0]:["conflict",c]:["create-index",c,await u.oid(),await u.mode()];case"commit-tree":return;case"commit-blob":return["conflict",c];default:return["error",`new entry Unhandled type ${u.type}`]}case"100":return["delete-index",c];case"101":switch(await d.type()){case"tree":return["rmdir-index",c];case"blob":return await d.oid()!==await f.oid()?a?["delete",c]:["conflict",c]:["delete",c];case"commit":return["rmdir-index",c];default:return["error",`delete entry Unhandled type ${await d.type()}`]}case"110":case"111":switch(`${await d.type()}-${await u.type()}`){case"tree-tree":return;case"blob-blob":{if(await d.oid()===await u.oid()&&await d.mode()===await u.mode()&&!a)return;if(f){if(await f.oid()!==await d.oid()&&await f.oid()!==await u.oid())return a?["update",c,await u.oid(),await u.mode(),await u.mode()!==await f.mode()]:["conflict",c]}else if(a)return["update",c,await u.oid(),await u.mode(),await u.mode()!==await d.mode()];return await u.mode()!==await d.mode()?["update",c,await u.oid(),await u.mode(),!0]:await u.oid()!==await d.oid()?["update",c,await u.oid(),await u.mode(),!1]:void 0}case"tree-blob":return["update-dir-to-blob",c,await u.oid()];case"blob-tree":return["update-blob-to-tree",c];case"commit-commit":return["mkdir-index",c,await u.oid(),await u.mode()];default:return["error",`update entry Unhandled type ${await d.type()}-${await u.type()}`]}}},reduce:async function(c,u){return u=pS(u),c?c&&c[0]==="rmdir"?(u.push(c),u):(u.unshift(c),u):u}})}async function QL({index:t,fullpath:e,stats:r,oid:i}){try{t.insert({filepath:e,stats:r,oid:i})}catch(n){console.warn(`Error inserting ${e} into index:`,n)}}async function JL({fs:t,cache:e,gitdir:r,dir:i},[n,s,a,o,l]){let c=`${i}/${s}`;if(n!=="create-index"&&n!=="mkdir-index"){await fu(t,i,s);let{object:f}=await st({fs:t,cache:e,gitdir:r,oid:a});if(l&&await t.rm(c),o===33188)await t.write(c,f);else if(o===33261)await t.write(c,f,{mode:511});else if(o===40960)await t.writelink(c,f);else throw new he(`Invalid mode 0o${o.toString(8)} detected in blob ${a}`)}let u=await t.lstat(c);return o===33261&&(u.mode=493),n==="mkdir-index"&&(u.mode=57344),[s,a,u]}async function qE(t,e,r,i){let n=[],s=[];for(let a=0;ac());(await Promise.allSettled(o)).forEach(c=>{var u,f;c.status==="fulfilled"?n.push(c.value):(s.push(c.reason),console.error(`[isomorphic-git ${t}] task rejected:`,(f=(u=c.reason)==null?void 0:u.stack)!=null?f:c.reason))}),r&&await r({phase:"Updating workdir",loaded:a+o.length,total:e.length})}if(s.length>0)throw new Ca(s);return n}async function ES({fs:t,onProgress:e,onPostCheckout:r,dir:i,gitdir:n=N(i,".git"),remote:s="origin",ref:a,filepaths:o,noCheckout:l=!1,noUpdateHead:c=a===void 0,dryRun:u=!1,force:f=!1,track:d=!0,cache:h={},nonBlocking:p=!1,batchSize:g=100}){try{R("fs",t),R("dir",i),R("gitdir",n);let v=a||"HEAD",b=new te(t),_=await ie({fsp:b,dotgit:n});return await ov({fs:b,cache:h,onProgress:e,onPostCheckout:r,dir:i,gitdir:_,remote:s,ref:v,filepaths:o,noCheckout:l,noUpdateHead:c,dryRun:u,force:f,track:d,nonBlocking:p,batchSize:g})}catch(v){throw v.caller="git.checkout",v}}var Gg=/^.*(\r?\n|$)/gm;function eN({branches:t,contents:e}){let r=t[1],i=t[2],n=e[0],s=e[1],a=e[2],o=s.match(Gg),l=n.match(Gg),c=a.match(Gg),u=(0,sS.default)(o,l,c),f=7,d="",h=!0;for(let p of u)p.ok&&(d+=p.ok.join("")),p.conflict&&(h=!1,d+=`${"<".repeat(f)} ${r} +`,d+=p.conflict.a.join(""),d+=`${"=".repeat(f)} +`,d+=p.conflict.b.join(""),d+=`${">".repeat(f)} ${i} +`);return{cleanMerge:h,mergedText:d}}async function SS({fs:t,cache:e,dir:r,gitdir:i=N(r,".git"),index:n,ourOid:s,baseOid:a,theirOid:o,ourName:l="ours",baseName:c="base",theirName:u="theirs",dryRun:f=!1,abortOnConflict:d=!0,mergeDriver:h}){let p=Dr({ref:s}),g=Dr({ref:a}),v=Dr({ref:o}),b=[],_=[],C=[],x=[],E=await Jn({fs:t,cache:e,dir:r,gitdir:i,trees:[p,g,v],map:async function(A,[w,S,y]){let P=Sd(A),T=await Pd(w,S),I=await Pd(y,S);switch(`${T}-${I}`){case"false-false":return{mode:await S.mode(),path:P,oid:await S.oid(),type:await S.type()};case"false-true":return!y&&await w.type()==="tree"?{mode:await w.mode(),path:P,oid:await w.oid(),type:await w.type()}:y?{mode:await y.mode(),path:P,oid:await y.oid(),type:await y.type()}:void 0;case"true-false":return!w&&await y.type()==="tree"?{mode:await y.mode(),path:P,oid:await y.oid(),type:await y.type()}:w?{mode:await w.mode(),path:P,oid:await w.oid(),type:await w.type()}:void 0;case"true-true":{if(w&&y&&await w.type()==="tree"&&await y.type()==="tree")return{mode:await w.mode(),path:P,oid:await w.oid(),type:"tree"};if(w&&y&&await w.type()==="blob"&&await y.type()==="blob")return tN({fs:t,gitdir:i,path:P,ours:w,base:S,theirs:y,ourName:l,baseName:c,theirName:u,mergeDriver:h}).then(async M=>{if(M.cleanMerge)d||n.insert({filepath:A,oid:M.mergeResult.oid,stage:0});else if(b.push(A),_.push(A),!d){let B="";S&&await S.type()==="blob"&&(B=await S.oid());let re=await w.oid(),Ae=await y.oid();n.delete({filepath:A}),B&&n.insert({filepath:A,oid:B,stage:1}),n.insert({filepath:A,oid:re,stage:2}),n.insert({filepath:A,oid:Ae,stage:3})}return M.mergeResult});if(S&&!w&&y&&await S.type()==="blob"&&await y.type()==="blob"){if(b.push(A),C.push(A),!d){let M=await S.oid(),B=await y.oid();n.delete({filepath:A}),n.insert({filepath:A,oid:M,stage:1}),n.insert({filepath:A,oid:B,stage:3})}return{mode:await y.mode(),oid:await y.oid(),type:"blob",path:P}}if(S&&w&&!y&&await S.type()==="blob"&&await w.type()==="blob"){if(b.push(A),x.push(A),!d){let M=await S.oid(),B=await w.oid();n.delete({filepath:A}),n.insert({filepath:A,oid:M,stage:1}),n.insert({filepath:A,oid:B,stage:2})}return{mode:await w.mode(),oid:await w.oid(),type:"blob",path:P}}if(S&&!w&&!y&&(await S.type()==="blob"||await S.type()==="tree"))return;throw new Qo}}},reduce:b.length!==0&&(!r||d)?void 0:async(A,w)=>{let S=w.filter(Boolean);if(A&&!(A&&A.type==="tree"&&S.length===0&&A.path!==".")){if(S.length>0||A.path==="."&&S.length===0){let P=new Lr(S).toObject(),T=await Br({fs:t,gitdir:i,type:"tree",object:P,dryRun:f});A.oid=T}return A}}});return b.length!==0?(r&&!d&&await Jn({fs:t,cache:e,dir:r,gitdir:i,trees:[Dr({ref:E.oid})],map:async function(A,[w]){let S=`${r}/${A}`;if(await w.type()==="blob"){let y=await w.mode(),P=await w.content();await t.write(S,P,{mode:y})}return!0}}),new ka(b,_,C,x)):E.oid}async function tN({fs:t,gitdir:e,path:r,ours:i,base:n,theirs:s,ourName:a,theirName:o,baseName:l,dryRun:c,mergeDriver:u=eN}){let f="blob",d="100755",h="",p="";n&&await n.type()==="blob"&&(d=await n.mode(),h=await n.oid(),p=k.from(await n.content()).toString("utf8"));let g=d===await i.mode()?await s.mode():await i.mode();if(await i.oid()===await s.oid())return{cleanMerge:!0,mergeResult:{mode:g,path:r,oid:await i.oid(),type:f}};if(await i.oid()===h)return{cleanMerge:!0,mergeResult:{mode:g,path:r,oid:await s.oid(),type:f}};if(await s.oid()===h)return{cleanMerge:!0,mergeResult:{mode:g,path:r,oid:await i.oid(),type:f}};let v=k.from(await i.content()).toString("utf8"),b=k.from(await s.content()).toString("utf8"),{mergedText:_,cleanMerge:C}=await u({branches:[l,a,o],contents:[p,v,b],path:r}),x=await Br({fs:t,gitdir:e,type:"blob",object:k.from(_,"utf8"),dryRun:c});return{cleanMerge:C,mergeResult:{mode:g,path:r,oid:x,type:f}}}var rN={stage:sl,workdir:hu},jg;async function rl(t,e){return jg===void 0&&(jg=new Yo.default),jg.acquire(t,e)}async function iN(t,e,r,i,n=null){let s=N(r,i),a=await t.lstat(s);if(!a)throw new ze(s);if(a.isDirectory())throw new he(`${s}: file expected, but found directory`);let o=n?await fS({fs:t,gitdir:e,oid:n}):void 0,l=o?n:void 0;return o||await rl({fs:t,gitdir:e,currentFilepath:s},async()=>{let c=a.isSymbolicLink()?await t.readlink(s).then(gS):await t.read(s);if(c===null)throw new ze(s);l=await Br({fs:t,gitdir:e,type:"blob",object:c})}),l}async function nN({fs:t,dir:e,gitdir:r,entries:i}){async function n(s){if(s.type==="tree"){if(!s.oid){let a=await Promise.all(s.children.map(n));s.oid=await gu({fs:t,gitdir:r,tree:a}),s.mode=16384}}else s.type==="blob"&&(s.oid=await iN(t,r,e,s.path,s.oid),s.mode=33188);return s.path=s.path.split("/").pop(),s}return Promise.all(i.map(n))}async function YE({fs:t,dir:e,gitdir:r,treePair:i}){let n=i[1]==="stage",s=i.map(h=>typeof h=="string"?rN[h]():h),a=[],u=await Jn({fs:t,cache:{},dir:e,gitdir:r,trees:s,map:async(h,[p,g])=>{if(!(h==="."||await Ls.isIgnored({fs:t,dir:e,gitdir:r,filepath:h}))&&g)return(!p||await p.oid()!==await g.oid()&&await g.oid()!==void 0)&&a.push([p,g]),{mode:await g.mode(),path:h,oid:await g.oid(),type:await g.type()}},reduce:async(h,p)=>(p=p.filter(Boolean),h?(h.children=p,h):p.length>0?p:void 0),iterate:async(h,p)=>{let g=[];for(let v of p){let[b,_]=v;n?_&&(await t.exists(`${e}/${_.toString()}`)?g.push(v):a.push([null,_])):b&&(_?g.push(v):a.push([b,null]))}return g.length?Promise.all(g.map(h)):[]}});if(a.length===0||u.length===0)return null;let d=(await nN({fs:t,dir:e,gitdir:r,entries:u})).filter(Boolean).map(h=>({mode:h.mode,path:h.path,oid:h.oid,type:h.type}));return gu({fs:t,gitdir:r,tree:d})}async function kS({fs:t,dir:e,gitdir:r,stashCommit:i,parentCommit:n,wasStaged:s}){let a=[],o=[],l=await Jn({fs:t,cache:{},dir:e,gitdir:r,trees:[Dr({ref:n}),Dr({ref:i})],map:async(c,[u,f])=>{if(c==="."||await Ls.isIgnored({fs:t,dir:e,gitdir:r,filepath:c}))return;let d=f?await f.type():await u.type();if(d!=="tree"&&d!=="blob")return;if(!f&&u){let p=d==="tree"?"rmdir":"rm";return d==="tree"&&a.push(c),d==="blob"&&s&&o.push({filepath:c,oid:await u.oid()}),{method:p,filepath:c}}let h=await f.oid();if(!u||await u.oid()!==h)return d==="tree"?{method:"mkdir",filepath:c}:(s&&o.push({filepath:c,oid:h,stats:await t.lstat(N(e,c))}),{method:"write",filepath:c,oid:h})}});await rl({fs:t,gitdir:r,dirRemoved:a,ops:l},async()=>{for(let c of l){let u=N(e,c.filepath);switch(c.method){case"rmdir":await t.rmdir(u);break;case"mkdir":await fu(t,e,c.filepath),await t.mkdir(u);break;case"rm":await t.rm(u);break;case"write":if(!a.some(f=>u.startsWith(f))){await fu(t,e,c.filepath);let{object:f}=await st({fs:t,cache:{},gitdir:r,oid:c.oid});await t.exists(u)&&await t.rm(u),await t.write(u,f)}break}}}),await gt.acquire({fs:t,gitdir:r,cache:{}},async c=>{o.forEach(({filepath:u,stats:f,oid:d})=>{c.insert({filepath:u,stats:f,oid:d})})})}async function ZE({fs:t,cache:e,dir:r,gitdir:i,oid:n,dryRun:s=!1,noUpdateBranch:a=!1,abortOnConflict:o=!0,committer:l,mergeDriver:c}){let{commit:u,oid:f}=await xn({fs:t,cache:e,gitdir:i,oid:n});if(u.parent.length>1)throw new Kc(f,u.parent.length);if(u.parent.length===0)throw new Xc(f);let d=await q.resolve({fs:t,gitdir:i,ref:"HEAD"}),{commit:h}=await xn({fs:t,cache:e,gitdir:i,oid:d}),p=u.parent[0],{commit:g}=await xn({fs:t,cache:e,gitdir:i,oid:p}),v=await gt.acquire({fs:t,gitdir:i,cache:e,allowUnmerged:!1},async _=>SS({fs:t,cache:e,dir:r,gitdir:i,index:_,ourOid:h.tree,baseOid:g.tree,theirOid:u.tree,ourName:"HEAD",baseName:`parent of ${f.slice(0,7)}`,theirName:f.slice(0,7),dryRun:s,abortOnConflict:o,mergeDriver:c}));if(v instanceof ka)throw v;let b=await pu({fs:t,cache:e,gitdir:i,message:u.message,tree:v,parent:[d],author:u.author,committer:l,dryRun:s,noUpdateBranch:a});return r&&!s&&!a&&await kS({fs:t,dir:r,gitdir:i,stashCommit:b,parentCommit:d,wasStaged:!0}),b}async function sN({fs:t,dir:e,gitdir:r=N(e,".git"),oid:i,cache:n={},committer:s,dryRun:a=!1,noUpdateBranch:o=!1,abortOnConflict:l=!0,mergeDriver:c}){try{R("fs",t),R("gitdir",r),R("oid",i);let u=new te(t),f=await ie({fsp:u,dotgit:r}),{commit:d}=await xn({fs:u,cache:n,gitdir:f,oid:i});if(d.parent&&d.parent.length>1)return await ZE({fs:u,cache:n,dir:e,gitdir:f,oid:i,dryRun:a,noUpdateBranch:o,abortOnConflict:l,committer:void 0,mergeDriver:c});let h=await Ta({fs:u,gitdir:f,committer:s});if(!h)throw new Jt("committer");return await ZE({fs:u,cache:n,dir:e,gitdir:f,oid:i,dryRun:a,noUpdateBranch:o,abortOnConflict:l,committer:h,mergeDriver:c})}catch(u){throw u.caller="git.cherryPick",u}}var aN=/^refs\/(heads\/|tags\/|remotes\/)?(.*)/;function xa(t){let e=aN.exec(t);return e?e[1]==="remotes/"&&t.endsWith("/HEAD")?e[2].slice(0,-5):e[2]:t}async function Bs({fs:t,gitdir:e,fullname:r=!1,test:i=!1}){let n=await q.resolve({fs:t,gitdir:e,ref:"HEAD",depth:2});if(i)try{await q.resolve({fs:t,gitdir:e,ref:n})}catch(s){return}if(n.startsWith("refs/"))return r?n:xa(n)}function oN(t){return t=t.replace(/^git@([^:]+):/,"https://$1/"),t=t.replace(/^ssh:\/\//,"https://"),t}function CS({username:t="",password:e=""}){return`Basic ${k.from(`${t}:${e}`).toString("base64")}`}async function vu(t,e){let r=dS(t);for(;;){let{value:i,done:n}=await r.next();if(i&&await e(i),n)break}r.return&&r.return()}async function Rd(t){let e=0,r=[];await vu(t,s=>{r.push(s),e+=s.byteLength});let i=new Uint8Array(e),n=0;for(let s of r)i.set(s,n),n+=s.byteLength;return i}function KE(t){let e=t.match(/^https?:\/\/([^/]+)@/);if(e==null)return{url:t,auth:{}};e=e[1];let[r,i]=e.split(":");return t=t.replace(`${e}@`,""),{url:t,auth:{username:r,password:i}}}function nv(t,e){let r=e.toString(16);return"0".repeat(t-r.length)+r}var dt=class{static flush(){return k.from("0000","utf8")}static delim(){return k.from("0001","utf8")}static encode(e){typeof e=="string"&&(e=k.from(e));let r=e.length+4,i=nv(4,r);return k.concat([k.from(i,"utf8"),e])}static streamReader(e){let r=new Ad(e);return async function(){try{let n=await r.read(4);if(n==null)return!0;if(n=parseInt(n.toString("utf8"),16),n===0||n===1)return null;let s=await r.read(n-4);return s==null?!0:s}catch(n){return e.error=n,!0}}}};async function XE(t){let e={},r;for(;r=await t(),r!==!0;){if(r===null)continue;r=r.toString("utf8").replace(/\n$/,"");let i=r.indexOf("=");if(i>-1){let n=r.slice(0,i),s=r.slice(i+1);e[n]=s}else e[r]=!0}return{protocolVersion:2,capabilities2:e}}async function QE(t,{service:e}){let r=new Set,i=new Map,n=new Map,s=dt.streamReader(t),a=await s();for(;a===null;)a=await s();if(a===!0)throw new eu;if(a.includes("version 2"))return XE(s);if(a.toString("utf8").replace(/\n$/,"")!==`# service=${e}`)throw new Aa(`# service=${e}\\n`,a.toString("utf8"));let o=await s();for(;o===null;)o=await s();if(o===!0)return{capabilities:r,refs:i,symrefs:n};if(o=o.toString("utf8"),o.includes("version 2"))return XE(s);let[l,c]=Vg(o,"\0","\\x00");if(c.split(" ").map(u=>r.add(u)),l!=="0000000000000000000000000000000000000000 capabilities^{}"){let[u,f]=Vg(l," "," ");for(i.set(f,u);;){let d=await s();if(d===!0)break;if(d!==null){let[h,p]=Vg(d.toString("utf8")," "," ");i.set(p,h)}}}for(let u of r)if(u.startsWith("symref=")){let f=u.match(/symref=([^:]+):(.*)/);f.length===3&&n.set(f[1],f[2])}return{protocolVersion:1,capabilities:r,refs:i,symrefs:n}}function Vg(t,e,r){let i=t.trim().split(e);if(i.length!==2)throw new Aa(`Two strings separated by '${r}'`,t.toString("utf8"));return i}var JE=(t,e)=>t.endsWith("?")?`${t}${e}`:`${t}/${e.replace(/^https?:\/\//,"")}`,eS=(t,e)=>{(e.username||e.password)&&(t.Authorization=CS(e)),e.headers&&Object.assign(t,e.headers)},zg=async t=>{try{let e=k.from(await Rd(t.body)),r=e.toString("utf8");return{preview:r.length<256?r:r.slice(0,256)+"...",response:r,data:e}}catch(e){return{}}},il=class{static async capabilities(){return["discover","connect"]}static async discover({http:e,onProgress:r,onAuth:i,onAuthSuccess:n,onAuthFailure:s,corsProxy:a,service:o,url:l,headers:c,protocolVersion:u}){let{url:f,auth:d}=KE(l),h=a?JE(a,f):f;(d.username||d.password)&&(c.Authorization=CS(d)),u===2&&(c["Git-Protocol"]="version=2");let p,g,v=!1;do if(p=await e.request({onProgress:r,method:"GET",url:`${h}/info/refs?service=${o}`,headers:c}),g=!1,p.statusCode===401||p.statusCode===203){let b=v?s:i;if(b){if(d=await b(f,{...d,headers:{...c}}),d&&d.cancel)throw new el;d&&(eS(c,d),v=!0,g=!0)}}else p.statusCode===200&&v&&n&&await n(f,d);while(g);if(p.statusCode!==200){let{response:b}=await zg(p);throw new Xo(p.statusCode,p.statusMessage,b)}if(p.headers["content-type"]===`application/x-${o}-advertisement`){let b=await QE(p.body,{service:o});return b.auth=d,b}else{let{preview:b,response:_,data:C}=await zg(p);try{let x=await QE([C],{service:o});return x.auth=d,x}catch(x){throw new nu(b,_)}}}static async connect({http:e,onProgress:r,corsProxy:i,service:n,url:s,auth:a,body:o,headers:l}){let c=KE(s);c&&(s=c.url),i&&(s=JE(i,s)),l["content-type"]=`application/x-${n}-request`,l.accept=`application/x-${n}-result`,eS(l,a);let u=await e.request({onProgress:r,method:"POST",url:`${s}/${n}`,body:o,headers:l});if(u.statusCode!==200){let{response:f}=zg(u);throw new Xo(u.statusCode,u.statusMessage,f)}return u}},nl=class{static getRemoteHelperFor({url:e}){let r=new Map;r.set("http",il),r.set("https",il);let i=lN({url:e});if(!i)throw new au(e);if(r.has(i.transport))return r.get(i.transport);throw new su(e,i.transport,i.transport==="ssh"?oN(e):void 0)}};function lN({url:t}){if(t.startsWith("git@"))return{transport:"ssh",address:t};let e=t.match(/(\w+)(:\/\/|::)(.*)/);if(e!==null){if(e[2]==="://")return{transport:e[1],address:e[0]};if(e[2]==="::")return{transport:e[1],address:e[3]}}}var ya=null,Pa=class{static async read({fs:e,gitdir:r}){ya===null&&(ya=new Yo.default);let i=N(r,"shallow"),n=new Set;return await ya.acquire(i,async function(){let s=await e.read(i,{encoding:"utf8"});if(s===null||s.trim()==="")return n;s.trim().split(` +`).map(a=>n.add(a))}),n}static async write({fs:e,gitdir:r,oids:i}){ya===null&&(ya=new Yo.default);let n=N(r,"shallow");if(i.size>0){let s=[...i].join(` +`)+` +`;await ya.acquire(n,async function(){await e.write(n,s,{encoding:"utf8"})})}else await ya.acquire(n,async function(){await e.rm(n)})}};async function cN({fs:t,gitdir:e,oid:r}){let i=`objects/${r.slice(0,2)}/${r.slice(2)}`;return t.exists(`${e}/${i}`)}async function uN({fs:t,cache:e,gitdir:r,oid:i,getExternalRefDelta:n}){let s=await t.readdir(N(r,"objects/pack"));s=s.filter(a=>a.endsWith(".idx"));for(let a of s){let o=`${r}/objects/pack/${a}`,l=await av({fs:t,cache:e,filename:o,getExternalRefDelta:n});if(l.error)throw new he(l.error);if(l.offsets.has(i))return!0}return!1}async function tS({fs:t,cache:e,gitdir:r,oid:i,format:n="content"}){let s=o=>st({fs:t,cache:e,gitdir:r,oid:o}),a=await cN({fs:t,gitdir:r,oid:i});return a||(a=await uN({fs:t,cache:e,gitdir:r,oid:i,getExternalRefDelta:s})),a}function $d({config:t,onAuth:e}){return e&&(async(r,i)=>{let n=i.username||await t.get(`credential.${r}.username`);return e(r,n?{...i,username:n}:i)})}function fN(t){let n="5041434b"+"00000002"+"00000000";return t.slice(0,12).toString("hex")===n}function AS(t,e){let r=t.map(i=>i.split("=",1)[0]);return e.filter(i=>{let n=i.split("=",1)[0];return r.includes(n)})}var Ld={name:"isomorphic-git",version:"1.40.0",agent:"git/isomorphic-git@1.40.0"},qo=class{constructor(){this._queue=[]}write(e){if(this._ended)throw Error("You cannot write to a FIFO that has already been ended!");if(this._waiting){let r=this._waiting;this._waiting=null,r({value:e})}else this._queue.push(e)}end(){if(this._ended=!0,this._waiting){let e=this._waiting;this._waiting=null,e({done:!0})}}destroy(e){this.error=e,this.end()}async next(){if(this._queue.length>0)return{value:this._queue.shift()};if(this._ended)return{done:!0};if(this._waiting)throw Error("You cannot call read until the previous call to read has returned!");return new Promise(e=>{this._waiting=e})}};function dN(t){let e=t.indexOf("\r"),r=t.indexOf(` +`);return e===-1&&r===-1?-1:e===-1?r+1:r===-1?e+1:r===e+1?r+1:Math.min(e,r)+1}function TS(t){let e=new qo,r="";return(async()=>(await vu(t,i=>{for(i=i.toString("utf8"),r+=i;;){let n=dN(r);if(n===-1)break;e.write(r.slice(0,n)),r=r.slice(n)}}),r.length>0&&e.write(r),e.end()))(),e}var Fd=class{static demux(e){let r=dt.streamReader(e),i=new qo,n=new qo,s=new qo,a=async function(){let o=await r();if(o===null)return a();if(o===!0){i.end(),s.end(),e.error?n.destroy(e.error):n.end();return}switch(o[0]){case 1:{n.write(o.slice(1));break}case 2:{s.write(o.slice(1));break}case 3:{let l=o.slice(1);s.write(l),i.end(),s.end(),n.destroy(new Error(l.toString("utf8")));return}default:i.write(o)}a()};return a(),{packetlines:i,packfile:n,progress:s}}};async function hN(t){let{packetlines:e,packfile:r,progress:i}=Fd.demux(t),n=[],s=[],a=[],o=!1,l=!1;return new Promise((c,u)=>{vu(e,f=>{let d=f.toString("utf8").trim();if(d.startsWith("shallow")){let h=d.slice(-41).trim();h.length!==40&&u(new Ms(h)),n.push(h)}else if(d.startsWith("unshallow")){let h=d.slice(-41).trim();h.length!==40&&u(new Ms(h)),s.push(h)}else if(d.startsWith("ACK")){let[,h,p]=d.split(" ");a.push({oid:h,status:p}),p||(l=!0)}else d.startsWith("NAK")?(o=!0,l=!0):(l=!0,o=!0);l&&(t.error?u(t.error):c({shallows:n,unshallows:s,acks:a,nak:o,packfile:r,progress:i}))}).finally(()=>{l||(t.error?u(t.error):c({shallows:n,unshallows:s,acks:a,nak:o,packfile:r,progress:i}))})})}function pN({capabilities:t=[],wants:e=[],haves:r=[],shallows:i=[],depth:n=null,since:s=null,exclude:a=[]}){let o=[];e=[...new Set(e)];let l=` ${t.join(" ")}`;for(let c of e)o.push(dt.encode(`want ${c}${l} +`)),l="";for(let c of i)o.push(dt.encode(`shallow ${c} +`));n!==null&&o.push(dt.encode(`deepen ${n} +`)),s!==null&&o.push(dt.encode(`deepen-since ${Math.floor(s.valueOf()/1e3)} +`));for(let c of a)o.push(dt.encode(`deepen-not ${c} +`));o.push(dt.flush());for(let c of r)o.push(dt.encode(`have ${c} +`));return o.push(dt.encode(`done +`)),o}async function lv({fs:t,cache:e,http:r,onProgress:i,onMessage:n,onAuth:s,onAuthSuccess:a,onAuthFailure:o,gitdir:l,ref:c,remoteRef:u,remote:f,url:d,corsProxy:h,depth:p=null,since:g=null,exclude:v=[],relative:b=!1,tags:_=!1,singleBranch:C=!1,headers:x={},prune:E=!1,pruneTags:A=!1}){let w=c||await Bs({fs:t,gitdir:l,test:!0}),S=await vt.get({fs:t,gitdir:l}),y=f||w&&await S.get(`branch.${w}.remote`)||"origin",P=d||await S.get(`remote.${y}.url`);if(typeof P=="undefined")throw new Or("remote OR url");let T=u||w&&await S.get(`branch.${w}.merge`)||c||"HEAD";h===void 0&&(h=await S.get("http.corsProxy"));let I=nl.getRemoteHelperFor({url:P}),M=await I.discover({http:r,onAuth:$d({config:S,onAuth:s}),onAuthSuccess:a,onAuthFailure:$d({config:S,onAuth:o}),corsProxy:h,service:"git-upload-pack",url:P,headers:x,protocolVersion:1}),B=M.auth,re=M.refs;if(re.size===0)return{defaultBranch:null,fetchHead:null,fetchHeadDescription:null};if(p!==null&&!M.capabilities.has("shallow"))throw new Is("shallow","depth");if(g!==null&&!M.capabilities.has("deepen-since"))throw new Is("deepen-since","since");if(v.length>0&&!M.capabilities.has("deepen-not"))throw new Is("deepen-not","exclude");if(b===!0&&!M.capabilities.has("deepen-relative"))throw new Is("deepen-relative","relative");let{oid:Ae,fullref:K}=q.resolveAgainstMap({ref:T,map:re});for(let L of re.keys())L===K||L==="HEAD"||L.startsWith("refs/heads/")||_&&L.startsWith("refs/tags/")||re.delete(L);let Q=AS([...M.capabilities],["multi_ack_detailed","no-done","side-band-64k","ofs-delta",`agent=${Ld.agent}`]);b&&Q.push("deepen-relative");let fe=C?[Ae]:re.values(),ce=C?[w]:await q.listRefs({fs:t,gitdir:l,filepath:"refs"}),z=[];for(let L of ce)try{L=await q.expand({fs:t,gitdir:l,ref:L});let W=await q.resolve({fs:t,gitdir:l,ref:L});await tS({fs:t,cache:e,gitdir:l,oid:W})&&z.push(W)}catch(W){}z=[...new Set(z)];let X=await Pa.read({fs:t,gitdir:l}),j=M.capabilities.has("shallow")?[...X]:[],Ze=pN({capabilities:Q,wants:fe,haves:z,shallows:j,depth:p,since:g,exclude:v}),$r=k.from(await Rd(Ze)),cr=await I.connect({http:r,onProgress:i,corsProxy:h,service:"git-upload-pack",url:P,auth:B,body:[$r],headers:x}),Ie=await hN(cr.body);cr.headers&&(Ie.headers=cr.headers);for(let L of Ie.shallows)if(!X.has(L))try{let{object:W}=await st({fs:t,cache:e,gitdir:l,oid:L}),xe=new Nr(W),Xe=await Promise.all(xe.headers().parent.map(ti=>tS({fs:t,cache:e,gitdir:l,oid:ti})));Xe.length===0||Xe.every(ti=>ti)||X.add(L)}catch(W){X.add(L)}for(let L of Ie.unshallows)X.delete(L);if(await Pa.write({fs:t,gitdir:l,oids:X}),C){let L=new Map([[K,Ae]]),W=new Map,xe=10,Xe=K;for(;xe--;){let aa=M.symrefs.get(Xe);if(aa===void 0)break;W.set(Xe,aa),Xe=aa}let Dt=re.get(Xe);Dt&&L.set(Xe,Dt);let{pruned:ti}=await q.updateRemoteRefs({fs:t,gitdir:l,remote:y,refs:L,symrefs:W,tags:_,prune:E});E&&(Ie.pruned=ti)}else{let{pruned:L}=await q.updateRemoteRefs({fs:t,gitdir:l,remote:y,refs:re,symrefs:M.symrefs,tags:_,prune:E,pruneTags:A});E&&(Ie.pruned=L)}if(Ie.HEAD=M.symrefs.get("HEAD"),Ie.HEAD===void 0){let{oid:L}=q.resolveAgainstMap({ref:"HEAD",map:re});for(let[W,xe]of re.entries())if(W!=="HEAD"&&xe===L){Ie.HEAD=W;break}}let yt=K.startsWith("refs/tags")?"tag":"branch";if(Ie.FETCH_HEAD={oid:Ae,description:`${yt} '${xa(K)}' of ${P}`},i||n){let L=TS(Ie.progress);vu(L,async W=>{if(n&&await n(W),i){let xe=W.match(/([^:]*).*\((\d+?)\/(\d+?)\)/);xe&&await i({phase:xe[1].trim(),loaded:parseInt(xe[2],10),total:parseInt(xe[3],10)})}})}let Tt=k.from(await Rd(Ie.packfile));if(cr.body.error)throw cr.body.error;let Ke=Tt.slice(-20).toString("hex"),J={defaultBranch:Ie.HEAD,fetchHead:Ie.FETCH_HEAD.oid,fetchHeadDescription:Ie.FETCH_HEAD.description};if(Ie.headers&&(J.headers=Ie.headers),E&&(J.pruned=Ie.pruned),Ke!==""&&!fN(Tt)){J.packfile=`objects/pack/pack-${Ke}.pack`;let L=N(l,J.packfile);await t.write(L,Tt);let W=Xe=>st({fs:t,cache:e,gitdir:l,oid:Xe}),xe=await qc.fromPack({pack:Tt,getExternalRefDelta:W,onProgress:i});await t.write(L.replace(/\.pack$/,".idx"),await xe.toBuffer())}return J}async function PS({fs:t,bare:e=!1,dir:r,gitdir:i=e?r:N(r,".git"),defaultBranch:n="master"}){if(await t.exists(i+"/config"))return;let s=["hooks","info","objects/info","objects/pack","refs/heads","refs/tags"];s=s.map(a=>i+"/"+a);for(let a of s)await t.mkdir(a);await t.write(i+"/config",`[core] + repositoryformatversion = 0 + filemode = false + bare = ${e} +`+(e?"":` logallrefupdates = true +`)+` symlinks = false + ignorecase = true +`),await t.write(i+"/HEAD",`ref: refs/heads/${n} +`)}async function mN({fs:t,cache:e,http:r,onProgress:i,onMessage:n,onAuth:s,onAuthSuccess:a,onAuthFailure:o,onPostCheckout:l,dir:c,gitdir:u,url:f,corsProxy:d,ref:h,remote:p,depth:g,since:v,exclude:b,relative:_,singleBranch:C,noCheckout:x,noTags:E,headers:A,nonBlocking:w,batchSize:S=100}){try{if(await PS({fs:t,gitdir:u}),await yS({fs:t,gitdir:u,remote:p,url:f,force:!1}),d){let T=await vt.get({fs:t,gitdir:u});await T.set("http.corsProxy",d),await vt.save({fs:t,gitdir:u,config:T})}let{defaultBranch:y,fetchHead:P}=await lv({fs:t,cache:e,http:r,onProgress:i,onMessage:n,onAuth:s,onAuthSuccess:a,onAuthFailure:o,gitdir:u,ref:h,remote:p,corsProxy:d,depth:g,since:v,exclude:b,relative:_,singleBranch:C,headers:A,tags:!E});if(P===null)return;h=h||y,h=h.replace("refs/heads/",""),await ov({fs:t,cache:e,onProgress:i,onPostCheckout:l,dir:c,gitdir:u,ref:h,remote:p,noCheckout:x,nonBlocking:w,batchSize:S})}catch(y){throw await t.rmdir(u,{recursive:!0,maxRetries:10}).catch(()=>{}),y}}async function gN({fs:t,http:e,onProgress:r,onMessage:i,onAuth:n,onAuthSuccess:s,onAuthFailure:a,onPostCheckout:o,dir:l,gitdir:c=N(l,".git"),url:u,corsProxy:f=void 0,ref:d=void 0,remote:h="origin",depth:p=void 0,since:g=void 0,exclude:v=[],relative:b=!1,singleBranch:_=!1,noCheckout:C=!1,noTags:x=!1,headers:E={},cache:A={},nonBlocking:w=!1,batchSize:S=100}){try{R("fs",t),R("http",e),R("gitdir",c),C||R("dir",l),R("url",u);let y=new te(t),P=await ie({fsp:y,dotgit:c});return await mN({fs:y,cache:A,http:e,onProgress:r,onMessage:i,onAuth:n,onAuthSuccess:s,onAuthFailure:a,onPostCheckout:o,dir:l,gitdir:P,url:u,corsProxy:f,ref:d,remote:h,depth:p,since:g,exclude:v,relative:b,singleBranch:_,noCheckout:C,noTags:x,headers:E,nonBlocking:w,batchSize:S})}catch(y){throw y.caller="git.clone",y}}async function vN({fs:t,onSign:e,dir:r,gitdir:i=N(r,".git"),message:n,author:s,committer:a,signingKey:o,amend:l=!1,dryRun:c=!1,noUpdateBranch:u=!1,disallowEmpty:f=!1,ref:d,parent:h,tree:p,cache:g={}}){try{R("fs",t),l||R("message",n),o&&R("onSign",e);let v=new te(t),b=await ie({fsp:v,dotgit:i});return await pu({fs:v,cache:g,onSign:e,gitdir:b,message:n,author:s,committer:a,signingKey:o,amend:l,dryRun:c,noUpdateBranch:u,disallowEmpty:f,ref:d,parent:h,tree:p})}catch(v){throw v.caller="git.commit",v}}async function wN({fs:t,dir:e,gitdir:r=N(e,".git"),fullname:i=!1,test:n=!1}){try{R("fs",t),R("gitdir",r);let s=new te(t),a=await ie({fsp:s,dotgit:r});return await Bs({fs:s,gitdir:a,fullname:i,test:n})}catch(s){throw s.caller="git.currentBranch",s}}async function bN({fs:t,gitdir:e,ref:r}){if(r=r.startsWith("refs/heads/")?r:`refs/heads/${r}`,!await q.exists({fs:t,gitdir:e,ref:r}))throw new ze(r);let n=await q.expand({fs:t,gitdir:e,ref:r}),s=await Bs({fs:t,gitdir:e,fullname:!0});if(n===s){let l=await q.resolve({fs:t,gitdir:e,ref:n});await q.writeRef({fs:t,gitdir:e,ref:"HEAD",value:l})}await q.deleteRef({fs:t,gitdir:e,ref:n});let a=xa(r),o=await vt.get({fs:t,gitdir:e});await o.deleteSection("branch",a),await vt.save({fs:t,gitdir:e,config:o})}async function _N({fs:t,dir:e,gitdir:r=N(e,".git"),ref:i}){try{R("fs",t),R("ref",i);let n=new te(t),s=await ie({fsp:n,dotgit:r});return await bN({fs:n,gitdir:s,ref:i})}catch(n){throw n.caller="git.deleteBranch",n}}async function yN({fs:t,dir:e,gitdir:r=N(e,".git"),ref:i}){try{R("fs",t),R("ref",i);let n=new te(t),s=await ie({fsp:n,dotgit:r});await q.deleteRef({fs:n,gitdir:s,ref:i})}catch(n){throw n.caller="git.deleteRef",n}}async function xN({fs:t,gitdir:e,remote:r}){let i=await vt.get({fs:t,gitdir:e});await i.deleteSection("remote",r),await vt.save({fs:t,gitdir:e,config:i})}async function EN({fs:t,dir:e,gitdir:r=N(e,".git"),remote:i}){try{R("fs",t),R("remote",i);let n=new te(t),s=await ie({fsp:n,dotgit:r});return await xN({fs:n,gitdir:s,remote:i})}catch(n){throw n.caller="git.deleteRemote",n}}async function SN({fs:t,gitdir:e,ref:r}){r=r.startsWith("refs/tags/")?r:`refs/tags/${r}`,await q.deleteRef({fs:t,gitdir:e,ref:r})}async function kN({fs:t,dir:e,gitdir:r=N(e,".git"),ref:i}){try{R("fs",t),R("ref",i);let n=new te(t),s=await ie({fsp:n,dotgit:r});return await SN({fs:n,gitdir:s,ref:i})}catch(n){throw n.caller="git.deleteTag",n}}async function CN({fs:t,gitdir:e,oid:r}){let i=r.slice(0,2);return(await t.readdir(`${e}/objects/${i}`)).map(s=>`${i}${s}`).filter(s=>s.startsWith(r))}async function AN({fs:t,cache:e,gitdir:r,oid:i,getExternalRefDelta:n}){let s=[],a=await t.readdir(N(r,"objects/pack"));a=a.filter(o=>o.endsWith(".idx"));for(let o of a){let l=`${r}/objects/pack/${o}`,c=await av({fs:t,cache:e,filename:l,getExternalRefDelta:n});if(c.error)throw new he(c.error);for(let u of c.offsets.keys())u.startsWith(i)&&s.push(u)}return s}async function TN({fs:t,cache:e,gitdir:r,oid:i}){let n=o=>st({fs:t,cache:e,gitdir:r,oid:o}),s=await CN({fs:t,gitdir:r,oid:i}),a=await AN({fs:t,cache:e,gitdir:r,oid:i,getExternalRefDelta:n});for(let o of a)s.indexOf(o)===-1&&s.push(o);if(s.length===1)return s[0];throw s.length>1?new Yc("oids",i,s):new ze(`an object matching "${i}"`)}async function PN({fs:t,dir:e,gitdir:r=N(e,".git"),oid:i,cache:n={}}){try{R("fs",t),R("gitdir",r),R("oid",i);let s=new te(t),a=await ie({fsp:s,dotgit:r});return await TN({fs:s,cache:n,gitdir:a,oid:i})}catch(s){throw s.caller="git.expandOid",s}}async function RN({fs:t,dir:e,gitdir:r=N(e,".git"),ref:i}){try{R("fs",t),R("gitdir",r),R("ref",i);let n=new te(t),s=await ie({fsp:n,dotgit:r});return await q.expand({fs:n,gitdir:s,ref:i})}catch(n){throw n.caller="git.expandRef",n}}async function cv({fs:t,cache:e,gitdir:r,oids:i}){let n={},s=i.length,a=i.map((o,l)=>({index:l,oid:o}));for(;a.length;){let o=new Set;for(let{oid:c,index:u}of a)n[c]||(n[c]=new Set),n[c].add(u),n[c].size===s&&o.add(c);if(o.size>0)return[...o];let l=new Map;for(let{oid:c,index:u}of a)try{let{object:f}=await st({fs:t,cache:e,gitdir:r,oid:c}),d=Nr.from(f),{parent:h}=d.parseHeaders();for(let p of h)(!n[p]||!n[p].has(u))&&l.set(p+":"+u,{oid:p,index:u})}catch(f){}a=Array.from(l.values())}return[]}async function RS({fs:t,cache:e,dir:r,gitdir:i,ours:n,theirs:s,fastForward:a=!0,fastForwardOnly:o=!1,dryRun:l=!1,noUpdateBranch:c=!1,abortOnConflict:u=!0,message:f,author:d,committer:h,signingKey:p,onSign:g,mergeDriver:v,allowUnrelatedHistories:b=!1}){n===void 0&&(n=await Bs({fs:t,gitdir:i,fullname:!0})),n=await q.expand({fs:t,gitdir:i,ref:n}),s=await q.expand({fs:t,gitdir:i,ref:s});let _=await q.resolve({fs:t,gitdir:i,ref:n}),C=await q.resolve({fs:t,gitdir:i,ref:s}),x=await cv({fs:t,cache:e,gitdir:i,oids:[_,C]});if(x.length!==1)if(x.length===0&&b)x.push("4b825dc642cb6eb9a060e54bf8d69288fbee4904");else throw new Qo;let E=x[0];if(E===C)return{oid:_,alreadyMerged:!0};if(a&&E===_)return!l&&!c&&await q.writeRef({fs:t,gitdir:i,ref:n,value:C}),{oid:C,fastForward:!0};{if(o)throw new tu;let A=await gt.acquire({fs:t,gitdir:i,cache:e,allowUnmerged:!1},async S=>SS({fs:t,cache:e,dir:r,gitdir:i,index:S,ourOid:_,theirOid:C,baseOid:E,ourName:xa(n),baseName:"base",theirName:xa(s),dryRun:l,abortOnConflict:u,mergeDriver:v}));if(A instanceof ka)throw A;return f||(f=`Merge branch '${xa(s)}' into ${xa(n)}`),{oid:await pu({fs:t,cache:e,gitdir:i,message:f,ref:n,tree:A,parent:[_,C],author:d,committer:h,signingKey:p,onSign:g,dryRun:l,noUpdateBranch:c}),tree:A,mergeCommit:!0}}}async function $S({fs:t,cache:e,http:r,onProgress:i,onMessage:n,onAuth:s,onAuthSuccess:a,onAuthFailure:o,dir:l,gitdir:c,ref:u,url:f,remote:d,remoteRef:h,prune:p,pruneTags:g,fastForward:v,fastForwardOnly:b,corsProxy:_,singleBranch:C,headers:x,author:E,committer:A,signingKey:w}){try{if(!u){let P=await Bs({fs:t,gitdir:c});if(!P)throw new Or("ref");u=P}let{fetchHead:S,fetchHeadDescription:y}=await lv({fs:t,cache:e,http:r,onProgress:i,onMessage:n,onAuth:s,onAuthSuccess:a,onAuthFailure:o,gitdir:c,corsProxy:_,ref:u,url:f,remote:d,remoteRef:h,singleBranch:C,headers:x,prune:p,pruneTags:g});await RS({fs:t,cache:e,gitdir:c,ours:u,theirs:S,fastForward:v,fastForwardOnly:b,message:`Merge ${y}`,author:E,committer:A,signingKey:w,dryRun:!1,noUpdateBranch:!1}),await ov({fs:t,cache:e,onProgress:i,dir:l,gitdir:c,ref:u,remote:d,noCheckout:!1})}catch(S){throw S.caller="git.pull",S}}async function $N({fs:t,http:e,onProgress:r,onMessage:i,onAuth:n,onAuthSuccess:s,onAuthFailure:a,dir:o,gitdir:l=N(o,".git"),ref:c,url:u,remote:f,remoteRef:d,corsProxy:h,singleBranch:p,headers:g={},cache:v={}}){try{R("fs",t),R("http",e),R("gitdir",l);let b={name:"",email:"",timestamp:Date.now(),timezoneOffset:0},_=new te(t),C=await ie({fsp:_,dotgit:l});return await $S({fs:_,cache:v,http:e,onProgress:r,onMessage:i,onAuth:n,onAuthSuccess:s,onAuthFailure:a,dir:o,gitdir:C,ref:c,url:u,remote:f,remoteRef:d,fastForwardOnly:!0,corsProxy:h,singleBranch:p,headers:g,author:b,committer:b})}catch(b){throw b.caller="git.fastForward",b}}async function FN({fs:t,http:e,onProgress:r,onMessage:i,onAuth:n,onAuthSuccess:s,onAuthFailure:a,dir:o,gitdir:l=N(o,".git"),ref:c,remote:u,remoteRef:f,url:d,corsProxy:h,depth:p=null,since:g=null,exclude:v=[],relative:b=!1,tags:_=!1,singleBranch:C=!1,headers:x={},prune:E=!1,pruneTags:A=!1,cache:w={}}){try{R("fs",t),R("http",e),R("gitdir",l);let S=new te(t),y=await ie({fsp:S,dotgit:l});return await lv({fs:S,cache:w,http:e,onProgress:r,onMessage:i,onAuth:n,onAuthSuccess:s,onAuthFailure:a,gitdir:y,ref:c,remote:u,remoteRef:f,url:d,corsProxy:h,depth:p,since:g,exclude:v,relative:b,tags:_,singleBranch:C,headers:x,prune:E,pruneTags:A})}catch(S){throw S.caller="git.fetch",S}}async function IN({fs:t,dir:e,gitdir:r=N(e,".git"),oids:i,cache:n={}}){try{R("fs",t),R("gitdir",r),R("oids",i);let s=new te(t),a=await ie({fsp:s,dotgit:r});return await cv({fs:s,cache:n,gitdir:a,oids:i})}catch(s){throw s.caller="git.findMergeBase",s}}async function FS({fs:t,filepath:e}){if(await t.exists(N(e,".git")))return e;{let r=Sa(e);if(r===e)throw new ze(`git root for ${e}`);return FS({fs:t,filepath:r})}}async function MN({fs:t,filepath:e}){try{return R("fs",t),R("filepath",e),await FS({fs:new te(t),filepath:e})}catch(r){throw r.caller="git.findRoot",r}}async function DN({fs:t,dir:e,gitdir:r=N(e,".git"),path:i}){try{R("fs",t),R("gitdir",r),R("path",i);let n=new te(t),s=await ie({fsp:n,dotgit:r});return await cu({fs:n,gitdir:s,path:i})}catch(n){throw n.caller="git.getConfig",n}}async function ON({fs:t,gitdir:e,path:r}){return(await vt.get({fs:t,gitdir:e})).getall(r)}async function LN({fs:t,dir:e,gitdir:r=N(e,".git"),path:i}){try{R("fs",t),R("gitdir",r),R("path",i);let n=new te(t),s=await ie({fsp:n,dotgit:r});return await ON({fs:n,gitdir:s,path:i})}catch(n){throw n.caller="git.getConfigAll",n}}async function NN({http:t,onAuth:e,onAuthSuccess:r,onAuthFailure:i,corsProxy:n,url:s,headers:a={},forPush:o=!1}){try{R("http",t),R("url",s);let c=await nl.getRemoteHelperFor({url:s}).discover({http:t,onAuth:e,onAuthSuccess:r,onAuthFailure:i,corsProxy:n,service:o?"git-receive-pack":"git-upload-pack",url:s,headers:a,protocolVersion:1}),u={capabilities:[...c.capabilities]};for(let[f,d]of c.refs){let h=f.split("/"),p=h.pop(),g=u;for(let v of h)g[v]=g[v]||{},g=g[v];g[p]=d}for(let[f,d]of c.symrefs){let h=f.split("/"),p=h.pop(),g=u;for(let v of h)g[v]=g[v]||{},g=g[v];g[p]=d}return u}catch(l){throw l.caller="git.getRemoteInfo",l}}function IS(t,e,r,i){let n=[];for(let[s,a]of t.refs){if(e&&!s.startsWith(e))continue;if(s.endsWith("^{}")){if(i){let l=s.replace("^{}",""),c=n[n.length-1],u=c.ref===l?c:n.find(f=>f.ref===l);if(u===void 0)throw new Error("I did not expect this to happen");u.peeled=a}continue}let o={ref:s,oid:a};r&&t.symrefs.has(s)&&(o.target=t.symrefs.get(s)),n.push(o)}return n}async function BN({http:t,onAuth:e,onAuthSuccess:r,onAuthFailure:i,corsProxy:n,url:s,headers:a={},forPush:o=!1,protocolVersion:l=2}){try{R("http",t),R("url",s);let u=await nl.getRemoteHelperFor({url:s}).discover({http:t,onAuth:e,onAuthSuccess:r,onAuthFailure:i,corsProxy:n,service:o?"git-receive-pack":"git-upload-pack",url:s,headers:a,protocolVersion:l});if(u.protocolVersion===2)return{protocolVersion:u.protocolVersion,capabilities:u.capabilities2};let f={};for(let d of u.capabilities){let[h,p]=d.split("=");p?f[h]=p:f[h]=!0}return{protocolVersion:1,capabilities:f,refs:IS(u,void 0,!0,!0)}}catch(c){throw c.caller="git.getRemoteInfo2",c}}async function HN({type:t,object:e,format:r="content",oid:i=void 0}){return r!=="deflated"&&(r!=="wrapped"&&(e=Ds.wrap({type:t,object:e})),i=await En(e)),{oid:i,object:e}}async function UN({object:t}){try{R("object",t),typeof t=="string"?t=k.from(t,"utf8"):t instanceof Uint8Array||(t=new Uint8Array(t));let e="blob",{oid:r,object:i}=await HN({type:e,format:"content",object:t});return{oid:r,type:e,object:i,format:"wrapped"}}catch(e){throw e.caller="git.hashBlob",e}}async function GN({fs:t,cache:e,onProgress:r,dir:i,gitdir:n,filepath:s}){try{s=N(i,s);let a=await t.read(s),o=c=>st({fs:t,cache:e,gitdir:n,oid:c}),l=await qc.fromPack({pack:a,getExternalRefDelta:o,onProgress:r});return await t.write(s.replace(/\.pack$/,".idx"),await l.toBuffer()),{oids:[...l.hashes]}}catch(a){throw a.caller="git.indexPack",a}}async function jN({fs:t,onProgress:e,dir:r,gitdir:i=N(r,".git"),filepath:n,cache:s={}}){try{R("fs",t),R("dir",r),R("gitdir",r),R("filepath",n);let a=new te(t),o=await ie({fsp:a,dotgit:i});return await GN({fs:a,cache:s,onProgress:e,dir:r,gitdir:o,filepath:n})}catch(a){throw a.caller="git.indexPack",a}}async function VN({fs:t,bare:e=!1,dir:r,gitdir:i=e?r:N(r,".git"),defaultBranch:n="master"}){try{R("fs",t),R("gitdir",i),e||R("dir",r);let s=new te(t),a=await ie({fsp:s,dotgit:i});return await PS({fs:s,bare:e,dir:r,gitdir:a,defaultBranch:n})}catch(s){throw s.caller="git.init",s}}async function MS({fs:t,cache:e,gitdir:r,oid:i,ancestor:n,depth:s}){let a=await Pa.read({fs:t,gitdir:r});if(!i)throw new Or("oid");if(!n)throw new Or("ancestor");if(i===n)return!1;let o=[i],l=new Set,c=0;for(;o.length;){if(c++===s)throw new iu(s);let u=o.shift(),{type:f,object:d}=await st({fs:t,cache:e,gitdir:r,oid:u});if(f!=="commit")throw new xr(u,f,"commit");let h=Nr.from(d).parse();for(let p of h.parent)if(p===n)return!0;if(!a.has(u))for(let p of h.parent)l.has(p)||(o.push(p),l.add(p))}return!1}async function zN({fs:t,dir:e,gitdir:r=N(e,".git"),oid:i,ancestor:n,depth:s=-1,cache:a={}}){try{R("fs",t),R("gitdir",r),R("oid",i),R("ancestor",n);let o=new te(t),l=await ie({fsp:o,dotgit:r});return await MS({fs:o,cache:a,gitdir:l,oid:i,ancestor:n,depth:s})}catch(o){throw o.caller="git.isDescendent",o}}async function WN({fs:t,dir:e,gitdir:r=N(e,".git"),filepath:i}){try{R("fs",t),R("dir",e),R("gitdir",r),R("filepath",i);let n=new te(t),s=await ie({fsp:n,dotgit:r});return Ls.isIgnored({fs:n,dir:e,gitdir:s,filepath:i})}catch(n){throw n.caller="git.isIgnored",n}}async function qN({fs:t,dir:e,gitdir:r=N(e,".git"),remote:i}){try{R("fs",t),R("gitdir",r);let n=new te(t),s=await ie({fsp:n,dotgit:r});return q.listBranches({fs:n,gitdir:s,remote:i})}catch(n){throw n.caller="git.listBranches",n}}async function YN({fs:t,gitdir:e,ref:r,cache:i}){if(r){let n=await q.resolve({gitdir:e,fs:t,ref:r}),s=[];return await DS({fs:t,cache:i,gitdir:e,oid:n,filenames:s,prefix:""}),s}else return gt.acquire({fs:t,gitdir:e,cache:i},async function(n){return n.entries.map(s=>s.path)})}async function DS({fs:t,cache:e,gitdir:r,oid:i,filenames:n,prefix:s}){let{tree:a}=await al({fs:t,cache:e,gitdir:r,oid:i});for(let o of a)o.type==="tree"?await DS({fs:t,cache:e,gitdir:r,oid:o.oid,filenames:n,prefix:N(s,o.path)}):n.push(N(s,o.path))}async function ZN({fs:t,dir:e,gitdir:r=N(e,".git"),ref:i,cache:n={}}){try{R("fs",t),R("gitdir",r);let s=new te(t),a=await ie({fsp:s,dotgit:r});return await YN({fs:s,cache:n,gitdir:a,ref:i})}catch(s){throw s.caller="git.listFiles",s}}async function KN({fs:t,cache:e,gitdir:r,ref:i}){let n;try{n=await q.resolve({gitdir:r,fs:t,ref:i})}catch(o){if(o instanceof ze)return[]}return(await al({fs:t,cache:e,gitdir:r,oid:n})).tree.map(o=>({target:o.path,note:o.oid}))}async function XN({fs:t,dir:e,gitdir:r=N(e,".git"),ref:i="refs/notes/commits",cache:n={}}){try{R("fs",t),R("gitdir",r),R("ref",i);let s=new te(t),a=await ie({fsp:s,dotgit:r});return await KN({fs:s,cache:n,gitdir:a,ref:i})}catch(s){throw s.caller="git.listNotes",s}}async function QN({fs:t,dir:e,gitdir:r=N(e,".git"),filepath:i}){try{R("fs",t),R("gitdir",r);let n=new te(t),s=await ie({fsp:n,dotgit:r});return q.listRefs({fs:n,gitdir:s,filepath:i})}catch(n){throw n.caller="git.listRefs",n}}async function JN({fs:t,gitdir:e}){let r=await vt.get({fs:t,gitdir:e}),i=await r.getSubsections("remote");return Promise.all(i.map(async s=>{let a=await r.get(`remote.${s}.url`);return{remote:s,url:a}}))}async function eB({fs:t,dir:e,gitdir:r=N(e,".git")}){try{R("fs",t),R("gitdir",r);let i=new te(t),n=await ie({fsp:i,dotgit:r});return await JN({fs:i,gitdir:n})}catch(i){throw i.caller="git.listRemotes",i}}async function tB(t){let e=dt.streamReader(t),r=[],i;for(;i=await e(),i!==!0;){if(i===null)continue;i=i.toString("utf8").replace(/\n$/,"");let[n,s,...a]=i.split(" "),o={ref:s,oid:n};for(let l of a){let[c,u]=l.split(":");c==="symref-target"?o.target=u:c==="peeled"&&(o.peeled=u)}r.push(o)}return r}async function rB({prefix:t,symrefs:e,peelTags:r}){let i=[];return i.push(dt.encode(`command=ls-refs +`)),i.push(dt.encode(`agent=${Ld.agent} +`)),(r||e||t)&&i.push(dt.delim()),r&&i.push(dt.encode("peel")),e&&i.push(dt.encode("symrefs")),t&&i.push(dt.encode(`ref-prefix ${t}`)),i.push(dt.flush()),i}async function iB({http:t,onAuth:e,onAuthSuccess:r,onAuthFailure:i,corsProxy:n,url:s,headers:a={},forPush:o=!1,protocolVersion:l=2,prefix:c,symrefs:u,peelTags:f}){try{R("http",t),R("url",s);let d=await il.discover({http:t,onAuth:e,onAuthSuccess:r,onAuthFailure:i,corsProxy:n,service:o?"git-receive-pack":"git-upload-pack",url:s,headers:a,protocolVersion:l});if(d.protocolVersion===1)return IS(d,c,u,f);let h=await rB({prefix:c,symrefs:u,peelTags:f}),p=await il.connect({http:t,auth:d.auth,headers:a,corsProxy:n,service:o?"git-receive-pack":"git-upload-pack",url:s,body:h});return tB(p.body)}catch(d){throw d.caller="git.listServerRefs",d}}async function nB({fs:t,dir:e,gitdir:r=N(e,".git")}){try{R("fs",t),R("gitdir",r);let i=new te(t),n=await ie({fsp:i,dotgit:r});return q.listTags({fs:i,gitdir:n})}catch(i){throw i.caller="git.listTags",i}}function sB(t,e){return t.committer.timestamp-e.committer.timestamp}var aB="e69de29bb2d1d6434b8b29ae775ad8c2e48c5391";async function rS({fs:t,cache:e,gitdir:r,oid:i,fileId:n}){if(n===aB)return;let s=i,a,o=await tl({fs:t,cache:e,gitdir:r,oid:i}),l=o.tree;return n===o.oid?a=o.path:(a=await OS({fs:t,cache:e,gitdir:r,tree:l,fileId:n,oid:s}),Array.isArray(a)&&(a.length===0?a=void 0:a.length===1&&(a=a[0]))),a}async function OS({fs:t,cache:e,gitdir:r,tree:i,fileId:n,oid:s,filepaths:a=[],parentPath:o=""}){let l=i.entries().map(function(c){let u;return c.oid===n?(u=N(o,c.path),a.push(u)):c.type==="tree"&&(u=st({fs:t,cache:e,gitdir:r,oid:c.oid}).then(function({object:f}){return OS({fs:t,cache:e,gitdir:r,tree:Lr.from(f),fileId:n,oid:s,filepaths:a,parentPath:N(o,c.path)})})),u});return await Promise.all(l),a}async function oB({fs:t,cache:e,gitdir:r,filepath:i,ref:n,depth:s,since:a,force:o,follow:l,includeChanges:c}){let u=typeof a=="undefined"?void 0:Math.floor(a.valueOf()/1e3),f=[],d=await Pa.read({fs:t,gitdir:r}),h=await q.resolve({fs:t,gitdir:r,ref:n}),p=[await xn({fs:t,cache:e,gitdir:r,oid:h})],g,v,b;function _(C){b&&i&&f.push(C)}for(;p.length>0;){let C=p.pop();if(u!==void 0&&C.commit.committer.timestamp<=u)break;if(i){let x;try{x=await mu({fs:t,cache:e,gitdir:r,oid:C.commit.tree,filepath:i}),v&&g!==x&&f.push(v),g=x,v=C,b=!0}catch(E){if(E instanceof ze){let A=l&&g;if(A&&(A=await rS({fs:t,cache:e,gitdir:r,oid:C.commit.tree,fileId:g}),A))if(Array.isArray(A)){if(v){let w=await rS({fs:t,cache:e,gitdir:r,oid:v.commit.tree,fileId:g});if(Array.isArray(w))if(A=A.filter(S=>w.indexOf(S)===-1),A.length===1)A=A[0],i=A,v&&f.push(v);else{A=!1,v&&f.push(v);break}}}else i=A,v&&f.push(v);if(!A){if(b&&g&&(f.push(v),!o))break;if(!o&&!l)throw E}v=C,b=!1}else throw E}}else f.push(C);if(s!==void 0&&f.length===s){_(C);break}if(!d.has(C.oid))for(let x of C.commit.parent){let E=await xn({fs:t,cache:e,gitdir:r,oid:x});p.map(A=>A.oid).includes(E.oid)||p.push(E)}p.length===0&&_(C),p.sort((x,E)=>sB(x.commit,E.commit))}if(c)for(let C of f)C.commit.changes=await lB({fs:t,cache:e,gitdir:r,commit:C,shallow:d.has(C.oid)});return f}async function lB({fs:t,cache:e,gitdir:r,commit:i,shallow:n}){let s=n||!i.commit.parent[0]?"4b825dc642cb6eb9a060e54bf8d69288fbee4904":i.commit.parent[0];return Jn({fs:t,cache:e,gitdir:r,trees:[Dr({ref:i.oid}),Dr({ref:s})],map:async(a,[o,l])=>{let[c,u]=await Promise.all([o&&o.type(),l&&l.type()]);if(c==="tree")return u&&u!=="tree"?[null,await l.oid(),a]:void 0;if(u==="tree")return c?[await o.oid(),null,a]:void 0;let[f,d]=await Promise.all([o?o.oid():null,l?l.oid():null]);if(f!==d)return[f,d,a]}})}async function cB({fs:t,dir:e,gitdir:r=N(e,".git"),filepath:i,ref:n="HEAD",depth:s,since:a,force:o,follow:l,includeChanges:c=!1,cache:u={}}){try{R("fs",t),R("gitdir",r),R("ref",n);let f=new te(t),d=await ie({fsp:f,dotgit:r});return await oB({fs:f,cache:u,gitdir:d,filepath:i,ref:n,depth:s,since:a,force:o,follow:l,includeChanges:c})}catch(f){throw f.caller="git.log",f}}async function uB({fs:t,onSign:e,dir:r,gitdir:i=N(r,".git"),ours:n,theirs:s,fastForward:a=!0,fastForwardOnly:o=!1,dryRun:l=!1,noUpdateBranch:c=!1,abortOnConflict:u=!0,message:f,author:d,committer:h,signingKey:p,cache:g={},mergeDriver:v,allowUnrelatedHistories:b=!1}){try{R("fs",t),p&&R("onSign",e);let _=new te(t),C=await ie({fsp:_,dotgit:i}),x=await Ns({fs:_,gitdir:C,author:d});if(!x&&(!o||!a))throw new Jt("author");let E=await Ta({fs:_,gitdir:C,author:x,committer:h});if(!E&&(!o||!a))throw new Jt("committer");return await RS({fs:_,cache:g,dir:r,gitdir:C,ours:n,theirs:s,fastForward:a,fastForwardOnly:o,dryRun:l,noUpdateBranch:c,abortOnConflict:u,message:f,author:x,committer:E,signingKey:p,onSign:e,mergeDriver:v,allowUnrelatedHistories:b})}catch(_){throw _.caller="git.merge",_}}var fB={commit:16,tree:32,blob:48,tag:64,ofs_delta:96,ref_delta:112};async function LS({fs:t,cache:e,dir:r,gitdir:i=N(r,".git"),oids:n}){let s=new sv.default,a=[];function o(u,f){let d=k.from(u,f);a.push(d),s.update(d)}async function l({stype:u,object:f}){let d=fB[u],h=f.length,p=h>15?128:0,g=h&15;h=h>>>4;let v=(p|d|g).toString(16);for(o(v,"hex");p;)p=h>127?128:0,v=p|h&127,o(nv(2,v),"hex"),h=h>>>7;o(k.from(await mS(f)))}o("PACK"),o("00000002","hex"),o(nv(8,n.length),"hex");for(let u of n){let{type:f,object:d}=await st({fs:t,cache:e,gitdir:i,oid:u});await l({write:o,object:d,stype:f})}let c=s.digest();return a.push(c),a}async function dB({fs:t,cache:e,gitdir:r,oids:i,write:n}){let s=await LS({fs:t,cache:e,gitdir:r,oids:i}),a=k.from(await Rd(s)),l=`pack-${a.slice(-20).toString("hex")}.pack`;return n?(await t.write(N(r,`objects/pack/${l}`),a),{filename:l}):{filename:l,packfile:new Uint8Array(a)}}async function hB({fs:t,dir:e,gitdir:r=N(e,".git"),oids:i,write:n=!1,cache:s={}}){try{R("fs",t),R("gitdir",r),R("oids",i);let a=new te(t),o=await ie({fsp:a,dotgit:r});return await dB({fs:a,cache:s,gitdir:o,oids:i,write:n})}catch(a){throw a.caller="git.packObjects",a}}async function pB({fs:t,http:e,onProgress:r,onMessage:i,onAuth:n,onAuthSuccess:s,onAuthFailure:a,dir:o,gitdir:l=N(o,".git"),ref:c,url:u,remote:f,remoteRef:d,prune:h=!1,pruneTags:p=!1,fastForward:g=!0,fastForwardOnly:v=!1,corsProxy:b,singleBranch:_,headers:C={},author:x,committer:E,signingKey:A,cache:w={}}){try{R("fs",t),R("gitdir",l);let S=new te(t),y=await ie({fsp:S,dotgit:l}),P=await Ns({fs:S,gitdir:y,author:x});if(!P)throw new Jt("author");let T=await Ta({fs:S,gitdir:y,author:P,committer:E});if(!T)throw new Jt("committer");return await $S({fs:S,cache:w,http:e,onProgress:r,onMessage:i,onAuth:n,onAuthSuccess:s,onAuthFailure:a,dir:o,gitdir:y,ref:c,url:u,remote:f,remoteRef:d,fastForward:g,fastForwardOnly:v,corsProxy:b,singleBranch:_,headers:C,author:P,committer:T,signingKey:A,prune:h,pruneTags:p})}catch(S){throw S.caller="git.pull",S}}async function mB({fs:t,cache:e,dir:r,gitdir:i=N(r,".git"),start:n,finish:s}){let a=await Pa.read({fs:t,gitdir:i}),o=new Set,l=new Set;for(let f of n)o.add(await q.resolve({fs:t,gitdir:i,ref:f}));for(let f of s)try{let d=await q.resolve({fs:t,gitdir:i,ref:f});l.add(d)}catch(d){}let c=new Set;async function u(f){c.add(f);let{type:d,object:h}=await st({fs:t,cache:e,gitdir:i,oid:f});if(d==="tag"){let g=ni.from(h).headers().object;return u(g)}if(d!=="commit")throw new xr(f,d,"commit");if(!a.has(f)){let g=Nr.from(h).headers().parent;for(f of g)!l.has(f)&&!c.has(f)&&await u(f)}}for(let f of o)await u(f);return c}async function Wg({fs:t,cache:e,dir:r,gitdir:i=N(r,".git"),oids:n}){let s=new Set;async function a(o){if(s.has(o))return;s.add(o);let{type:l,object:c}=await st({fs:t,cache:e,gitdir:i,oid:o});if(l==="tag"){let f=ni.from(c).headers().object;await a(f)}else if(l==="commit"){let f=Nr.from(c).headers().tree;await a(f)}else if(l==="tree"){let u=Lr.from(c);for(let f of u)f.type==="blob"&&s.add(f.oid),f.type==="tree"&&await a(f.oid)}}for(let o of n)await a(o);return s}async function gB(t){let e={},r="",i=dt.streamReader(t),n=await i();for(;n!==!0;)n!==null&&(r+=n.toString("utf8")+` +`),n=await i();let s=r.toString("utf8").split(` +`);if(n=s.shift(),!n.startsWith("unpack "))throw new Aa('unpack ok" or "unpack [error message]',n);e.ok=n==="unpack ok",e.ok||(e.error=n.slice(7)),e.refs={};for(let a of s){if(a.trim()==="")continue;let o=a.slice(0,2),l=a.slice(3),c=l.indexOf(" ");c===-1&&(c=l.length);let u=l.slice(0,c),f=l.slice(c+1);e.refs[u]={ok:o==="ok",error:f}}return e}async function vB({capabilities:t=[],triplets:e=[]}){let r=[],i=`\0 ${t.join(" ")}`;for(let n of e)r.push(dt.encode(`${n.oldoid} ${n.oid} ${n.fullRef}${i} +`)),i="";return r.push(dt.flush()),r}async function wB({fs:t,cache:e,http:r,onProgress:i,onMessage:n,onAuth:s,onAuthSuccess:a,onAuthFailure:o,onPrePush:l,gitdir:c,ref:u,remoteRef:f,remote:d,url:h,force:p=!1,delete:g=!1,corsProxy:v,headers:b={}}){let _=u||await Bs({fs:t,gitdir:c});if(typeof _=="undefined")throw new Or("ref");let C=await vt.get({fs:t,gitdir:c});d=d||await C.get(`branch.${_}.pushRemote`)||await C.get("remote.pushDefault")||await C.get(`branch.${_}.remote`)||"origin";let x=h||await C.get(`remote.${d}.pushurl`)||await C.get(`remote.${d}.url`);if(typeof x=="undefined")throw new Or("remote OR url");let E=f||await C.get(`branch.${_}.merge`);if(typeof x=="undefined")throw new Or("remoteRef");v===void 0&&(v=await C.get("http.corsProxy"));let A=await q.expand({fs:t,gitdir:c,ref:_}),w=g?"0000000000000000000000000000000000000000":await q.resolve({fs:t,gitdir:c,ref:A}),S=nl.getRemoteHelperFor({url:x}),y=await S.discover({http:r,onAuth:$d({config:C,onAuth:s}),onAuthSuccess:a,onAuthFailure:$d({config:C,onAuth:o}),corsProxy:v,service:"git-receive-pack",url:x,headers:b,protocolVersion:1}),P=y.auth,T;if(!E)T=A;else try{T=await q.expandAgainstMap({ref:E,map:y.refs})}catch(X){if(X instanceof ze)T=E.startsWith("refs/")?E:`refs/heads/${E}`;else throw X}let I=y.refs.get(T)||"0000000000000000000000000000000000000000";if(l&&!await l({remote:d,url:x,localRef:{ref:g?"(delete)":A,oid:w},remoteRef:{ref:T,oid:I}}))throw new el;let M=!y.capabilities.has("no-thin"),B=new Set;if(!g){let X=[...y.refs.values()],j=new Set;if(I!=="0000000000000000000000000000000000000000"){let Ze=await cv({fs:t,cache:e,gitdir:c,oids:[w,I]});for(let $r of Ze)X.push($r);M&&(j=await Wg({fs:t,cache:e,gitdir:c,oids:Ze}))}if(!X.includes(w)){let Ze=await mB({fs:t,cache:e,gitdir:c,start:[w],finish:X});B=await Wg({fs:t,cache:e,gitdir:c,oids:Ze})}if(M){try{let Ze=await q.resolve({fs:t,gitdir:c,ref:`refs/remotes/${d}/HEAD`,depth:2}),{oid:$r}=await q.resolveAgainstMap({ref:Ze.replace(`refs/remotes/${d}/`,""),fullref:Ze,map:y.refs}),cr=[$r];for(let Ie of await Wg({fs:t,cache:e,gitdir:c,oids:cr}))j.add(Ie)}catch(Ze){}for(let Ze of j)B.delete(Ze)}if(w===I&&(p=!0),!p){if(A.startsWith("refs/tags")&&I!=="0000000000000000000000000000000000000000")throw new Jo("tag-exists");if(w!=="0000000000000000000000000000000000000000"&&I!=="0000000000000000000000000000000000000000"&&!await MS({fs:t,cache:e,gitdir:c,oid:w,ancestor:I,depth:-1}))throw new Jo("not-fast-forward")}}let re=AS([...y.capabilities],["report-status","side-band-64k",`agent=${Ld.agent}`]),Ae=await vB({capabilities:re,triplets:[{oldoid:I,oid:w,fullRef:T}]}),K=g?[]:await LS({fs:t,cache:e,gitdir:c,oids:[...B]}),Q=await S.connect({http:r,onProgress:i,corsProxy:v,service:"git-receive-pack",url:x,auth:P,headers:b,body:[...Ae,...K]}),{packfile:fe,progress:ce}=await Fd.demux(Q.body);if(n){let X=TS(ce);vu(X,async j=>{await n(j)})}let z=await gB(fe);if(Q.headers&&(z.headers=Q.headers),d&&z.ok&&z.refs[T].ok&&!A.startsWith("refs/tags")){let X=`refs/remotes/${d}/${T.replace("refs/heads","")}`;g?await q.deleteRef({fs:t,gitdir:c,ref:X}):await q.writeRef({fs:t,gitdir:c,ref:X,value:w})}if(z.ok&&Object.values(z.refs).every(X=>X.ok))return z;{let X=Object.entries(z.refs).filter(([j,Ze])=>!Ze.ok).map(([j,Ze])=>` + - ${j}: ${Ze.error}`).join("");throw new ru(X,z)}}async function bB({fs:t,http:e,onProgress:r,onMessage:i,onAuth:n,onAuthSuccess:s,onAuthFailure:a,onPrePush:o,dir:l,gitdir:c=N(l,".git"),ref:u,remoteRef:f,remote:d="origin",url:h,force:p=!1,delete:g=!1,corsProxy:v,headers:b={},cache:_={}}){try{R("fs",t),R("http",e),R("gitdir",c);let C=new te(t),x=await ie({fsp:C,dotgit:c});return await wB({fs:C,cache:_,http:e,onProgress:r,onMessage:i,onAuth:n,onAuthSuccess:s,onAuthFailure:a,onPrePush:o,gitdir:x,ref:u,remoteRef:f,remote:d,url:h,force:p,delete:g,corsProxy:v,headers:b})}catch(C){throw C.caller="git.push",C}}async function NS({fs:t,cache:e,gitdir:r,oid:i}){let{type:n,object:s}=await st({fs:t,cache:e,gitdir:r,oid:i});if(n==="tag")return i=ni.from(s).parse().object,NS({fs:t,cache:e,gitdir:r,oid:i});if(n!=="blob")throw new xr(i,n,"blob");return{oid:i,blob:new Uint8Array(s)}}async function BS({fs:t,cache:e,gitdir:r,oid:i,filepath:n=void 0}){return n!==void 0&&(i=await mu({fs:t,cache:e,gitdir:r,oid:i,filepath:n})),await NS({fs:t,cache:e,gitdir:r,oid:i})}async function wu({fs:t,dir:e,gitdir:r=N(e,".git"),oid:i,filepath:n,cache:s={}}){try{R("fs",t),R("gitdir",r),R("oid",i);let a=new te(t),o=await ie({fsp:a,dotgit:r});return await BS({fs:a,cache:s,gitdir:o,oid:i,filepath:n})}catch(a){throw a.caller="git.readBlob",a}}async function HS({fs:t,dir:e,gitdir:r=N(e,".git"),oid:i,cache:n={}}){try{R("fs",t),R("gitdir",r),R("oid",i);let s=new te(t),a=await ie({fsp:s,dotgit:r});return await xn({fs:s,cache:n,gitdir:a,oid:i})}catch(s){throw s.caller="git.readCommit",s}}async function _B({fs:t,cache:e,gitdir:r,ref:i="refs/notes/commits",oid:n}){let s=await q.resolve({gitdir:r,fs:t,ref:i}),{blob:a}=await BS({fs:t,cache:e,gitdir:r,oid:s,filepath:n});return a}async function yB({fs:t,dir:e,gitdir:r=N(e,".git"),ref:i="refs/notes/commits",oid:n,cache:s={}}){try{R("fs",t),R("gitdir",r),R("ref",i),R("oid",n);let a=new te(t),o=await ie({fsp:a,dotgit:r});return await _B({fs:a,cache:s,gitdir:o,ref:i,oid:n})}catch(a){throw a.caller="git.readNote",a}}async function xB({fs:t,dir:e,gitdir:r=N(e,".git"),oid:i,format:n="parsed",filepath:s=void 0,encoding:a=void 0,cache:o={}}){try{R("fs",t),R("gitdir",r),R("oid",i);let l=new te(t),c=await ie({fsp:l,dotgit:r});s!==void 0&&(i=await mu({fs:l,cache:o,gitdir:c,oid:i,filepath:s}));let f=await st({fs:l,cache:o,gitdir:c,oid:i,format:n==="parsed"?"content":n});if(f.oid=i,n==="parsed")switch(f.format="parsed",f.type){case"commit":f.object=Nr.from(f.object).parse();break;case"tree":f.object=Lr.from(f.object).entries();break;case"blob":a?f.object=f.object.toString(a):(f.object=new Uint8Array(f.object),f.format="content");break;case"tag":f.object=ni.from(f.object).parse();break;default:throw new xr(f.oid,f.type,"blob|commit|tag|tree")}else(f.format==="deflated"||f.format==="wrapped")&&(f.type=f.format);return f}catch(l){throw l.caller="git.readObject",l}}async function EB({fs:t,cache:e,gitdir:r,oid:i}){let{type:n,object:s}=await st({fs:t,cache:e,gitdir:r,oid:i,format:"content"});if(n!=="tag")throw new xr(i,n,"tag");let a=ni.from(s);return{oid:i,tag:a.parse(),payload:a.payload()}}async function SB({fs:t,dir:e,gitdir:r=N(e,".git"),oid:i,cache:n={}}){try{R("fs",t),R("gitdir",r),R("oid",i);let s=new te(t),a=await ie({fsp:s,dotgit:r});return await EB({fs:s,cache:n,gitdir:a,oid:i})}catch(s){throw s.caller="git.readTag",s}}async function kB({fs:t,dir:e,gitdir:r=N(e,".git"),oid:i,filepath:n=void 0,cache:s={}}){try{R("fs",t),R("gitdir",r),R("oid",i);let a=new te(t),o=await ie({fsp:a,dotgit:r});return await al({fs:a,cache:s,gitdir:o,oid:i,filepath:n})}catch(a){throw a.caller="git.readTree",a}}async function CB({fs:t,dir:e,gitdir:r=N(e,".git"),filepath:i,cache:n={}}){try{R("fs",t),R("gitdir",r),R("filepath",i);let s=new te(t),a=await ie({fsp:s,dotgit:r});await gt.acquire({fs:s,gitdir:a,cache:n},async function(o){o.delete({filepath:i})})}catch(s){throw s.caller="git.remove",s}}async function AB({fs:t,cache:e,onSign:r,gitdir:i,ref:n="refs/notes/commits",oid:s,author:a,committer:o,signingKey:l}){let c;try{c=await q.resolve({gitdir:i,fs:t,ref:n})}catch(p){if(!(p instanceof ze))throw p}let f=(await al({fs:t,cache:e,gitdir:i,oid:c||"4b825dc642cb6eb9a060e54bf8d69288fbee4904"})).tree;f=f.filter(p=>p.path!==s);let d=await gu({fs:t,gitdir:i,tree:f});return await pu({fs:t,cache:e,onSign:r,gitdir:i,ref:n,tree:d,parent:c&&[c],message:`Note removed by 'isomorphic-git removeNote' +`,author:a,committer:o,signingKey:l})}async function TB({fs:t,onSign:e,dir:r,gitdir:i=N(r,".git"),ref:n="refs/notes/commits",oid:s,author:a,committer:o,signingKey:l,cache:c={}}){try{R("fs",t),R("gitdir",i),R("oid",s);let u=new te(t),f=await ie({fsp:u,dotgit:i}),d=await Ns({fs:u,gitdir:f,author:a});if(!d)throw new Jt("author");let h=await Ta({fs:u,gitdir:f,author:d,committer:o});if(!h)throw new Jt("committer");return await AB({fs:u,cache:c,onSign:e,gitdir:f,ref:n,oid:s,author:d,committer:h,signingKey:l})}catch(u){throw u.caller="git.removeNote",u}}async function PB({fs:t,gitdir:e,oldref:r,ref:i,checkout:n=!1}){if(!uu(i,!0))throw new qi(i,Zo.default.clean(i));if(!uu(r,!0))throw new qi(r,Zo.default.clean(r));let s=`refs/heads/${r}`,a=`refs/heads/${i}`;if(await q.exists({fs:t,gitdir:e,ref:a}))throw new Wi("branch",i,!1);let l=await q.resolve({fs:t,gitdir:e,ref:s,depth:1});await q.writeRef({fs:t,gitdir:e,ref:a,value:l}),await q.deleteRef({fs:t,gitdir:e,ref:s});let u=await Bs({fs:t,gitdir:e,fullname:!0})===s;(n||u)&&await q.writeSymbolicRef({fs:t,gitdir:e,ref:"HEAD",value:a})}async function RB({fs:t,dir:e,gitdir:r=N(e,".git"),ref:i,oldref:n,checkout:s=!1}){try{R("fs",t),R("gitdir",r),R("ref",i),R("oldref",n);let a=new te(t),o=await ie({fsp:a,dotgit:r});return await PB({fs:a,gitdir:o,ref:i,oldref:n,checkout:s})}catch(a){throw a.caller="git.renameBranch",a}}async function US({gitdir:t,type:e,object:r}){return En(Ds.wrap({type:e,object:r}))}async function $B({fs:t,dir:e,gitdir:r=N(e,".git"),filepath:i,ref:n,cache:s={}}){try{R("fs",t),R("gitdir",r),R("filepath",i);let a=new te(t),o=await ie({fsp:a,dotgit:r}),l,c;try{l=await q.resolve({fs:a,gitdir:o,ref:n||"HEAD"})}catch(d){if(n)throw d}if(l)try{l=await mu({fs:a,cache:s,gitdir:o,oid:l,filepath:i})}catch(d){l=null}let u={ctime:new Date(0),mtime:new Date(0),dev:0,ino:0,mode:0,uid:0,gid:0,size:0},f=e&&await a.read(N(e,i));f&&(c=await US({gitdir:o,type:"blob",object:f}),l===c&&(u=await a.lstat(N(e,i)))),await gt.acquire({fs:a,gitdir:o,cache:s},async function(d){d.delete({filepath:i}),l&&d.insert({filepath:i,stats:u,oid:l})})}catch(a){throw a.caller="git.reset",a}}async function FB({fs:t,dir:e,gitdir:r=N(e,".git"),ref:i,depth:n}){try{R("fs",t),R("gitdir",r),R("ref",i);let s=new te(t),a=await ie({fsp:s,dotgit:r});return await q.resolve({fs:s,gitdir:a,ref:i,depth:n})}catch(s){throw s.caller="git.resolveRef",s}}async function IB({fs:t,dir:e,gitdir:r=N(e,".git"),path:i,value:n,append:s=!1}){try{R("fs",t),R("gitdir",r),R("path",i);let a=new te(t),o=await ie({fsp:a,dotgit:r}),l=await vt.get({fs:a,gitdir:o});s?await l.append(i,n):await l.set(i,n),await vt.save({fs:a,gitdir:o,config:l})}catch(a){throw a.caller="git.setConfig",a}}async function GS({fs:t,gitdir:e,commit:r}){let i=Nr.from(r).toObject();return await Br({fs:t,gitdir:e,type:"commit",object:i,format:"content"})}var Id=class t{static get timezoneOffsetForRefLogEntry(){let e=new Date().getTimezoneOffset(),r=Math.abs(Math.floor(e/60)),i=Math.abs(e%60).toString().padStart(2,"0");return`${e>0?"-":"+"}${r.toString().padStart(2,"0")}${i}`}static createStashReflogEntry(e,r,i){let n=e.name.replace(/\s/g,""),s="0000000000000000000000000000000000000000",a=Math.floor(Date.now()/1e3),o=t.timezoneOffsetForRefLogEntry;return`${s} ${r} ${n} ${e.email} ${a} ${o} ${i} +`}static getStashReflogEntry(e,r=!1){return e.split(` +`).filter(s=>s).reverse().map((s,a)=>r?`stash@{${a}}: ${s.split(" ")[1]}`:s)}},Ra=class t{constructor({fs:e,dir:r,gitdir:i=N(r,".git")}){Object.assign(this,{fs:e,dir:r,gitdir:i,_author:null})}static get refStash(){return"refs/stash"}static get refLogsStash(){return"logs/refs/stash"}get refStashPath(){return N(this.gitdir,t.refStash)}get refLogsStashPath(){return N(this.gitdir,t.refLogsStash)}async getAuthor(){if(!this._author&&(this._author=await Ns({fs:this.fs,gitdir:this.gitdir,author:{}}),!this._author))throw new Jt("author");return this._author}async getStashSHA(e,r){return await this.fs.exists(this.refStashPath)?(r||await this.readStashReflogs({parsed:!1}))[e].split(" ")[1]:null}async writeStashCommit({message:e,tree:r,parent:i}){return GS({fs:this.fs,gitdir:this.gitdir,commit:{message:e,tree:r,parent:i,author:await this.getAuthor(),committer:await this.getAuthor()}})}async readStashCommit(e){let r=await this.readStashReflogs({parsed:!1});if(e!==0&&(e<0||e>r.length-1))throw new qi(`stash@${e}`,"number that is in range of [0, num of stash pushed]");let i=await this.getStashSHA(e,r);return i?xn({fs:this.fs,cache:{},gitdir:this.gitdir,oid:i}):{}}async writeStashRef(e){return q.writeRef({fs:this.fs,gitdir:this.gitdir,ref:t.refStash,value:e})}async writeStashReflogEntry({stashCommit:e,message:r}){let i=await this.getAuthor(),n=Id.createStashReflogEntry(i,e,r),s=this.refLogsStashPath;await rl({filepath:s,entry:n},async()=>{let a=await this.fs.exists(s)?await this.fs.read(s,"utf8"):"";await this.fs.write(s,a+n,"utf8")})}async readStashReflogs({parsed:e=!1}){if(!await this.fs.exists(this.refLogsStashPath))return[];let r=await this.fs.read(this.refLogsStashPath,"utf8");return Id.getStashReflogEntry(r,e)}};async function jS({fs:t,dir:e,gitdir:r,message:i=""}){let n=new Ra({fs:t,dir:e,gitdir:r});await n.getAuthor();let s=await Bs({fs:t,gitdir:r,fullname:!1}),a=await q.resolve({fs:t,gitdir:r,ref:"HEAD"}),l=(await HS({fs:t,dir:e,gitdir:r,oid:a})).commit.message,c=[a],u=null,f=Dr({ref:"HEAD"}),d=await YE({fs:t,dir:e,gitdir:r,treePair:[Dr({ref:"HEAD"}),"stage"]});if(d){let v=await n.writeStashCommit({message:`stash-Index: WIP on ${s} - ${new Date().toISOString()}`,tree:d,parent:c});c.push(v),u=d,f=sl()}let h=await YE({fs:t,dir:e,gitdir:r,treePair:[f,"workdir"]});if(h){let v=await n.writeStashCommit({message:`stash-WorkDir: WIP on ${s} - ${new Date().toISOString()}`,tree:h,parent:[c[c.length-1]]});c.push(v),u=h}if(!u||!d&&!h)throw new ze("changes, nothing to stash");let p=(i.trim()||`WIP on ${s}`)+`: ${a.substring(0,7)} ${l}`;return{stashCommit:await n.writeStashCommit({message:p,tree:u,parent:c}),stashMsg:p,branch:s,stashMgr:n}}async function MB({fs:t,dir:e,gitdir:r,message:i=""}){let{stashCommit:n,stashMsg:s,branch:a,stashMgr:o}=await jS({fs:t,dir:e,gitdir:r,message:i});return await o.writeStashRef(n),await o.writeStashReflogEntry({stashCommit:n,message:s}),await ES({fs:t,dir:e,gitdir:r,ref:a,track:!1,force:!0}),n}async function DB({fs:t,dir:e,gitdir:r,message:i=""}){let{stashCommit:n}=await jS({fs:t,dir:e,gitdir:r,message:i});return n}async function VS({fs:t,dir:e,gitdir:r,refIdx:i=0}){let s=await new Ra({fs:t,dir:e,gitdir:r}).readStashCommit(i),{parent:a=null}=s.commit?s.commit:{};if(!(!a||!Array.isArray(a)))for(let o=0;o{await t.exists(a)&&await t.rm(a)});let o=await n.readStashReflogs({parsed:!1});if(!o.length)return;o.splice(i,1);let l=n.refLogsStashPath;await rl({reflogEntries:o,stashReflogPath:l,stashMgr:n},async()=>{if(o.length){await t.write(l,o.reverse().join(` +`)+` +`,"utf8");let c=o[o.length-1].split(" ")[1];await n.writeStashRef(c)}else await t.rm(l)})}async function OB({fs:t,dir:e,gitdir:r}){return new Ra({fs:t,dir:e,gitdir:r}).readStashReflogs({parsed:!0})}async function LB({fs:t,dir:e,gitdir:r}){let i=new Ra({fs:t,dir:e,gitdir:r}),n=[i.refStashPath,i.refLogsStashPath];await rl(n,async()=>{await Promise.all(n.map(async s=>{if(await t.exists(s))return t.rm(s)}))})}async function NB({fs:t,dir:e,gitdir:r,refIdx:i=0}){await VS({fs:t,dir:e,gitdir:r,refIdx:i}),await zS({fs:t,dir:e,gitdir:r,refIdx:i})}async function BB({fs:t,dir:e,gitdir:r=N(e,".git"),op:i="push",message:n="",refIdx:s=0}){R("fs",t),R("dir",e),R("gitdir",r),R("op",i);let a={push:MB,apply:VS,drop:zS,list:OB,clear:LB,pop:NB,create:DB},o=["apply","drop","pop"];try{let l=new te(t),c=await ie({fsp:l,dotgit:r});["refs","logs","logs/refs"].map(d=>N(c,d)).forEach(async d=>{await l.exists(d)||await l.mkdir(d)});let f=a[i];if(f){if(o.includes(i)&&s<0)throw new qi(`stash@${s}`,"number that is in range of [0, num of stash pushed]");return await f({fs:l,dir:e,gitdir:c,message:n,refIdx:s})}throw new Error(`To be implemented: ${i}`)}catch(l){throw l.caller="git.stash",l}}async function HB({fs:t,dir:e,gitdir:r=N(e,".git"),filepath:i,cache:n={},refresh:s=!0}){try{R("fs",t),R("gitdir",r),R("filepath",i);let a=new te(t),o=await ie({fsp:a,dotgit:r});if(await Ls.isIgnored({fs:a,gitdir:o,dir:e,filepath:i}))return"ignored";let c=await UB({fs:a,cache:n,gitdir:o}),u=await WS({fs:a,cache:n,gitdir:o,tree:c,path:i}),f=await gt.acquire({fs:a,gitdir:o,cache:n},async function(b){for(let _ of b)if(_.path===i)return _;return null}),d=await a.lstat(N(e,i)),h=u!==null,p=f!==null,g=d!==null,v=async()=>{if(p&&!Ed(f,d))return f.oid;{let b=await a.read(N(e,i)),_=await US({gitdir:o,type:"blob",object:b});return s&&p&&f.oid===_&&d.size!==-1&>.acquire({fs:a,gitdir:o,cache:n},async function(C){C.insert({filepath:i,stats:d,oid:_})}),_}};if(!h&&!g&&!p)return"absent";if(!h&&!g&&p)return"*absent";if(!h&&g&&!p)return"*added";if(!h&&g&&p)return await v()===f.oid?"added":"*added";if(h&&!g&&!p)return"deleted";if(h&&!g&&p)return u===f.oid,"*deleted";if(h&&g&&!p)return await v()===u?"*undeleted":"*undeletemodified";if(h&&g&&p){let b=await v();return b===u?b===f.oid?"unmodified":"*unmodified":b===f.oid?"modified":"*modified"}}catch(a){throw a.caller="git.status",a}}async function WS({fs:t,cache:e,gitdir:r,tree:i,path:n}){typeof n=="string"&&(n=n.split("/"));let s=n.shift();for(let a of i)if(a.path===s){if(n.length===0)return a.oid;let{type:o,object:l}=await st({fs:t,cache:e,gitdir:r,oid:a.oid});if(o==="tree"){let c=Lr.from(l);return WS({fs:t,cache:e,gitdir:r,tree:c,path:n})}if(o==="blob")throw new xr(a.oid,o,"blob",n.join("/"))}return null}async function UB({fs:t,cache:e,gitdir:r}){let i;try{i=await q.resolve({fs:t,gitdir:r,ref:"HEAD"})}catch(s){if(s instanceof ze)return[]}let{tree:n}=await al({fs:t,cache:e,gitdir:r,oid:i});return n}async function GB({fs:t,dir:e,gitdir:r=N(e,".git"),ref:i="HEAD",filepaths:n=["."],filter:s,cache:a={},ignored:o=!1,refresh:l=!0}){try{R("fs",t),R("gitdir",r),R("ref",i);let c=new te(t),u=await ie({fsp:c,dotgit:r});return await Jn({fs:c,cache:a,dir:e,gitdir:u,trees:[Dr({ref:i}),hu({refresh:l}),sl()],map:async function(f,[d,h,p]){if(!d&&!p&&h&&!o&&await Ls.isIgnored({fs:c,dir:e,filepath:f})||!n.some(S=>xS(f,S)))return null;if(s&&!s(f))return;let[g,v,b]=await Promise.all([d&&d.type(),h&&h.type(),p&&p.type()]),_=[g,v,b].includes("blob");if((g==="tree"||g==="special")&&!_)return;if(g==="commit")return null;if((v==="tree"||v==="special")&&!_)return;if(b==="commit")return null;if((b==="tree"||b==="special")&&!_)return;let C=g==="blob"?await d.oid():void 0,x=b==="blob"?await p.oid():void 0,E;g!=="blob"&&v==="blob"&&b!=="blob"?E="42":v==="blob"&&(E=await h.oid());let A=[void 0,C,E,x],w=A.map(S=>A.indexOf(S));return w.shift(),[f,...w]}})}catch(c){throw c.caller="git.statusMatrix",c}}async function jB({fs:t,dir:e,gitdir:r=N(e,".git"),ref:i,object:n,force:s=!1}){try{R("fs",t),R("gitdir",r),R("ref",i);let a=new te(t);if(i===void 0)throw new Or("ref");i=i.startsWith("refs/tags/")?i:`refs/tags/${i}`;let o=await ie({fsp:a,dotgit:r}),l=await q.resolve({fs:a,gitdir:o,ref:n||"HEAD"});if(!s&&await q.exists({fs:a,gitdir:o,ref:i}))throw new Wi("tag",i);await q.writeRef({fs:a,gitdir:o,ref:i,value:l})}catch(a){throw a.caller="git.tag",a}}async function VB({fs:t,dir:e,gitdir:r=N(e,".git"),cache:i={},filepath:n,oid:s,mode:a,add:o,remove:l,force:c}){try{R("fs",t),R("gitdir",r),R("filepath",n);let u=new te(t),f=await ie({fsp:u,dotgit:r});if(l)return await gt.acquire({fs:u,gitdir:f,cache:i},async function(h){if(!c){let p=await u.lstat(N(e,n));if(p){if(p.isDirectory())throw new Os("directory");return}}h.has({filepath:n})&&h.delete({filepath:n})});let d;if(!s){if(d=await u.lstat(N(e,n)),!d)throw new ze(`file at "${n}" on disk and "remove" not set`);if(d.isDirectory())throw new Os("directory")}return await gt.acquire({fs:u,gitdir:f,cache:i},async function(h){if(!o&&!h.has({filepath:n}))throw new ze(`file at "${n}" in index and "add" not set`);let p;if(s)p={ctime:new Date(0),mtime:new Date(0),dev:0,ino:0,mode:a,uid:0,gid:0,size:0};else{p=d;let g=p.isSymbolicLink()?await u.readlink(N(e,n)):await u.read(N(e,n));s=await Br({fs:u,gitdir:f,type:"blob",format:"content",object:g})}return h.insert({filepath:n,oid:s,stats:p}),s})}catch(u){throw u.caller="git.updateIndex",u}}function zB(){try{return Ld.version}catch(t){throw t.caller="git.version",t}}async function WB({fs:t,dir:e,gitdir:r=N(e,".git"),trees:i,map:n,reduce:s,iterate:a,cache:o={}}){try{R("fs",t),R("gitdir",r),R("trees",i);let l=new te(t),c=await ie({fsp:l,dotgit:r});return await Jn({fs:l,cache:o,dir:e,gitdir:c,trees:i,map:n,reduce:s,iterate:a})}catch(l){throw l.caller="git.walk",l}}async function qB({fs:t,dir:e,gitdir:r=N(e,".git"),blob:i}){try{R("fs",t),R("gitdir",r),R("blob",i);let n=new te(t),s=await ie({fsp:n,dotgit:r});return await Br({fs:n,gitdir:s,type:"blob",object:i,format:"content"})}catch(n){throw n.caller="git.writeBlob",n}}async function YB({fs:t,dir:e,gitdir:r=N(e,".git"),commit:i}){try{R("fs",t),R("gitdir",r),R("commit",i);let n=new te(t),s=await ie({fsp:n,dotgit:r});return await GS({fs:n,gitdir:s,commit:i})}catch(n){throw n.caller="git.writeCommit",n}}async function ZB({fs:t,dir:e,gitdir:r=N(e,".git"),type:i,object:n,format:s="parsed",oid:a,encoding:o=void 0}){try{let l=new te(t),c=await ie({fsp:l,dotgit:r});if(s==="parsed"){switch(i){case"commit":n=Nr.from(n).toObject();break;case"tree":n=Lr.from(n).toObject();break;case"blob":n=k.from(n,o);break;case"tag":n=ni.from(n).toObject();break;default:throw new xr(a||"",i,"blob|commit|tag|tree")}s="content"}return a=await Br({fs:l,gitdir:c,type:i,object:n,oid:a,format:s}),a}catch(l){throw l.caller="git.writeObject",l}}async function KB({fs:t,dir:e,gitdir:r=N(e,".git"),ref:i,value:n,force:s=!1,symbolic:a=!1}){try{R("fs",t),R("gitdir",r),R("ref",i),R("value",n);let o=new te(t);if(!uu(i,!0))throw new qi(i,Zo.default.clean(i));let l=await ie({fsp:o,dotgit:r});if(!s&&await q.exists({fs:o,gitdir:l,ref:i}))throw new Wi("ref",i);a?await q.writeSymbolicRef({fs:o,gitdir:l,ref:i,value:n}):(n=await q.resolve({fs:o,gitdir:l,ref:n}),await q.writeRef({fs:o,gitdir:l,ref:i,value:n}))}catch(o){throw o.caller="git.writeRef",o}}async function XB({fs:t,gitdir:e,tag:r}){let i=ni.from(r).toObject();return await Br({fs:t,gitdir:e,type:"tag",object:i,format:"content"})}async function QB({fs:t,dir:e,gitdir:r=N(e,".git"),tag:i}){try{R("fs",t),R("gitdir",r),R("tag",i);let n=new te(t),s=await ie({fsp:n,dotgit:r});return await XB({fs:n,gitdir:s,tag:i})}catch(n){throw n.caller="git.writeTag",n}}async function JB({fs:t,dir:e,gitdir:r=N(e,".git"),tree:i}){try{R("fs",t),R("gitdir",r),R("tree",i);let n=new te(t),s=await ie({fsp:n,dotgit:r});return await gu({fs:n,gitdir:s,tree:i})}catch(n){throw n.caller="git.writeTree",n}}var e3={Errors:du,STAGE:sl,TREE:Dr,WORKDIR:hu,add:UL,abortMerge:LL,addNote:VL,addRemote:WL,annotatedTag:YL,branch:KL,cherryPick:sN,checkout:ES,clone:gN,commit:vN,getConfig:DN,getConfigAll:LN,setConfig:IB,currentBranch:wN,deleteBranch:_N,deleteRef:yN,deleteRemote:EN,deleteTag:kN,expandOid:PN,expandRef:RN,fastForward:$N,fetch:FN,findMergeBase:IN,findRoot:MN,getRemoteInfo:NN,getRemoteInfo2:BN,hashBlob:UN,indexPack:jN,init:VN,isDescendent:zN,isIgnored:WN,listBranches:qN,listFiles:ZN,listNotes:XN,listRefs:QN,listRemotes:eB,listServerRefs:iB,listTags:nB,log:cB,merge:uB,packObjects:hB,pull:pB,push:bB,readBlob:wu,readCommit:HS,readNote:yB,readObject:xB,readTag:SB,readTree:kB,remove:CB,removeNote:TB,renameBranch:RB,resetIndex:$B,updateIndex:VB,resolveRef:FB,status:HB,statusMatrix:GB,tag:jB,version:zB,walk:WB,writeBlob:qB,writeCommit:YB,writeObject:ZB,writeRef:KB,writeTag:QB,writeTree:JB,stash:BB},pe=e3;var Ce=require("obsidian"),k$=mt(require("path"),1),am=mt(require("fs/promises"),1);m();var Et={};m();var Nd=class{constructor(e){this.plugin=e;this.tasks=[];this.currentTask=null}addTask(e,r){this.tasks.push({task:e,onFinished:i=>{r&&r(i)}}),this.kickstart()}kickstart(){if(this.currentTask!==null||this.tasks.length===0)return;let e=this.tasks.shift();this.currentTask=Promise.resolve().then(()=>e.task()).then(r=>{try{e.onFinished(r)}catch(i){console.error(i)}},r=>{this.plugin.displayError(r);try{e.onFinished(void 0)}catch(i){console.error(i)}}).finally(()=>{this.currentTask=null,this.kickstart()})}clear(){this.tasks=[]}};m();var U=require("obsidian");m();var qS=require("obsidian"),Bd="YYYY-MM-DD",uv=`${Bd} HH:mm`,fv=`${Bd} HH:mm:ss`,Hd=40,ol="conflict-files-obsidian-git.md",tt={commitMessage:"vault backup: {{date}}",autoCommitMessage:"vault backup: {{date}}",commitMessageScript:"",commitDateFormat:fv,autoSaveInterval:0,autoPushInterval:0,autoPullInterval:0,autoPullOnBoot:!1,autoCommitOnlyStaged:!1,disablePush:!1,pullBeforePush:!0,squashCommitsBeforePush:!1,disablePopups:!1,showErrorNotices:!0,disablePopupsForNoChanges:!1,listChangedFilesInMessageBody:!1,showStatusBar:!0,updateSubmodules:!1,syncMethod:"merge",mergeStrategy:"none",customMessageOnAutoBackup:!1,autoBackupAfterFileChange:!1,treeStructure:!1,refreshSourceControl:qS.Platform.isDesktopApp,basePath:"",differentIntervalCommitAndPush:!1,changedFilesInStatusBar:!1,showedMobileNotice:!1,refreshSourceControlTimer:7e3,showBranchStatusBar:!0,setLastSaveToLastCommit:!1,submoduleRecurseCheckout:!1,gitDir:"",showFileMenu:!0,authorInHistoryView:"hide",dateInHistoryView:!1,diffStyle:"split",diffTimeout:50,autoStageOnEmptyIndex:!0,hunks:{showSigns:!1,hunkCommands:!1,statusBar:"disabled"},lineAuthor:{show:!1,followMovement:"inactive",authorDisplay:"initials",showCommitHash:!1,dateTimeFormatOptions:"date",dateTimeFormatCustomString:uv,dateTimeTimezone:"viewer-local",coloringMaxAge:"1y",colorNew:{r:255,g:150,b:150},colorOld:{r:120,g:160,b:255},textColorCss:"var(--text-muted)",ignoreWhitespace:!1}},er={type:"git-view",name:"Source Control",icon:"git-pull-request"},Ei={type:"git-history-view",name:"History",icon:"history"},Hs={type:"split-diff-view",name:"Diff view",icon:"diff"},Us={type:"diff-view",name:"Diff View",icon:"git-pull-request"},Ud="C:\\Program Files\\Git\\cmd\\git.exe",Gd=".git_credentials_input",$a="obsidian_askpass.sh",YS=`#!/bin/sh + +PROMPT="$1" +TEMP_FILE="$OBSIDIAN_GIT_CREDENTIALS_INPUT" + +cleanup() { + rm -f "$TEMP_FILE" "$TEMP_FILE.response" +} +trap cleanup EXIT + +echo "$PROMPT" > "$TEMP_FILE" + +while [ ! -e "$TEMP_FILE.response" ]; do + if [ ! -e "$TEMP_FILE" ]; then + echo "Trigger file got removed: Abort" >&2 + exit 1 + fi + sleep 0.1 +done + +RESPONSE=$(cat "$TEMP_FILE.response") + +echo "$RESPONSE" +`,ZS=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"];m();m();m();var bu=class{diff(e,r,i={}){let n;typeof i=="function"?(n=i,i={}):"callback"in i&&(n=i.callback);let s=this.castInput(e,i),a=this.castInput(r,i),o=this.removeEmpty(this.tokenize(s,i)),l=this.removeEmpty(this.tokenize(a,i));return this.diffWithOptionsObj(o,l,i,n)}diffWithOptionsObj(e,r,i,n){var s;let a=_=>{if(_=this.postProcess(_,i),n){setTimeout(function(){n(_)},0);return}else return _},o=r.length,l=e.length,c=1,u=o+l;i.maxEditLength!=null&&(u=Math.min(u,i.maxEditLength));let f=(s=i.timeout)!==null&&s!==void 0?s:1/0,d=Date.now()+f,h=[{oldPos:-1,lastComponent:void 0}],p=this.extractCommon(h[0],r,e,0,i);if(h[0].oldPos+1>=l&&p+1>=o)return a(this.buildValues(h[0].lastComponent,r,e));let g=-1/0,v=1/0,b=()=>{for(let _=Math.max(g,-c);_<=Math.min(v,c);_+=2){let C,x=h[_-1],E=h[_+1];x&&(h[_-1]=void 0);let A=!1;if(E){let S=E.oldPos-_;A=E&&0<=S&&S=l&&p+1>=o)return a(this.buildValues(C.lastComponent,r,e))||!0;h[_]=C,C.oldPos+1>=l&&(v=Math.min(v,_-1)),p+1>=o&&(g=Math.max(g,_+1))}c++};if(n)(function _(){setTimeout(function(){if(c>u||Date.now()>d)return n(void 0);b()||_()},0)})();else for(;c<=u&&Date.now()<=d;){let _=b();if(_)return _}}addToPath(e,r,i,n,s){let a=e.lastComponent;return a&&!s.oneChangePerToken&&a.added===r&&a.removed===i?{oldPos:e.oldPos+n,lastComponent:{count:a.count+1,added:r,removed:i,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+n,lastComponent:{count:1,added:r,removed:i,previousComponent:a}}}extractCommon(e,r,i,n,s){let a=r.length,o=i.length,l=e.oldPos,c=l-n,u=0;for(;c+1d.length?p:d}),u.value=this.join(f)}else u.value=this.join(r.slice(l,l+u.count));l+=u.count,u.added||(c+=u.count)}}return n}};m();var dv=class extends bu{constructor(){super(...arguments),this.tokenize=r3}equals(e,r,i){return i.ignoreWhitespace?((!i.newlineIsToken||!e.includes(` +`))&&(e=e.trim()),(!i.newlineIsToken||!r.includes(` +`))&&(r=r.trim())):i.ignoreNewlineAtEof&&!i.newlineIsToken&&(e.endsWith(` +`)&&(e=e.slice(0,-1)),r.endsWith(` +`)&&(r=r.slice(0,-1))),super.equals(e,r,i)}},t3=new dv;function hv(t,e,r){return t3.diff(t,e,r)}function r3(t,e){e.stripTrailingCr&&(t=t.replace(/\r\n/g,` +`));let r=[],i=t.split(/(\n|\r\n)/);i[i.length-1]||i.pop();for(let n=0;n"~"||t[e]==='"'||t[e]==="\\")return!0;return!1}function Gs(t){if(!i3(t))return t;let e='"',r=new TextEncoder().encode(t),i=0;for(;i=32&&n<=126?e+=String.fromCharCode(n):e+="\\"+n.toString(8).padStart(3,"0"),i++}return e+='"',e}var pv={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function mv(t,e,r,i,n,s,a){let o;a?typeof a=="function"?o={callback:a}:o=a:o={},typeof o.context=="undefined"&&(o.context=4);let l=o.context;if(o.newlineIsToken)throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");if(o.callback){let{callback:u}=o;hv(r,i,Object.assign(Object.assign({},o),{callback:f=>{let d=c(f);u(d)}}))}else return c(hv(r,i,o));function c(u){if(!u)return;u.push({value:"",lines:[]});function f(_){return _.map(function(C){return" "+C})}let d=[],h=0,p=0,g=[],v=1,b=1;for(let _=0;_0?f(E.lines.slice(-l)):[],h-=g.length,p-=g.length)}for(let E of x)g.push((C.added?"+":"-")+E);C.added?b+=x.length:v+=x.length}else{if(h)if(x.length<=l*2&&_1&&!e.includeFileHeaders&&!t.every(u=>u.isGit))throw new Error("Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)");return t.map(u=>jd(u,e)).join(` +`)}let l=[];if(t.isGit){if(e=pv,!t.oldFileName)throw new Error("oldFileName must be specified for Git patches");if(!t.newFileName)throw new Error("newFileName must be specified for Git patches");let u=t.oldFileName,f=t.newFileName;t.isCreate&&u==="/dev/null"?u=f.replace(/^b\//,"a/"):t.isDelete&&f==="/dev/null"&&(f=u.replace(/^a\//,"b/")),l.push("diff --git "+Gs(u)+" "+Gs(f)),t.isDelete&&l.push("deleted file mode "+((r=t.oldMode)!==null&&r!==void 0?r:"100644")),t.isCreate&&l.push("new file mode "+((i=t.newMode)!==null&&i!==void 0?i:"100644")),t.oldMode&&t.newMode&&!t.isDelete&&!t.isCreate&&(l.push("old mode "+t.oldMode),l.push("new mode "+t.newMode)),t.isRename&&(l.push("rename from "+Gs(((n=t.oldFileName)!==null&&n!==void 0?n:"").replace(/^a\//,""))),l.push("rename to "+Gs(((s=t.newFileName)!==null&&s!==void 0?s:"").replace(/^b\//,"")))),t.isCopy&&(l.push("copy from "+Gs(((a=t.oldFileName)!==null&&a!==void 0?a:"").replace(/^a\//,""))),l.push("copy to "+Gs(((o=t.newFileName)!==null&&o!==void 0?o:"").replace(/^b\//,""))))}else e.includeIndex&&t.oldFileName==t.newFileName&&t.oldFileName!==void 0&&l.push("Index: "+t.oldFileName),e.includeUnderline&&l.push("===================================================================");let c=t.hunks.length>0;e.includeFileHeaders&&t.oldFileName!==void 0&&t.newFileName!==void 0&&(!t.isGit||c)&&(l.push("--- "+Gs(t.oldFileName)+(t.oldHeader?" "+t.oldHeader:"")),l.push("+++ "+Gs(t.newFileName)+(t.newHeader?" "+t.newHeader:"")));for(let u=0;u{o(l?jd(l,a.headerOptions):void 0)}}))}else{let o=mv(t,e,r,i,n,s,a);return o?jd(o,a==null?void 0:a.headerOptions):void 0}}function _u(t,e,r,i,n,s){return KS(t,t,e,r,i,n,s)}function n3(t){let e=t.endsWith(` +`),r=t.split(` +`).map(i=>i+` +`);return e?r.pop():r.push(r.pop().slice(0,-1)),r}var Cn=require("obsidian");m();function XS(t,e){let r=Object.assign({},t.lineAuthor,e.lineAuthor);return Object.assign({},t,e,{lineAuthor:r})}var ll=class extends Error{constructor(r){super("No network connection available");this.originalError=r}};m();var QS=require("obsidian"),s3={options:[],placeholder:"",allowEmpty:!1,onlySelection:!1,initialValue:void 0,obscure:!1},at=class extends QS.SuggestModal{constructor(e,r){if(super(e.app),this.config={...s3,...r},this.setPlaceholder(this.config.placeholder),this.config.obscure){this.inputEl.type="password";let i=this.containerEl.querySelector(".prompt-input-container");i.addClass("git-obscure-prompt"),i.setAttr("git-is-obscured","true");let n=i==null?void 0:i.createDiv({cls:"search-input-clear-button"});n.style.marginRight="32px",n.id="git-show-password",n.addEventListener("click",()=>{i.getAttr("git-is-obscured")==="true"?(this.inputEl.type="text",i.setAttr("git-is-obscured","false")):(this.inputEl.type="password",i.setAttr("git-is-obscured","true"))})}}openAndGetResult(){return new Promise(e=>{this.resolve=e,this.open(),this.config.initialValue!=null&&(this.inputEl.value=this.config.initialValue,this.inputEl.dispatchEvent(new Event("input")))})}onClose(){new Promise(e=>window.setTimeout(e,10)).then(()=>{this.resolve&&this.resolve(void 0)})}getSuggestions(e){return this.config.onlySelection?this.config.options:this.config.allowEmpty?[e.length>0?e:" ",...this.config.options]:[e.length>0?e:"...",...this.config.options]}renderSuggestion(e,r){this.config.obscure?r.hide():r.setText(e)}onChooseSuggestion(e,r){if(this.resolve){let i;this.config.allowEmpty&&e===" "?i="":e==="..."?i=void 0:i=e,this.resolve(i)}}};m();var vk=mt(gk(),1),wk=require("child_process"),ts=require("obsidian");function zd(t){throw new Error(`Unexpected object: ${String(t)}`)}function xu(t,e,r){return t===1?`${t} ${e}`:`${t} ${r!=null?r:e+"s"}`}var wv=(t,e)=>t==="."||e==null||e.length===0||e==="."?!0:e.length>=t.length?e.startsWith(t):t.startsWith(e);function Yi(t,e){let r;if(e){if(e.button===0||e.button===1){let i=ts.Keymap.isModEvent(e);r=t.workspace.getLeaf(i)}}else r=t.workspace.getLeaf(!1);return r}function Hr(t){return t.getRoot().side==="left"?"right":"left"}function Sn(t,e,r,i,n){if(e.button==2){let s=t.vault.getAbstractFileByPath(r);if(s!=null){let a=new ts.Menu;t.workspace.trigger("file-menu",a,s,n,i),a.showAtPosition({x:e.pageX,y:e.pageY})}else{let a=new ts.Menu;t.workspace.trigger("obsidian-git:menu",a,r,n,i),a.showAtPosition({x:e.pageX,y:e.pageY})}}}function js(t){throw new Error(`Impossible branch: ${String(t)}`)}function bv(t){return`rgb(${t.r},${t.g},${t.b})`}function bk(t){var s;let e=(s=vk.fromString(t))==null?void 0:s.toRgbaArray();if(e===void 0)return;let[r,i,n]=e;return{r,g:i,b:n}}function _k(t){return t.diff(ts.moment.unix(0),"seconds")}function yk(t){if(t.length!==0)return t.slice().sort()[Math.floor(t.length/2)]}function Eu(t,e){return new Proxy(t,{get(r,i){return i==="length"?Math.min(e,r.length):r[i]}})}function xk(t,e,r){return t.length<=e?new Array(e-t.length).fill(r).join("")+t:t.substring(t.length-e)}function Ek(t,e){if(e<=0)return t;let r=new Array(e).fill(" ").join(""),i=t.substring(e,t.length);return r+i}function _v(t,e,r){return t<=e&&e<=r}function Vs(t){let[e,...r]=t.split("/");return[e!=null?e:"",r.length===0?void 0:r.join("/")]}function kn(t){return t.endsWith("/")?t:t.split("/").last().replace(/\.md$/,"")}function Sk(t){return t===1?"1 minute":`${t} minutes`}function _3(t){let e=t.lastIndexOf(".");return t.substring(e+1)}function ul(t){if(t.endsWith(".md"))return!1;let e=_3(t);return ZS.includes(e)}function yv(t){return(t.startsWith("https://github.com/")||t.startsWith("https://gitlab.com/"))&&(t.endsWith(".git")||(t=t+".git")),t}function fl(t,e){let r=e.vault.getAbstractFileByPath(t);if(!(r instanceof ts.TFile))return!1;try{return!!e.viewRegistry.getTypeByExtension(r.extension)}catch(i){return!0}}function kk({isFolder:t,gitRelativePath:e}){let r="/";return r+=e,t&&(r+="/"),r.replace(/([\\!#*?[\]])/g,String.raw`\$1`).replace(/\s(?=\s*$)/g,String.raw`\ `)}function dl(t,e,r,i){let n=e.target;t.workspace.trigger("hover-link",{event:e,source:r.getViewType(),hoverParent:r,targetEl:n,linktext:i})}function Su(t,e,r={}){return new Promise((i,n)=>{let s=(0,wk.spawn)(t,e,r),a="",o="";s.stdout.on("data",l=>{a+=l.toString()}),s.stderr.on("data",l=>{o+=l.toString()}),s.on("error",l=>{i({error:new Error(l.message),stdout:a,stderr:o,code:1})}),s.on("close",l=>{i({stdout:a,stderr:o,code:l!=null?l:1,error:void 0})})})}m();var Ck=require("os"),qd=require("obsidian");var hl=class{constructor(e){this.plugin=e,this.app=e.app}async withGitOperation(e,r){var i;this.plugin.setPluginState({operation:e});try{return await r()}finally{(i=this.plugin.statusBar)==null||i.clearProgress(!1),this.plugin.setPluginState({operation:0})}}getRelativeVaultPath(e){return this.plugin.settings.basePath?e===""||e==="."?this.plugin.settings.basePath:this.plugin.settings.basePath+"/"+e:e}getRelativeRepoPath(e,r=!0){if(r){let i=this.plugin.settings.basePath;if(i&&i.length>0){if(e.startsWith(i+"/"))return e.substring(i.length+1);if(e===i)return""}}return e}unload(){}simplify(e){var r,i,n,s;for(let a of e){for(;;){let o=((r=a.children)==null?void 0:r.length)==1,l=((n=(i=a.children)==null?void 0:i.first())==null?void 0:n.data)==null;if(!(a.children!=null&&o&&l))break;let c=a.children.first();a.title+="/"+c.title,a.data=c.data,a.path=c.path,a.vaultPath=c.vaultPath,a.children=c.children}a.children!=null&&this.simplify(a.children),(s=a.children)==null||s.sort((o,l)=>{let c=(l.data==null?1:0)-(o.data==null?1:0);return c!=0?c:o.title.localeCompare(l.title)})}return e.sort((a,o)=>{let l=(o.data==null?1:0)-(a.data==null?1:0);return l!=0?l:a.title.localeCompare(o.title)})}getTreeStructure(e){let r=new Map;for(let a of e){let o=a.path.split("/"),l=r,c="";for(let u=0;u{let o=[];for(let l of a.values())l.children.size>0?o.push({title:l.title,path:l.path,vaultPath:this.getRelativeVaultPath(l.path),children:i(l.children)}):o.push({title:l.title,data:l.data,path:l.path,vaultPath:this.getRelativeVaultPath(l.path)});return o},n=i(r);return this.simplify(n)}async formatCommitMessage(e){let r;if(e.includes("{{numFiles}}")){r=await this.status();let i=r.staged.length;e=e.replace("{{numFiles}}",String(i))}if(e.includes("{{hostname}}")){let i=this.plugin.localStorage.getHostname()||"";!i&&qd.Platform.isDesktopApp&&(i=(0,Ck.hostname)()),e=e.replace("{{hostname}}",i)}if(e.includes("{{files}}")){r=r!=null?r:await this.status();let i={},n="";if(r.staged.length<100){r.staged.forEach(a=>{a.index in i?i[a.index].push(a.path):i[a.index]=[a.path]});let s=[];for(let[a,o]of Object.entries(i))s.push(a+" "+o.join(" "));n=s.join(", ")}else n="Too many files to list";e=e.replace("{{files}}",n)}if(e=e.replace("{{date}}",(0,qd.moment)().format(this.plugin.settings.commitDateFormat)),this.plugin.settings.listChangedFilesInMessageBody){let i=r!=null?r:await this.status(),n="";i.staged.length<100?n=i.staged.map(s=>s.path).join(` +`):n="Too many files to list",e=e+` + +Affected files: +`+n}return e}};m();var Wt=require("obsidian"),Yd=class extends Error{constructor(r){super(`File not found: ${r}`);this.code="ENOENT";this.name="FileNotFoundError"}},Zd=class{constructor(e,r){this.plugin=r;this.adapter=e.adapter,this.vault=e,this.lastBasePath=this.plugin.settings.basePath,this.promises={readFile:this.readFile.bind(this),writeFile:this.writeFile.bind(this),readdir:this.readdir.bind(this),mkdir:this.mkdir.bind(this),rmdir:this.rmdir.bind(this),stat:this.stat.bind(this),unlink:this.unlink.bind(this),lstat:this.lstat.bind(this),readlink:this.readlink.bind(this),symlink:this.symlink.bind(this)}}async readFile(e,r){var n;if(e===void 0)return;if(e=(0,Wt.normalizePath)(e),this.maybeLog("Read: "+e+JSON.stringify(r)),(typeof r=="string"?r:r==null?void 0:r.encoding)==="utf8"){let s=this.vault.getAbstractFileByPath(e);return s instanceof Wt.TFile?(this.maybeLog("Reuse"),this.vault.read(s)):this.adapter.read(e)}else{if(this.isIndexPath(e))return this.plugin.settings.basePath!=this.lastBasePath?(this.clearIndex(),this.lastBasePath=this.plugin.settings.basePath,this.adapter.readBinary(e)):(n=this.index)!=null?n:this.adapter.readBinary(e);let s=this.vault.getAbstractFileByPath(e);return s instanceof Wt.TFile?(this.maybeLog("Reuse"),this.vault.readBinary(s)):this.adapter.readBinary(e)}}async writeFile(e,r){var i;if(this.maybeLog("Write: "+e),e=(0,Wt.normalizePath)(e),typeof r=="string"){let n=this.vault.getAbstractFileByPath(e);if(n instanceof Wt.TFile)return this.vault.modify(n,r);if(!this.isHiddenPath(e))await this.vault.create(e,r);else return this.adapter.write(e,r)}else{let n=y3(r);if(this.isIndexPath(e)){this.index=n;let s=Date.now();(i=this.indexctime)!=null||(this.indexctime=s),this.indexmtime=s}else{let s=this.vault.getAbstractFileByPath(e);if(s instanceof Wt.TFile)return this.vault.modifyBinary(s,n);if(!this.isHiddenPath(e))await this.vault.createBinary(e,n);else return this.adapter.writeBinary(e,n)}}}async readdir(e){e=(0,Wt.normalizePath)(e),this.maybeLog("ReadDir: "+e),e==="."&&(e="/");let r=await this.adapter.list(e),i=[...r.files,...r.folders],n;return e!=="/"?n=i.map(s=>(0,Wt.normalizePath)(s.substring(e.length))):n=i,n}async mkdir(e){if(e=(0,Wt.normalizePath)(e),!(e==="."||e==="/")){if(!this.isHiddenPath(e)){if(this.vault.getFolderByPath(e))return;await this.vault.createFolder(e);return}return this.adapter.mkdir(e)}}async rmdir(e,r){var i,n;if(e=(0,Wt.normalizePath)(e),this.maybeLog("Rmdir: "+e+JSON.stringify(r)),!this.isHiddenPath(e)){let s=this.vault.getAbstractFileByPath(e);if(s instanceof Wt.TFolder){await this.vault.delete(s,(r==null?void 0:r.recursive)===!0||((i=r==null?void 0:r.options)==null?void 0:i.recursive)===!0);return}}return this.adapter.rmdir(e,(r==null?void 0:r.recursive)===!0||((n=r==null?void 0:r.options)==null?void 0:n.recursive)===!0)}async stat(e){if(e=(0,Wt.normalizePath)(e),this.isIndexPath(e)){if(this.index!==void 0&&this.indexctime!=null&&this.indexmtime!=null)return{isFile:()=>!0,isDirectory:()=>!1,isSymbolicLink:()=>!1,size:this.index.byteLength,type:"file",ctimeMs:this.indexctime,mtimeMs:this.indexmtime};{let i=await this.adapter.stat(e);if(i==null)throw new Yd(e);return this.indexctime=i.ctime,this.indexmtime=i.mtime,{ctimeMs:i.ctime,mtimeMs:i.mtime,size:i.size,type:"file",isFile:()=>!0,isDirectory:()=>!1,isSymbolicLink:()=>!1}}}e==="."&&(e="/");let r=this.vault.getAbstractFileByPath(e);if(this.maybeLog("Stat: "+e),r instanceof Wt.TFile)return this.maybeLog("Reuse stat"),{ctimeMs:r.stat.ctime,mtimeMs:r.stat.mtime,size:r.stat.size,type:"file",isFile:()=>!0,isDirectory:()=>!1,isSymbolicLink:()=>!1};{let i=await this.adapter.stat(e);if(i)return{ctimeMs:i.ctime,mtimeMs:i.mtime,size:i.size,type:i.type==="folder"?"directory":i.type,isFile:()=>i.type==="file",isDirectory:()=>i.type==="folder",isSymbolicLink:()=>!1};throw new Yd(e)}}async unlink(e){if(e=(0,Wt.normalizePath)(e),!this.isHiddenPath(e)){let r=this.vault.getAbstractFileByPath(e);if(r instanceof Wt.TFile)return this.vault.delete(r)}return this.adapter.remove(e)}async lstat(e){return this.stat(e)}readlink(e){return Promise.reject(new Error(`readlink of (${e}) is not implemented.`))}symlink(e){return Promise.reject(new Error(`symlink of (${e}) is not implemented.`))}async saveAndClear(){this.index!==void 0&&await this.adapter.writeBinary(this.getIndexPath(),this.index,{ctime:this.indexctime,mtime:this.indexmtime}),this.clearIndex()}clearIndex(){this.index=void 0,this.indexctime=void 0,this.indexmtime=void 0}get gitDir(){return this.plugin.settings.gitDir||".git"}getIndexPath(){return this.plugin.gitManager.getRelativeVaultPath(this.gitDir+"/index")}isIndexPath(e){return e===this.getIndexPath()}isHiddenPath(e){return e.startsWith(this.gitDir)?!0:e.split("/").some(r=>r.startsWith(".")&&r!==".")}maybeLog(e){}};function y3(t){return t instanceof ArrayBuffer?t:t.buffer instanceof ArrayBuffer&&t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice().buffer}var Fk=mt($k(),1),Zi=class extends hl{constructor(r){super(r);this.FILE=0;this.HEAD=1;this.WORKDIR=2;this.STAGE=3;this.status_mapping={"000":" ","003":"AD","020":"??","022":"A ","023":"AM",100:"D ",101:" D",103:"MD",110:"DA",111:" ",113:"MM",120:"DA",121:" M",122:"M ",123:"MM"};this.noticeLength=999999;this.fs=new Zd(this.app.vault,this.plugin)}getRepo(){return{fs:this.fs,dir:this.plugin.settings.basePath,gitdir:this.plugin.settings.gitDir?this.getGitDirPath():void 0,onAuth:()=>{var r,i;return{username:(r=this.plugin.localStorage.getUsername())!=null?r:void 0,password:(i=this.plugin.localStorage.getPassword())!=null?i:void 0}},onAuthFailure:async()=>{new Cn.Notice("Authentication failed. Please try with different credentials");let r=await new at(this.plugin,{placeholder:"Specify your username"}).openAndGetResult();if(r){let i=await new at(this.plugin,{placeholder:"Specify your password/personal access token",obscure:!0}).openAndGetResult();if(i)return this.plugin.localStorage.setUsername(r),this.plugin.localStorage.setPassword(i),{username:r,password:i}}return{cancel:!0}},http:{async request({url:r,method:i,headers:n,body:s}){let a;s&&(a=await k3(s));let o=await(0,Cn.requestUrl)({url:r,method:i,headers:{"Accept-Encoding":"identity",...n},body:a,throw:!1}),l=await C3(o.arrayBuffer);return{url:r,method:i,headers:o.headers,body:S3(l),statusCode:o.status,statusMessage:o.status.toString()}}}}}async wrapFS(r){try{let i=await r;return await this.fs.saveAndClear(),i}catch(i){throw await this.fs.saveAndClear(),i}}async status(r){let i,n=window.setTimeout(()=>{i=new Cn.Notice("This takes longer: Getting status",this.noticeLength)},2e4);try{let s={...this.getRepo()};(r==null?void 0:r.path)!=null&&(s.filepaths=[`${r.path}/`]);let a=(await this.wrapFS(pe.statusMatrix(s))).map(f=>this.getFileStatusResult(f)),o=[],l=[],c=[];for(let f of a)f.workingDir!==" "&&o.push(f),f.index!==" "&&f.index!=="U"&&l.push(f),(f.index!=" "||f.workingDir!=" ")&&c.push(f);let u=[];return window.clearTimeout(n),i==null||i.hide(),{all:c,changed:o,staged:l,conflicted:u}}catch(s){throw window.clearTimeout(n),i==null||i.hide(),this.plugin.displayError(s),s}}async commitAll({message:r,status:i,unstagedFiles:n}){try{return await this.checkAuthorInfo(),await this.stageAll({status:i,unstagedFiles:n}),this.commit({message:r})}catch(s){throw this.plugin.displayError(s),s}}async commit({message:r}){return this.withGitOperation(2,async()=>{try{await this.checkAuthorInfo();let i=await this.formatCommitMessage(r),n=this.plugin.localStorage.getConflict(),s;if(n){let a=await this.branchInfo();s=[a.current,a.tracking]}await this.wrapFS(pe.commit({...this.getRepo(),message:i,parent:s})),this.plugin.localStorage.setConflict(!1);return}catch(i){throw this.plugin.displayError(i),i}})}async stage(r,i){let n=this.getRelativeRepoPath(r,i),s;i?s=r:s=this.getRelativeVaultPath(r);try{await this.app.vault.adapter.exists(s)?await this.wrapFS(pe.add({...this.getRepo(),filepath:n})):await this.wrapFS(pe.remove({...this.getRepo(),filepath:n}))}catch(a){throw this.plugin.displayError(a),a}}async stageAll({dir:r,status:i,unstagedFiles:n}){try{if(i)await this.stageFiles(i.changed.map(s=>({path:s.path,deleted:s.workingDir==="D"})));else{let s=n!=null?n:await this.getUnstagedFiles(r!=null?r:".");await this.stageFiles(s.map(({path:a,type:o})=>({path:a,deleted:o==="D"})))}}catch(s){throw this.plugin.displayError(s),s}}async stageFiles(r){let n=(await this.wrapFS(Promise.allSettled(r.map(s=>s.deleted?pe.remove({...this.getRepo(),filepath:s.path}):pe.add({...this.getRepo(),filepath:s.path}))))).find(s=>s.status==="rejected");if((n==null?void 0:n.status)==="rejected")throw n.reason}async unstage(r,i){try{r=this.getRelativeRepoPath(r,i),await this.wrapFS(pe.resetIndex({...this.getRepo(),filepath:r}))}catch(n){throw this.plugin.displayError(n),n}}async unstageAll({dir:r,status:i}){try{let n;i?n=i.staged.map(s=>s.path):n=(await this.getStagedFiles(r!=null?r:".")).map(({path:a})=>a),await this.wrapFS(Promise.all(n.map(s=>pe.resetIndex({...this.getRepo(),filepath:s}))))}catch(n){throw this.plugin.displayError(n),n}}async discard(r){try{await this.wrapFS(pe.checkout({...this.getRepo(),filepaths:[r],force:!0}))}catch(i){throw this.plugin.displayError(i),i}}async discardAll({dir:r,status:i}){let n=[];i?r!=null?n=i.changed.filter(s=>s.workingDir!="U"&&s.path.startsWith(r)).map(s=>s.path):n=i.changed.filter(s=>s.workingDir!="U").map(s=>s.path):n=(await this.getUnstagedFiles(r)).filter(s=>s.type!="A").map(({path:s})=>s);try{await this.wrapFS(pe.checkout({...this.getRepo(),filepaths:n,force:!0}))}catch(s){throw this.plugin.displayError(s),s}}async getUntrackedPaths(r){let i=[];if(r.status)for(let n of r.status.changed)n.index=="U"&&n.workingDir==="U"&&n.path.startsWith(r.path!=null?`${r.path}/`:"")&&i.push(n.path);else{let n=await this.status({path:r==null?void 0:r.path});for(let s of n.changed)s.index==="U"&&s.workingDir==="U"&&i.push(s.path)}return i}getProgressText(r,i){let n=`${r} progress:`;return i.phase&&(n=`${n} ${i.phase}:`),i.loaded&&(n=`${n} ${i.loaded}`,i.total&&(n=`${n} of ${i.total}`)),n}resolveRef(r){return this.wrapFS(pe.resolveRef({...this.getRepo(),ref:r}))}async pull(){let r=this.showNotice("Initializing pull");return this.withGitOperation(1,async()=>{try{let i=await this.resolveRef("HEAD");await this.fetch();let n=await this.branchInfo();await this.checkAuthorInfo(),(await this.wrapFS(pe.merge({...this.getRepo(),ours:n.current,theirs:n.tracking,abortOnConflict:!1,mergeDriver:this.plugin.settings.mergeStrategy!=="none"?({contents:l})=>{var _,C,x;let c=l[0],u=l[1],f=l[2],d=/^.*(\r?\n|$)/gm,h=(_=u.match(d))!=null?_:[],p=(C=c.match(d))!=null?C:[],g=(x=f.match(d))!=null?x:[],v=(0,Fk.default)(h,p,g),b="";for(let E of v)E.ok&&(b+=E.ok.join("")),E.conflict&&(b+=this.plugin.settings.mergeStrategy==="ours"?E.conflict.a.join(""):E.conflict.b.join(""));return{cleanMerge:!0,mergedText:b}}:void 0}))).alreadyMerged||await this.wrapFS(pe.checkout({...this.getRepo(),ref:n.current,onProgress:l=>{r!==void 0&&r.setMessage(this.getProgressText("Checkout",l))},remote:n.remote})),r==null||r.hide();let a=await this.resolveRef("HEAD"),o=await this.getFileChangesCount(i,a);return this.showNotice("Finished pull",!1),o.map(l=>({path:l.path,workingDir:"P",index:"P",vaultPath:this.getRelativeVaultPath(l.path)}))}catch(i){throw r==null||r.hide(),i instanceof du.MergeConflictError&&await this.plugin.handleConflict(i.data.filepaths.map(n=>this.getRelativeVaultPath(n))),this.plugin.displayError(i),i}})}async push(){if(!await this.canPush())return 0;let r=this.showNotice("Initializing push");return this.withGitOperation(3,async()=>{try{let i=await this.branchInfo(),n=i.tracking,s=i.current,a=(await this.getFileChangesCount(s,n)).length,o=await this.getCurrentRemote();return await this.wrapFS(pe.push({...this.getRepo(),remote:o,onProgress:l=>{r!==void 0&&r.setMessage(this.getProgressText("Pushing",l))}})),r==null||r.hide(),a}catch(i){throw r==null||r.hide(),this.plugin.displayError(i),i}})}async getUnpushedCommits(){let r=await this.branchInfo(),i=r.tracking,n=r.current;if(i==null||n==null)return 0;let s=await this.resolveRef(n),a=await this.resolveRef(i);return(await this.getFileChangesCount(s,a)).length}async canPush(){let r=await this.branchInfo(),i=r.tracking,n=r.current,s=await this.resolveRef(n),a=await this.resolveRef(i);return s!=a}async checkRequirements(){return await this.plugin.app.vault.adapter.exists((0,Cn.normalizePath)(`${this.getGitDirPath()}/HEAD`))?"valid":"missing-repo"}async branchInfo(){var r,i;try{let n=await pe.currentBranch(this.getRepo())||"",s=await pe.listBranches(this.getRepo()),a=(r=await this.getConfig(`branch.${n}.remote`))!=null?r:"origin",o=(i=await this.getConfig(`branch.${n}.merge`))==null?void 0:i.split("refs/heads")[1],l=o?a+o:void 0;return{current:n,tracking:l,branches:s,remote:a}}catch(n){throw this.plugin.displayError(n),n}}async getCurrentRemote(){var n;let r=await pe.currentBranch(this.getRepo())||"";return(n=await this.getConfig(`branch.${r}.remote`))!=null?n:"origin"}async checkout(r,i){try{return this.wrapFS(pe.checkout({...this.getRepo(),ref:r,force:!!i,remote:i}))}catch(n){throw this.plugin.displayError(n),n}}async createBranch(r){try{await this.wrapFS(pe.branch({...this.getRepo(),ref:r,checkout:!0}))}catch(i){throw this.plugin.displayError(i),i}}async deleteBranch(r){try{await this.wrapFS(pe.deleteBranch({...this.getRepo(),ref:r}))}catch(i){throw this.plugin.displayError(i),i}}branchIsMerged(r){return Promise.resolve(!0)}async init(){try{await this.wrapFS(pe.init(this.getRepo()))}catch(r){throw this.plugin.displayError(r),r}}async clone(r,i,n){let s=this.showNotice("Initializing clone");try{await this.wrapFS(pe.clone({...this.getRepo(),dir:i,url:r,depth:n,onProgress:a=>{s!==void 0&&s.setMessage(this.getProgressText("Cloning",a))}})),s==null||s.hide()}catch(a){throw s==null||s.hide(),this.plugin.displayError(a),a}}async setConfig(r,i){try{return this.wrapFS(pe.setConfig({...this.getRepo(),path:r,value:i}))}catch(n){throw this.plugin.displayError(n),n}}async getConfig(r){try{return this.wrapFS(pe.getConfig({...this.getRepo(),path:r}))}catch(i){throw this.plugin.displayError(i),i}}async fetch(r){let i=this.showNotice("Initializing fetch");try{let n={...this.getRepo(),onProgress:s=>{i!==void 0&&i.setMessage(this.getProgressText("Fetching",s))},remote:r!=null?r:await this.getCurrentRemote()};await this.wrapFS(pe.fetch(n)),i==null||i.hide()}catch(n){throw this.plugin.displayError(n),i==null||i.hide(),n}}async setRemote(r,i){try{await this.wrapFS(pe.addRemote({...this.getRepo(),remote:r,url:i,force:!0}))}catch(n){throw this.plugin.displayError(n),n}}async getRemoteBranches(r){let i=[];return i.push(...await this.wrapFS(pe.listBranches({...this.getRepo(),remote:r}))),i.remove("HEAD"),i=i.map(n=>`${r}/${n}`),i}async getRemotes(){return(await this.wrapFS(pe.listRemotes({...this.getRepo()}))).map(r=>r.remote)}async removeRemote(r){await this.wrapFS(pe.deleteRemote({...this.getRepo(),remote:r}))}async getRemoteUrl(r){var i;return(i=(await this.wrapFS(pe.listRemotes({...this.getRepo()}))).filter(n=>n.remote==r)[0])==null?void 0:i.url}async log(r,i=!0,n,s){let a=await this.wrapFS(pe.log({...this.getRepo(),depth:n,ref:s}));return Promise.all(a.map(async o=>{var c;let l=o.commit.message.split(` + +`);return{message:(c=l[0])!=null?c:"",author:{name:o.commit.author.name,email:o.commit.author.email},body:l.slice(1).join(` + +`),date:new Date(o.commit.committer.timestamp).toDateString(),diff:{changed:0,files:(await this.getFileChangesCount(o.commit.parent.first(),o.oid)).map(u=>({path:u.path,status:u.type,vaultPath:this.getRelativeVaultPath(u.path),hash:o.oid}))},hash:o.oid,refs:[]}}))}updateBasePath(r){return this.getRepo().dir=r,Promise.resolve()}getGitDirPath(){return(0,Cn.normalizePath)(this.getRelativeVaultPath(this.plugin.settings.gitDir||".git"))}async updateUpstreamBranch(r){let[i,n]=Vs(r),s=await this.branchInfo();await this.wrapFS(pe.push({...this.getRepo(),remote:i,remoteRef:n})),await this.setConfig(`branch.${s.current}.merge`,`refs/heads/${n}`)}updateGitPath(r){return Promise.resolve()}async getFileChangesCount(r,i){return this.walkDifference({walkers:[pe.TREE({ref:r}),pe.TREE({ref:i})]})}async walkDifference({walkers:r,dir:i}){return this.wrapFS(xv({...this.getRepo(),trees:r,map:async function(n,[s,a]){if(!wv(n,i))return null;if(await(s==null?void 0:s.type())==="tree"||await(a==null?void 0:a.type())==="tree")return;let o=await(s==null?void 0:s.oid()),l=await(a==null?void 0:a.oid()),c="equal";if(o!==l&&(c="M"),o===void 0&&(c="A"),l===void 0&&(c="D"),o===void 0&&l===void 0&&(console.log("Something weird happened:"),console.log(s),console.log(a)),c!=="equal")return{path:n,type:c}}}))}async getStagedFiles(r="."){return(await this.walkDifference({walkers:[pe.TREE({ref:"HEAD"}),pe.STAGE()],dir:r})).map(n=>({vaultPath:this.getRelativeVaultPath(n.path),path:n.path}))}async getUnstagedFiles(r="."){let i,n=window.setTimeout(()=>{i=new Cn.Notice("This takes longer: Getting status",this.noticeLength)},2e4);try{let s=this.getRepo(),a=await this.wrapFS(xv({...s,trees:[pe.WORKDIR(),pe.STAGE()],map:async function(o,[l,c]){if(!c&&l&&await pe.isIgnored({...s,filepath:o})||!wv(o,r))return null;let[u,f]=await Promise.all([l&&l.type(),c&&c.type()]),d=[u,f].includes("blob");if((u==="tree"||u==="special")&&!d)return;if(f==="commit")return null;if((f==="tree"||f==="special")&&!d)return;let h=f==="blob"?await c.oid():void 0,p;return u==="blob"&&f!=="blob"?p="42":u==="blob"&&(p=await l.oid()),p?h?p!==h?{path:o,type:"M"}:null:{path:o,type:"A"}:{path:o,type:"D"}}}));return window.clearTimeout(n),i==null||i.hide(),a}catch(s){throw window.clearTimeout(n),i==null||i.hide(),this.plugin.displayError(s),s}}async getDiffString(r,i=!1,n){let s=this.getRelativeVaultPath(r),a=async(c,[u])=>{if(r==c){let f=await u.oid();return(await pe.readBlob({...this.getRepo(),oid:f})).blob}};if(n){let c=await wu({...this.getRepo(),filepath:r,oid:n}).then(p=>new TextDecoder().decode(p.blob)).catch(p=>{if(!(p instanceof pe.Errors.NotFoundError))throw p}),f=(await pe.readCommit({...this.getRepo(),oid:n})).commit.parent.first(),d;return f&&(d=await wu({...this.getRepo(),filepath:r,oid:f}).then(p=>new TextDecoder().decode(p.blob)).catch(p=>{if(!(p instanceof pe.Errors.NotFoundError))throw p})),_u(s,d!=null?d:"",c!=null?c:"")}let o=(await xv({...this.getRepo(),trees:[pe.STAGE()],map:a})).first(),l=new TextDecoder().decode(o);if(i){let c=await this.resolveRef("HEAD").then(f=>wu({...this.getRepo(),filepath:r,oid:f})).then(f=>new TextDecoder().decode(f.blob)).catch(f=>{if(!(f instanceof pe.Errors.NotFoundError))throw f});return _u(s,c!=null?c:"",l)}else{let c;return await this.app.vault.adapter.exists(s)?c=await this.app.vault.adapter.read(s):c="",_u(s,l,c)}}async getLastCommitTime(){let r=this.getRepo(),i=await this.resolveRef("HEAD"),s=(await pe.readCommit({...r,oid:i})).commit.committer.timestamp;return new Date(s*1e3)}getFileStatusResult(r){var s,a;let i=`${r[this.HEAD]}${r[this.WORKDIR]}${r[this.STAGE]}`,n=this.status_mapping[i];if(n===void 0)throw new Error(`Unsupported status matrix row: ${i}`);return{index:n[0]=="?"?"U":(s=n[0])!=null?s:" ",workingDir:n[1]=="?"?"U":(a=n[1])!=null?a:" ",path:r[this.FILE],vaultPath:this.getRelativeVaultPath(r[this.FILE])}}async checkAuthorInfo(){let r=await this.getConfig("user.name"),i=await this.getConfig("user.email");if(!r||!i)throw Error("Git author name and email are not set. Please set both fields in the settings.")}showNotice(r,i=!0){if(!this.plugin.settings.disablePopups)return new Cn.Notice(r,i?this.noticeLength:void 0)}};async function xv(t){let e=await pe.walk(t);if(!Array.isArray(e))throw new TypeError("isomorphic-git walk returned a non-array result");return e}function S3(t){let e=[new Uint8Array(t)].values();return{next:()=>Promise.resolve(e.next()),[Symbol.asyncIterator](){return this}}}async function k3(t){let e=new ReadableStream({async start(i){for await(let n of t)i.enqueue(n);i.close()}});return await new Response(e).arrayBuffer()}async function C3(t){let e=new Uint8Array(t);if(e.length<2||e[0]!==31||e[1]!==139)return t;try{let r=new Blob([t]).stream().pipeThrough(new DecompressionStream("gzip"));return await new Response(r).arrayBuffer()}catch(r){return t}}m();var PT=mt(Qd(),1),oi=mt(require("fs/promises"),1),rs=require("obsidian"),Be=mt(require("path"),1),Mu=require("path");m();var lh=mt(Nk(),1);m();var Ev=new WeakMap;function wl(...t){let e=new String(t);return Ev.set(e,t),e}function Si(t){return t instanceof String&&Ev.has(t)}function bl(t){var e;return(e=Ev.get(t))!=null?e:[]}var ah=mt(Qd(),1),pA=require("child_process");var QA=mt(kv(),1),cT=require("node:path");m();function*Bk(t,e){let r=e==="global";for(let i of t)i.isGlobal===r&&(yield i)}var z3=new Set(["--add","--edit","--remove-section","--rename-section","--replace-all","--unset","--unset-all","-e"]),W3=new Set(["--get","--get-all","--get-color","--get-colorbool","--get-regexp","--get-urlmatch","--list","-l"]),q3=new Set(["edit","remove-section","rename-section","set","unset"]),Y3=new Set(["get","get-color","get-colorbool","list"]);function Z3(t,e){var i;for(let{name:n}of Bk(t,"task")){if(z3.has(n))return _l(!0,e);if(W3.has(n))return _l(!1,e)}let r=(i=e.at(0))==null?void 0:i.toLowerCase();return r===void 0?null:q3.has(r)?_l(!0,e.slice(1)):Y3.has(r)?_l(!1,e.slice(1)):e.length===1?_l(!1,e):_l(!0,e)}function _l(t=!1,e=[]){var i;let r=(i=e.at(0))==null?void 0:i.toLowerCase();return r===void 0?null:{isWrite:t,isRead:!t,key:r,value:e.at(1)}}function K3(t,e){return e.isWrite&&e.value!==void 0?{key:e.key,value:e.value,scope:t}:{key:e.key,scope:t}}function X3(t){let e=(t==null?void 0:t.indexOf("="))||-1;return!t||e<0?null:{key:t.slice(0,e).trim().toLowerCase(),value:t.slice(e+1)}}function Q3(t){for(let{name:e}of Bk(t,"task"))switch(e){case"--global":return"global";case"--system":return"system";case"--worktree":return"worktree";case"--local":return"local";case"--file":case"-f":return"file"}return"local"}function J3({name:t}){if(t==="-c"||t==="--config")return"inline";if(t==="--config-env")return"env"}function*e8(t){for(let e of t){let r=J3(e),i=r&&X3(e.value);i&&(yield{...i,scope:r})}}function t8(t,e,r){let i={read:[],write:[...e8(e)]};return t==="config"&&r8(i,Q3(e),Z3(e,r)),i}function r8(t,e,r){if(r===null)return;let i=K3(e,r);r.isWrite?t.write.push(i):t.read.push(i)}var Hk={short:new Map([["c",!0]])},i8={short:new Map([["C",!0],["P",!1],["h",!1],["p",!1],["v",!1],...Hk.short.entries()]),long:new Set(["attr-source","config-env","exec-path","git-dir","list-cmds","namespace","super-prefix","work-tree"])},n8={clone:{short:new Map([["b",!0],["j",!0],["l",!1],["n",!1],["o",!0],["q",!1],["s",!1],["u",!0]]),long:new Set(["branch","config","jobs","origin","upload-pack","u","template"])},commit:{short:new Map([["C",!0],["F",!0],["c",!0],["m",!0],["t",!0]]),long:new Set(["file","message","reedit-message","reuse-message","template"])},config:{short:new Map([["e",!1],["f",!0],["l",!1]]),long:new Set(["blob","comment","default","file","type","value"])},fetch:{short:new Map,long:new Set(["upload-pack"])},init:{short:new Map,long:new Set(["template"])},pull:{short:new Map,long:new Set(["upload-pack"])},push:{short:new Map,long:new Set(["exec","receive-pack"])}},s8={short:new Map,long:new Set};function a8(t){var r;let e=(r=n8[t!=null?t:""])!=null?r:s8;return{short:new Map([...Hk.short.entries(),...e.short.entries()]),long:e.long}}function Uk(t,e=i8){if(t.startsWith("--")){let r=t.indexOf("=");if(r>2)return[{name:t.slice(0,r),value:t.slice(r+1),needsNext:!1}];let i=t.slice(2);return[{name:t,needsNext:e.long.has(i)}]}if(t.length===2){let r=t.charAt(1),i=e.short.get(r);return[{name:t,needsNext:i===!0}]}return o8(t,e.short)}function o8(t,e){let r=t.slice(1).split(""),i=[];for(let n=0;ne.has(l)))return i.push({name:`-${s}`,value:o,needsNext:!1}),i}i.push({name:`-${s}`,needsNext:a})}return i}function l8(t,e=[]){let r=0;for(;rfunction(){return t&&(e=(0,t[qv(t)[0]])(t=0)),e},E8=(t,e)=>function(){return e||(0,t[qv(t)[0]])((e={exports:{}}).exports,e),e.exports},Pt=(t,e)=>{for(var r in e)Wv(t,r,{get:e[r],enumerable:!0})},S8=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of qv(e))!x8.call(t,n)&&n!==r&&Wv(t,n,{get:()=>e[n],enumerable:!(i=y8(e,n))||i.enumerable});return t},St=t=>S8(Wv({},"__esModule",{value:!0}),t),jr,Ws=Y({"src/lib/errors/git-error.ts"(){"use strict";jr=class extends Error{constructor(t,e){super(e),this.task=t,Object.setPrototypeOf(this,new.target.prototype)}}}}),Pu,Sl=Y({"src/lib/errors/git-response-error.ts"(){"use strict";Ws(),Pu=class extends jr{constructor(t,e){super(void 0,e||String(t)),this.git=t}}}}),EC,SC=Y({"src/lib/errors/task-configuration-error.ts"(){"use strict";Ws(),EC=class extends jr{constructor(t){super(void 0,t)}}}});function kC(t){return typeof t!="function"?La:t}function CC(t){return typeof t=="function"&&t!==La}function AC(t,e){let r=t.indexOf(e);return r<=0?[t,""]:[t.substr(0,r),t.substr(r+1)]}function TC(t,e=0){return PC(t)&&t.length>e?t[e]:void 0}function Oa(t,e=0){if(PC(t)&&t.length>e)return t[t.length-1-e]}function PC(t){return dh(t)}function Ru(t="",e=!0,r=` +`){return t.split(r).reduce((i,n)=>{let s=e?n.trim():n;return s&&i.push(s),i},[])}function Yv(t,e){return Ru(t,!0).map(r=>e(r))}function Zv(t){return(0,lh.exists)(t,lh.FOLDER)}function Ai(t,e){return Array.isArray(t)?t.includes(e)||t.push(e):t.add(e),e}function RC(t,e){return Array.isArray(t)&&!t.includes(e)&&t.push(e),t}function ch(t,e){if(Array.isArray(t)){let r=t.indexOf(e);r>=0&&t.splice(r,1)}else t.delete(e);return e}function An(t){return Array.isArray(t)?t:[t]}function $C(t){return t.replace(/[\s-]+(.)/g,(e,r)=>r.toUpperCase())}function kl(t){return An(t).map(e=>e instanceof String?e:String(e))}function rt(t,e=0){if(t==null)return e;let r=parseInt(t,10);return Number.isNaN(r)?e:r}function Au(t,e){let r=[];for(let i=0,n=t.length;i{t[i]!==void 0&&(r[i]=t[i])}),r}function Fv(t=0){return new Promise(e=>setTimeout(e,t))}function Iv(t){if(t!==!1)return t}var xl,La,$u,uh=Y({"src/lib/utils/util.ts"(){"use strict";Kv(),xl="\0",La=()=>{},$u=Object.prototype.toString.call.bind(Object.prototype.toString)}});function ur(t,e,r){return e(t)?t:arguments.length>2?r:void 0}function Mv(t,e){let r=Si(t)?"string":typeof t;return/number|string|boolean/.test(r)&&(!e||!e.includes(r))}function fh(t){return!!t&&$u(t)==="[object Object]"}function IC(t){return typeof t=="function"}var Fu,MC,wt,nh,dh,Kv=Y({"src/lib/utils/argument-filters.ts"(){"use strict";uh(),Fu=t=>Array.isArray(t),MC=t=>typeof t=="number",wt=t=>typeof t=="string"||Si(t),nh=t=>wt(t)||Array.isArray(t)&&t.every(wt),dh=t=>t==null||"number|boolean|function".includes(typeof t)?!1:typeof t.length=="number"}}),Dv,k8=Y({"src/lib/utils/exit-codes.ts"(){"use strict";Dv=(t=>(t[t.SUCCESS=0]="SUCCESS",t[t.ERROR=1]="ERROR",t[t.NOT_FOUND=-2]="NOT_FOUND",t[t.UNCLEAN=128]="UNCLEAN",t))(Dv||{})}}),sh,C8=Y({"src/lib/utils/git-output-streams.ts"(){"use strict";sh=class DC{constructor(e,r){this.stdOut=e,this.stdErr=r}asStrings(){return new DC(this.stdOut.toString("utf8"),this.stdErr.toString("utf8"))}}}});function A8(){throw new Error("LineParser:useMatches not implemented")}var be,zs,T8=Y({"src/lib/utils/line-parser.ts"(){"use strict";be=class{constructor(t,e){this.matches=[],this.useMatches=A8,this.parse=(r,i)=>(this.resetMatches(),this._regExp.every((n,s)=>this.addMatch(n,s,r(s)))?this.useMatches(i,this.prepareMatches())!==!1:!1),this._regExp=Array.isArray(t)?t:[t],e&&(this.useMatches=e)}resetMatches(){this.matches.length=0}prepareMatches(){return this.matches}addMatch(t,e,r){let i=r&&t.exec(r);return i&&this.pushMatch(e,i),!!i}pushMatch(t,e){this.matches.push(...e.slice(1))}},zs=class extends be{addMatch(t,e,r){return/^remote:\s/.test(String(r))&&super.addMatch(t,e,r)}pushMatch(t,e){(t>0||e.length>1)&&super.pushMatch(t,e)}}}});function OC(...t){let e=process.cwd(),r=Object.assign({baseDir:e,...LC},...t.filter(i=>typeof i=="object"&&i));return r.baseDir=r.baseDir||e,r.trimmed=r.trimmed===!0,r}var LC,P8=Y({"src/lib/utils/simple-git-options.ts"(){"use strict";LC={binary:"git",maxConcurrentProcesses:5,config:[],trimmed:!1}}});function Xv(t,e=[]){return fh(t)?Object.keys(t).reduce((r,i)=>{let n=t[i];if(Si(n))r.push(n);else if(Mv(n,["boolean"]))r.push(i+"="+n);else if(Array.isArray(n))for(let s of n)Mv(s,["string","number"])||r.push(i+"="+s);else r.push(i);return r},e):e}function Sr(t,e=0,r=!1){let i=[];for(let n=0,s=e<0?t.length:e;n{for(let s=Ru(n,i),a=0,o=s.length;a{if(!(a+c>=o))return s[a+c]};e.some(({parse:c})=>c(l,t))}}),t}var F8=Y({"src/lib/utils/task-parser.ts"(){"use strict";uh()}}),NC={};Pt(NC,{ExitCodes:()=>Dv,GitOutputStreams:()=>sh,LineParser:()=>be,NOOP:()=>La,NULL:()=>xl,RemoteLineParser:()=>zs,append:()=>Ai,appendTaskOptions:()=>Xv,asArray:()=>An,asCamelCase:()=>$C,asFunction:()=>kC,asNumber:()=>rt,asStringArray:()=>kl,bufferToString:()=>Tu,callTaskParser:()=>Ov,createInstanceConfig:()=>OC,delay:()=>Fv,filterArray:()=>Fu,filterFunction:()=>IC,filterHasLength:()=>dh,filterNumber:()=>MC,filterPlainObject:()=>fh,filterPrimitives:()=>Mv,filterString:()=>wt,filterStringOrStringArray:()=>nh,filterType:()=>ur,first:()=>TC,folderExists:()=>Zv,forEachLineWithContent:()=>Yv,getTrailingOptions:()=>Sr,including:()=>RC,isUserFunction:()=>CC,last:()=>Oa,objectToString:()=>$u,orVoid:()=>Iv,parseStringResponse:()=>Vr,pick:()=>FC,prefixedArray:()=>Au,remove:()=>ch,splitOn:()=>AC,toLinesWithContent:()=>Ru,trailingFunctionArgument:()=>ct,trailingOptionsArgument:()=>Qv});var ve=Y({"src/lib/utils/index.ts"(){"use strict";Kv(),k8(),C8(),T8(),P8(),$8(),F8(),uh()}}),BC={};Pt(BC,{CheckRepoActions:()=>Lv,checkIsBareRepoTask:()=>UC,checkIsRepoRootTask:()=>HC,checkIsRepoTask:()=>I8});function I8(t){switch(t){case"bare":return UC();case"root":return HC()}return{commands:["rev-parse","--is-inside-work-tree"],format:"utf-8",onError:hh,parser:Jv}}function HC(){return{commands:["rev-parse","--git-dir"],format:"utf-8",onError:hh,parser(e){return/^\.(git)?$/.test(e.trim())}}}function UC(){return{commands:["rev-parse","--is-bare-repository"],format:"utf-8",onError:hh,parser:Jv}}function M8(t){return/(Not a git repository|Kein Git-Repository)/i.test(String(t))}var Lv,hh,Jv,GC=Y({"src/lib/tasks/check-is-repo.ts"(){"use strict";ve(),Lv=(t=>(t.BARE="bare",t.IN_TREE="tree",t.IS_REPO_ROOT="root",t))(Lv||{}),hh=({exitCode:t},e,r,i)=>{if(t===128&&M8(e))return r(k.from("false"));i(e)},Jv=t=>t.trim()==="true"}});function D8(t,e){let r=new jC(t),i=t?zC:VC;return Ru(e).forEach(n=>{let s=n.replace(i,"");r.paths.push(s),(WC.test(s)?r.folders:r.files).push(s)}),r}var jC,VC,zC,WC,O8=Y({"src/lib/responses/CleanSummary.ts"(){"use strict";ve(),jC=class{constructor(t){this.dryRun=t,this.paths=[],this.files=[],this.folders=[]}},VC=/^[a-z]+\s*/i,zC=/^[a-z]+\s+[a-z]+\s*/i,WC=/\/$/}}),Nv={};Pt(Nv,{EMPTY_COMMANDS:()=>ph,adhocExecTask:()=>qC,configurationErrorTask:()=>Gr,isBufferTask:()=>ZC,isEmptyTask:()=>KC,straightThroughBufferTask:()=>YC,straightThroughStringTask:()=>kr});function qC(t){return{commands:ph,format:"empty",parser:t}}function Gr(t){return{commands:ph,format:"empty",parser(){throw typeof t=="string"?new EC(t):t}}}function kr(t,e=!1){return{commands:t,format:"utf-8",parser(r){return e?String(r).trim():r}}}function YC(t){return{commands:t,format:"buffer",parser(e){return e}}}function ZC(t){return t.format==="buffer"}function KC(t){return t.format==="empty"||!t.commands.length}var ph,kt=Y({"src/lib/tasks/task.ts"(){"use strict";SC(),ph=[]}}),XC={};Pt(XC,{CONFIG_ERROR_INTERACTIVE_MODE:()=>ew,CONFIG_ERROR_MODE_REQUIRED:()=>tw,CONFIG_ERROR_UNKNOWN_OPTION:()=>rw,CleanOptions:()=>Da,cleanTask:()=>QC,cleanWithOptionsTask:()=>L8,isCleanOptionsArray:()=>N8});function L8(t,e){let{cleanMode:r,options:i,valid:n}=B8(t);return r?n.options?(i.push(...e),i.some(G8)?Gr(ew):QC(r,i)):Gr(rw+JSON.stringify(t)):Gr(tw)}function QC(t,e){return{commands:["clean",`-${t}`,...e],format:"utf-8",parser(i){return D8(t==="n",i)}}}function N8(t){return Array.isArray(t)&&t.every(e=>iw.has(e))}function B8(t){let e,r=[],i={cleanMode:!1,options:!0};return t.replace(/[^a-z]i/g,"").split("").forEach(n=>{H8(n)?(e=n,i.cleanMode=!0):i.options=i.options&&U8(r[r.length]=`-${n}`)}),{cleanMode:e,options:r,valid:i}}function H8(t){return t==="f"||t==="n"}function U8(t){return/^-[a-z]$/i.test(t)&&iw.has(t.charAt(1))}function G8(t){return/^-[^\-]/.test(t)?t.indexOf("i")>0:t==="--interactive"}var ew,tw,rw,Da,iw,JC=Y({"src/lib/tasks/clean.ts"(){"use strict";O8(),ve(),kt(),ew="Git clean interactive mode is not supported",tw='Git clean mode parameter ("n" or "f") is required',rw="Git clean unknown option found in: ",Da=(t=>(t.DRY_RUN="n",t.FORCE="f",t.IGNORED_INCLUDED="x",t.IGNORED_ONLY="X",t.EXCLUDING="e",t.QUIET="q",t.RECURSIVE="d",t))(Da||{}),iw=new Set(["i",...kl(Object.values(Da))])}});function j8(t){let e=new tA;for(let r of eA(t))e.addValue(r.file,String(r.key),r.value);return e}function V8(t,e){let r=null,i=[],n=new Map;for(let s of eA(t,e))s.key===e&&(i.push(r=s.value),n.has(s.file)||n.set(s.file,[]),n.get(s.file).push(r));return{key:e,paths:Array.from(n.keys()),scopes:n,value:r,values:i}}function z8(t){return t.replace(/^(file):/,"")}function*eA(t,e=null){let r=t.split("\0");for(let i=0,n=r.length-1;iObject.assign(t,this.values[e]),{})),this._all}addFile(t){if(!(t in this.values)){let e=Oa(this.files);this.values[t]=e?Object.create(this.values[e]):{},this.files.push(t)}return this.values[t]}addValue(t,e,r){let i=this.addFile(t);Object.hasOwn(i,e)?Array.isArray(i[e])?i[e].push(r):i[e]=[i[e],r]:i[e]=r,this._all=void 0}}}});function Cv(t,e){return typeof t=="string"&&Object.hasOwn(Bv,t)?t:e}function q8(t,e,r,i){let n=["config",`--${i}`];return r&&n.push("--add"),n.push(t,e),{commands:n,format:"utf-8",parser(s){return s}}}function Y8(t,e){let r=["config","--null","--show-origin","--get-all",t];return e&&r.splice(1,0,`--${e}`),{commands:r,format:"utf-8",parser(i){return V8(i,t)}}}function Z8(t){let e=["config","--list","--show-origin","--null"];return t&&e.push(`--${t}`),{commands:e,format:"utf-8",parser(r){return j8(r)}}}function K8(){return{addConfig(t,e,...r){return this._runTask(q8(t,e,r[0]===!0,Cv(r[1],"local")),ct(arguments))},getConfig(t,e){return this._runTask(Y8(t,Cv(e,void 0)),ct(arguments))},listConfig(...t){return this._runTask(Z8(Cv(t[0],void 0)),ct(arguments))}}}var Bv,rA=Y({"src/lib/tasks/config.ts"(){"use strict";W8(),ve(),Bv=(t=>(t.system="system",t.global="global",t.local="local",t.worktree="worktree",t))(Bv||{})}});function X8(t){return iA.has(t)}var Av,iA,nA=Y({"src/lib/tasks/diff-name-status.ts"(){"use strict";Av=(t=>(t.ADDED="A",t.COPIED="C",t.DELETED="D",t.MODIFIED="M",t.RENAMED="R",t.CHANGED="T",t.UNMERGED="U",t.UNKNOWN="X",t.BROKEN="B",t))(Av||{}),iA=new Set(Object.values(Av))}});function Q8(...t){return new aA().param(...t)}function J8(t){let e=new Set,r={};return Yv(t,i=>{let[n,s,a]=i.split(xl);e.add(n),(r[n]=r[n]||[]).push({line:rt(s),path:n,preview:a})}),{paths:e,results:r}}function eH(){return{grep(t){let e=ct(arguments),r=Sr(arguments);for(let n of sA)if(r.includes(n))return this._runTask(Gr(`git.grep: use of "${n}" is not supported.`),e);typeof t=="string"&&(t=Q8().param(t));let i=["grep","--null","-n","--full-name",...r,...t];return this._runTask({commands:i,format:"utf-8",parser(n){return J8(n)}},e)}}}var sA,Cu,Wk,aA,oA=Y({"src/lib/tasks/grep.ts"(){"use strict";ve(),kt(),sA=["-h"],Cu=Symbol("grepQuery"),aA=class{constructor(){this[Wk]=[]}*[(Wk=Cu,Symbol.iterator)](){for(let t of this[Cu])yield t}and(...t){return t.length&&this[Cu].push("--and","(",...Au(t,"-e"),")"),this}param(...t){return this[Cu].push(...Au(t,"-e")),this}}}}),lA={};Pt(lA,{ResetMode:()=>th,getResetMode:()=>rH,resetTask:()=>tH});function tH(t,e){let r=["reset"];return cA(t)&&r.push(`--${t}`),r.push(...e),kr(r)}function rH(t){if(cA(t))return t;switch(typeof t){case"string":case"undefined":return"soft"}}function cA(t){return typeof t=="string"&&uA.includes(t)}var th,uA,fA=Y({"src/lib/tasks/reset.ts"(){"use strict";ve(),kt(),th=(t=>(t.MIXED="mixed",t.SOFT="soft",t.HARD="hard",t.MERGE="merge",t.KEEP="keep",t))(th||{}),uA=kl(Object.values(th))}});function iH(){return(0,ah.default)("simple-git")}function qk(t,e,r){return!e||!String(e).replace(/\s*/,"")?r?(i,...n)=>{t(i,...n),r(i,...n)}:t:(i,...n)=>{t(`%s ${i}`,e,...n),r&&r(i,...n)}}function nH(t,e,{namespace:r}){if(typeof t=="string")return t;let i=e&&e.namespace||"";return i.startsWith(r)?i.substr(r.length+1):i||r}function nw(t,e,r,i=iH()){let n=t&&`[${t}]`||"",s=[],a=typeof e=="string"?i.extend(e):e,o=nH(ur(e,wt),a,i);return c(r);function l(u,f){return Ai(s,nw(t,o.replace(/^[^:]+/,u),f,i))}function c(u){let f=u&&`[${u}]`||"",d=a&&qk(a,f)||La,h=qk(i,`${n} ${f}`,d);return Object.assign(a?d:h,{label:t,sibling:l,info:h,step:c})}}var dA=Y({"src/lib/git-logger.ts"(){"use strict";ve(),ah.default.formatters.L=t=>String(dh(t)?t.length:"-"),ah.default.formatters.B=t=>k.isBuffer(t)?t.toString("utf8"):$u(t)}}),hA,sH=Y({"src/lib/runners/tasks-pending-queue.ts"(){"use strict";var t;Ws(),dA(),hA=(t=class{constructor(r="GitExecutor"){this.logLabel=r,this._queue=new Map}withProgress(r){return this._queue.get(r)}createProgress(r){let i=t.getName(r.commands[0]),n=nw(this.logLabel,i);return{task:r,logger:n,name:i}}push(r){let i=this.createProgress(r);return i.logger("Adding task to the queue, commands = %o",r.commands),this._queue.set(r,i),i}fatal(r){for(let[i,{logger:n}]of Array.from(this._queue.entries()))i===r.task?(n.info("Failed %o",r),n("Fatal exception, any as-yet un-started tasks run through this executor will not be attempted")):n.info("A fatal exception occurred in a previous task, the queue has been purged: %o",r.message),this.complete(i);if(this._queue.size!==0)throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`)}complete(r){this.withProgress(r)&&this._queue.delete(r)}attempt(r){let i=this.withProgress(r);if(!i)throw new jr(void 0,"TasksPendingQueue: attempt called for an unknown task");return i.logger("Starting task"),i}static getName(r="empty"){return`task:${r}:${++t.counter}`}},t.counter=0,t)}});function Ma(t,e){return{method:TC(t.commands)||"",commands:e}}function aH(t,e){return r=>{e("[ERROR] child process exception %o",r),t.push(k.from(String(r.stack),"ascii"))}}function Yk(t,e,r,i){return n=>{r("%s received %L bytes",e,n),i("%B",n),t.push(n)}}var Hv,oH=Y({"src/lib/runners/git-executor-chain.ts"(){"use strict";Ws(),kt(),ve(),sH(),Hv=class{constructor(t,e,r){this._executor=t,this._scheduler=e,this._plugins=r,this._chain=Promise.resolve(),this._queue=new hA}get cwd(){return this._cwd||this._executor.cwd}set cwd(t){this._cwd=t}get env(){return this._executor.env}get outputHandler(){return this._executor.outputHandler}chain(){return this}push(t){return this._queue.push(t),this._chain=this._chain.then(()=>this.attemptTask(t))}async attemptTask(t){let e=await this._scheduler.next(),r=()=>this._queue.complete(t);try{let{logger:i}=this._queue.attempt(t);return await(KC(t)?this.attemptEmptyTask(t,i):this.attemptRemoteTask(t,i))}catch(i){throw this.onFatalException(t,i)}finally{r(),e()}}onFatalException(t,e){let r=e instanceof jr?Object.assign(e,{task:t}):new jr(t,e&&String(e));return this._chain=Promise.resolve(),this._queue.fatal(r),r}async attemptRemoteTask(t,e){let r=this._plugins.exec("spawn.binary","",Ma(t,t.commands)),i=this._plugins.exec("spawn.args",[...t.commands],{...Ma(t,t.commands),env:{...this.env}}),n=await this.gitResponse(t,r,i,this.outputHandler,e.step("SPAWN")),s=await this.handleTaskData(t,i,n,e.step("HANDLE"));return e("passing response to task's parser as a %s",t.format),ZC(t)?Ov(t.parser,s):Ov(t.parser,s.asStrings())}async attemptEmptyTask(t,e){return e("empty task bypassing child process to call to task's parser"),t.parser(this)}handleTaskData(t,e,r,i){let{exitCode:n,rejection:s,stdOut:a,stdErr:o}=r;return new Promise((l,c)=>{i("Preparing to handle process response exitCode=%d stdOut=",n);let{error:u}=this._plugins.exec("task.error",{error:s},{...Ma(t,e),...r});if(u&&t.onError)return i.info("exitCode=%s handling with custom error handler"),t.onError(r,u,f=>{i.info("custom error handler treated as success"),i("custom error returned a %s",$u(f)),l(new sh(Array.isArray(f)?k.concat(f):f,k.concat(o)))},c);if(u)return i.info("handling as error: exitCode=%s stdErr=%s rejection=%o",n,o.length,s),c(u);i.info("retrieving task output complete"),l(new sh(k.concat(a),k.concat(o)))})}async gitResponse(t,e,r,i,n){let s=n.sibling("output"),a=this._plugins.exec("spawn.options",{cwd:this.cwd,env:this.env,windowsHide:!0},Ma(t,t.commands));return new Promise(o=>{let l=[],c=[];n.info("%s %o",e,r),n("%O",a);let u=this._beforeSpawn(t,r);if(u)return o({stdOut:l,stdErr:c,exitCode:9901,rejection:u});this._plugins.exec("spawn.before",void 0,{...Ma(t,r),kill(d){u=d||u}});let f=(0,pA.spawn)(e,r,a);f.stdout.on("data",Yk(l,"stdOut",n,s.step("stdOut"))),f.stderr.on("data",Yk(c,"stdErr",n,s.step("stdErr"))),f.on("error",aH(c,n)),i&&(n("Passing child process stdOut/stdErr to custom outputHandler"),i(e,f.stdout,f.stderr,[...r])),this._plugins.exec("spawn.after",void 0,{...Ma(t,r),spawned:f,close(d,h){o({stdOut:l,stdErr:c,exitCode:d,rejection:u||h})},kill(d){f.killed||(u=d,f.kill("SIGINT"))}})})}_beforeSpawn(t,e){let r;return this._plugins.exec("spawn.before",void 0,{...Ma(t,e),kill(i){r=i||r}}),r}}}}),mA={};Pt(mA,{GitExecutor:()=>gA});var gA,lH=Y({"src/lib/runners/git-executor.ts"(){"use strict";oH(),gA=class{constructor(t,e,r){this.cwd=t,this._scheduler=e,this._plugins=r,this._chain=new Hv(this,this._scheduler,this._plugins)}chain(){return new Hv(this,this._scheduler,this._plugins)}push(t){return this._chain.push(t)}}}});function cH(t,e,r=La){let i=s=>{r(null,s)},n=s=>{(s==null?void 0:s.task)===t&&r(s instanceof Pu?uH(s):s,void 0)};e.then(i,n)}function uH(t){let e=i=>{console.warn(`simple-git deprecation notice: accessing GitResponseError.${i} should be GitResponseError.git.${i}, this will no longer be available in version 3`),e=La};return Object.create(t,Object.getOwnPropertyNames(t.git).reduce(r,{}));function r(i,n){return n in t||(i[n]={enumerable:!1,configurable:!1,get(){return e(n),t.git[n]}}),i}}var fH=Y({"src/lib/task-callback.ts"(){"use strict";Sl(),ve()}});function Zk(t,e){return qC(r=>{if(!Zv(t))throw new Error(`Git.cwd: cannot change to non-directory "${t}"`);return(e||r).cwd=t})}var dH=Y({"src/lib/tasks/change-working-directory.ts"(){"use strict";ve(),kt()}});function Tv(t){let e=["checkout",...t];return e[1]==="-b"&&e.includes("-B")&&(e[1]=ch(e,"-B")),kr(e)}function hH(){return{checkout(){return this._runTask(Tv(Sr(arguments,1)),ct(arguments))},checkoutBranch(t,e){return this._runTask(Tv(["-b",t,e,...Sr(arguments)]),ct(arguments))},checkoutLocalBranch(t){return this._runTask(Tv(["-b",t,...Sr(arguments)]),ct(arguments))}}}var pH=Y({"src/lib/tasks/checkout.ts"(){"use strict";ve(),kt()}});function mH(){return{count:0,garbage:0,inPack:0,packs:0,prunePackable:0,size:0,sizeGarbage:0,sizePack:0}}function gH(){return{countObjects(){return this._runTask({commands:["count-objects","--verbose"],format:"utf-8",parser(t){return Vr(mH(),[vA],t)}})}}}var vA,vH=Y({"src/lib/tasks/count-objects.ts"(){"use strict";ve(),vA=new be(/([a-z-]+): (\d+)$/,(t,[e,r])=>{let i=$C(e);Object.hasOwn(t,i)&&(t[i]=rt(r))})}});function wH(t){return Vr({author:null,branch:"",commit:"",root:!1,summary:{changes:0,insertions:0,deletions:0}},wA,t)}var wA,bH=Y({"src/lib/parsers/parse-commit.ts"(){"use strict";ve(),wA=[new be(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/,(t,[e,r,i])=>{t.branch=e,t.commit=i,t.root=!!r}),new be(/\s*Author:\s(.+)/i,(t,[e])=>{let r=e.split("<"),i=r.pop();!i||!i.includes("@")||(t.author={email:i.substr(0,i.length-1),name:r.join("<").trim()})}),new be(/(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g,(t,[e,r,i])=>{t.summary.changes=parseInt(e,10)||0,t.summary.insertions=parseInt(r,10)||0,t.summary.deletions=parseInt(i,10)||0}),new be(/^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/,(t,[e,r,i])=>{t.summary.changes=parseInt(e,10)||0;let n=parseInt(r,10)||0;i==="-"?t.summary.deletions=n:i==="+"&&(t.summary.insertions=n)})]}});function _H(t,e,r){return{commands:["-c","core.abbrev=40","commit",...Au(t,"-m"),...e,...r],format:"utf-8",parser:wH}}function yH(){return{commit(e,...r){let i=ct(arguments),n=t(e)||_H(An(e),An(ur(r[0],nh,[])),[...kl(ur(r[1],Fu,[])),...Sr(arguments,0,!0)]);return this._runTask(n,i)}};function t(e){return!nh(e)&&Gr("git.commit: requires the commit message to be supplied as a string/string[]")}}var xH=Y({"src/lib/tasks/commit.ts"(){"use strict";bH(),ve(),kt()}});function EH(){return{firstCommit(){return this._runTask(kr(["rev-list","--max-parents=0","HEAD"],!0),ct(arguments))}}}var SH=Y({"src/lib/tasks/first-commit.ts"(){"use strict";ve(),kt()}});function kH(t,e){let r=["hash-object",t];return e&&r.push("-w"),kr(r,!0)}var CH=Y({"src/lib/tasks/hash-object.ts"(){"use strict";kt()}});function AH(t,e,r){let i=String(r).trim(),n;if(n=bA.exec(i))return new rh(t,e,!1,n[1]);if(n=_A.exec(i))return new rh(t,e,!0,n[1]);let s="",a=i.split(" ");for(;a.length;)if(a.shift()==="in"){s=a.join(" ");break}return new rh(t,e,/^re/i.test(i),s)}var rh,bA,_A,TH=Y({"src/lib/responses/InitSummary.ts"(){"use strict";rh=class{constructor(t,e,r,i){this.bare=t,this.path=e,this.existing=r,this.gitDir=i}},bA=/^Init.+ repository in (.+)$/,_A=/^Rein.+ in (.+)$/}});function PH(t){return t.includes(sw)}function RH(t=!1,e,r){let i=["init",...r];return t&&!PH(i)&&i.splice(1,0,sw),{commands:i,format:"utf-8",parser(n){return AH(i.includes("--bare"),e,n)}}}var sw,$H=Y({"src/lib/tasks/init.ts"(){"use strict";TH(),sw="--bare"}});function aw(t){for(let e=0;eVr(new yA,e,r,!1)}var Pv,Kk,Xk,Qk,EA,SA=Y({"src/lib/parsers/parse-diff-summary.ts"(){"use strict";Iu(),IH(),nA(),ve(),Pv=[new be(/^(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/,(t,[e,r,i=""])=>{t.files.push({file:e.trim(),changes:rt(r),insertions:i.replace(/[^+]/g,"").length,deletions:i.replace(/[^-]/g,"").length,binary:!1})}),new be(/^(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/,(t,[e,r,i])=>{t.files.push({file:e.trim(),before:rt(r),after:rt(i),binary:!0})}),new be(/(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/,(t,[e,r])=>{let i=/(\d+) i/.exec(r),n=/(\d+) d/.exec(r);t.changed=rt(e),t.insertions=rt(i==null?void 0:i[1]),t.deletions=rt(n==null?void 0:n[1])})],Kk=[new be(/(\d+)\t(\d+)\t(.+)$/,(t,[e,r,i])=>{let n=rt(e),s=rt(r);t.changed++,t.insertions+=n,t.deletions+=s,t.files.push({file:i,changes:n+s,insertions:n,deletions:s,binary:!1})}),new be(/-\t-\t(.+)$/,(t,[e])=>{t.changed++,t.files.push({file:e,after:0,before:0,binary:!0})})],Xk=[new be(/(.+)$/,(t,[e])=>{t.changed++,t.files.push({file:e,changes:0,insertions:0,deletions:0,binary:!1})})],Qk=[new be(/([ACDMRTUXB])([0-9]{0,3})\t(.[^\t]*)(\t(.[^\t]*))?$/,(t,[e,r,i,n,s])=>{t.changed++,t.files.push({file:s!=null?s:i,changes:0,insertions:0,deletions:0,binary:!1,status:Iv(X8(e)&&e),from:Iv(!!s&&i!==s&&i),similarity:rt(r)})})],EA={"":Pv,"--stat":Pv,"--numstat":Kk,"--name-status":Qk,"--name-only":Xk}}});function MH(t,e){return e.reduce((r,i,n)=>(r[i]=t[n]||"",r),Object.create({diff:null}))}function kA(t=uw,e=CA,r=""){let i=xA(r);return function(n){let s=Ru(n.trim(),!1,lw).map(function(a){let o=a.split(cw),l=MH(o[0].split(t),e);return o.length>1&&o[1].trim()&&(l.diff=i(o[1])),l});return{all:s,latest:s.length&&s[0]||null,total:s.length}}}var lw,cw,uw,CA,AA=Y({"src/lib/parsers/parse-list-log-summary.ts"(){"use strict";ve(),SA(),Iu(),lw="\xF2\xF2\xF2\xF2\xF2\xF2 ",cw=" \xF2\xF2",uw=" \xF2 ",CA=["hash","date","message","refs","author_name","author_email"]}}),TA={};Pt(TA,{diffSummaryTask:()=>DH,validateLogFormatConfig:()=>mh});function DH(t){let e=aw(t),r=["diff"];return e===""&&(e="--stat",r.push("--stat=4096")),r.push(...t),mh(r)||{commands:r,format:"utf-8",parser:xA(e)}}function mh(t){let e=t.filter(FH);if(e.length>1)return Gr(`Summary flags are mutually exclusive - pick one of ${e.join(",")}`);if(e.length&&t.includes("-z"))return Gr(`Summary flag ${e} parsing is not compatible with null termination option '-z'`)}var fw=Y({"src/lib/tasks/diff.ts"(){"use strict";Iu(),SA(),kt()}});function OH(t,e){let r=[],i=[];return Object.keys(t).forEach(n=>{r.push(n),i.push(String(t[n]))}),[r,i.join(e)]}function LH(t){return Object.keys(t).reduce((e,r)=>(r in Uv||(e[r]=t[r]),e),{})}function PA(t={},e=[]){let r=ur(t.splitter,wt,uw),i=fh(t.format)?t.format:{hash:"%H",date:t.strictDate===!1?"%ai":"%aI",message:"%s",refs:"%D",body:t.multiLine?"%B":"%b",author_name:t.mailMap!==!1?"%aN":"%an",author_email:t.mailMap!==!1?"%aE":"%ae"},[n,s]=OH(i,r),a=[],o=[`--pretty=format:${lw}${s}${cw}`,...e],l=t.n||t["max-count"]||t.maxCount;if(l&&o.push(`--max-count=${l}`),t.from||t.to){let c=t.symmetric!==!1?"...":"..";a.push(`${t.from||""}${c}${t.to||""}`)}return wt(t.file)&&o.push("--follow",wl(t.file)),Xv(LH(t),o),{fields:n,splitter:r,commands:[...o,...a]}}function NH(t,e,r){let i=kA(t,e,aw(r));return{commands:["log",...r],format:"utf-8",parser:i}}function BH(){return{log(...r){let i=ct(arguments),n=PA(Qv(arguments),kl(ur(arguments[0],Fu,[]))),s=e(...r)||mh(n.commands)||t(n);return this._runTask(s,i)}};function t(r){return NH(r.splitter,r.fields,r.commands)}function e(r,i){return wt(r)&&wt(i)&&Gr("git.log(string, string) should be replaced with git.log({ from: string, to: string })")}}var Uv,RA=Y({"src/lib/tasks/log.ts"(){"use strict";Iu(),AA(),ve(),kt(),fw(),Uv=(t=>(t[t["--pretty"]=0]="--pretty",t[t["max-count"]=1]="max-count",t[t.maxCount=2]="maxCount",t[t.n=3]="n",t[t.file=4]="file",t[t.format=5]="format",t[t.from=6]="from",t[t.to=7]="to",t[t.splitter=8]="splitter",t[t.symmetric=9]="symmetric",t[t.mailMap=10]="mailMap",t[t.multiLine=11]="multiLine",t[t.strictDate=12]="strictDate",t))(Uv||{})}}),ih,$A,HH=Y({"src/lib/responses/MergeSummary.ts"(){"use strict";ih=class{constructor(t,e=null,r){this.reason=t,this.file=e,this.meta=r}toString(){return`${this.file}:${this.reason}`}},$A=class{constructor(){this.conflicts=[],this.merges=[],this.result="success"}get failed(){return this.conflicts.length>0}get reason(){return this.result}toString(){return this.conflicts.length?`CONFLICTS: ${this.conflicts.join(", ")}`:"OK"}}}}),Gv,FA,UH=Y({"src/lib/responses/PullSummary.ts"(){"use strict";Gv=class{constructor(){this.remoteMessages={all:[]},this.created=[],this.deleted=[],this.files=[],this.deletions={},this.insertions={},this.summary={changes:0,deletions:0,insertions:0}}},FA=class{constructor(){this.remote="",this.hash={local:"",remote:""},this.branch={local:"",remote:""},this.message=""}toString(){return this.message}}}});function Rv(t){return t.objects=t.objects||{compressing:0,counting:0,enumerating:0,packReused:0,reused:{count:0,delta:0},total:{count:0,delta:0}}}function Jk(t){let e=/^\s*(\d+)/.exec(t),r=/delta (\d+)/i.exec(t);return{count:rt(e&&e[1]||"0"),delta:rt(r&&r[1]||"0")}}var IA,GH=Y({"src/lib/parsers/parse-remote-objects.ts"(){"use strict";ve(),IA=[new zs(/^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i,(t,[e,r])=>{let i=e.toLowerCase(),n=Rv(t.remoteMessages);Object.assign(n,{[i]:rt(r)})}),new zs(/^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i,(t,[e,r])=>{let i=e.toLowerCase(),n=Rv(t.remoteMessages);Object.assign(n,{[i]:rt(r)})}),new zs(/total ([^,]+), reused ([^,]+), pack-reused (\d+)/i,(t,[e,r,i])=>{let n=Rv(t.remoteMessages);n.total=Jk(e),n.reused=Jk(r),n.packReused=rt(i)})]}});function MA(t,e){return Vr({remoteMessages:new OA},DA,e)}var DA,OA,LA=Y({"src/lib/parsers/parse-remote-messages.ts"(){"use strict";ve(),GH(),DA=[new zs(/^remote:\s*(.+)$/,(t,[e])=>(t.remoteMessages.all.push(e.trim()),!1)),...IA,new zs([/create a (?:pull|merge) request/i,/\s(https?:\/\/\S+)$/],(t,[e])=>{t.remoteMessages.pullRequestUrl=e}),new zs([/found (\d+) vulnerabilities.+\(([^)]+)\)/i,/\s(https?:\/\/\S+)$/],(t,[e,r,i])=>{t.remoteMessages.vulnerabilities={count:rt(e),summary:r,url:i}})],OA=class{constructor(){this.all=[]}}}});function jH(t,e){let r=Vr(new FA,NA,[t,e]);return r.message&&r}var eC,tC,rC,iC,NA,nC,dw,BA=Y({"src/lib/parsers/parse-pull.ts"(){"use strict";UH(),ve(),LA(),eC=/^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/,tC=/(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/,rC=/^(create|delete) mode \d+ (.+)/,iC=[new be(eC,(t,[e,r,i])=>{t.files.push(e),r&&(t.insertions[e]=r.length),i&&(t.deletions[e]=i.length)}),new be(tC,(t,[e,,r,,i])=>r!==void 0||i!==void 0?(t.summary.changes=+e||0,t.summary.insertions=+r||0,t.summary.deletions=+i||0,!0):!1),new be(rC,(t,[e,r])=>{Ai(t.files,r),Ai(e==="create"?t.created:t.deleted,r)})],NA=[new be(/^from\s(.+)$/i,(t,[e])=>{t.remote=e}),new be(/^fatal:\s(.+)$/,(t,[e])=>{t.message=e}),new be(/([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/,(t,[e,r,i,n])=>{t.branch.local=i,t.hash.local=e,t.branch.remote=n,t.hash.remote=r})],nC=(t,e)=>Vr(new Gv,iC,[t,e]),dw=(t,e)=>Object.assign(new Gv,nC(t,e),MA(t,e))}}),sC,HA,aC,VH=Y({"src/lib/parsers/parse-merge.ts"(){"use strict";HH(),ve(),BA(),sC=[new be(/^Auto-merging\s+(.+)$/,(t,[e])=>{t.merges.push(e)}),new be(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/,(t,[e,r])=>{t.conflicts.push(new ih(e,r))}),new be(/^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/,(t,[e,r,i])=>{t.conflicts.push(new ih(e,r,{deleteRef:i}))}),new be(/^CONFLICT\s+\((.+)\):/,(t,[e])=>{t.conflicts.push(new ih(e,null))}),new be(/^Automatic merge failed;\s+(.+)$/,(t,[e])=>{t.result=e})],HA=(t,e)=>Object.assign(aC(t,e),dw(t,e)),aC=t=>Vr(new $A,sC,t)}});function oC(t){return t.length?{commands:["merge",...t],format:"utf-8",parser(e,r){let i=HA(e,r);if(i.failed)throw new Pu(i);return i}}:Gr("Git.merge requires at least one option")}var zH=Y({"src/lib/tasks/merge.ts"(){"use strict";Sl(),VH(),kt()}});function WH(t,e,r){let i=r.includes("deleted"),n=r.includes("tag")||/^refs\/tags/.test(t),s=!r.includes("new");return{deleted:i,tag:n,branch:!n,new:!s,alreadyUpdated:s,local:t,remote:e}}var lC,UA,cC,qH=Y({"src/lib/parsers/parse-push.ts"(){"use strict";ve(),LA(),lC=[new be(/^Pushing to (.+)$/,(t,[e])=>{t.repo=e}),new be(/^updating local tracking ref '(.+)'/,(t,[e])=>{t.ref={...t.ref||{},local:e}}),new be(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/,(t,[e,r,i])=>{t.pushed.push(WH(e,r,i))}),new be(/^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/,(t,[e,r,i])=>{t.branch={...t.branch||{},local:e,remote:r,remoteName:i}}),new be(/^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/,(t,[e,r,i,n])=>{t.update={head:{local:e,remote:r},hash:{from:i,to:n}}})],UA=(t,e)=>{let r=cC(t,e),i=MA(t,e);return{...r,...i}},cC=(t,e)=>Vr({pushed:[]},lC,[t,e])}}),GA={};Pt(GA,{pushTagsTask:()=>YH,pushTask:()=>hw});function YH(t={},e){return Ai(e,"--tags"),hw(t,e)}function hw(t={},e){let r=["push",...e];return t.branch&&r.splice(1,0,t.branch),t.remote&&r.splice(1,0,t.remote),ch(r,"-v"),Ai(r,"--verbose"),Ai(r,"--porcelain"),{commands:r,format:"utf-8",parser:UA}}var jA=Y({"src/lib/tasks/push.ts"(){"use strict";qH(),ve()}});function ZH(){return{showBuffer(){let t=["show",...Sr(arguments,1)];return t.includes("--binary")||t.splice(1,0,"--binary"),this._runTask(YC(t),ct(arguments))},show(){let t=["show",...Sr(arguments,1)];return this._runTask(kr(t),ct(arguments))}}}var KH=Y({"src/lib/tasks/show.ts"(){"use strict";ve(),kt()}}),uC,VA,XH=Y({"src/lib/responses/FileStatusSummary.ts"(){"use strict";uC=/^(.+)\0(.+)$/,VA=class{constructor(t,e,r){if(this.path=t,this.index=e,this.working_dir=r,e==="R"||r==="R"){let i=uC.exec(t)||[null,t,t];this.from=i[2]||"",this.path=i[1]||""}}}}});function fC(t){let[e,r]=t.split(xl);return{from:r||e,to:e}}function ai(t,e,r){return[`${t}${e}`,r]}function $v(t,...e){return e.map(r=>ai(t,r,(i,n)=>i.conflicted.push(n)))}function QH(t,e){let r=e.trim();switch(" "){case r.charAt(2):return i(r.charAt(0),r.charAt(1),r.slice(3));case r.charAt(1):return i(" ",r.charAt(0),r.slice(2));default:return}function i(n,s,a){let o=`${n}${s}`,l=zA.get(o);l&&l(t,a),o!=="##"&&o!=="!!"&&t.files.push(new VA(a,n,s))}}var dC,zA,WA,JH=Y({"src/lib/responses/StatusSummary.ts"(){"use strict";ve(),XH(),dC=class{constructor(){this.not_added=[],this.conflicted=[],this.created=[],this.deleted=[],this.ignored=void 0,this.modified=[],this.renamed=[],this.files=[],this.staged=[],this.ahead=0,this.behind=0,this.current=null,this.tracking=null,this.detached=!1,this.isClean=()=>!this.files.length}},zA=new Map([ai(" ","A",(t,e)=>t.created.push(e)),ai(" ","D",(t,e)=>t.deleted.push(e)),ai(" ","M",(t,e)=>t.modified.push(e)),ai("A"," ",(t,e)=>{t.created.push(e),t.staged.push(e)}),ai("A","M",(t,e)=>{t.created.push(e),t.staged.push(e),t.modified.push(e)}),ai("D"," ",(t,e)=>{t.deleted.push(e),t.staged.push(e)}),ai("M"," ",(t,e)=>{t.modified.push(e),t.staged.push(e)}),ai("M","M",(t,e)=>{t.modified.push(e),t.staged.push(e)}),ai("R"," ",(t,e)=>{t.renamed.push(fC(e))}),ai("R","M",(t,e)=>{let r=fC(e);t.renamed.push(r),t.modified.push(r.to)}),ai("!","!",(t,e)=>{(t.ignored=t.ignored||[]).push(e)}),ai("?","?",(t,e)=>t.not_added.push(e)),...$v("A","A","U"),...$v("D","D","U"),...$v("U","A","D","U"),["##",(t,e)=>{let r=/ahead (\d+)/,i=/behind (\d+)/,n=/^(.+?(?=(?:\.{3}|\s|$)))/,s=/\.{3}(\S*)/,a=/\son\s(\S+?)(?=\.{3}|$)/,o=r.exec(e);t.ahead=o&&+o[1]||0,o=i.exec(e),t.behind=o&&+o[1]||0,o=n.exec(e),t.current=ur(o==null?void 0:o[1],wt,null),o=s.exec(e),t.tracking=ur(o==null?void 0:o[1],wt,null),o=a.exec(e),o&&(t.current=ur(o==null?void 0:o[1],wt,t.current)),t.detached=/\(no branch\)/.test(e)}]]),WA=function(t){let e=t.split(xl),r=new dC;for(let i=0,n=e.length;i!qA.includes(r))],parser(r){return WA(r)}}}var qA,t6=Y({"src/lib/tasks/status.ts"(){"use strict";JH(),qA=["--null","-z"]}});function oh(t=0,e=0,r=0,i="",n=!0){return Object.defineProperty({major:t,minor:e,patch:r,agent:i,installed:n},"toString",{value(){return`${this.major}.${this.minor}.${this.patch}`},configurable:!1,enumerable:!1})}function r6(){return oh(0,0,0,"",!1)}function i6(){return{version(){return this._runTask({commands:["--version"],format:"utf-8",parser:n6,onError(t,e,r,i){if(t.exitCode===-2)return r(k.from(pw));i(e)}})}}}function n6(t){return t===pw?r6():Vr(oh(0,0,0,t),YA,t)}var pw,YA,s6=Y({"src/lib/tasks/version.ts"(){"use strict";ve(),pw="installed=false",YA=[new be(/version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/,(t,[e,r,i,n=""])=>{Object.assign(t,oh(rt(e),rt(r),rt(i),n))}),new be(/version (\d+)\.(\d+)\.(\D+)(.+)?$/,(t,[e,r,i,n=""])=>{Object.assign(t,oh(rt(e),rt(r),i,n))})]}});function hC(t,e,r,...i){return wt(r)?e(r,ur(i[0],wt),Sr(arguments)):Gr(`git.${t}() requires a string 'repoPath'`)}function a6(){return{clone(t,...e){return this._runTask(hC("clone",jv,ur(t,wt),...e),ct(arguments))},mirror(t,...e){return this._runTask(hC("mirror",ZA,ur(t,wt),...e),ct(arguments))}}}var jv,ZA,o6=Y({"src/lib/tasks/clone.ts"(){"use strict";kt(),ve(),jv=(t,e,r)=>{let i=["clone",...r];return wt(t)&&i.push(wl(t)),wt(e)&&i.push(wl(e)),kr(i)},ZA=(t,e,r)=>(Ai(r,"--mirror"),jv(t,e,r))}}),KA={};Pt(KA,{SimpleGitApi:()=>Vv});var Vv,l6=Y({"src/lib/simple-git-api.ts"(){"use strict";fH(),dH(),pH(),vH(),xH(),rA(),SH(),oA(),CH(),$H(),RA(),zH(),jA(),KH(),t6(),kt(),s6(),ve(),o6(),Vv=class{constructor(t){this._executor=t}_runTask(t,e){let r=this._executor.chain(),i=r.push(t);return e&&cH(t,i,e),Object.create(this,{then:{value:i.then.bind(i)},catch:{value:i.catch.bind(i)},_executor:{value:r}})}add(t){return this._runTask(kr(["add",...An(t)]),ct(arguments))}cwd(t){let e=ct(arguments);return typeof t=="string"?this._runTask(Zk(t,this._executor),e):typeof(t==null?void 0:t.path)=="string"?this._runTask(Zk(t.path,t.root&&this._executor||void 0),e):this._runTask(Gr("Git.cwd: workingDirectory must be supplied as a string"),e)}hashObject(t,e){return this._runTask(kH(t,e===!0),ct(arguments))}init(t){return this._runTask(RH(t===!0,this._executor.cwd,Sr(arguments)),ct(arguments))}merge(){return this._runTask(oC(Sr(arguments)),ct(arguments))}mergeFromTo(t,e){return wt(t)&&wt(e)?this._runTask(oC([t,e,...Sr(arguments)]),ct(arguments,!1)):this._runTask(Gr("Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings"))}outputHandler(t){return this._executor.outputHandler=t,this}push(){let t=hw({remote:ur(arguments[0],wt),branch:ur(arguments[1],wt)},Sr(arguments));return this._runTask(t,ct(arguments))}stash(){return this._runTask(kr(["stash",...Sr(arguments)]),ct(arguments))}status(){return this._runTask(e6(Sr(arguments)),ct(arguments))}},Object.assign(Vv.prototype,hH(),a6(),yH(),K8(),gH(),EH(),eH(),BH(),ZH(),i6())}}),XA={};Pt(XA,{Scheduler:()=>JA});var pC,JA,c6=Y({"src/lib/runners/scheduler.ts"(){"use strict";ve(),dA(),pC=(()=>{let t=0;return()=>{t++;let{promise:e,done:r}=(0,QA.createDeferred)();return{promise:e,done:r,id:t}}})(),JA=class{constructor(t=2){this.concurrency=t,this.logger=nw("","scheduler"),this.pending=[],this.running=[],this.logger("Constructed, concurrency=%s",t)}schedule(){if(!this.pending.length||this.running.length>=this.concurrency){this.logger("Schedule attempt ignored, pending=%s running=%s concurrency=%s",this.pending.length,this.running.length,this.concurrency);return}let t=Ai(this.running,this.pending.shift());this.logger("Attempting id=%s",t.id),t.done(()=>{this.logger("Completing id=",t.id),ch(this.running,t),this.schedule()})}next(){let{promise:t,id:e}=Ai(this.pending,pC());return this.logger("Scheduling id=%s",e),this.schedule(),t}}}}),eT={};Pt(eT,{applyPatchTask:()=>u6});function u6(t,e){return kr(["apply",...e,...t])}var f6=Y({"src/lib/tasks/apply-patch.ts"(){"use strict";kt()}});function d6(t,e){return{branch:t,hash:e,success:!0}}function h6(t){return{branch:t,hash:null,success:!1}}var tT,p6=Y({"src/lib/responses/BranchDeleteSummary.ts"(){"use strict";tT=class{constructor(){this.all=[],this.branches={},this.errors=[]}get success(){return!this.errors.length}}}});function rT(t,e){return e===1&&zv.test(t)}var mC,zv,gC,gh,m6=Y({"src/lib/parsers/parse-branch-delete.ts"(){"use strict";p6(),ve(),mC=/(\S+)\s+\(\S+\s([^)]+)\)/,zv=/^error[^']+'([^']+)'/m,gC=[new be(mC,(t,[e,r])=>{let i=d6(e,r);t.all.push(i),t.branches[e]=i}),new be(zv,(t,[e])=>{let r=h6(e);t.errors.push(r),t.all.push(r),t.branches[e]=r})],gh=(t,e)=>Vr(new tT,gC,[t,e])}}),iT,g6=Y({"src/lib/responses/BranchSummary.ts"(){"use strict";iT=class{constructor(){this.all=[],this.branches={},this.current="",this.detached=!1}push(t,e,r,i,n){t==="*"&&(this.detached=e,this.current=r),this.all.push(r),this.branches[r]={current:t==="*",linkedWorkTree:t==="+",name:r,commit:i,label:n}}}}});function vC(t){return t?t.charAt(0):""}function nT(t,e=!1){return Vr(new iT,e?[aT]:sT,t)}var sT,aT,v6=Y({"src/lib/parsers/parse-branch.ts"(){"use strict";g6(),ve(),sT=[new be(/^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/,(t,[e,r,i,n])=>{t.push(vC(e),!0,r,i,n)}),new be(/^([*+]\s)?(\S+)\s+([a-z0-9]+)\s?(.*)$/s,(t,[e,r,i,n])=>{t.push(vC(e),!1,r,i,n)})],aT=new be(/^(\S+)$/s,(t,[e])=>{t.push("*",!1,e,"","")})}}),oT={};Pt(oT,{branchLocalTask:()=>b6,branchTask:()=>w6,containsDeleteBranchCommand:()=>lT,deleteBranchTask:()=>y6,deleteBranchesTask:()=>_6});function lT(t){let e=["-d","-D","--delete"];return t.some(r=>e.includes(r))}function w6(t){let e=lT(t),r=t.includes("--show-current"),i=["branch",...t];return i.length===1&&i.push("-a"),i.includes("-v")||i.splice(1,0,"-v"),{format:"utf-8",commands:i,parser(n,s){return e?gh(n,s).all[0]:nT(n,r)}}}function b6(){return{format:"utf-8",commands:["branch","-v"],parser(t){return nT(t)}}}function _6(t,e=!1){return{format:"utf-8",commands:["branch","-v",e?"-D":"-d",...t],parser(r,i){return gh(r,i)},onError({exitCode:r,stdOut:i},n,s,a){if(!rT(String(n),r))return a(n);s(i)}}}function y6(t,e=!1){let r={format:"utf-8",commands:["branch","-v",e?"-D":"-d",t],parser(i,n){return gh(i,n).branches[t]},onError({exitCode:i,stdErr:n,stdOut:s},a,o,l){if(!rT(String(a),i))return l(a);throw new Pu(r.parser(Tu(s),Tu(n)),String(a))}};return r}var x6=Y({"src/lib/tasks/branch.ts"(){"use strict";Sl(),m6(),v6(),ve()}});function E6(t){let e=t.trim().replace(/^["']|["']$/g,"");return e&&(0,cT.normalize)(e)}var uT,S6=Y({"src/lib/responses/CheckIgnore.ts"(){"use strict";uT=t=>t.split(/\n/g).map(E6).filter(Boolean)}}),fT={};Pt(fT,{checkIgnoreTask:()=>k6});function k6(t){return{commands:["check-ignore",...t],format:"utf-8",parser:uT}}var C6=Y({"src/lib/tasks/check-ignore.ts"(){"use strict";S6()}});function A6(t,e){return Vr({raw:t,remote:null,branches:[],tags:[],updated:[],deleted:[]},dT,[t,e])}var dT,T6=Y({"src/lib/parsers/parse-fetch.ts"(){"use strict";ve(),dT=[new be(/From (.+)$/,(t,[e])=>{t.remote=e}),new be(/\* \[new branch]\s+(\S+)\s*-> (.+)$/,(t,[e,r])=>{t.branches.push({name:e,tracking:r})}),new be(/\* \[new tag]\s+(\S+)\s*-> (.+)$/,(t,[e,r])=>{t.tags.push({name:e,tracking:r})}),new be(/- \[deleted]\s+\S+\s*-> (.+)$/,(t,[e])=>{t.deleted.push({tracking:e})}),new be(/\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/,(t,[e,r,i,n])=>{t.updated.push({name:i,tracking:n,to:r,from:e})})]}}),hT={};Pt(hT,{fetchTask:()=>R6});function P6(t){return/^--upload-pack(=|$)/.test(t)}function R6(t,e,r){let i=["fetch",...r];return t&&e&&i.push(t,e),i.find(P6)?Gr("git.fetch: potential exploit argument blocked."):{commands:i,format:"utf-8",parser:A6}}var $6=Y({"src/lib/tasks/fetch.ts"(){"use strict";T6(),kt()}});function F6(t){return Vr({moves:[]},pT,t)}var pT,I6=Y({"src/lib/parsers/parse-move.ts"(){"use strict";ve(),pT=[new be(/^Renaming (.+) to (.+)$/,(t,[e,r])=>{t.moves.push({from:e,to:r})})]}}),mT={};Pt(mT,{moveTask:()=>M6});function M6(t,e){return{commands:["mv","-v",...An(t),e],format:"utf-8",parser:F6}}var D6=Y({"src/lib/tasks/move.ts"(){"use strict";I6(),ve()}}),gT={};Pt(gT,{pullTask:()=>O6});function O6(t,e,r){let i=["pull",...r];return t&&e&&i.splice(1,0,t,e),{commands:i,format:"utf-8",parser(n,s){return dw(n,s)},onError(n,s,a,o){let l=jH(Tu(n.stdOut),Tu(n.stdErr));if(l)return o(new Pu(l));o(s)}}}var L6=Y({"src/lib/tasks/pull.ts"(){"use strict";Sl(),BA(),ve()}});function N6(t){let e={};return vT(t,([r])=>e[r]={name:r}),Object.values(e)}function B6(t){let e={};return vT(t,([r,i,n])=>{Object.hasOwn(e,r)||(e[r]={name:r,refs:{fetch:"",push:""}}),n&&i&&(e[r].refs[n.replace(/[^a-z]/g,"")]=i)}),Object.values(e)}function vT(t,e){Yv(t,r=>e(r.split(/\s+/)))}var H6=Y({"src/lib/responses/GetRemoteSummary.ts"(){"use strict";ve()}}),wT={};Pt(wT,{addRemoteTask:()=>U6,getRemotesTask:()=>G6,listRemotesTask:()=>j6,remoteTask:()=>V6,removeRemoteTask:()=>z6});function U6(t,e,r){return kr(["remote","add",...r,t,e])}function G6(t){let e=["remote"];return t&&e.push("-v"),{commands:e,format:"utf-8",parser:t?B6:N6}}function j6(t){let e=[...t];return e[0]!=="ls-remote"&&e.unshift("ls-remote"),kr(e)}function V6(t){let e=[...t];return e[0]!=="remote"&&e.unshift("remote"),kr(e)}function z6(t){return kr(["remote","remove",t])}var W6=Y({"src/lib/tasks/remote.ts"(){"use strict";H6(),kt()}}),bT={};Pt(bT,{stashListTask:()=>q6});function q6(t={},e){let r=PA(t),i=["stash","list",...r.commands,...e],n=kA(r.splitter,r.fields,aw(i));return mh(i)||{commands:i,format:"utf-8",parser:n}}var Y6=Y({"src/lib/tasks/stash-list.ts"(){"use strict";Iu(),AA(),fw(),RA()}}),_T={};Pt(_T,{addSubModuleTask:()=>Z6,initSubModuleTask:()=>K6,subModuleTask:()=>vh,updateSubModuleTask:()=>X6});function Z6(t,e){return vh(["add",t,e])}function K6(t){return vh(["init",...t])}function vh(t){let e=[...t];return e[0]!=="submodule"&&e.unshift("submodule"),kr(e)}function X6(t){return vh(["update",...t])}var Q6=Y({"src/lib/tasks/sub-module.ts"(){"use strict";kt()}});function J6(t,e){let r=Number.isNaN(t),i=Number.isNaN(e);return r!==i?r?1:-1:r?yT(t,e):0}function yT(t,e){return t===e?0:t>e?1:-1}function e5(t){return t.trim()}function eh(t){return typeof t=="string"&&parseInt(t.replace(/^\D+/g,""),10)||0}var wC,xT,t5=Y({"src/lib/responses/TagList.ts"(){"use strict";wC=class{constructor(t,e){this.all=t,this.latest=e}},xT=function(t,e=!1){let r=t.split(` +`).map(e5).filter(Boolean);e||r.sort(function(n,s){let a=n.split("."),o=s.split(".");if(a.length===1||o.length===1)return J6(eh(a[0]),eh(o[0]));for(let l=0,c=Math.max(a.length,o.length);ln.indexOf(".")>=0);return new wC(r,i)}}}),ET={};Pt(ET,{addAnnotatedTagTask:()=>n5,addTagTask:()=>i5,tagListTask:()=>r5});function r5(t=[]){let e=t.some(r=>/^--sort=/.test(r));return{format:"utf-8",commands:["tag","-l",...t],parser(r){return xT(r,e)}}}function i5(t){return{format:"utf-8",commands:["tag",t],parser(){return{name:t}}}}function n5(t,e){return{format:"utf-8",commands:["tag","-a","-m",e,t],parser(){return{name:t}}}}var s5=Y({"src/lib/tasks/tag.ts"(){"use strict";t5()}}),a5=E8({"src/git.js"(t,e){"use strict";var{GitExecutor:r}=(lH(),St(mA)),{SimpleGitApi:i}=(l6(),St(KA)),{Scheduler:n}=(c6(),St(XA)),{adhocExecTask:s,configurationErrorTask:a}=(kt(),St(Nv)),{asArray:o,filterArray:l,filterPrimitives:c,filterString:u,filterStringOrStringArray:f,filterType:d,getTrailingOptions:h,trailingFunctionArgument:p,trailingOptionsArgument:g}=(ve(),St(NC)),{applyPatchTask:v}=(f6(),St(eT)),{branchTask:b,branchLocalTask:_,deleteBranchesTask:C,deleteBranchTask:x}=(x6(),St(oT)),{checkIgnoreTask:E}=(C6(),St(fT)),{checkIsRepoTask:A}=(GC(),St(BC)),{cleanWithOptionsTask:w,isCleanOptionsArray:S}=(JC(),St(XC)),{diffSummaryTask:y}=(fw(),St(TA)),{fetchTask:P}=($6(),St(hT)),{moveTask:T}=(D6(),St(mT)),{pullTask:I}=(L6(),St(gT)),{pushTagsTask:M}=(jA(),St(GA)),{addRemoteTask:B,getRemotesTask:re,listRemotesTask:Ae,remoteTask:K,removeRemoteTask:Q}=(W6(),St(wT)),{getResetMode:fe,resetTask:ce}=(fA(),St(lA)),{stashListTask:z}=(Y6(),St(bT)),{addSubModuleTask:X,initSubModuleTask:j,subModuleTask:Ze,updateSubModuleTask:$r}=(Q6(),St(_T)),{addAnnotatedTagTask:cr,addTagTask:Ie,tagListTask:yt}=(s5(),St(ET)),{straightThroughBufferTask:Tt,straightThroughStringTask:Ke}=(kt(),St(Nv));function J(L,W){this._plugins=W,this._executor=new r(L.baseDir,new n(L.maxConcurrentProcesses),W),this._trimmed=L.trimmed}(J.prototype=Object.create(i.prototype)).constructor=J,J.prototype.customBinary=function(L){return this._plugins.reconfigure("binary",L),this},J.prototype.env=function(L,W){return arguments.length===1&&typeof L=="object"?this._executor.env=L:(this._executor.env=this._executor.env||{})[L]=W,this},J.prototype.stashList=function(L){return this._runTask(z(g(arguments)||{},l(L)&&L||[]),p(arguments))},J.prototype.mv=function(L,W){return this._runTask(T(L,W),p(arguments))},J.prototype.checkoutLatestTag=function(L){var W=this;return this.pull(function(){W.tags(function(xe,Xe){W.checkout(Xe.latest,L)})})},J.prototype.pull=function(L,W,xe,Xe){return this._runTask(I(d(L,u),d(W,u),h(arguments)),p(arguments))},J.prototype.fetch=function(L,W){return this._runTask(P(d(L,u),d(W,u),h(arguments)),p(arguments))},J.prototype.silent=function(L){return this._runTask(s(()=>console.warn("simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this method will be removed.")))},J.prototype.tags=function(L,W){return this._runTask(yt(h(arguments)),p(arguments))},J.prototype.rebase=function(){return this._runTask(Ke(["rebase",...h(arguments)]),p(arguments))},J.prototype.reset=function(L){return this._runTask(ce(fe(L),h(arguments)),p(arguments))},J.prototype.revert=function(L){let W=p(arguments);return typeof L!="string"?this._runTask(a("Commit must be a string"),W):this._runTask(Ke(["revert",...h(arguments,0,!0),L]),W)},J.prototype.addTag=function(L){let W=typeof L=="string"?Ie(L):a("Git.addTag requires a tag name");return this._runTask(W,p(arguments))},J.prototype.addAnnotatedTag=function(L,W){return this._runTask(cr(L,W),p(arguments))},J.prototype.deleteLocalBranch=function(L,W,xe){return this._runTask(x(L,typeof W=="boolean"?W:!1),p(arguments))},J.prototype.deleteLocalBranches=function(L,W,xe){return this._runTask(C(L,typeof W=="boolean"?W:!1),p(arguments))},J.prototype.branch=function(L,W){return this._runTask(b(h(arguments)),p(arguments))},J.prototype.branchLocal=function(L){return this._runTask(_(),p(arguments))},J.prototype.raw=function(L){let W=!Array.isArray(L),xe=[].slice.call(W?arguments:L,0);for(let Dt=0;Dtconsole.warn("simple-git deprecation notice: clearQueue() is deprecated and will be removed, switch to using the abortPlugin instead.")))},J.prototype.checkIgnore=function(L,W){return this._runTask(E(o(d(L,f,[]))),p(arguments))},J.prototype.checkIsRepo=function(L,W){return this._runTask(A(d(L,u)),p(arguments))},e.exports=J}});Ws();var o5=class extends jr{constructor(t,e){super(void 0,e),this.config=t}};Ws();Ws();var El=class extends jr{constructor(t,e,r){super(t,r),this.task=t,this.plugin=e,Object.setPrototypeOf(this,new.target.prototype)}};Sl();SC();GC();JC();rA();nA();oA();fA();function l5(t){return t?[{type:"spawn.before",action(i,n){t.aborted&&n.kill(new El(void 0,"abort","Abort already signaled"))}},{type:"spawn.after",action(i,n){function s(){n.kill(new El(void 0,"abort","Abort signal received"))}t.addEventListener("abort",s),n.spawned.on("close",()=>t.removeEventListener("abort",s))}}]:void 0}function c5(t={}){return{type:"spawn.args",action(e,{env:r}){for(let i of zk(e,r))if(t[i.category]!==!0)throw new El(void 0,"unsafe",i.message);return e}}}ve();function u5(t){let e=Au(t,"-c");return{type:"spawn.args",action(r){return[...e,...r]}}}ve();var bC=(0,yl.deferred)().promise;function f5({onClose:t=!0,onExit:e=50}={}){function r(){let n=-1,s={close:(0,yl.deferred)(),closeTimeout:(0,yl.deferred)(),exit:(0,yl.deferred)(),exitTimeout:(0,yl.deferred)()},a=Promise.race([t===!1?bC:s.closeTimeout.promise,e===!1?bC:s.exitTimeout.promise]);return i(t,s.close,s.closeTimeout),i(e,s.exit,s.exitTimeout),{close(o){n=o,s.close.done()},exit(o){n=o,s.exit.done()},get exitCode(){return n},result:a}}function i(n,s,a){n!==!1&&(n===!0?s.promise:s.promise.then(()=>Fv(n))).then(a.done)}return{type:"spawn.after",async action(n,{spawned:s,close:a}){var u,f;let o=r(),l=!0,c=()=>{l=!1};(u=s.stdout)==null||u.on("data",c),(f=s.stderr)==null||f.on("data",c),s.on("error",c),s.on("close",d=>o.close(d)),s.on("exit",d=>o.exit(d));try{await o.result,l&&await Fv(50),a(o.exitCode)}catch(d){a(o.exitCode,d)}}}}ve();var d5="Invalid value supplied for custom binary, requires a single string or an array containing either one or two strings",_C="Invalid value supplied for custom binary, restricted characters must be removed or supply the unsafe.allowUnsafeCustomBinary option";function h5(t){return!t||!/^([a-z]:)?([a-z0-9/.\\_~-]+)$/i.test(t)}function yC(t,e){if(t.length<1||t.length>2)throw new El(void 0,"binary",d5);if(t.some(h5))if(e)console.warn(_C);else throw new El(void 0,"binary",_C);let[i,n]=t;return{binary:i,prefix:n}}function p5(t,e=["git"],r=!1){let i=yC(An(e),r);t.on("binary",n=>{i=yC(An(n),r)}),t.append("spawn.binary",()=>i.binary),t.append("spawn.args",n=>i.prefix?[i.prefix,...n]:n)}Ws();function m5(t){return!!(t.exitCode&&t.stdErr.length)}function g5(t){return k.concat([...t.stdOut,...t.stdErr])}function v5(t=!1,e=m5,r=g5){return(i,n)=>!t&&i||!e(n)?i:r(n)}function xC(t){return{type:"task.error",action(e,r){let i=t(e.error,{stdErr:r.stdErr,stdOut:r.stdOut,exitCode:r.exitCode});return k.isBuffer(i)?{error:new jr(void 0,i.toString("utf-8"))}:{error:i}}}}ve();var w5=class{constructor(){this.plugins=new Set,this.events=new ST.EventEmitter}on(t,e){this.events.on(t,e)}reconfigure(t,e){this.events.emit(t,e)}append(t,e){let r=Ai(this.plugins,{type:t,action:e});return()=>this.plugins.delete(r)}add(t){let e=[];return An(t).forEach(r=>r&&this.plugins.add(Ai(e,r))),()=>{e.forEach(r=>this.plugins.delete(r))}}exec(t,e,r){let i=e,n=Object.freeze(Object.create(r));for(let s of this.plugins)s.type===t&&(i=s.action(i,n));return i}};ve();function b5(t){let e="--progress",r=["checkout","clone","fetch","pull","push"];return[{type:"spawn.args",action(s,a){return r.includes(a.method)?RC(s,e):s}},{type:"spawn.after",action(s,a){var o;a.commands.includes(e)&&((o=a.spawned.stderr)==null||o.on("data",l=>{let c=/^([\s\S]+?):\s*(\d+)% \((\d+)\/(\d+)\)/.exec(l.toString("utf8"));c&&t({method:a.method,stage:_5(c[1]),progress:rt(c[2]),processed:rt(c[3]),total:rt(c[4])})}))}}]}function _5(t){return String(t.toLowerCase().split(" ",1))||"unknown"}ve();function y5(t){let e=FC(t,["uid","gid"]);return{type:"spawn.options",action(r){return{...e,...r}}}}function x5({block:t,stdErr:e=!0,stdOut:r=!0}){if(t>0)return{type:"spawn.after",action(i,n){var c,u;let s;function a(){s&&clearTimeout(s),s=setTimeout(l,t)}function o(){var f,d;(f=n.spawned.stdout)==null||f.off("data",a),(d=n.spawned.stderr)==null||d.off("data",a),n.spawned.off("exit",o),n.spawned.off("close",o),s&&clearTimeout(s)}function l(){o(),n.kill(new El(void 0,"timeout","block timeout reached"))}r&&((c=n.spawned.stdout)==null||c.on("data",a)),e&&((u=n.spawned.stderr)==null||u.on("data",a)),n.spawned.on("exit",o),n.spawned.on("close",o),a()}}}function E5(){return{type:"spawn.args",action(t){let e=[],r;function i(n){(r=r||[]).push(...n)}for(let n=0;nSi(a)&&bl(a)||a));break}e.push(s)}return r?[...e,"--",...r.map(String)]:e}}}ve();var S5=a5();function k5(t,e){var n;let r=new w5,i=OC(t&&(typeof t=="string"?{baseDir:t}:t)||{},e);if(!Zv(i.baseDir))throw new o5(i,"Cannot use simple-git on a directory that does not exist");return Array.isArray(i.config)&&r.add(u5(i.config)),r.add(c5(i.unsafe)),r.add(f5(i.completion)),i.abort&&r.add(l5(i.abort)),i.progress&&r.add(b5(i.progress)),i.timeout&&r.add(x5(i.timeout)),i.spawnOptions&&r.add(y5(i.spawnOptions)),r.add(E5()),r.add(xC(v5(!0))),i.errors&&r.add(xC(i.errors)),p5(r,i.binary,(n=i.unsafe)==null?void 0:n.allowUnsafeCustomBinary),new S5(i,r)}Sl();var kT=k5;var ke=class extends hl{constructor(r){super(r);this.useDefaultWindowsGitPath=!1}async setGitInstance(r=!1){var i;if(await this.isGitInstalled()){let n=this.app.vault.adapter,s=n.getBasePath(),a=s;this.plugin.settings.basePath&&(await n.exists((0,rs.normalizePath)(this.plugin.settings.basePath))?a=Be.join(s,this.plugin.settings.basePath):r||new rs.Notice("ObsidianGit: Base path does not exist")),this.absoluteRepoPath=a,this.git=kT({baseDir:a,binary:this.plugin.localStorage.getGitPath()||(this.useDefaultWindowsGitPath?Ud:void 0),config:["core.quotepath=off"],progress:b=>{var _;(_=this.plugin.statusBar)==null||_.displayProgress(this.toGitProgress(b))},unsafe:{allowUnsafeCustomBinary:!0,allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeConfigPaths:!0,allowUnsafeCredentialHelper:!0,allowUnsafeGitProxy:!0,allowUnsafeGpgProgram:!0,allowUnsafeHooksPath:!0,allowUnsafeMergeDriver:!0,allowUnsafeSshCommand:!0,allowUnsafePager:!0}});let o=this.plugin.localStorage.getPATHPaths(),l=this.plugin.localStorage.getEnvVars(),c=this.plugin.settings.gitDir,u={...process.env};if(o.length>0){let b=o.join(Be.delimiter)+Be.delimiter+u.PATH;u.PATH=b}c&&(u.GIT_DIR=c,u.GIT_WORK_TREE=a);for(let b of l){let[_,C]=b.split("=");_!==void 0&&(u[_]=C)}let f="simple-git",d=",",p=((i=localStorage.debug)!=null?i:"").split(d);if(!p.includes(f)&&!p.includes(`-${f}`)&&(p.push(f),PT.default.enable(p.join(d))),await this.git.env(u).checkIsRepo()){let b=await this.git.revparse("--show-cdup"),_=(0,Mu.resolve)(a+Mu.sep+b);this.absoluteRepoPath=_,await this.git.cwd(_)}let g=Be.join(s,this.app.vault.configDir,"plugins","obsidian-git"),v=Be.join(g,$a);u.SSH_ASKPASS==null&&(u.SSH_ASKPASS=v),u.SSH_ASKPASS_REQUIRE="force",u.OBSIDIAN_GIT_CREDENTIALS_INPUT=Be.join(g,Gd),u.SSH_ASKPASS==v&&this.askpass().catch(b=>this.plugin.displayError(b)),u.OBSIDIAN_GIT="1",this.git=this.git.env(u)}}toGitProgress(r){return{action:this.getProgressAction(r.method),stage:r.stage,progress:r.progress,processed:r.processed,total:r.total}}getProgressAction(r){switch(r){case"fetch":return"Fetching";case"push":return"Pushing";case"pull":return"Pulling";case"checkout":return"Checking out";default:return r?r.charAt(0).toUpperCase()+r.slice(1):"Working"}}getRelativeVaultPath(r){let n=this.app.vault.adapter.getBasePath(),s=Be.join(this.absoluteRepoPath,r),a=Be.relative(n,s);return rs.Platform.isWin&&(a=a.replace(/\\/g,"/")),a}getRelativeRepoPath(r,i=!0){if(i){let s=this.plugin.app.vault.adapter.getBasePath(),a=this.absoluteRepoPath,o=Be.join(s,r),l=Be.relative(a,o);return rs.Platform.isWin&&(l=l.replace(/\\/g,"/")),l}return r}get absPluginConfigPath(){let i=this.app.vault.adapter.getBasePath();return Be.join(i,this.app.vault.configDir,"plugins","obsidian-git")}get relPluginConfigPath(){return Be.join(this.app.vault.configDir,"plugins","obsidian-git")}async askpass(){let r=this.app.vault.adapter,i=this.app.vault.configDir+"/plugins/obsidian-git/";await this.addAskPassScriptToExclude(),await oi.writeFile(Be.join(this.absPluginConfigPath,$a),YS),await oi.chmod(Be.join(this.absPluginConfigPath,$a),493),this.watchAbortController=new AbortController;let{signal:n}=this.watchAbortController;try{let s=oi.watch(this.absPluginConfigPath,{signal:n});for await(let a of s){if(a.filename!=Gd)continue;let o=i+Gd;if(await new Promise(d=>window.setTimeout(d,200)),!await r.exists(o))continue;let l=await r.read(o),c;l.length>60&&(c=new rs.Notice(l,999999));let u=!0;l.contains("Username for")&&(u=!1);let f=await new at(this.plugin,{allowEmpty:!0,obscure:u,placeholder:l.length>60?"Enter a response to the message.":l}).openAndGetResult();c==null||c.hide(),await r.exists(o)&&await r.write(`${o}.response`,f!=null?f:"")}}catch(s){this.plugin.displayError(s),await oi.rm(Be.join(this.absPluginConfigPath,$a),{force:!0}),await oi.rm(Be.join(this.absPluginConfigPath,`${$a}.response`),{force:!0}),await new Promise(a=>window.setTimeout(a,5e3)),this.plugin.log("Retry watch for ask pass"),await this.askpass()}}async addAskPassScriptToExclude(){try{if(!await this.git.checkIsRepo())return;let r=await this.git.revparse(["--path-format=absolute","--git-path","info/exclude"]),i=Be.join(this.app.vault.configDir,"plugins","obsidian-git",$a),n=this.getRelativeRepoPath(i,!0);(await oi.readFile(r,"utf-8")).split(` +`).some(l=>l.contains(n))||await oi.appendFile(r,n+` +`)}catch(r){console.error("Error while adding askpass script to exclude file:",r)}}unload(){var r;(r=this.watchAbortController)==null||r.abort()}async status(r){let i=r==null?void 0:r.path,n=await this.git.status(i!=null?["--",i]:[]),s=n.files.map(a=>{let o=this.formatPath(a);return{path:o.path,from:o.from,index:a.index==="?"?"U":a.index,workingDir:a.working_dir==="?"?"U":a.working_dir,vaultPath:this.getRelativeVaultPath(o.path)}});return{all:s,changed:s.filter(a=>a.workingDir!==" "),staged:s.filter(a=>a.index!==" "&&a.index!="U"),conflicted:n.conflicted.map(a=>this.formatPath({path:a}).path)}}async submoduleAwareHeadRevisonInContainingDirectory(r){let i=this.getRelativeRepoPath(r),s=["-C",Be.dirname(i),"rev-parse","HEAD"],a=this.git.raw(s);return a.catch(o=>console.warn("obsidian-git: rev-parse error:",o)),(await a).trim()}async getSubmodulePaths(){return new Promise(r=>{this.git.outputHandler((i,n,s,a)=>{if(!(a.contains("submodule")&&a.contains("foreach")))return;let o="",l=this.absoluteRepoPath;n.on("data",c=>{o+=c.toString("utf8")}),n.on("end",()=>{let u=o.split(` +`).map(f=>{let d=f.match(/'([^']*)'/);if(d!=null)return l+"/"+d[1]+Mu.sep}).filter(f=>!!f);u.reverse(),r(u)})}),this.git.subModule(["foreach","--recursive",""]).then(()=>{this.git.outputHandler(()=>{})},i=>this.plugin.displayError(i))})}formatPath(r){function i(n){if(n!=null)return n.startsWith('"')&&n.endsWith('"')?n.substring(1,n.length-1):n}return r.from!=null?{from:i(r.from),path:i(r.path)}:{path:i(r.path)}}async blame(r,i,n){if(r=this.getRelativeRepoPath(r),!await this.isTracked(r))return"untracked";let s=await this.getSubmoduleOfFile(r),a=s?["-C",s.submodule]:[],o=s?s.relativeFilepath:r;a.push("blame","--porcelain"),n&&a.push("-w");let l=`-C${Hd}`;switch(i){case"inactive":break;case"same-commit":a.push("-C",l);break;case"all-commits":a.push("-C","-C",l);break;default:js(i)}a.push("--",o);let c=await this.git.raw(a);return C5(c)}async isTracked(r){let i=await this.getSubmoduleOfFile(r),n=i?["-C",i.submodule]:[],s=i?i.relativeFilepath:r;return n.push("ls-files","--",s),this.git.raw(n).then(a=>a.trim()!=="")}async commitAll({message:r}){return this.withGitOperation(2,async()=>{if(this.plugin.settings.updateSubmodules){let n=await this.getSubmodulePaths();for(let s of n)await this.git.cwd({path:s,root:!1}).add("-A"),await this.git.cwd({path:s,root:!1}).commit(await this.formatCommitMessage(r))}await this.git.add("-A");let i=await this.git.commit(await this.formatCommitMessage(r));return this.app.workspace.trigger("obsidian-git:head-change"),i.summary.changes})}async commit({message:r,amend:i}){return this.withGitOperation(2,async()=>{let n=(await this.git.commit(await this.formatCommitMessage(r),i?["--amend"]:[])).summary.changes;return this.app.workspace.trigger("obsidian-git:head-change"),n})}async stage(r,i){r=this.getRelativeRepoPath(r,i),await this.git.add(["--",r])}async stageAll({dir:r}){await this.git.add(r!=null?r:"-A")}async unstageAll({dir:r}){await this.git.reset(r!=null?["--",r]:[])}async unstage(r,i){r=this.getRelativeRepoPath(r,i),await this.git.reset(["--",r])}async discard(r){await this.isTracked(r)&&await this.git.checkout(["--progress","--",r])}async applyPatch(r){let i=Be.join(this.relPluginConfigPath,"patch");await this.app.vault.adapter.write(i,r),await this.git.applyPatch(i,{"--cached":null,"--unidiff-zero":null,"--whitespace":"nowarn"}),await this.app.vault.adapter.remove(i)}async getUntrackedPaths(r){let i=r==null?void 0:r.path,n=[];return i!=null&&n.push("--",i),(await this.git.clean(Da.RECURSIVE+Da.DRY_RUN,n)).paths}async hashObject(r){r=this.getRelativeRepoPath(r);let i=await this.getSubmoduleOfFile(r),n=i?["-C",i.submodule]:[],s=i?i.relativeFilepath:r;return n.push("hash-object","--",s),this.git.raw(n)}async discardAll({dir:r}){return this.discard(r!=null?r:".")}async pull(){return this.withGitOperation(1,async()=>{try{this.plugin.settings.updateSubmodules&&await this.git.subModule(["update","--remote","--merge","--recursive"]);let r=await this.branchInfo();if(!r.current){this.plugin.displayError("No current branch found. Cannot pull.");return}let i=await this.git.revparse([r.current]);if(!r.tracking&&this.plugin.settings.updateSubmodules){this.plugin.log("No tracking branch found. Ignoring pull of main repo and updating submodules only.");return}await this.git.fetch();let n=await this.git.revparse([r.tracking]);if(i!==n){if(this.plugin.settings.syncMethod==="merge"||this.plugin.settings.syncMethod==="rebase")try{let o=[r.tracking];switch(this.plugin.settings.mergeStrategy!=="none"&&o.push(`--strategy-option=${this.plugin.settings.mergeStrategy}`),this.plugin.settings.syncMethod){case"merge":await this.git.merge(o);break;case"rebase":await this.git.rebase(o)}}catch(o){this.plugin.displayError(`Pull failed (${this.plugin.settings.syncMethod}): ${TT(o)}`);return}else if(this.plugin.settings.syncMethod==="reset")try{await this.git.raw(["update-ref",`refs/heads/${r.current}`,n]),await this.git.reset([])}catch(o){this.plugin.displayError(`Sync failed (${this.plugin.settings.syncMethod}): ${TT(o)}`)}this.app.workspace.trigger("obsidian-git:head-change");let s=await this.git.revparse([r.current]);return(await this.git.diff([`${i}..${s}`,"--name-only"])).split(/\r\n|\r|\n/).filter(o=>o.length>0).map(o=>({path:o,workingDir:"P",vaultPath:this.getRelativeVaultPath(o)}))}else return[]}catch(r){this.convertErrors(r)}})}async push(){return this.withGitOperation(3,async()=>{try{if(this.plugin.settings.updateSubmodules){let a=await this.git.subModule(["foreach","--recursive",`tracking=$(git for-each-ref --format='%(upstream:short)' "$(git symbolic-ref -q HEAD)"); echo $tracking; if [ ! -z "$(git diff --shortstat $tracking)" ]; then git push; fi`]);console.log(a)}let i=(await this.git.status()).current;if(!i){this.plugin.displayError("No current branch found. Cannot push.");return}let n=await this.getPushTarget(i);if(!n&&this.plugin.settings.updateSubmodules){this.plugin.log("No push target found. Ignoring push of main repo and updating submodules only.");return}let s=null;return n!=null&&n.exists&&(s=(await this.git.diffSummary([i,n.ref,"--"])).changed),await this.git.push(),s}catch(r){this.convertErrors(r)}})}async getPushTarget(r){let i=(await this.git.raw(["for-each-ref","--format=%(push)",`refs/heads/${r}`])).trim();if(!i)return;let n=(await this.git.raw(["for-each-ref","--format=%(refname)",i])).trim();return{ref:i,exists:n===i}}async squashAllUnpushedCommits(){let r=await this.git.status();if(!r.current)return;let i=await this.getPushTarget(r.current);if(!(i!=null&&i.exists)||(await this.git.raw(["diff","--cached","--name-only"])).trim().length>0)return;let s=`${i.ref}..HEAD`;if(parseInt((await this.git.raw(["rev-list","--count",s])).trim(),10)<2||parseInt((await this.git.raw(["rev-list","--merges","--count",s])).trim(),10)>0)return;let l=(await this.git.raw(["rev-parse","HEAD"])).trim();await this.withGitOperation(2,async()=>{await this.git.reset(["--soft",i.ref]),await this.git.raw(["commit","-C",l]),this.app.workspace.trigger("obsidian-git:head-change")})}async getUnpushedCommits(){let i=(await this.git.status()).current;if(i==null)return 0;let n=await this.getPushTarget(i);return n?n.exists?(await this.git.diffSummary([i,n.ref,"--"])).changed:(this.plugin.log(`Push target ${n.ref} does not exist on the remote yet.`),0):0}async canPush(){if(this.plugin.settings.updateSubmodules===!0)return!0;let i=(await this.git.status()).current;if(!i)return this.plugin.log("During canPush check, no current branch found."),!1;let n=await this.getPushTarget(i);if(!n)return!1;if(!n.exists)return!0;let[s,a]=await Promise.all([this.git.revparse([i]),this.git.revparse([n.ref])]);return s!==a}async checkRequirements(){return await this.isGitInstalled()?await this.git.checkIsRepo()?"valid":"missing-repo":"missing-git"}async branchInfo(){let r=await this.git.status(),i=await this.git.branch(["--no-color"]);return{current:r.current||void 0,tracking:r.tracking||void 0,branches:i.all}}async getRemoteUrl(r){try{return await this.git.remote(["get-url",r])||void 0}catch(i){if(String(i).contains(r))return;throw i}}async log(r,i=!0,n,s){let a;r&&(a=this.getRelativeRepoPath(r,i));let o={file:a,maxCount:n,"--diff-merges":"first-parent","--name-status":null};return s&&(o[s]=null),(await this.git.log(o)).all.map(c=>{var u,f,d,h;return{...c,author:{name:c.author_name,email:c.author_email},refs:c.refs.split(", ").filter(p=>p.length>0),diff:{...c.diff,files:(f=(u=c.diff)==null?void 0:u.files.map(p=>{let g="from"in p?p.from:void 0;return{...p,status:"status"in p?p.status:"M",path:p.file,hash:c.hash,vaultPath:this.getRelativeVaultPath(p.file),fromPath:g,fromVaultPath:g!=null?this.getRelativeVaultPath(g):void 0,binary:p.binary}}))!=null?f:[]},fileName:(h=(d=c.diff)==null?void 0:d.files.first())==null?void 0:h.file}})}async show(r,i,n=!0){let s=this.getRelativeRepoPath(i,n);return this.git.show([r+":"+s])}async getLocalBranchUpstream(r){try{let n=(await this.git.raw(["rev-parse","--abbrev-ref",`${r}@{upstream}`])).trim();return n.length>0?n:void 0}catch(i){return}}getAvailableLocalBranchName(r,i,n){let s=r;if(!n.includes(s))return s;let a=`${r}-${i}`,o=a,l=0;for(;n.includes(o);)l+=1,o=`${a}-${l}`;return o}async checkout(r,i){return this.withGitOperation(5,async()=>{if(i){let n=`${i}/${r}`,s=await this.branchInfo();if(s.branches.includes(r)&&await this.getLocalBranchUpstream(r)===n)await this.git.checkout(r);else{let l=this.getAvailableLocalBranchName(r,i,s.branches);await this.git.checkout(["-b",l,n])}}else await this.git.checkout(r);if(this.plugin.settings.submoduleRecurseCheckout){let n=await this.getSubmodulePaths();for(let s of n){let a=await this.git.cwd({path:s,root:!1}).branch();Object.keys(a.branches).includes(r)&&await this.git.cwd({path:s,root:!1}).checkout(r)}}})}async createBranch(r){await this.git.checkout(["-b",r])}async deleteBranch(r,i){await this.git.branch([i?"-D":"-d",r])}async branchIsMerged(r){return!(await this.git.branch(["--no-merged"])).all.contains(r)}async init(){await this.git.init(!1)}async clone(r,i,n){await this.git.clone(r,Be.join(this.app.vault.adapter.getBasePath(),i),n?["--depth",`${n}`]:[]),await this.setGitInstance()}async setConfig(r,i){i==null?await this.git.raw(["config","--local","--unset",r]):await this.git.addConfig(r,i)}async getConfig(r,i="local"){var s;return(s=(await this.git.getConfig(r.toLowerCase(),i=="all"?void 0:i)).value)!=null?s:void 0}async fetch(r){return this.withGitOperation(4,async()=>{await this.git.fetch(r!=null?[r]:[])})}async setRemote(r,i){(await this.getRemotes()).includes(r)?await this.git.remote(["set-url",r,i]):await this.git.remote(["add",r,i])}async getRemoteBranches(r){let i=await this.git.branch(["-r","--list",`${r}*`]),n=[];for(let s in i.branches)n.push(i.branches[s].name);return n}async getRemotes(){let r=await this.git.remote([]);return r?r.trim().split(` +`):[]}async removeRemote(r){await this.git.removeRemote(r)}async updateUpstreamBranch(r){try{await this.git.branch(["--set-upstream-to",r])}catch(i){try{await this.git.branch(["--set-upstream",r])}catch(n){let[s,a]=Vs(r),o=await this.branchInfo();await this.git.push(["--set-upstream",s,`${o.current}:${a}`])}}}updateGitPath(r){return this.setGitInstance()}updateBasePath(r){return this.setGitInstance(!0)}async getDiffString(r,i=!1,n){return i?await this.git.diff(["--cached","--",r]):n?await this.git.show([`${n}`,"--",r]):await this.git.diff(["--",r])}async diff(r,i,n){return await this.git.diff([`${i}..${n}`,"--",r])}async rawCommand(r){let i=r.split(" "),n=i[0];return n===void 0?"":await this.git.raw(n,...i.slice(1))}async getSubmoduleOfFile(r){if(!await this.app.vault.adapter.exists(Be.dirname(r)))return;let i=await this.git.raw(["-C",Be.dirname(r),"rev-parse","--show-toplevel"],l=>l&&console.warn("get-submodule-of-file",l==null?void 0:l.message));if(i=i.trim(),(await this.git.raw(["-C",Be.dirname(r),"rev-parse","--show-superproject-working-tree"],l=>l&&console.warn("get-submodule-of-file",l==null?void 0:l.message))).trim()==="")return;let a=this.app.vault.adapter.getFullPath(Be.normalize(r)),o=Be.relative(i,a);return{submodule:i,relativeFilepath:o}}async getLastCommitTime(){try{let r=await this.git.log({n:1});if(r!=null&&r.latest!=null)return new Date(r.latest.date)}catch(r){if(r instanceof jr){if(r.message.contains("does not have any commits yet"))return}else throw r}}async isGitInstalled(){let r=this.plugin.localStorage.getGitPath(),i=await Su(r||"git",["--version"],{});if(i.error)if(rs.Platform.isWin&&!r){this.plugin.log(`Git not found in PATH. Checking standard installation path(${Ud}) of Git for Windows.`);let n=await Su(Ud,["--version"]);if(n.error)return console.error(n.error),!1;this.useDefaultWindowsGitPath=!0}else return console.error(i.error),!1;else this.useDefaultWindowsGitPath=!1;return!0}convertErrors(r){if(r instanceof jr){let i=String(r.message);if(i.contains("Could not resolve host")||i.contains("Unable to resolve host")||i.contains("Unable to open connection")||i.match(/ssh: connect to host .*? port .*?: Operation timed out/)!=null||i.match(/ssh: connect to host .*? port .*?: Network is unreachable/)!=null||i.match(/ssh: connect to host .*? port .*?: Undefined error: 0/)!=null)throw new ll(i)}throw r}async isFileTrackedByLFS(r){try{return(await this.git.raw(["check-attr","filter",r])).includes("filter: lfs")}catch(i){let n=i instanceof Error?i.message:String(i);return this.plugin.displayError(`Error checking LFS status: ${n}`),!1}}},RT={hash:"000000",isZeroCommit:!0,summary:""};function C5(t){let r=t.replace(`\r +`,` +`).split(` +`),i={commits:new Map,hashPerLine:[void 0],originalFileLineNrPerLine:[void 0],finalFileLineNrPerLine:[void 0],groupSizePerStartingLine:new Map},n=1;for(let s=0;s=4&&r.groupSizePerStartingLine.set(e,parseInt(t[3])),parseInt(s)!==e)throw Error(`git-blame output is out of order: ${e} vs ${s}`);return i}function T5(t,e,r){let i=t[0],n=t.slice(1).join(" "),s=e.hashPerLine[r];if(s===void 0)throw Error(`No commit hash found for git-blame line ${r}`);let a=e.commits.get(s)||{hash:s,author:{},committer:{},previous:{}};switch(i){case"summary":a.summary=n;break;case"author":a.author.name=n;break;case"author-mail":a.author.email=AT(n);break;case"author-time":a.author.epochSeconds=parseInt(n);break;case"author-tz":a.author.tz=n;break;case"committer":a.committer.name=n;break;case"committer-mail":a.committer.email=AT(n);break;case"committer-time":a.committer.epochSeconds=parseInt(n);break;case"committer-tz":a.committer.tz=n;break;case"previous":a.previous.commitHash=n;break;case"filename":a.previous.filename=n;break}e.commits.set(s,a)}function P5(t){if(t.summary===void 0)throw Error(`Summary not provided for commit: ${t.hash}`);mw(t.author)&&(t.author=void 0),mw(t.committer)&&(t.committer=void 0),mw(t.previous)&&(t.previous=void 0),t.isZeroCommit=!!t.hash.match(/^0*$/)}function mw(t){return!t||Object.keys(t).length===0}function CT(t){return t===void 0?!1:t.length>0&&t[0].trim()===t[0]}function AT(t){let e=t.startsWith("<")?t.substring(1):t;return e.endsWith(">")?e.substring(0,e.length-1):e}function TT(t){return t instanceof Error?t.message:String(t)}m();var t2=require("@codemirror/state");m();var gw=class{constructor(){this.eventsPerFilepath=new Map;this.init()}ifFilepathDefinedTransformSubscribers(e,r){if(e)return this.ensureInitialized(e),r(this.eventsPerFilepath.get(e))}forEachSubscriber(e){this.eventsPerFilepath.forEach(r=>r.forEach(e))}ensureInitialized(e){this.eventsPerFilepath.get(e)||this.eventsPerFilepath.set(e,new Set)}init(){this.removeStalesSubscribersTimer===void 0&&this.startRemoveStalesSubscribersInterval()}startRemoveStalesSubscribersInterval(){this.removeStalesSubscribersTimer=window.setInterval(()=>this==null?void 0:this.forEachSubscriber(e=>e==null?void 0:e.removeIfStale()),6e4)}clear(){this.removeStalesSubscribersTimer!==void 0&&(window.clearInterval(this.removeStalesSubscribersTimer),this.removeStalesSubscribersTimer=void 0),this.eventsPerFilepath.clear()}},Ti=new gw;m();var wh=require("@codemirror/state");m();function R5(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var $T={exports:{}};(function(t){(function(){var e="input is invalid type",r=typeof window=="object",i=r?window:{};i.JS_SHA256_NO_WINDOW&&(r=!1);var n=!r&&typeof self=="object";n&&(i=self);var s=!i.JS_SHA256_NO_COMMON_JS&&!0&&t.exports,a=!i.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer!="undefined",o="0123456789abcdef".split(""),l=[-2147483648,8388608,32768,128],c=[24,16,8,0],u=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],f=["hex","array","digest","arrayBuffer"],d=[];(i.JS_SHA256_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(x){return Object.prototype.toString.call(x)==="[object Array]"}),a&&(i.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(x){return typeof x=="object"&&x.buffer&&x.buffer.constructor===ArrayBuffer});var h=function(x,E){return function(A){return new b(E,!0).update(A)[x]()}},p=function(x){var E=h("hex",x);E.create=function(){return new b(x)},E.update=function(S){return E.create().update(S)};for(var A=0;A>>2]|=x[S]<>>2]|=w<>>2]|=(192|w>>>6)<>>2]|=(128|w&63)<=57344?(T[y>>>2]|=(224|w>>>12)<>>2]|=(128|w>>>6&63)<>>2]|=(128|w&63)<>>2]|=(240|w>>>18)<>>2]|=(128|w>>>12&63)<>>2]|=(128|w>>>6&63)<>>2]|=(128|w&63)<=64?(this.block=T[16],this.start=y-64,this.hash(),this.hashed=!0):this.start=y}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},b.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var x=this.blocks,E=this.lastByteIndex;x[16]=this.block,x[E>>>2]|=l[E&3],this.block=x[16],E>=56&&(this.hashed||this.hash(),x[0]=this.block,x[16]=x[1]=x[2]=x[3]=x[4]=x[5]=x[6]=x[7]=x[8]=x[9]=x[10]=x[11]=x[12]=x[13]=x[14]=x[15]=0),x[14]=this.hBytes<<3|this.bytes>>>29,x[15]=this.bytes<<3,this.hash()}},b.prototype.hash=function(){var x=this.h0,E=this.h1,A=this.h2,w=this.h3,S=this.h4,y=this.h5,P=this.h6,T=this.h7,I=this.blocks,M,B,re,Ae,K,Q,fe,ce,z,X,j;for(M=16;M<64;++M)K=I[M-15],B=(K>>>7|K<<25)^(K>>>18|K<<14)^K>>>3,K=I[M-2],re=(K>>>17|K<<15)^(K>>>19|K<<13)^K>>>10,I[M]=I[M-16]+B+I[M-7]+re<<0;for(j=E&A,M=0;M<64;M+=4)this.first?(this.is224?(ce=300032,K=I[0]-1413257819,T=K-150054599<<0,w=K+24177077<<0):(ce=704751109,K=I[0]-210244248,T=K-1521486534<<0,w=K+143694565<<0),this.first=!1):(B=(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10),re=(S>>>6|S<<26)^(S>>>11|S<<21)^(S>>>25|S<<7),ce=x&E,Ae=ce^x&A^j,fe=S&y^~S&P,K=T+re+fe+u[M]+I[M],Q=B+Ae,T=w+K<<0,w=K+Q<<0),B=(w>>>2|w<<30)^(w>>>13|w<<19)^(w>>>22|w<<10),re=(T>>>6|T<<26)^(T>>>11|T<<21)^(T>>>25|T<<7),z=w&x,Ae=z^w&E^ce,fe=T&S^~T&y,K=P+re+fe+u[M+1]+I[M+1],Q=B+Ae,P=A+K<<0,A=K+Q<<0,B=(A>>>2|A<<30)^(A>>>13|A<<19)^(A>>>22|A<<10),re=(P>>>6|P<<26)^(P>>>11|P<<21)^(P>>>25|P<<7),X=A&w,Ae=X^A&x^z,fe=P&T^~P&S,K=y+re+fe+u[M+2]+I[M+2],Q=B+Ae,y=E+K<<0,E=K+Q<<0,B=(E>>>2|E<<30)^(E>>>13|E<<19)^(E>>>22|E<<10),re=(y>>>6|y<<26)^(y>>>11|y<<21)^(y>>>25|y<<7),j=E&A,Ae=j^E&w^X,fe=y&P^~y&T,K=S+re+fe+u[M+3]+I[M+3],Q=B+Ae,S=x+K<<0,x=K+Q<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+x<<0,this.h1=this.h1+E<<0,this.h2=this.h2+A<<0,this.h3=this.h3+w<<0,this.h4=this.h4+S<<0,this.h5=this.h5+y<<0,this.h6=this.h6+P<<0,this.h7=this.h7+T<<0},b.prototype.hex=function(){this.finalize();var x=this.h0,E=this.h1,A=this.h2,w=this.h3,S=this.h4,y=this.h5,P=this.h6,T=this.h7,I=o[x>>>28&15]+o[x>>>24&15]+o[x>>>20&15]+o[x>>>16&15]+o[x>>>12&15]+o[x>>>8&15]+o[x>>>4&15]+o[x&15]+o[E>>>28&15]+o[E>>>24&15]+o[E>>>20&15]+o[E>>>16&15]+o[E>>>12&15]+o[E>>>8&15]+o[E>>>4&15]+o[E&15]+o[A>>>28&15]+o[A>>>24&15]+o[A>>>20&15]+o[A>>>16&15]+o[A>>>12&15]+o[A>>>8&15]+o[A>>>4&15]+o[A&15]+o[w>>>28&15]+o[w>>>24&15]+o[w>>>20&15]+o[w>>>16&15]+o[w>>>12&15]+o[w>>>8&15]+o[w>>>4&15]+o[w&15]+o[S>>>28&15]+o[S>>>24&15]+o[S>>>20&15]+o[S>>>16&15]+o[S>>>12&15]+o[S>>>8&15]+o[S>>>4&15]+o[S&15]+o[y>>>28&15]+o[y>>>24&15]+o[y>>>20&15]+o[y>>>16&15]+o[y>>>12&15]+o[y>>>8&15]+o[y>>>4&15]+o[y&15]+o[P>>>28&15]+o[P>>>24&15]+o[P>>>20&15]+o[P>>>16&15]+o[P>>>12&15]+o[P>>>8&15]+o[P>>>4&15]+o[P&15];return this.is224||(I+=o[T>>>28&15]+o[T>>>24&15]+o[T>>>20&15]+o[T>>>16&15]+o[T>>>12&15]+o[T>>>8&15]+o[T>>>4&15]+o[T&15]),I},b.prototype.toString=b.prototype.hex,b.prototype.digest=function(){this.finalize();var x=this.h0,E=this.h1,A=this.h2,w=this.h3,S=this.h4,y=this.h5,P=this.h6,T=this.h7,I=[x>>>24&255,x>>>16&255,x>>>8&255,x&255,E>>>24&255,E>>>16&255,E>>>8&255,E&255,A>>>24&255,A>>>16&255,A>>>8&255,A&255,w>>>24&255,w>>>16&255,w>>>8&255,w&255,S>>>24&255,S>>>16&255,S>>>8&255,S&255,y>>>24&255,y>>>16&255,y>>>8&255,y&255,P>>>24&255,P>>>16&255,P>>>8&255,P&255];return this.is224||I.push(T>>>24&255,T>>>16&255,T>>>8&255,T&255),I},b.prototype.array=b.prototype.digest,b.prototype.arrayBuffer=function(){this.finalize();var x=new ArrayBuffer(this.is224?28:32),E=new DataView(x);return E.setUint32(0,this.h0),E.setUint32(4,this.h1),E.setUint32(8,this.h2),E.setUint32(12,this.h3),E.setUint32(16,this.h4),E.setUint32(20,this.h5),E.setUint32(24,this.h6),this.is224||E.setUint32(28,this.h7),x};function _(x,E,A){var w,S=typeof x;if(S==="string"){var y=[],P=x.length,T=0,I;for(w=0;w>>6,y[T++]=128|I&63):I<55296||I>=57344?(y[T++]=224|I>>>12,y[T++]=128|I>>>6&63,y[T++]=128|I&63):(I=65536+((I&1023)<<10|x.charCodeAt(++w)&1023),y[T++]=240|I>>>18,y[T++]=128|I>>>12&63,y[T++]=128|I>>>6&63,y[T++]=128|I&63);x=y}else if(S==="object"){if(x===null)throw new Error(e);if(a&&x.constructor===ArrayBuffer)x=new Uint8Array(x);else if(!Array.isArray(x)&&(!a||!ArrayBuffer.isView(x)))throw new Error(e)}else throw new Error(e);x.length>64&&(x=new b(E,!0).update(x).array());var M=[],B=[];for(w=0;w<64;++w){var re=x[w]||0;M[w]=92^re,B[w]=54^re}b.call(this,E,A),this.update(B),this.oKeyPad=M,this.inner=!0,this.sharedMemory=A}_.prototype=new b,_.prototype.finalize=function(){if(b.prototype.finalize.call(this),this.inner){this.inner=!1;var x=this.array();b.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(x),b.prototype.finalize.call(this)}};var C=p();C.sha256=C,C.sha224=p(!0),C.sha256.hmac=v(),C.sha224.hmac=v(!0),s?t.exports=C:(i.sha256=C.sha256,i.sha224=C.sha224)})()})($T);var $5=$T.exports,Du=R5($5),{sha224:a7}=Du;function FT(t,e,r){if(!(t===void 0||e===void 0||r===void 0))return`head${t}-obj${e}-path${r}`}var IT=wh.StateEffect.define();function MT(t,e,r){return r.update({effects:IT.of({key:t,la:e,lineOffsetsFromUnsavedChanges:new Map})})}var Cl=wh.StateField.define({create:t=>{},update:(t,e)=>{for(let r of e.effects)if(r.is(IT))return r.value;return F5(e,t)},compare:(t,e)=>(t==null?void 0:t.key)===(e==null?void 0:e.key)});function bh(t){var s;let e=Du.create();if(!t)return e;let{la:r,key:i,lineOffsetsFromUnsavedChanges:n}=t;e.update(r==="untracked"?"t":"f"),e.update(i);for(let[a,o]of(s=n.entries())!=null?s:[])e.update([a,o]);return e}var Ou={get:void 0,save:void 0};function DT(t,e){Ou.get=t,Ou.save=e}function _h(t){var e,r;return(r=(e=Lu(t.coloringMaxAge))==null?void 0:e.asDays())!=null?r:Lu(tt.lineAuthor.coloringMaxAge).asDays()}function F5(t,e){if(e)return t.changes.empty||t.changes.iterChanges((r,i,n,s)=>{var p;let a=t.startState.doc,{newDoc:o}=t,l=a.lineAt(r).number,c=a.lineAt(i).number,u=o.lineAt(n).number,f=o.lineAt(s).number,d=c-l+1,h=f-u+1;for(let g=u;g<=f;g++){let v=(p=e.lineOffsetsFromUnsavedChanges.get(g))!=null?p:0,b=f===g,_=h-d;b&&(v+=_),e.lineOffsetsFromUnsavedChanges.set(g,v)}}),e}m();function OT(){Al=void 0,vw=[],yh=0,Eh.clear(),Sh.clear(),Tl.clear()}var Al,xh=()=>Al;function LT(t,e){var n;let r=e.length;if(r<((n=Al==null?void 0:Al.length)!=null?n:0))return;Al={gutter:t,length:r,text:e};let i=Et.plugin.localStorage.getGutterSpacingFallbackLength();r!==i&&Et.plugin.localStorage.setGutterSpacingFallbackLength(r)}var vw=[],I5=15,yh=0;function NT(t){vw[yh]=t,yh=(yh+1)%I5}function BT(){return yk(vw)}var Eh=new Map,Sh=new Map,Tl=new Set;m();var QT=require("@codemirror/state"),JT=require("@codemirror/view");m();var yw=require("@codemirror/view");var Pl=require("obsidian");m();m();var kh={x:-10,y:-10};function HT(){kh.x===-10&&window.addEventListener("mousedown",t=>{kh.x=t.clientX,kh.y=t.clientY})}function UT(){for(let t of Tl)if(M5(t,kh))return t}function M5(t,e){let{x:r,y:i,width:n,height:s}=t.getBoundingClientRect();return r<=e.x&&e.x<=r+n&&i<=e.y&&e.y<=i+s}var GT="data-commit";function jT(t,e,r){if(e.hasFocus())return;let i=UT();if(!i)return;let n=O5(i);n&&(!n.isZeroCommit&&!n.isWaitingGutter&&D5(n,t),ww("showCommitHash",t),ww("authorDisplay",t),ww("dateTimeFormatOptions",t))}function D5(t,e){e.addItem(r=>r.setTitle("Copy commit hash").setIcon("copy").setSection("obs-git-line-author-copy").onClick(i=>navigator.clipboard.writeText(t.hash)))}function ww(t,e){var l,c;let r,i,n=Et.plugin.settings.lineAuthor,s=n[t],a=typeof s=="boolean"?s:s!=="hide",o=tt.lineAuthor[t];if(t==="showCommitHash")r="Show commit hash",i=s;else if(t==="authorDisplay"){let u=(l=n.lastShownAuthorDisplay)!=null?l:o;r="Show author "+(a?s:u),i=a?"hide":u}else if(t==="dateTimeFormatOptions"){let u=(c=n.lastShownDateTimeFormatOptions)!=null?c:o;r="Show "+(a?s:u),r+=r.contains("date")?"":" date",i=a?"hide":u}else js(t);e.addItem(u=>u.setTitle(r).setSection("obs-git-line-author-configure").setChecked(a).onClick(f=>{var d,h;return(h=(d=Et.plugin)==null?void 0:d.settingsTab)==null?void 0:h.lineAuthorSettingHandler(t,i)}))}function VT(t,e,r){r.setAttr(GT,JSON.stringify({hash:t.hash,isZeroCommit:t.isZeroCommit,isWaitingGutter:e}))}function O5(t){let e=t.getAttr(GT);return e?JSON.parse(e):void 0}m();function Ah(t,e){return t==="oldest"?Ch(0,!1,e).color:Ch(void 0,!0,e).color}function Ch(t,e,r){let i=_h(r),n=Date.now()/1e3,s=t!=null?t:0,o=(e?0:n-s)/60/60/24,l=Math.pow(Math.clamp(o/i,0,1),1/2.3),c=L5(),u=r.colorNew,f=r.colorOld,d=c?.4:1,h=bw(u.r,f.r,l)*d,p=bw(u.g,f.g,l)*d,g=bw(u.b,f.b,l)*d;return{color:`rgba(${h},${p},${g},${c?.75:.25})`,daysSinceCommit:o}}function bw(t,e,r){return t+(e-t)*r}function L5(){var t,e,r;return(r=(e=(t=Et.plugin)==null?void 0:t.app)==null?void 0:e.isDarkMode())!=null?r:!1}function zT(t){activeDocument.body.style.setProperty("--obs-git-gutter-text",t.textColorCss)}m();function WT(t,e,r){let i;for(let n=e;n<=r;n++){let s=t.hashPerLine[n];if(s===void 0)continue;let a=t.commits.get(s);(!i||a.isZeroCommit||N5(a,i))&&(i=a)}return i}function N5(t,e){var n,s,a,o;let r=(s=(n=t.author)==null?void 0:n.epochSeconds)!=null?s:0,i=(o=(a=e.author)==null?void 0:a.epochSeconds)!=null?o:0;return r>i}var YT=require("node:util");var qT="-",B5="+",H5=3,U5="*",G5=/\S/g,j5="%",Rl=class t extends yw.GutterMarker{constructor(r){super();this.text=r}eq(r){return r instanceof t&&this.text===r.text}toDOM(){return activeDocument.createTextNode(this.text)}destroy(r){}},_w=class extends yw.GutterMarker{constructor(r,i,n,s,a,o){super();this.lineAuthoring=r;this.startLine=i;this.endLine=n;this.key=s;this.settings=a;this.options=o;this.point=!1;this.elementClass="obs-git-blame-gutter"}eq(r){return this.key===(r==null?void 0:r.key)&&this.startLine===(r==null?void 0:r.startLine)&&this.endLine===(r==null?void 0:r.endLine)&&(this==null?void 0:this.options)===(r==null?void 0:r.options)}toDOM(){var r;return this.precomputedDomProvider=(r=this.precomputedDomProvider)!=null?r:this.computeDom(),this.precomputedDomProvider()}destroy(r){r&&(activeDocument.body.contains(r)||Tl.delete(r))}computeDom(){let r=WT(this.lineAuthoring,this.startLine,this.endLine),i=r.isZeroCommit?"":this.renderNonZeroCommit(r);return!r.isZeroCommit&&this.options!=="waiting-for-result"?LT(this,i):i=this.adaptTextForFakeCommit(r,i,this.options),this.createHtmlNode(r,i,this.options==="waiting-for-result")}createHtmlNode(r,i,n){var c,u,f,d,h,p;let s=window.createDiv();s.setText(i);let{color:a,daysSinceCommit:o}=Ch((c=r==null?void 0:r.author)==null?void 0:c.epochSeconds,r==null?void 0:r.isZeroCommit,this.settings);s.style.backgroundColor=a,s.setAttribute("data-author",(f=(u=r==null?void 0:r.author)==null?void 0:u.name)!=null?f:""),s.setAttribute("data-author-email",(h=(d=r==null?void 0:r.author)==null?void 0:d.email)!=null?h:""),(0,Pl.setTooltip)(s,(p=r==null?void 0:r.summary)!=null?p:""),VT(r,n,s);function l(){let g=s.cloneNode(!0);return Tl.add(g),n||NT(o),g}return l}renderNonZeroCommit(r){let i=this.settings.showCommitHash?this.renderHash(r):"",n=this.settings.authorDisplay==="hide"?"":`${this.renderAuthorName(r,this.settings.authorDisplay)}`,s=this.settings.dateTimeFormatOptions==="hide"?"":`${this.renderAuthoringDate(r,this.settings.dateTimeFormatOptions,this.settings.dateTimeFormatCustomString,this.settings.dateTimeTimezone)}`;return[i,n,s].filter(o=>o.length>=1).join(" ")}renderHash(r){return r.hash.substring(0,6)}renderAuthorName(r,i){var o,l,c,u;let n=(l=(o=r==null?void 0:r.author)==null?void 0:o.name)!=null?l:"",s=n.split(" ").filter(f=>f.length>=1),a;switch(i){case"initials":a=s.map(f=>f[0].toUpperCase()).join("");break;case"first name":a=(c=s.first())!=null?c:qT;break;case"last name":a=(u=s.last())!=null?u:qT;break;case"full":a=n;break;default:return js(i)}return(0,YT.isDeepStrictEqual)(r==null?void 0:r.author,r==null?void 0:r.committer)||(a=a+U5),a}renderAuthoringDate(r,i,n,s){var c;if(((c=r==null?void 0:r.author)==null?void 0:c.epochSeconds)===void 0)return"?";let o;switch(i){case"date":o=Bd;break;case"datetime":o=uv;break;case"custom":o=n;break;case"natural language":o=u=>{let f=u.diff((0,Pl.moment)());return Pl.moment.duration(f).humanize(!0)};break;default:return js(i)}let l=Pl.moment.unix(r.author.epochSeconds);switch(s){case"viewer-local":break;case"author-local":l=l.utcOffset(r.author.tz),typeof o=="string"&&(o+=" Z");break;case"utc0000":l=l.utc(),typeof o=="string"&&(o+="[Z]");break;default:return js(s)}return typeof o=="string"?l.format(o):o(l)}adaptTextForFakeCommit(r,i,n){var l,c,u;let s=(c=(l=xh())==null?void 0:l.text)!=null?c:i,a=n!=="waiting-for-result"&&r.isZeroCommit?B5:j5;i=s.replace(G5,a);let o=(u=Et.plugin.localStorage.getGutterSpacingFallbackLength())!=null?u:i.length;if(i=xk(i,o,a),n!=="waiting-for-result"&&r.isZeroCommit){let f=Math.min(o,H5);i=Ek(i,o-f)}return i}};function Na(t,e,r,i,n,s){let a=Du.create();a.update(JSON.stringify(n)),a.update(`s${e}-e${r}-k${i}-o${s}`);let o=a.hex(),l=Eh.get(o);if(l)return l;let c=new _w(t,e,r,i,n,s);return Eh.set(o,c),c}m();var ZT=require("obsidian");function xw(){let t=Et.plugin.localStorage.getGutterSpacingFallbackLength();return new Rl(Array(t).fill("-").join(""))}function Ew(t){let{lineAuthoring:e,ageForInitialRender:r}=V5(t);return Na(e,1,1,"initialGutter"+r,t,"waiting-for-result")}function V5(t){var s;let e=(s=BT())!=null?s:_h(t)*.25,r=(0,ZT.moment)().add(-e,"days"),i={name:"",epochSeconds:_k(r),tz:"+0000"},n={hash:"waiting-for-result",author:i,committer:i,isZeroCommit:!1};return{lineAuthoring:{hashPerLine:[void 0,"waiting-for-result"],commits:new Map([["waiting-for-result",n]])},ageForInitialRender:e}}m();function KT(t,e){return Na({hashPerLine:[void 0,"000000"],commits:new Map([["000000",RT]])},1,1,t,e)}var Sw=new Rl(""),e2=(0,JT.gutter)({class:"line-author-gutter-container",markers(t){let e=t.state.field(Cl,!1);return z5(t,e)},lineMarkerChange(t){let e=bh(t.state.field(Cl));return bh(t.startState.field(Cl))!==e},renderEmptyElements:!0,initialSpacer:t=>(XT(t),xw()),updateSpacer:(t,e)=>{var r,i;return XT(e.view),(i=(r=xh())==null?void 0:r.gutter)!=null?i:xw()}});function z5(t,e){let r=bh(e),i=t.state.doc,n=new Map;for(let u=1;u<=i.lines;u++){let f=i.line(u).from,d=t.lineBlockAt(f).to;n.set(u,[f,d]),r.update([f,d,0])}let s=Ou.get();r.update("s"+Object.values(Ou).join(","));let a=r.hex(),o=Sh.get(a);if(o)return o;let{result:l,allowCache:c}=W5(i,n,s,e);return c&&Sh.set(a,l),l}function W5(t,e,r,i){let n=!0,s=t.lines,a=[];function o(f,d,h){return a.push(h.range(f,d))}let l=q5(s,i),c=t.length===0,u=t.iterLines(s,s+1).next().value==="";for(let f=1;f<=s;f++){let[d,h]=e.get(f),p=t.lineAt(h).number;if(c){o(d,h,Sw);continue}if(f===s&&u){o(d,h,Sw);continue}if(i===void 0){o(d,h,Ew(r)),n=!1;continue}let{key:g,la:v}=i;if(v==="untracked"){o(d,h,KT(v,r));continue}let b=v.hashPerLine.length-1,_=l[f],C=l[p];if(C&&C>b&&o(d,h,Sw),_!==void 0&&_v(1,_,b)&&C!==void 0&&_v(1,C,b)){o(d,h,Na(v,_,C,g,r));continue}if(b<1){o(d,h,Ew(r)),n=!1;continue}let x=Math.clamp(_!=null?_:f,1,b),E=Math.clamp(C!=null?C:p,1,b);o(d,h,Na(v,x,E,g+"computing",r,"waiting-for-result"))}return{result:QT.RangeSet.of(a,!0),allowCache:n}}function q5(t,e){if(!(e!=null&&e.lineOffsetsFromUnsavedChanges))return Array.from(new Array(t+1),n=>n);let r=[void 0],i=0;for(let n=1;n<=t;n++){let s=e.lineOffsetsFromUnsavedChanges.get(n);i+=s!=null?s:0,r[n]=s===void 0?n-i:void 0}return r}function XT(t){t.dom.querySelectorAll(".cm-gutters").forEach(r=>{r!=null&&r.style&&(r.style.marginLeft||(r.style.marginLeft="unset"))})}var Th=class{constructor(e){this.plugin=e;this.lineAuthorings=new Map}async trackChanged(e){try{await this.trackChangedHelper(e)}catch(r){throw console.warn("Git: Error in trackChanged.",r),r}}async trackChangedHelper(e){if(e){if(e.path===void 0){console.warn("Git: Attempted to track change of undefined filepath. Unforeseen situation.");return}return this.computeLineAuthorInfo(e.path)}}destroy(){this.lineAuthorings.clear(),OT()}async computeLineAuthorInfo(e){let r=this.plugin.editorIntegration.lineAuthoringFeature.isAvailableOnCurrentPlatform().gitManager,i=await r.submoduleAwareHeadRevisonInContainingDirectory(e),n=await r.hashObject(e),s=FT(i,n,e);if(s!==void 0){if(!this.lineAuthorings.has(s)){let a=await r.blame(e,this.plugin.settings.lineAuthor.followMovement,this.plugin.settings.lineAuthor.ignoreWhitespace);this.lineAuthorings.set(s,a)}this.notifyComputationResultToSubscribers(e,s)}}notifyComputationResultToSubscribers(e,r){Ti.ifFilepathDefinedTransformSubscribers(e,i=>i.forEach(n=>n.notifyLineAuthoring(r,this.lineAuthorings.get(r))))}},r2=t2.Prec.high([Cl,e2]);var i2="https://momentjs.com/docs/#/parsing/string-format/",Y5="https://publish.obsidian.md/git-doc/Line+Authoring",Ph=class extends U.PluginSettingTab{constructor(r,i){super(r,i);this.plugin=i;this.lineAuthorColorSettings=new Map;this.icon="git-pull-request"}get settings(){return this.plugin.settings}display(){let{containerEl:r}=this,i=this.plugin,n;i.settings.differentIntervalCommitAndPush?n="commit":n="commit-and-sync";let s=i.gitReady;r.empty(),s||(r.createEl("p",{text:"Git is not ready. When all settings are correct you can configure commit-sync, etc."}),r.createEl("br"));let a;if(s){new U.Setting(r).setName("Automatic").setHeading(),new U.Setting(r).setName("Split timers for automatic commit and sync").setDesc("Enable to use one interval for commit and another for sync.").addToggle(f=>f.setValue(i.settings.differentIntervalCommitAndPush).onChange(async d=>{i.settings.differentIntervalCommitAndPush=d,await i.saveSettings(),i.automaticsManager.reload("commit","push"),this.refreshDisplayWithDelay()})),new U.Setting(r).setName(`Auto ${n} interval (minutes)`).setDesc(`${i.settings.differentIntervalCommitAndPush?"Commit":"Commit and sync"} changes every X minutes. Set to 0 (default) to disable. (See below setting for further configuration!)`).addText(f=>{f.inputEl.type="number",this.setNonDefaultValue({text:f,settingsProperty:"autoSaveInterval"}),f.setPlaceholder(String(tt.autoSaveInterval)),f.onChange(async d=>{d!==""?i.settings.autoSaveInterval=Number(d):i.settings.autoSaveInterval=tt.autoSaveInterval,await i.saveSettings(),i.automaticsManager.reload("commit")})}),a=new U.Setting(r).setName(`Auto ${n} after stopping file edits`).setDesc(`Requires the ${n} interval not to be 0. + If turned on, do auto ${n} every ${Sk(i.settings.autoSaveInterval)} after stopping file edits. + This also prevents auto ${n} while editing a file. If turned off, it's independent from the last file edit.`).addToggle(f=>f.setValue(i.settings.autoBackupAfterFileChange).onChange(async d=>{i.settings.autoBackupAfterFileChange=d,this.refreshDisplayWithDelay(),await i.saveSettings(),i.automaticsManager.reload("commit")})),this.mayDisableSetting(a,i.settings.setLastSaveToLastCommit),a=new U.Setting(r).setName(`Auto ${n} after latest commit`).setDesc(`If turned on, sets last auto ${n} timestamp to the latest commit timestamp. This reduces the frequency of auto ${n} when doing manual commits.`).addToggle(f=>f.setValue(i.settings.setLastSaveToLastCommit).onChange(async d=>{i.settings.setLastSaveToLastCommit=d,await i.saveSettings(),i.automaticsManager.reload("commit"),this.refreshDisplayWithDelay()})),this.mayDisableSetting(a,i.settings.autoBackupAfterFileChange),a=new U.Setting(r).setName("Auto push interval (minutes)").setDesc("Push commits every X minutes. Set to 0 (default) to disable.").addText(f=>{f.inputEl.type="number",this.setNonDefaultValue({text:f,settingsProperty:"autoPushInterval"}),f.setPlaceholder(String(tt.autoPushInterval)),f.onChange(async d=>{d!==""?i.settings.autoPushInterval=Number(d):i.settings.autoPushInterval=tt.autoPushInterval,await i.saveSettings(),i.automaticsManager.reload("push")})}),this.mayDisableSetting(a,!i.settings.differentIntervalCommitAndPush),new U.Setting(r).setName("Auto pull interval (minutes)").setDesc("Pull changes every X minutes. Set to 0 (default) to disable.").addText(f=>{f.inputEl.type="number",this.setNonDefaultValue({text:f,settingsProperty:"autoPullInterval"}),f.setPlaceholder(String(tt.autoPullInterval)),f.onChange(async d=>{d!==""?i.settings.autoPullInterval=Number(d):i.settings.autoPullInterval=tt.autoPullInterval,await i.saveSettings(),i.automaticsManager.reload("pull")})}),new U.Setting(r).setName(`Auto ${n} only staged files`).setDesc(`If turned on, only staged files are committed on ${n}. If turned off, all changed files are committed.`).addToggle(f=>f.setValue(i.settings.autoCommitOnlyStaged).onChange(async d=>{i.settings.autoCommitOnlyStaged=d,await i.saveSettings()})),new U.Setting(r).setName(`Specify custom commit message on auto ${n}`).setDesc("You will get a pop up to specify your message.").addToggle(f=>f.setValue(i.settings.customMessageOnAutoBackup).onChange(async d=>{i.settings.customMessageOnAutoBackup=d,await i.saveSettings(),this.refreshDisplayWithDelay()})),a=new U.Setting(r).setName(`Commit message on auto ${n}`).setDesc("Available placeholders: {{date}} (see below), {{hostname}} (see below), {{numFiles}} (number of changed files in the commit) and {{files}} (changed files in commit message).").addTextArea(f=>{f.setPlaceholder(tt.autoCommitMessage).onChange(async d=>{d===""?i.settings.autoCommitMessage=tt.autoCommitMessage:i.settings.autoCommitMessage=d,await i.saveSettings()}),this.setNonDefaultValue({text:f,settingsProperty:"autoCommitMessage"})}),this.mayDisableSetting(a,i.settings.customMessageOnAutoBackup),new U.Setting(r).setName("Commit").setHeading(),new U.Setting(r).setName("Stage all changes when nothing is staged").setDesc("When using Commit with nothing staged, stage and commit all changes. When disabled, changes must be staged first. Commit all changes and Commit-and-sync are unaffected.").addToggle(f=>f.setValue(i.settings.autoStageOnEmptyIndex).onChange(async d=>{i.settings.autoStageOnEmptyIndex=d,await i.saveSettings()}));let c=new U.Setting(r).setName("Commit message on manual commit").setDesc("Available placeholders: {{date}} (see below), {{hostname}} (see below), {{numFiles}} (number of changed files in the commit) and {{files}} (changed files in commit message). Leave empty to require manual input on each commit.");c.addTextArea(f=>{c.addButton(d=>{d.setIcon("reset").setTooltip(`Set to default: "${tt.commitMessage}"`).onClick(()=>{f.setValue(tt.commitMessage),f.onChanged()})}),f.setValue(i.settings.commitMessage),f.onChange(async d=>{i.settings.commitMessage=d,await i.saveSettings()})}),U.Platform.isDesktopApp&&new U.Setting(r).setName("Commit message script").setDesc("A script that is run using 'sh -c' to generate the commit message. May be used to generate commit messages using AI tools. Available placeholders: {{hostname}}, {{date}}.").addText(f=>{f.onChange(async d=>{d===""?i.settings.commitMessageScript=tt.commitMessageScript:i.settings.commitMessageScript=d,await i.saveSettings()}),this.setNonDefaultValue({text:f,settingsProperty:"commitMessageScript"})});let u=new U.Setting(r).setName("{{date}} placeholder format").addMomentFormat(f=>f.setDefaultFormat(i.settings.commitDateFormat).setValue(i.settings.commitDateFormat).onChange(async d=>{i.settings.commitDateFormat=d,await i.saveSettings()}));u.descEl.createSpan({text:` Specify custom date format. E.g. "${fv}. See `}),u.descEl.createEl("a",{text:"Moment.js documentation",href:i2,attr:{target:"_blank"}}),u.descEl.createSpan({text:" for more formats."}),new U.Setting(r).setName("{{hostname}} placeholder replacement").setDesc("Specify custom hostname for every device. Defaults to the OS hostname if not set on desktop.").addText(f=>{var d;return f.setValue((d=i.localStorage.getHostname())!=null?d:"").onChange(h=>{i.localStorage.setHostname(h)})}),new U.Setting(r).setName("Preview commit message").addButton(f=>f.setButtonText("Preview").onClick(async()=>{let d=await i.gitManager.formatCommitMessage(i.settings.commitMessage);new U.Notice(`${d}`)})),new U.Setting(r).setName("List filenames affected by commit in the commit body").addToggle(f=>f.setValue(i.settings.listChangedFilesInMessageBody).onChange(async d=>{i.settings.listChangedFilesInMessageBody=d,await i.saveSettings()})),new U.Setting(r).setName("Pull").setHeading(),i.gitManager instanceof ke&&new U.Setting(r).setName("Merge strategy").setDesc("Decide how to integrate commits from your remote branch into your local branch.").addDropdown(f=>{let d={merge:"Merge",rebase:"Rebase",reset:"Other sync service (Only updates the HEAD without touching the working directory)"};f.addOptions(d),f.setValue(i.settings.syncMethod),f.onChange(async h=>{i.settings.syncMethod=h,await i.saveSettings()})}),new U.Setting(r).setName("Merge strategy on conflicts").setDesc("Decide how to solve conflicts when pulling remote changes. This can be used to favor your local changes or the remote changes automatically.").addDropdown(f=>{let d={none:"None (git default)",ours:"Our changes",theirs:"Their changes"};f.addOptions(d),f.setValue(i.settings.mergeStrategy),f.onChange(async h=>{i.settings.mergeStrategy=h,await i.saveSettings()})}),new U.Setting(r).setName("Pull on startup").setDesc("Automatically pull commits when Obsidian starts.").addToggle(f=>f.setValue(i.settings.autoPullOnBoot).onChange(async d=>{i.settings.autoPullOnBoot=d,await i.saveSettings()})),new U.Setting(r).setName("Commit-and-sync").setDesc("Commit-and-sync with default settings means staging everything -> committing -> pulling -> pushing. Ideally this is a single action that you do regularly to keep your local and remote repository in sync.").setHeading(),a=new U.Setting(r).setName("Push on commit-and-sync").setDesc(`Most of the time you want to push after committing. Turning this off turns a commit-and-sync action into commit ${i.settings.pullBeforePush?"and pull ":""}only. It will still be called commit-and-sync.`).addToggle(f=>f.setValue(!i.settings.disablePush).onChange(async d=>{i.settings.disablePush=!d,this.refreshDisplayWithDelay(),await i.saveSettings()})),new U.Setting(r).setName("Pull on commit-and-sync").setDesc(`On commit-and-sync, pull commits as well. Turning this off turns a commit-and-sync action into commit ${i.settings.disablePush?"":"and push "}only.`).addToggle(f=>f.setValue(i.settings.pullBeforePush).onChange(async d=>{i.settings.pullBeforePush=d,this.refreshDisplayWithDelay(),await i.saveSettings()})),i.gitManager instanceof ke&&new U.Setting(r).setName("Squash commits before push").setDesc("On commit-and-sync, squash all local unpushed commits into a single commit right before pushing. Keeps the remote history clean when committing often. Only unpushed commits are rewritten, so no force-push is needed.").addToggle(f=>f.setValue(i.settings.squashCommitsBeforePush).onChange(async d=>{i.settings.squashCommitsBeforePush=d,await i.saveSettings()})),i.gitManager instanceof ke&&(new U.Setting(r).setName("Hunk management").setDesc("Hunks are sections of grouped line changes right in your editor.").setHeading(),new U.Setting(r).setName("Signs").setDesc("This allows you to see your changes right in your editor via colored markers and stage/reset/preview individual hunks.").addToggle(f=>f.setValue(i.settings.hunks.showSigns).onChange(async d=>{i.settings.hunks.showSigns=d,await i.saveSettings(),i.editorIntegration.refreshSignsSettings()})),new U.Setting(r).setName("Hunk commands").setDesc("Adds commands to stage/reset individual Git diff hunks and navigate between them via 'Go to next/prev hunk' commands.").addToggle(f=>f.setValue(i.settings.hunks.hunkCommands).onChange(async d=>{i.settings.hunks.hunkCommands=d,await i.saveSettings(),i.editorIntegration.refreshSignsSettings()})),new U.Setting(r).setName("Status bar with summary of line changes").addDropdown(f=>f.addOptions({disabled:"Disabled",colored:"Colored",monochrome:"Monochrome"}).setValue(i.settings.hunks.statusBar).onChange(async d=>{i.settings.hunks.statusBar=d,await i.saveSettings(),i.editorIntegration.refreshSignsSettings()})),new U.Setting(r).setName("Line author information").setHeading(),this.addLineAuthorInfoSettings())}new U.Setting(r).setName("History view").setHeading(),new U.Setting(r).setName("Show Author").setDesc("Show the author of the commit in the history view.").addDropdown(c=>{let u={hide:"Hide",full:"Full",initials:"Initials"};c.addOptions(u),c.setValue(i.settings.authorInHistoryView),c.onChange(async f=>{i.settings.authorInHistoryView=f,await i.saveSettings(),await i.refresh()})}),new U.Setting(r).setName("Show Date").setDesc("Show the date of the commit in the history view. The {{date}} placeholder format is used to display the date.").addToggle(c=>c.setValue(i.settings.dateInHistoryView).onChange(async u=>{i.settings.dateInHistoryView=u,await i.saveSettings(),await i.refresh()})),new U.Setting(r).setName("Source control view").setHeading(),new U.Setting(r).setName("Automatically refresh source control view on file changes").setDesc("On slower machines this may cause lags. If so, just disable this option.").addToggle(c=>c.setValue(i.settings.refreshSourceControl).onChange(async u=>{i.settings.refreshSourceControl=u,await i.saveSettings()})),new U.Setting(r).setName("Source control view refresh interval").setDesc("Milliseconds to wait after file change before refreshing the Source Control View.").addText(c=>{c.inputEl.type="number",this.setNonDefaultValue({text:c,settingsProperty:"refreshSourceControlTimer"}),c.setPlaceholder(String(tt.refreshSourceControlTimer)),c.onChange(async f=>{f!==""&&Number.isInteger(Number(f))?i.settings.refreshSourceControlTimer=Math.max(Number(f),500):i.settings.refreshSourceControlTimer=tt.refreshSourceControlTimer,await i.saveSettings(),i.setRefreshDebouncer()})}),new U.Setting(r).setName("Miscellaneous").setHeading(),i.gitManager instanceof ke&&(new U.Setting(r).setName("Diff view style").setDesc('Set the style for the diff view. Note that the actual diff in "Split" mode is not generated by Git, but the editor itself instead so it may differ from the diff generated by Git. One advantage of this is that you can edit the text in that view.').addDropdown(c=>{let u={split:"Split",git_unified:"Unified"};c.addOptions(u),c.setValue(i.settings.diffStyle),c.onChange(async f=>{i.settings.diffStyle=f,await i.saveSettings()})}),new U.Setting(r).setName("Split diff view timeout").setDesc("Maximum time in milliseconds to compute a detailed split diff. Higher values improve accuracy for large files with many changes but may reduce responsiveness. Read-only diffs use ten times this value.").addText(c=>{c.inputEl.type="number",c.inputEl.min="1",c.inputEl.step="1",this.setNonDefaultValue({text:c,settingsProperty:"diffTimeout"}),c.setPlaceholder(String(tt.diffTimeout)),c.onChange(async u=>{let f=Number(u);i.settings.diffTimeout=u!==""&&Number.isInteger(f)&&f>0?f:tt.diffTimeout,await i.saveSettings()})})),new U.Setting(r).setName("Disable informative notifications").setDesc("Disable informative notifications for git operations to minimize distraction (refer to status bar for updates).").addToggle(c=>c.setValue(i.settings.disablePopups).onChange(async u=>{i.settings.disablePopups=u,this.refreshDisplayWithDelay(),await i.saveSettings()})),new U.Setting(r).setName("Disable error notifications").setDesc("Disable error notifications of any kind to minimize distraction (refer to status bar for updates).").addToggle(c=>c.setValue(!i.settings.showErrorNotices).onChange(async u=>{i.settings.showErrorNotices=!u,await i.saveSettings()})),i.settings.disablePopups||new U.Setting(r).setName("Hide notifications for no changes").setDesc("Don't show notifications when there are no changes to commit or push.").addToggle(c=>c.setValue(i.settings.disablePopupsForNoChanges).onChange(async u=>{i.settings.disablePopupsForNoChanges=u,await i.saveSettings()})),new U.Setting(r).setName("Show status bar").setDesc("Obsidian must be restarted for the changes to take affect.").addToggle(c=>c.setValue(i.settings.showStatusBar).onChange(async u=>{i.settings.showStatusBar=u,await i.saveSettings()})),new U.Setting(r).setName("File menu integration").setDesc('Add "Stage", "Unstage" and "Add to .gitignore" actions to the file menu.').addToggle(c=>c.setValue(i.settings.showFileMenu).onChange(async u=>{i.settings.showFileMenu=u,await i.saveSettings()})),new U.Setting(r).setName("Show branch status bar").setDesc("Obsidian must be restarted for the changes to take affect.").addToggle(c=>c.setValue(i.settings.showBranchStatusBar).onChange(async u=>{i.settings.showBranchStatusBar=u,await i.saveSettings()})),new U.Setting(r).setName("Show the count of modified files in the status bar").addToggle(c=>c.setValue(i.settings.changedFilesInStatusBar).onChange(async u=>{i.settings.changedFilesInStatusBar=u,await i.saveSettings()})),i.gitManager instanceof Zi?new U.Setting(r).setName("Authentication/commit author").setHeading():new U.Setting(r).setName("Commit author").setHeading(),i.gitManager instanceof Zi&&new U.Setting(r).setName("Username on your git server. E.g. your username on GitHub").addText(c=>{var u;c.setValue((u=i.localStorage.getUsername())!=null?u:""),c.onChange(f=>{i.localStorage.setUsername(f)})}),i.gitManager instanceof Zi&&new U.Setting(r).setName("Password/Personal access token").setDesc("Type in your password. You won't be able to see it again.").addText(c=>{c.inputEl.autocapitalize="off",c.inputEl.autocomplete="off",c.inputEl.spellcheck=!1,c.onChange(u=>{i.localStorage.setPassword(u)})}),i.gitReady&&new U.Setting(r).setName("Author name for commit").addText(async c=>{var u;c.setValue((u=await i.gitManager.getConfig("user.name"))!=null?u:""),c.onChange(async f=>{await i.gitManager.setConfig("user.name",f==""?void 0:f)})}),i.gitReady&&new U.Setting(r).setName("Author email for commit").addText(async c=>{var u;c.setValue((u=await i.gitManager.getConfig("user.email"))!=null?u:""),c.onChange(async f=>{await i.gitManager.setConfig("user.email",f==""?void 0:f)})}),new U.Setting(r).setName("Advanced").setDesc("These settings usually don't need to be changed, but may be required for special setups.").setHeading(),i.gitManager instanceof ke&&(new U.Setting(r).setName("Update submodules").setDesc('"Commit-and-sync" and "pull" takes care of submodules. Missing features: Conflicted files, count of pulled/pushed/committed files. Tracking branch needs to be set for each submodule.').addToggle(c=>c.setValue(i.settings.updateSubmodules).onChange(async u=>{i.settings.updateSubmodules=u,await i.saveSettings()})),i.settings.updateSubmodules&&new U.Setting(r).setName("Submodule recurse checkout/switch").setDesc("Whenever a checkout happens on the root repository, recurse the checkout on the submodules (if the branches exist).").addToggle(c=>c.setValue(i.settings.submoduleRecurseCheckout).onChange(async u=>{i.settings.submoduleRecurseCheckout=u,await i.saveSettings()}))),i.gitManager instanceof ke&&new U.Setting(r).setName("Custom Git binary path").setDesc("Specify the path to the Git binary/executable. Git should already be in your PATH. Should only be necessary for a custom Git installation.").addText(c=>{var u;c.setValue((u=i.localStorage.getGitPath())!=null?u:""),c.setPlaceholder("git"),c.onChange(f=>{i.localStorage.setGitPath(f),i.gitManager.updateGitPath(f||"git").catch(d=>i.displayError(d))})}),i.gitManager instanceof ke&&new U.Setting(r).setName("Additional environment variables").setDesc("Use each line for a new environment variable in the format KEY=VALUE .").addTextArea(c=>{c.setPlaceholder("GIT_DIR=/path/to/git/dir"),c.setValue(i.localStorage.getEnvVars().join(` +`)),c.onChange(u=>{i.localStorage.setEnvVars(u.split(` +`))})}),i.gitManager instanceof ke&&new U.Setting(r).setName("Additional PATH environment variable paths").setDesc("Use each line for one path").addTextArea(c=>{c.setValue(i.localStorage.getPATHPaths().join(` +`)),c.onChange(u=>{i.localStorage.setPATHPaths(u.split(` +`))})}),i.gitManager instanceof ke&&new U.Setting(r).setName("Reload with new environment variables").setDesc("Removing previously added environment variables will not take effect until Obsidian is restarted.").addButton(c=>{c.setButtonText("Reload"),c.setCta(),c.onClick(async()=>{await i.gitManager.setGitInstance()})}),new U.Setting(r).setName("Custom base path (Git repository path)").setDesc(` + Sets the relative path to the vault from which the Git binary should be executed. + Mostly used to set the path to the Git repository, which is only required if the Git repository is below the vault root directory. Use "\\" instead of "/" on Windows. + `).addText(c=>{c.setValue(i.settings.basePath),c.setPlaceholder("directory/directory-with-git-repo"),c.onChange(async u=>{i.settings.basePath=u,await i.saveSettings(),i.gitManager.updateBasePath(u||"").catch(f=>i.displayError(f))})}),new U.Setting(r).setName("Custom Git directory path (Instead of '.git')").setDesc('Corresponds to the GIT_DIR environment variable. Relative paths are resolved from the custom base path, or the vault root when no base path is configured. Requires restart of Obsidian to take effect. Use "\\" instead of "/" on Windows.').addText(c=>{c.setValue(i.settings.gitDir),c.setPlaceholder(".git"),c.onChange(async u=>{i.settings.gitDir=u,await i.saveSettings()})}),new U.Setting(r).setName("Disable on this device").setDesc("Disables the plugin on this device. This setting is not synced.").addToggle(c=>c.setValue(i.localStorage.getPluginDisabled()).onChange(u=>{i.localStorage.setPluginDisabled(u),u?i.unloadPlugin():i.init({fromReload:!0}).catch(f=>i.displayError(f)),new U.Notice("Obsidian must be restarted for the changes to take affect.")})),new U.Setting(r).setName("Support").setHeading(),new U.Setting(r).setName("Donate").setDesc("If you like this Plugin, consider donating to support continued development.").addButton(c=>{var f;let u=(f=c.buttonEl.parentElement)==null?void 0:f.createEl("a",{href:"https://ko-fi.com/F1F195IQ5",attr:{target:"_blank"}});u&&(u.createEl("img",{attr:{height:"36",style:"border:0px;height:36px;",src:"https://cdn.ko-fi.com/cdn/kofi3.png?v=3",border:"0",alt:"Buy Me a Coffee at ko-fi.com"}}),c.buttonEl.remove())});let o=r.createDiv();o.setAttr("align","center"),o.setAttr("style","margin: var(--size-4-2)");let l=o.createEl("button");if(l.setText("Copy Debug Information"),l.onclick=async()=>{await window.navigator.clipboard.writeText(JSON.stringify({settings:this.plugin.settings,pluginVersion:this.plugin.manifest.version},null,4)),new U.Notice("Debug information copied to clipboard. May contain sensitive information!")},U.Platform.isDesktopApp){let c=r.createDiv();c.setAttr("align","center"),c.setText(`Debugging and logging: +You can always see the logs of this and every other plugin by opening the console with`);let u=r.createDiv();u.setAttr("align","center"),u.addClass("obsidian-git-shortcuts"),U.Platform.isMacOS===!0?u.createEl("kbd",{text:"CMD (\u2318) + OPTION (\u2325) + I"}):u.createEl("kbd",{text:"CTRL + SHIFT + I"})}}mayDisableSetting(r,i){i&&(r.setDisabled(i),r.setClass("obsidian-git-disabled"))}configureLineAuthorShowStatus(r){this.settings.lineAuthor.show=r,this.plugin.saveSettings(),r?this.plugin.editorIntegration.activateLineAuthoring():this.plugin.editorIntegration.deactiveLineAuthoring()}async lineAuthorSettingHandler(r,i){this.settings.lineAuthor[r]=i,await this.plugin.saveSettings(),this.plugin.editorIntegration.lineAuthoringFeature.refreshLineAuthorViews()}beforeSaveSettings(){let r=this.settings.lineAuthor;r.authorDisplay!=="hide"&&(r.lastShownAuthorDisplay=r.authorDisplay),r.dateTimeFormatOptions!=="hide"&&(r.lastShownDateTimeFormatOptions=r.dateTimeFormatOptions)}addLineAuthorInfoSettings(){let r=new U.Setting(this.containerEl).setName("Show commit authoring information next to each line");if(this.plugin.editorIntegration.lineAuthoringFeature.isAvailableOnCurrentPlatform()||r.setDesc("Only available on desktop currently.").setDisabled(!0),r.descEl.createEl("a",{href:Y5,text:"Feature guide and quick examples",attr:{target:"_blank"}}),r.descEl.createEl("br"),r.descEl.createSpan({text:" The commit hash, author name and authoring date can all be individually toggled."}),r.descEl.createEl("br"),r.descEl.createSpan({text:"Hide everything, to only show the age-colored sidebar."}),r.addToggle(i=>i.setValue(this.settings.lineAuthor.show).onChange(n=>{this.configureLineAuthorShowStatus(n),this.refreshDisplayWithDelay()})),this.settings.lineAuthor.show){let i=new U.Setting(this.containerEl).setName("Follow movement and copies across files and commits").addDropdown(l=>{l.addOptions({inactive:"Do not follow (default)","same-commit":"Follow within same commit","all-commits":"Follow within all commits (maybe slow)"}),l.setValue(this.settings.lineAuthor.followMovement),l.onChange(c=>this.lineAuthorSettingHandler("followMovement",c))});if(i.descEl.createSpan({text:"By default (deactivated), each line only shows the newest commit where it was changed."}),i.descEl.createEl("br"),i.descEl.createSpan({text:"With "}),i.descEl.createEl("i",{text:"same commit"}),i.descEl.createSpan({text:", cut-copy-paste-ing of text is followed within the same commit and the original commit of authoring will be shown."}),i.descEl.createEl("br"),i.descEl.createSpan({text:"With "}),i.descEl.createEl("i",{text:"all commits"}),i.descEl.createSpan({text:", cut-copy-paste-ing text inbetween multiple commits will be detected."}),i.descEl.createEl("br"),i.descEl.createSpan({text:"It uses "}),i.descEl.createEl("a",{href:"https://git-scm.com/docs/git-blame",text:"git-blame",attr:{target:"_blank"}}),i.descEl.createSpan({text:` and for matches (at least ${Hd} characters) within the same (or all) commit(s), `}),i.descEl.createEl("em",{text:"the originating"}),i.descEl.createSpan({text:" commit's information is shown."}),new U.Setting(this.containerEl).setName("Show commit hash").addToggle(l=>{l.setValue(this.settings.lineAuthor.showCommitHash),l.onChange(c=>this.lineAuthorSettingHandler("showCommitHash",c))}),new U.Setting(this.containerEl).setName("Author name display").setDesc("If and how the author is displayed").addDropdown(l=>{let c={hide:"Hide",initials:"Initials (default)","first name":"First name","last name":"Last name",full:"Full name"};l.addOptions(c),l.setValue(this.settings.lineAuthor.authorDisplay),l.onChange(async u=>this.lineAuthorSettingHandler("authorDisplay",u))}),new U.Setting(this.containerEl).setName("Authoring date display").setDesc("If and how the date and time of authoring the line is displayed").addDropdown(l=>{let c={hide:"Hide",date:"Date (default)",datetime:"Date and time","natural language":"Natural language",custom:"Custom"};l.addOptions(c),l.setValue(this.settings.lineAuthor.dateTimeFormatOptions),l.onChange(async u=>{await this.lineAuthorSettingHandler("dateTimeFormatOptions",u),this.refreshDisplayWithDelay()})}),this.settings.lineAuthor.dateTimeFormatOptions==="custom"){let l=new U.Setting(this.containerEl);l.setName("Custom authoring date format").addText(c=>{c.setValue(this.settings.lineAuthor.dateTimeFormatCustomString),c.setPlaceholder("YYYY-MM-DD HH:mm"),c.onChange(async u=>{await this.lineAuthorSettingHandler("dateTimeFormatCustomString",u),this.setCustomDateTimeDescription(l.descEl,u)})}),this.setCustomDateTimeDescription(l.descEl,this.settings.lineAuthor.dateTimeFormatCustomString)}let n=new U.Setting(this.containerEl).setName("Authoring date display timezone").addDropdown(l=>{let c={"viewer-local":"My local (default)","author-local":"Author's local",utc0000:"UTC+0000/Z"};l.addOptions(c),l.setValue(this.settings.lineAuthor.dateTimeTimezone),l.onChange(async u=>this.lineAuthorSettingHandler("dateTimeTimezone",u))});n.descEl.empty(),n.descEl.createSpan({text:`The time-zone in which the authoring date should be shown. +Either your local time-zone (default), +the author's time-zone during commit creation or +`}),n.descEl.createEl("a",{text:"UTC\xB100:00",href:"https://en.wikipedia.org/wiki/UTC%C2%B100:00"}),n.descEl.createSpan({text:"."});let s=new U.Setting(this.containerEl).setName("Oldest age in coloring");this.setOldestAgeDescription(s.descEl,this.settings.lineAuthor.coloringMaxAge),s.addText(l=>{l.setPlaceholder("1y"),l.setValue(this.settings.lineAuthor.coloringMaxAge),l.onChange(async c=>{let f=Lu(c)!==void 0;this.setOldestAgeDescription(s.descEl,c),f&&(await this.lineAuthorSettingHandler("coloringMaxAge",c),this.refreshColorSettingsName("oldest"))})}),this.createColorSetting("newest"),this.createColorSetting("oldest");let a=new U.Setting(this.containerEl).setName("Text color").addText(l=>{l.setValue(this.settings.lineAuthor.textColorCss),l.onChange(async c=>{await this.lineAuthorSettingHandler("textColorCss",c)})});a.descEl.empty(),a.descEl.createSpan({text:"The CSS color of the gutter text."}),a.descEl.createEl("br"),a.descEl.createEl("br"),a.descEl.createSpan({text:"It is highly recommended to use "}),a.descEl.createEl("a",{text:"CSS variables",href:"https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties"}),a.descEl.createSpan({text:" defined by themes (e.g. "}),a.descEl.createEl("pre",{text:"var(--text-muted)",attr:{style:"display:inline"}}),a.descEl.createSpan({text:" or "}),a.descEl.createEl("pre",{text:"var(--text-on-accent)",attr:{style:"display:inline"}}),a.descEl.createSpan({text:"), because they automatically adapt to theme changes."}),a.descEl.createEl("br"),a.descEl.createEl("br"),a.descEl.createSpan({text:"See: "}),a.descEl.createEl("a",{text:"List of available CSS variables in Obsidian",href:"https://github.com/obsidian-community/obsidian-theme-template/blob/main/obsidian.css"});let o=new U.Setting(this.containerEl).setName("Ignore whitespace and newlines in changes").addToggle(l=>{l.setValue(this.settings.lineAuthor.ignoreWhitespace),l.onChange(c=>this.lineAuthorSettingHandler("ignoreWhitespace",c))});o.descEl.empty(),o.descEl.createSpan({text:"Whitespace and newlines are interpreted as part of the document and in changes by default (hence not ignored). This makes the last line being shown as 'changed' when a new subsequent line is added, even if the previously last line's text is the same."}),o.descEl.createEl("br"),o.descEl.createSpan({text:"If you don't care about purely-whitespace changes (e.g. list nesting / quote indentation changes), then activating this will provide more meaningful change detection."})}}createColorSetting(r){let i=new U.Setting(this.containerEl).setName("").addText(n=>{let s=kw(r,this.settings.lineAuthor),a=kw(r,tt.lineAuthor);n.setPlaceholder(bv(a)),n.setValue(bv(s)),n.onChange(async o=>{let l=bk(o);if(l!==void 0){let c=r==="newest"?"colorNew":"colorOld";await this.lineAuthorSettingHandler(c,l)}this.refreshColorSettingsDesc(r,l)})});this.lineAuthorColorSettings.set(r,i),this.refreshColorSettingsName(r),this.refreshColorSettingsDesc(r,kw(r,this.settings.lineAuthor))}refreshColorSettingsName(r){let i=this.lineAuthorColorSettings.get(r);if(i){let n=r==="oldest"?`oldest (${this.settings.lineAuthor.coloringMaxAge} or older)`:"newest";i.nameEl.setText(`Color for ${n} commits`)}}refreshColorSettingsDesc(r,i){let n=this.lineAuthorColorSettings.get(r);n&&this.colorSettingPreviewDesc(n.descEl,r,this.settings.lineAuthor,i!==void 0)}colorSettingPreviewDesc(r,i,n,s){r.empty(),r.createSpan({text:"Supports 'rgb(r,g,b)', 'hsl(h,s,l)', hex (#) and named colors (e.g. 'black', 'purple'). Color preview: "});let a=s?Ah(i,n):"rgba(127,127,127,0.3)",o=U.moment.unix(U.moment.now()/1e3).format("YYYY-MM-DD"),l=s?`abcdef Author Name ${o}`:"invalid color";r.createEl("div",{text:l,attr:{class:"line-author-settings-preview",style:`background-color: ${a}; width: 30ch;`}})}setCustomDateTimeDescription(r,i){r.empty(),r.createEl("a",{text:"Format string",href:i2}),r.createSpan({text:" to display the authoring date."}),r.createEl("br");let n=(0,U.moment)().format(i);r.createSpan({text:`Currently: ${n}`})}setOldestAgeDescription(r,i){let n=Lu(i),s=n!==void 0?`${n.asDays()} days`:"invalid!";r.empty(),r.createSpan({text:`The oldest age in the line author coloring. Everything older will have the same color. +Smallest valid age is "1d". Currently: ${s}`})}setNonDefaultValue({settingsProperty:r,text:i}){let n=this.plugin.settings[r];tt[r]!==n&&(typeof n=="string"||typeof n=="number"||typeof n=="boolean"?i.setValue(String(n)):i.setValue(JSON.stringify(n)))}refreshDisplayWithDelay(r=80){window.setTimeout(()=>this.display(),r)}};function kw(t,e){return t==="oldest"?e.colorOld:e.colorNew}function Lu(t){let e=U.moment.duration("P"+t.toUpperCase());return e.isValid()&&e.asDays()&&e.asDays()>=1?e:void 0}m();var zr=require("obsidian");var Rh=class{constructor(e,r){this.statusBarEl=e;this.plugin=r;this.messages=[];this.currentMessage=null;this.lastMessageTimestamp=null;this.base="obsidian-git-statusbar-";this.statusBarEl.setAttribute("data-tooltip-position","top"),r.registerEvent(r.app.workspace.on("obsidian-git:refreshed",()=>{this.refreshCommitTimestamp().catch(console.error)}))}displayMessage(e,r){this.messages.push({message:`Git: ${e.slice(0,100)}`,timeout:r}),this.display()}displayProgress(e){this.progress=e,this.display()}clearProgress(e=!0){this.progress=void 0,e&&this.display()}display(){this.progress?this.displayState():this.messages.length>0&&!this.currentMessage?(this.currentMessage=this.messages.shift(),this.statusBarEl.addClass(this.base+"message"),this.statusBarEl.ariaLabel="",this.statusBarEl.setText(this.currentMessage.message),this.lastMessageTimestamp=Date.now()):this.currentMessage?Date.now()-this.lastMessageTimestamp>=this.currentMessage.timeout&&(this.currentMessage=null,this.lastMessageTimestamp=null):this.displayState()}displayState(){if((this.statusBarEl.getText().length>3||!this.statusBarEl.hasChildNodes())&&(this.statusBarEl.empty(),this.conflictEl=this.statusBarEl.createDiv(),this.conflictEl.setAttribute("data-tooltip-position","top"),this.conflictEl.style.float="left",this.pausedEl=this.statusBarEl.createDiv(),this.pausedEl.setAttribute("data-tooltip-position","top"),this.pausedEl.style.float="left",this.iconEl=this.statusBarEl.createDiv(),this.iconEl.style.float="left",this.textEl=this.statusBarEl.createDiv(),this.textEl.style.float="right",this.textEl.style.marginLeft="5px"),this.plugin.localStorage.getConflict()?((0,zr.setIcon)(this.conflictEl,"alert-circle"),this.conflictEl.ariaLabel="You have merge conflicts. Resolve them and commit afterwards.",this.conflictEl.style.marginRight="5px",this.conflictEl.addClass(this.base+"conflict")):(this.conflictEl.empty(),this.conflictEl.style.marginRight=""),this.plugin.localStorage.getPausedAutomatics()?((0,zr.setIcon)(this.pausedEl,"pause-circle"),this.pausedEl.ariaLabel="Automatic routines are currently paused.",this.pausedEl.style.marginRight="5px",this.pausedEl.addClass(this.base+"paused")):(this.pausedEl.empty(),this.pausedEl.style.marginRight=""),this.progress){this.statusBarEl.ariaLabel=this.getProgressTooltip("Git operation in progress..."),(0,zr.setIcon)(this.iconEl,this.getProgressIcon()),this.displayProgressText(),this.statusBarEl.addClass(this.base+"progress");return}switch(this.plugin.state.operation){case 0:this.displayFromNow();break;case 2:this.statusBarEl.ariaLabel="Committing changes...",(0,zr.setIcon)(this.iconEl,"git-commit"),this.textEl.empty(),this.statusBarEl.addClass(this.base+"commit");break;case 3:this.statusBarEl.ariaLabel=this.getProgressTooltip("Pushing changes..."),(0,zr.setIcon)(this.iconEl,"upload"),this.displayProgressText(),this.statusBarEl.addClass(this.base+"push");break;case 1:this.statusBarEl.ariaLabel=this.getProgressTooltip("Pulling changes..."),(0,zr.setIcon)(this.iconEl,"download"),this.displayProgressText(),this.statusBarEl.addClass(this.base+"pull");break;case 4:this.statusBarEl.ariaLabel=this.getProgressTooltip("Fetching from remote..."),(0,zr.setIcon)(this.iconEl,"download"),this.displayProgressText(),this.statusBarEl.addClass(this.base+"fetch");break;case 5:this.statusBarEl.ariaLabel=this.getProgressTooltip("Checking out branch..."),(0,zr.setIcon)(this.iconEl,"git-branch"),this.displayProgressText(),this.statusBarEl.addClass(this.base+"checkout");break;default:this.statusBarEl.ariaLabel="Failed on initialization!",(0,zr.setIcon)(this.iconEl,"alert-triangle"),this.textEl.empty(),this.statusBarEl.addClass(this.base+"failed-init");break}}displayProgressText(){this.progress?this.textEl.setText(this.getCompactProgressText()):this.textEl.empty()}getProgressTooltip(e){if(!this.progress)return e;let r=this.progress.stage?`${this.progress.stage}: `:"";if(this.progress.progress===void 0)return this.progress.stage?`${this.progress.action}: ${this.progress.stage}...`:`${this.progress.action}...`;let i=this.progress.processed!==void 0&&this.progress.total!==void 0?` (${this.progress.processed}/${this.progress.total})`:"";return`${this.progress.action}: ${r}${Math.round(this.progress.progress)}%${i}`}getCompactProgressText(){return this.progress?this.progress.progress===void 0?`${this.progress.action}...`:`${this.progress.action} ${Math.round(this.progress.progress)}%`:""}getProgressIcon(){var e;switch((e=this.progress)==null?void 0:e.action){case"Fetching":case"Pulling":return"download";case"Pushing":return"upload";case"Checking out":return"git-branch";default:return"git-pull-request"}}displayFromNow(){var i;let e=this.lastCommitTimestamp,r=this.plugin.state.offlineMode;if(e){let n=(0,zr.moment)(e).fromNow();this.statusBarEl.ariaLabel=`${r?"Offline: ":""}Last Commit: ${n}`,((i=this.unPushedCommits)!=null?i:0)>0&&(this.statusBarEl.ariaLabel+=` +(${this.unPushedCommits} unpushed commits)`)}else this.statusBarEl.ariaLabel=r?"Git is offline":"Git is ready";r?(0,zr.setIcon)(this.iconEl,"globe"):(0,zr.setIcon)(this.iconEl,"check"),this.plugin.settings.changedFilesInStatusBar&&this.plugin.cachedStatus?this.textEl.setText(this.plugin.cachedStatus.changed.length.toString()):this.textEl.empty(),this.statusBarEl.addClass(this.base+"idle")}async refreshCommitTimestamp(){this.lastCommitTimestamp=await this.plugin.gitManager.getLastCommitTime(),this.unPushedCommits=await this.plugin.gitManager.getUnpushedCommits()}remove(){this.statusBarEl.remove()}};m();var Fh=require("obsidian"),$h=class extends Fh.SuggestModal{constructor(r){super(r.app);this.plugin=r;this.resolve=null;this.setPlaceholder("Type your message and select optional the version with the added date.")}openAndGetResult(){return new Promise(r=>{this.resolve=r,this.open()})}onClose(){new Promise(r=>window.setTimeout(r,10)).then(()=>{this.resolve&&this.resolve(void 0)})}getSuggestions(r){let i=(0,Fh.moment)().format(this.plugin.settings.commitDateFormat);return r==""&&(r="..."),[r,`${i}: ${r}`,`${r}: ${i}`]}renderSuggestion(r,i){i.innerText=r}onChooseSuggestion(r,i){this.resolve&&this.resolve(r)}};m();var n2=require("obsidian"),Nu=class{constructor(e){this.plugin=e}saveLastAuto(e,r){r==="backup"?this.plugin.localStorage.setLastAutoBackup(e.toString()):r==="pull"?this.plugin.localStorage.setLastAutoPull(e.toString()):r==="push"&&this.plugin.localStorage.setLastAutoPush(e.toString())}loadLastAuto(){var e,r,i;return{backup:new Date((e=this.plugin.localStorage.getLastAutoBackup())!=null?e:""),pull:new Date((r=this.plugin.localStorage.getLastAutoPull())!=null?r:""),push:new Date((i=this.plugin.localStorage.getLastAutoPush())!=null?i:"")}}async init(){await this.setUpAutoCommitAndSync();let e=this.loadLastAuto();if(this.plugin.settings.differentIntervalCommitAndPush&&this.plugin.settings.autoPushInterval>0){let r=this.diff(this.plugin.settings.autoPushInterval,e.push);this.startAutoPush(r)}if(this.plugin.settings.autoPullInterval>0){let r=this.diff(this.plugin.settings.autoPullInterval,e.pull);this.startAutoPull(r)}}unload(){this.clearAutoPull(),this.clearAutoPush(),this.clearAutoCommitAndSync()}reload(...e){this.plugin.localStorage.getPausedAutomatics()||(e.contains("commit")&&(this.clearAutoCommitAndSync(),this.plugin.settings.autoSaveInterval>0&&this.startAutoCommitAndSync(this.plugin.settings.autoSaveInterval)),e.contains("push")&&(this.clearAutoPush(),this.plugin.settings.differentIntervalCommitAndPush&&this.plugin.settings.autoPushInterval>0&&this.startAutoPush(this.plugin.settings.autoPushInterval)),e.contains("pull")&&(this.clearAutoPull(),this.plugin.settings.autoPullInterval>0&&this.startAutoPull(this.plugin.settings.autoPullInterval)))}async setUpAutoCommitAndSync(){if(this.plugin.settings.setLastSaveToLastCommit){this.clearAutoCommitAndSync();let e=await this.plugin.gitManager.getLastCommitTime();e&&this.saveLastAuto(e,"backup")}if(!this.timeoutIDCommitAndSync&&!this.plugin.autoCommitDebouncer){let e=this.loadLastAuto();if(this.plugin.settings.autoSaveInterval>0){let r=this.diff(this.plugin.settings.autoSaveInterval,e.backup);this.startAutoCommitAndSync(r)}}}get isAutomaticsDisabled(){return!this.plugin.gitReady||this.plugin.localStorage.getPausedAutomatics()}startAutoCommitAndSync(e){if(this.isAutomaticsDisabled)return;let r=(e!=null?e:this.plugin.settings.autoSaveInterval)*6e4;this.plugin.settings.autoBackupAfterFileChange?e===0?this.doAutoCommitAndSync():this.plugin.autoCommitDebouncer=(0,n2.debounce)(()=>this.doAutoCommitAndSync(),r,!0):(r>2147483647&&(r=2147483647),this.timeoutIDCommitAndSync=window.setTimeout(()=>this.doAutoCommitAndSync(),r))}doAutoCommitAndSync(){this.plugin.promiseQueue.addTask(async()=>{if(this.plugin.settings.setLastSaveToLastCommit){let r=await this.plugin.gitManager.getLastCommitTime();if(r){this.saveLastAuto(r,"backup");let i=this.diff(this.plugin.settings.autoSaveInterval,r);if(i>0)return this.startAutoCommitAndSync(i),!1}}let e=this.plugin.settings.autoCommitOnlyStaged?"staged":"all";return this.plugin.settings.differentIntervalCommitAndPush?await this.plugin.commit({fromAuto:!0,mode:e}):await this.plugin.commitAndSync({fromAutoBackup:!0,mode:e}),!0},e=>{e!==!1&&(this.saveLastAuto(new Date,"backup"),this.startAutoCommitAndSync())})}startAutoPull(e){if(this.isAutomaticsDisabled)return;let r=(e!=null?e:this.plugin.settings.autoPullInterval)*6e4;r>2147483647&&(r=2147483647),this.timeoutIDPull=window.setTimeout(()=>this.doAutoPull(),r)}doAutoPull(){this.plugin.promiseQueue.addTask(()=>this.plugin.pullChangesFromRemote(),()=>{this.saveLastAuto(new Date,"pull"),this.startAutoPull()})}startAutoPush(e){if(this.isAutomaticsDisabled)return;let r=(e!=null?e:this.plugin.settings.autoPushInterval)*6e4;r>2147483647&&(r=2147483647),this.timeoutIDPush=window.setTimeout(()=>this.doAutoPush(),r)}doAutoPush(){this.plugin.promiseQueue.addTask(()=>this.plugin.push(),()=>{this.saveLastAuto(new Date,"push"),this.startAutoPush()})}clearAutoCommitAndSync(){var r;let e=!1;return this.timeoutIDCommitAndSync&&(window.clearTimeout(this.timeoutIDCommitAndSync),this.timeoutIDCommitAndSync=void 0,e=!0),this.plugin.autoCommitDebouncer&&((r=this.plugin.autoCommitDebouncer)==null||r.cancel(),this.plugin.autoCommitDebouncer=void 0,e=!0),e}clearAutoPull(){return this.timeoutIDPull?(window.clearTimeout(this.timeoutIDPull),this.timeoutIDPull=void 0,!0):!1}clearAutoPush(){return this.timeoutIDPush?(window.clearTimeout(this.timeoutIDPush),this.timeoutIDPush=void 0,!0):!1}diff(e,r){if(isNaN(r.getTime()))return e;let n=e-Math.round((new Date().getTime()-r.getTime())/1e3/60);return Math.max(0,n)}};m();var Xi=require("obsidian");m();var Bu=require("obsidian");async function s2(t,e,r){let i=await o2(e,r);if(i.result==="failure"){new Bu.Notice(i.reason);return}let{isGitHub:n,branch:s,repo:a,user:o,filePath:l}=i;if(n){let c=t.getCursor("from").line+1,u=t.getCursor("to").line+1;c===u?window.open(`https://github.com/${o}/${a}/blob/${s}/${l}?plain=1#L${c}`):window.open(`https://github.com/${o}/${a}/blob/${s}/${l}?plain=1#L${c}-L${u}`)}else new Bu.Notice("It seems like you are not using GitHub")}async function a2(t,e){let r=await o2(t,e);if(r.result==="failure"){new Bu.Notice(r.reason);return}let{isGitHub:i,branch:n,repo:s,user:a,filePath:o}=r;i?window.open(`https://github.com/${a}/${s}/commits/${n}/${o}`):new Bu.Notice("It seems like you are not using GitHub")}async function o2(t,e){var l,c;let r=await e.branchInfo(),i=r.tracking,n=r.current,s,a=e.getRelativeRepoPath(t.path);if(e instanceof ke){let u=await e.getSubmoduleOfFile(e.getRelativeRepoPath(t.path));if(u){a=u.relativeFilepath;let f=await e.git.cwd({path:u.submodule,root:!1}).status();if(i=f.tracking||void 0,n=f.current||void 0,i){let d=i.substring(0,i.indexOf("/")),h=await e.git.cwd({path:u.submodule,root:!1}).getConfig(`remote.${d}.url`,"local");if(h.value!=null)s=h.value;else return{result:"failure",reason:"Failed to get remote url of submodule"}}}}if(i==null)return{result:"failure",reason:"Remote branch is not configured"};if(n==null)return{result:"failure",reason:"Failed to get current branch name"};if(s==null){let u=i.substring(0,i.indexOf("/"));if(s=await e.getConfig(`remote.${u}.url`),s==null)return{result:"failure",reason:"Failed to get remote url"}}let o=s.match(/(?:^https:\/\/github\.com\/(.+)\/(.+?)(?:\.git)?$)|(?:^[a-zA-Z]+@github\.com:(.+)\/(.+?)(?:\.git)?$)/);if(o==null)return{result:"failure",reason:"Could not parse remote url"};{let[u,f,d,h,p]=o;return{result:"success",isGitHub:!!u,repo:(l=d!=null?d:p)!=null?l:"",user:(c=f!=null?f:h)!=null?c:"",branch:n,filePath:a}}}m();var l2=require("obsidian"),Ih=class extends l2.FuzzySuggestModal{constructor(e,r){super(e.app),this.plugin=e,this.changedFiles=r,this.setPlaceholder("Not supported files will be opened by default app!")}getItems(){return this.changedFiles}getItemText(e){if(e.index=="U"&&e.workingDir=="U")return`Untracked | ${e.vaultPath}`;let r="",i="";return e.workingDir!=" "&&(r=`Working Dir: ${e.workingDir} `),e.index!=" "&&(i=`Index: ${e.index}`),`${r}${i} | ${e.vaultPath}`}onChooseItem(e,r){this.plugin.app.metadataCache.getFirstLinkpathDest(e.vaultPath,"")==null?this.app.openWithDefaultApp(e.vaultPath):this.plugin.app.workspace.openLinkText(e.vaultPath,"/")}};m();var c2=require("obsidian"),Mh=class extends c2.Modal{constructor(r,i){super(r);this.content=i;this.resolve=null}openAndGetReslt(){return new Promise(r=>{this.resolve=r,this.open()})}onOpen(){let{contentEl:r,titleEl:i}=this;i.setText("Edit .gitignore");let n=r.createDiv(),s=n.createEl("textarea",{text:this.content,cls:["obsidian-git-textarea"],attr:{rows:10,cols:30,wrap:"off"}});n.createEl("button",{cls:["mod-cta","obsidian-git-center-button"],text:"Save"}).addEventListener("click",()=>{this.resolve(s.value),this.close()})}onClose(){let{contentEl:r}=this;r.empty(),this.resolve&&this.resolve(void 0)}};m();var Ku=require("@codemirror/state"),ep=require("@codemirror/view");m();var Il=require("@codemirror/state");m();var qt=class t{static createHunk(e,r,i,n){return{removed:{start:e,count:r,lines:[]},added:{start:i,count:n,lines:[]},vend:i+Math.max(n-1,0),type:n===0?"delete":r===0?"add":"change"}}static getHunkHeader(e){return`@@ -${e.removed.start}${e.removed.count>0?`,${e.removed.count}`:""} +${e.added.start}${e.added.count>0?`,${e.added.count}`:""} @@`}static createPartialHunk(e,r,i){let n=r,s=i-r+1,a=0;for(let o of e){let l=o.added.count-o.removed.count,c=0;if(o.added.start>=r&&o.vend<=i)c=l;else{let u=Math.max(0,i+1-(o.added.start+o.removed.count)),f=Math.max(0,r-(o.added.start+o.removed.count));o.added.start>=r&&o.added.start<=i?c=u:o.vend>=r&&o.vend<=i?(c=l-f,n=n-f):o.added.start<=r&&o.vend>=i?(c=u-f,n=n-f):a++,r>o.vend&&(n=n-l)}s=s-c}if(a!==e.length)return s===0&&(n=n-1),this.createHunk(n,s,r,i-r+1)}static patchLines(e,r=!1){let i=[];for(let n of e.removed.lines)i.push("-"+n);for(let n of e.added.lines)i.push("+"+n);return r?i.map(n=>n.replace(/\r$/,"")):i}static parseDiffLine(e){var l,c,u;let i=(l=e.split("@@")[1])==null?void 0:l.trim();if(!i)throw Error(`Invalid diff line: ${e}`);let n=i.split(" "),s=(c=n[0])==null?void 0:c.substring(1).split(","),a=(u=n[1])==null?void 0:u.substring(1).split(",");if(!s||!a||s[0]===void 0||a[0]===void 0)throw Error(`Invalid diff hunk range: ${e}`);return this.createHunk(parseInt(s[0]),parseInt(s[1]||"1"),parseInt(a[0]),parseInt(a[1]||"1"))}static changeEnd(e){return e.added.count===0?e.added.start:e.removed.count===0?e.added.start+e.added.count-1:e.added.start+Math.min(e.added.count,e.removed.count)-1}static calcSigns(e,r,i,n=1,s=1/0,a){if(a&&r.type!=="add")return console.error(`Invalid hunk with untracked=${a} hunk="${t.getHunkHeader(r)}"`),[];n=Math.max(1,n);let{start:o,added:l,removed:c}={start:r.added.start,added:r.added.count,removed:r.removed.count},u=this.changeEnd(r),f=r.type==="delete"&&(o===0||e&&this.changeEnd(e)===o)&&(!i||i.added.start!==o+1);f&&n===1&&(n=0);let d=[];for(let h=Math.max(o,n);h<=Math.min(u,s);h++){let p=r.type==="change"&&(c>l&&h===u||e&&e.added.start===0);d.push({type:f?"topdelete":p?"changedelete":a?"untracked":r.type,count:h===o?r.type==="add"?l:c:void 0,lnum:h+(f?1:0)})}if(r.type==="change"&&l>c&&r.vend>=n&&u<=s)for(let h=Math.max(u,n);h<=Math.min(r.vend,s);h++)d.push({type:"add",count:h===r.vend?l-c:void 0,lnum:h});return d}static createPatch(e,r,i,n=!1){let s=[`diff --git a/${e} b/${e}`,`index 000000..000000 ${i}`,`--- a/${e}`,`+++ b/${e}`],a=0;r=structuredClone(r);for(let o of r){let l=o.removed.start,c=o.removed.count,u=o.added.count;o.type==="add"&&(l=l+1);let f=o.removed.lines,d=o.added.lines;n&&([c,u]=[u,c],[f,d]=[d,f]),s.push(`@@ -${l},${c} +${l+a},${u} @@`);for(let h of f)s.push("-"+h);(n?o.added:o.removed).no_nl_at_eof&&s.push("\\ No newline at end of file");for(let h of d)s.push("+"+h);(n?o.removed:o.added).no_nl_at_eof&&s.push("\\ No newline at end of file"),o.removed.start=l+a,a=a+(u-c)}return s}static getSummary(e){let r={added:0,changed:0,removed:0};for(let i of e)if(i.type==="add")r.added+=i.added.count;else if(i.type==="delete")r.removed+=i.removed.count;else if(i.type==="change"){let n=i.added.count,s=i.removed.count,a=Math.min(n,s);r.changed+=a,r.added+=n-a,r.removed+=s-a}return r}static findHunk(e,r){if(!r)return[void 0,void 0];for(let i=0;i=e)return[n,i]}return[void 0,void 0]}static findNearestHunk(e,r,i,n){if(r.length!==0){if(i==="first")return 0;if(i==="last")return r.length-1;if(i==="next"){if(r[0].added.start>e)return 0;for(let s=r.length-1;s>=0;s--)if(r[s].added.start<=e){if(s+1e)return s+1;if(n)return 0}}else if(i==="prev"){if(Math.max(r[r.length-1].vend)0&&Math.max(r[s-1].vend,1)l.added.start?n++:o.added.starta.map(v=>g.replace(/&/,v))).reduce((g,v)=>g.concat(v)),p,l);else if(p&&typeof p=="object"){if(!f)throw new RangeError("The value of a property ("+h+") should be a primitive value.");s(n(h),p,u,d)}else p!=null&&u.push(h.replace(/_.*/,"").replace(/[A-Z]/g,g=>"-"+g.toLowerCase())+": "+p+";")}(u.length||d)&&l.push((i&&!f&&!c?a.map(i):a).join(", ")+" {"+u.join(" ")+"}")}for(let a in e)s(n(a),e[a],this.rules)}getRules(){return this.rules.join(` +`)}static newName(){let e=f2[u2]||1;return f2[u2]=e+1,"\u037C"+e.toString(36)}static mount(e,r,i){let n=e[Cw],s=i&&i.nonce;n?s&&n.setNonce(s):n=new Aw(e,s),n.mount(Array.isArray(r)?r:[r],e)}},d2=new Map,Aw=class{constructor(e,r){let i=e.ownerDocument||e,n=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&n.CSSStyleSheet){let s=d2.get(i);if(s)return e[Cw]=s;this.sheet=new n.CSSStyleSheet,d2.set(i,this)}else this.styleTag=i.createElement("style"),r&&this.styleTag.setAttribute("nonce",r);this.modules=[],e[Cw]=this}mount(e,r){let i=this.sheet,n=0,s=0;for(let a=0;a-1&&(this.modules.splice(l,1),s--,l=-1),l==-1){if(this.modules.splice(s++,0,o),i)for(let c=0;cc){let f=t.slice(e,r).indexOf(i.slice(n,s));if(f>-1)return[new Rt(e,e+f,n,n),new Rt(e+f+c,r,s,s)]}else if(c>l){let f=i.slice(n,s).indexOf(t.slice(e,r));if(f>-1)return[new Rt(e,e,n,n+f),new Rt(r,r,n+f+l,s)]}if(l==1||c==1)return[new Rt(e,r,n,s)];let u=F2(t,e,r,i,n,s);if(u){let[f,d,h]=u;return Ha(t,e,f,i,n,d).concat(Ha(t,f+h,r,i,d+h,s))}return K5(t,e,r,i,n,s)}var Hu=1e9,Uu=0,Mw=!1;function K5(t,e,r,i,n,s){let a=r-e,o=s-n;if(Hu<1e9&&Math.min(a,o)>Hu*16||Uu>0&&Date.now()>Uu)return Math.min(a,o)>Hu*64?[new Rt(e,r,n,s)]:h2(t,e,r,i,n,s);let l=Math.ceil((a+o)/2);Tw.reset(l),Pw.reset(l);let c=(h,p)=>t.charCodeAt(e+h)==i.charCodeAt(n+p),u=(h,p)=>t.charCodeAt(r-h-1)==i.charCodeAt(s-p-1),f=(a-o)%2!=0?Pw:null,d=f?null:Tw;for(let h=0;hHu||Uu>0&&!(h&63)&&Date.now()>Uu)return h2(t,e,r,i,n,s);let p=Tw.advance(h,a,o,l,f,!1,c)||Pw.advance(h,a,o,l,d,!0,u);if(p)return X5(t,e,r,e+p[0],i,n,s,n+p[1])}return[new Rt(e,r,n,s)]}var Hh=class{constructor(){this.vec=[]}reset(e){this.len=e<<1;for(let r=0;rr)this.end+=2;else if(f>i)this.start+=2;else if(s){let d=n+(r-i)-l;if(d>=0&&d=r-u)return[h,n+h-d]}else{let h=r-s.vec[d];if(u>=h)return[u,f]}}}return null}},Tw=new Hh,Pw=new Hh;function X5(t,e,r,i,n,s,a,o){let l=!1;return!Fl(t,i)&&++i==r&&(l=!0),!Fl(n,o)&&++o==a&&(l=!0),l?[new Rt(e,r,s,a)]:Ha(t,e,i,n,s,o).concat(Ha(t,i,r,n,o,a))}function $2(t,e){let r=1,i=Math.min(t,e);for(;rr||u>s||t.slice(o,c)!=i.slice(l,u)){if(a==1)return o-e-(Fl(t,o)?0:1);a=a>>1}else{if(c==r||u==s)return c-e;o=c,l=u}}}function Ow(t,e,r,i,n,s){if(e==r||n==s||t.charCodeAt(r-1)!=i.charCodeAt(s-1))return 0;let a=$2(r-e,s-n);for(let o=r,l=s;;){let c=o-a,u=l-a;if(c>1}else{if(c==e||u==n)return r-c;o=c,l=u}}}function Rw(t,e,r,i,n,s,a,o){let l=i.slice(n,s),c=null;for(;;){if(c||a=r)break;let d=t.slice(u,f),h=-1;for(;(h=l.indexOf(d,h+1))!=-1;){let p=Dw(t,f,r,i,n+h+d.length,s),g=Ow(t,e,u,i,n,n+h),v=d.length+p+g;(!c||c[2]>1}}function F2(t,e,r,i,n,s){let a=r-e,o=s-n;if(an.fromA-e&&i.toB>n.fromB-e&&(t[r-1]=new Rt(i.fromA,n.toA,i.fromB,n.toB),t.splice(r--,1))}}function Q5(t,e,r){for(;;){I2(r,1);let i=!1;for(let n=0;n3||o>3){let l=n==t.length-1?e.length:t[n+1].fromA,c=s.fromA-i,u=l-s.toA,f=m2(e,s.fromA,c),d=p2(e,s.toA,u),h=s.fromA-f,p=d-s.toA;if((!a||!o)&&h&&p){let g=Math.max(a,o),[v,b,_]=a?[e,s.fromA,s.toA]:[r,s.fromB,s.toB];g>h&&e.slice(f,s.fromA)==v.slice(_-h,_)?(s=t[n]=new Rt(f,f+a,s.fromB-h,s.toB-h),f=s.fromA,d=p2(e,s.toA,l-s.toA)):g>p&&e.slice(s.toA,d)==v.slice(b,b+p)&&(s=t[n]=new Rt(d-a,d,s.fromB+p,s.toB+p),d=s.toA,f=m2(e,s.fromA,s.fromA-i)),h=s.fromA-f,p=d-s.toA}if(h||p)s=t[n]=new Rt(s.fromA-h,s.toA+p,s.fromB-h,s.toB+p);else if(a){if(!o){let g=v2(e,s.fromA,s.toA),v,b=g<0?-1:g2(e,s.toA,s.fromA);g>-1&&(v=g-s.fromA)<=u&&e.slice(s.fromA,g)==e.slice(s.toA,s.toA+v)?s=t[n]=s.offset(v):b>-1&&(v=s.toA-b)<=c&&e.slice(s.fromA-v,s.fromA)==e.slice(b,s.toA)&&(s=t[n]=s.offset(-v))}}else{let g=v2(r,s.fromB,s.toB),v,b=g<0?-1:g2(r,s.toB,s.fromB);g>-1&&(v=g-s.fromB)<=u&&r.slice(s.fromB,g)==r.slice(s.toB,s.toB+v)?s=t[n]=s.offset(v):b>-1&&(v=s.toB-b)<=c&&r.slice(s.fromB-v,s.fromB)==r.slice(b,s.toB)&&(s=t[n]=s.offset(-v))}}i=s.toA}return I2(t,3),t}var Ba;try{Ba=new RegExp("[\\p{Alphabetic}\\p{Number}]","u")}catch(t){}function M2(t){return t>48&&t<58||t>64&&t<91||t>96&&t<123}function D2(t,e){if(e==t.length)return 0;let r=t.charCodeAt(e);return r<192?M2(r)?1:0:Ba?!N2(r)||e==t.length-1?Ba.test(String.fromCharCode(r))?1:0:Ba.test(t.slice(e,e+2))?2:0:0}function O2(t,e){if(!e)return 0;let r=t.charCodeAt(e-1);return r<192?M2(r)?1:0:Ba?!B2(r)||e==1?Ba.test(String.fromCharCode(r))?1:0:Ba.test(t.slice(e-2,e))?2:0:0}var L2=8;function p2(t,e,r){if(e==t.length||!O2(t,e))return e;for(let i=e,n=e+r,s=0;sn)return i;i+=a}return e}function m2(t,e,r){if(!e||!D2(t,e))return e;for(let i=e,n=e-r,s=0;st>=55296&&t<=56319,B2=t=>t>=56320&&t<=57343;function Fl(t,e){return!e||e==t.length||!N2(t.charCodeAt(e-1))||!B2(t.charCodeAt(e))}function e4(t,e,r){var i;let n=r==null?void 0:r.override;return n?n(t,e):(Hu=((i=r==null?void 0:r.scanLimit)!==null&&i!==void 0?i:1e9)>>1,Uu=r!=null&&r.timeout?Date.now()+r.timeout:0,Mw=!1,Q5(t,e,Ha(t,0,t.length,e,0,e.length)))}function H2(){return!Mw}function U2(t,e,r){return J5(e4(t,e,r),t,e)}var Pi=Fe.Facet.define({combine:t=>t[0]}),$w=Fe.StateEffect.define(),t4=Fe.Facet.define(),Tn=Fe.StateField.define({create(t){return null},update(t,e){for(let r of e.effects)r.is($w)&&(t=r.value);for(let r of e.state.facet(t4))t=r(t,e);return t}});function Lw(t){let e=t.field(Tn,!1);if(!e)return null;let r=t.facet(Pi);return{chunks:e,side:r?r.side:null}}var is=class t{constructor(e,r,i,n,s,a=!0){this.changes=e,this.fromA=r,this.toA=i,this.fromB=n,this.toB=s,this.precise=a}offset(e,r){return e||r?new t(this.changes,this.fromA+e,this.toA+e,this.fromB+r,this.toB+r,this.precise):this}get endA(){return Math.max(this.fromA,this.toA-1)}get endB(){return Math.max(this.fromB,this.toB-1)}static build(e,r,i){let n=U2(e.toString(),r.toString(),i);return G2(n,e,r,0,0,H2())}static updateA(e,r,i,n,s){return x2(y2(e,n,!0,i.length),e,r,i,s)}static updateB(e,r,i,n,s){return x2(y2(e,n,!1,r.length),e,r,i,s)}};function w2(t,e,r,i){let n=r.lineAt(t),s=i.lineAt(e);return n.to==t&&s.to==e&&tf+1&&v>d+1)break;h.push(p.offset(-c+i,-u+n)),[f,d]=b2(p.toA+i,p.toB+n,e,r),o++}a.push(new is(h,c,Math.max(c,f),u,Math.max(u,d),s))}return a}var Oh=1e3;function _2(t,e,r,i){let n=0,s=t.length;for(;;){if(n==s){let u=0,f=0;n&&({toA:u,toB:f}=t[n-1]);let d=e-(r?u:f);return[u+d,f+d]}let a=n+s>>1,o=t[a],[l,c]=r?[o.fromA,o.toA]:[o.fromB,o.toB];if(l>e)s=a;else if(c<=e)n=a+1;else return i?[o.fromA,o.fromB]:[o.toA,o.toB]}}function y2(t,e,r,i){let n=[];return e.iterChangedRanges((s,a,o,l)=>{let c=0,u=r?e.length:i,f=0,d=r?i:e.length;s>Oh&&([c,f]=_2(t,s-Oh,r,!0)),a=c?n[n.length-1]={fromA:p.fromA,fromB:p.fromB,toA:u,toB:d,diffA:p.diffA+g,diffB:p.diffB+v}:n.push({fromA:c,toA:u,fromB:f,toB:d,diffA:g,diffB:v})}),n}function x2(t,e,r,i,n){if(!t.length)return e;let s=[];for(let a=0,o=0,l=0,c=0;;a++){let u=a==t.length?null:t[a],f=u?u.fromA+o:r.length,d=u?u.fromB+l:i.length;for(;cf||v.toB+l>d))break;s.push(v.offset(o,l)),c++}if(!u)break;let h=u.toA+o+u.diffA,p=u.toB+l+u.diffB,g=U2(r.sliceString(f,h),i.sliceString(d,p),n);for(let v of G2(g,r,i,f,d,H2()))s.push(v);for(o+=u.diffA,l+=u.diffB;ch&&v.fromB+l>p)break;c++}}return s}var r4={scanLimit:500},j2=Oe.ViewPlugin.fromClass(class{constructor(t){({deco:this.deco,gutter:this.gutter}=k2(t))}update(t){(t.docChanged||t.viewportChanged||i4(t.startState,t.state)||n4(t.startState,t.state))&&({deco:this.deco,gutter:this.gutter}=k2(t.view))}},{decorations:t=>t.deco}),Lh=Fe.Prec.low((0,Oe.gutter)({class:"cm-changeGutter",markers:t=>{var e;return((e=t.plugin(j2))===null||e===void 0?void 0:e.gutter)||Fe.RangeSet.empty}}));function i4(t,e){return t.field(Tn,!1)!=e.field(Tn,!1)}function n4(t,e){return t.facet(Pi)!=e.facet(Pi)}var E2=Oe.Decoration.line({class:"cm-changedLine"}),s4=Oe.Decoration.mark({class:"cm-changedText"}),a4=Oe.Decoration.mark({tagName:"ins",class:"cm-insertedLine"}),o4=Oe.Decoration.mark({tagName:"del",class:"cm-deletedLine"}),S2=new class extends Oe.GutterMarker{constructor(){super(...arguments),this.elementClass="cm-changedLineGutter"}};function l4(t,e,r,i,n,s){let a=r?t.fromA:t.fromB,o=r?t.toA:t.toB,l=0;if(a!=o){n.add(a,a,E2),n.add(a,o,r?o4:a4),s&&s.add(a,a,S2);for(let c=e.iterRange(a,o-1),u=a;!c.next().done;){if(c.lineBreak){u++,n.add(u,u,E2),s&&s.add(u,u,S2);continue}let f=u+c.value.length;if(i)for(;l=u)break;(a?f.toA:f.toB)>c&&(!s||!s(t.state,f,o,l))&&l4(f,t.state.doc,a,i,o,l)}return{deco:o.finish(),gutter:l&&l.finish()}}var $l=class extends Oe.WidgetType{constructor(e){super(),this.height=e}eq(e){return this.height==e.height}toDOM(){let e=document.createElement("div");return e.className="cm-mergeSpacer",e.style.height=this.height+"px",e}updateDOM(e){return e.style.height=this.height+"px",!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}},Uh=Fe.StateEffect.define({map:(t,e)=>t.map(e)}),Gu=Fe.StateField.define({create:()=>Oe.Decoration.none,update:(t,e)=>{for(let r of e.effects)if(r.is(Uh))return r.value;return t.map(e.changes)},provide:t=>Oe.EditorView.decorations.from(t)}),Nh=.01;function C2(t,e){if(t.size!=e.size)return!1;let r=t.iter(),i=e.iter();for(;r.value;){if(r.from!=i.from||Math.abs(r.value.spec.widget.height-i.value.spec.widget.height)>1)return!1;r.next(),i.next()}return!0}function c4(t,e,r){let i=new Fe.RangeSetBuilder,n=new Fe.RangeSetBuilder,s=t.state.field(Gu).iter(),a=e.state.field(Gu).iter(),o=0,l=0,c=0,u=0,f=t.viewport,d=e.viewport;for(let v=0;;v++){let b=vNh&&(u+=A,n.add(l,l,Oe.Decoration.widget({widget:new $l(A),block:!0,side:-1})))}if(_>o+1e3&&of.from&&ld.from){let x=Math.min(f.from-o,d.from-l);o+=x,l+=x,v--}else if(b)o=b.toA,l=b.toB;else break;for(;s.value&&s.fromNh&&n.add(e.state.doc.length,e.state.doc.length,Oe.Decoration.widget({widget:new $l(h),block:!0,side:1}));let p=i.finish(),g=n.finish();C2(p,t.state.field(Gu))||t.dispatch({effects:Uh.of(p)}),C2(g,e.state.field(Gu))||e.dispatch({effects:Uh.of(g)})}var Fw=Fe.StateEffect.define({map:(t,e)=>e.mapPos(t)});var Iw=class extends Oe.WidgetType{constructor(e){super(),this.lines=e}eq(e){return this.lines==e.lines}toDOM(e){let r=document.createElement("div");return r.className="cm-collapsedLines",r.textContent=e.state.phrase("$ unchanged lines",this.lines),r.addEventListener("click",i=>{let n=e.posAtDOM(i.target);e.dispatch({effects:Fw.of(n)});let{side:s,sibling:a}=e.state.facet(Pi);a&&a().dispatch({effects:Fw.of(u4(n,e.state.field(Tn),s=="a"))})}),r}ignoreEvent(e){return e instanceof MouseEvent}get estimatedHeight(){return 27}get type(){return"collapsed-unchanged-code"}};function u4(t,e,r){let i=0,n=0;for(let s=0;;s++){let a=s=t)return n+(t-i);[i,n]=r?[a.toA,a.toB]:[a.toB,a.toA]}}var f4=Fe.StateField.define({create(t){return Oe.Decoration.none},update(t,e){t=t.map(e.changes);for(let r of e.effects)r.is(Fw)&&(t=t.update({filter:i=>i!=r.value}));if(t.size&&e.state.field(Tn)!=e.startState.field(Tn,!1)){let r=e.state.facet(Pi).side=="a",i=[];for(let n of e.state.field(Tn))t.between(r?n.fromA:n.fromB,r?n.toA:n.toB,s=>{i.push(s)});i.length&&(t=t.update({filter:n=>i.indexOf(n)<0}))}return t},provide:t=>Oe.EditorView.decorations.from(t)});function A2({margin:t=3,minSize:e=4}){return f4.init(r=>d4(r,t,e))}function d4(t,e,r){let i=new Fe.RangeSetBuilder,n=t.facet(Pi).side=="a",s=t.field(Tn),a=1;for(let o=0;;o++){let l=o=r&&i.add(t.doc.line(c).from,t.doc.line(u).to,Oe.Decoration.replace({widget:new Iw(f),block:!0})),!l)break;a=t.doc.lineAt(Math.min(t.doc.length,n?l.toA:l.toB)).number}return i.finish()}var h4=Oe.EditorView.styleModule.of(new Dh({".cm-mergeView":{overflowY:"auto"},".cm-mergeViewEditors":{display:"flex",alignItems:"stretch"},".cm-mergeViewEditor":{flexGrow:1,flexBasis:0,overflow:"hidden"},".cm-merge-revert":{width:"1.6em",flexGrow:0,flexShrink:0,position:"relative"},".cm-merge-revert button":{position:"absolute",display:"block",width:"100%",boxSizing:"border-box",textAlign:"center",background:"none",border:"none",font:"inherit",cursor:"pointer"}})),p4=Oe.EditorView.baseTheme({".cm-mergeView & .cm-scroller, .cm-mergeView &":{height:"auto !important",overflowY:"visible !important"},"&.cm-merge-a .cm-changedLine, .cm-deletedChunk":{backgroundColor:"rgba(160, 128, 100, .08)"},"&.cm-merge-b .cm-changedLine, .cm-inlineChangedLine":{backgroundColor:"rgba(100, 160, 128, .08)"},"&light.cm-merge-a .cm-changedText, &light .cm-deletedChunk .cm-deletedText":{background:"linear-gradient(#ee443366, #ee443366) bottom/100% 2px no-repeat"},"&dark.cm-merge-a .cm-changedText, &dark .cm-deletedChunk .cm-deletedText":{background:"linear-gradient(#ffaa9966, #ffaa9966) bottom/100% 2px no-repeat"},"&light.cm-merge-b .cm-changedText":{background:"linear-gradient(#22bb22aa, #22bb22aa) bottom/100% 2px no-repeat"},"&dark.cm-merge-b .cm-changedText":{background:"linear-gradient(#88ff88aa, #88ff88aa) bottom/100% 2px no-repeat"},"&.cm-merge-b .cm-deletedText":{background:"#ff000033"},".cm-insertedLine, .cm-deletedLine, .cm-deletedLine del":{textDecoration:"none"},".cm-deletedChunk":{paddingLeft:"6px","& .cm-chunkButtons":{position:"absolute",insetInlineEnd:"5px"},"& button":{border:"none",cursor:"pointer",color:"white",margin:"0 2px",borderRadius:"3px","&[name=accept]":{background:"#2a2"},"&[name=reject]":{background:"#d43"}}},".cm-collapsedLines":{padding:"5px 5px 5px 10px",cursor:"pointer","&:before":{content:'"\u299A"',marginInlineEnd:"7px"},"&:after":{content:'"\u299A"',marginInlineStart:"7px"}},"&light .cm-collapsedLines":{color:"#444",background:"linear-gradient(to bottom, transparent 0, #f3f3f3 30%, #f3f3f3 70%, transparent 100%)"},"&dark .cm-collapsedLines":{color:"#ddd",background:"linear-gradient(to bottom, transparent 0, #222 30%, #222 70%, transparent 100%)"},".cm-changeGutter":{width:"3px",paddingLeft:"1px"},"&light.cm-merge-a .cm-changedLineGutter, &light .cm-deletedLineGutter":{background:"#e43"},"&dark.cm-merge-a .cm-changedLineGutter, &dark .cm-deletedLineGutter":{background:"#fa9"},"&light.cm-merge-b .cm-changedLineGutter":{background:"#2b2"},"&dark.cm-merge-b .cm-changedLineGutter":{background:"#8f8"},".cm-inlineChangedLineGutter":{background:"#75d"}}),T2=new Fe.Compartment,Bh=new Fe.Compartment,Gh=class{constructor(e){this.revertDOM=null,this.revertToA=!1,this.revertToLeft=!1,this.measuring=-1,this.diffConf=e.diffConfig||r4;let r=[Fe.Prec.low(j2),p4,h4,Gu,Oe.EditorView.updateListener.of(f=>{this.measuring<0&&(f.heightChanged||f.viewportChanged)&&!f.transactions.some(d=>d.effects.some(h=>h.is(Uh)))&&this.measure()})],i=[Pi.of({side:"a",sibling:()=>this.b,highlightChanges:e.highlightChanges!==!1,markGutter:e.gutter!==!1})];e.gutter!==!1&&i.push(Lh);let n=Fe.EditorState.create({doc:e.a.doc,selection:e.a.selection,extensions:[e.a.extensions||[],Oe.EditorView.editorAttributes.of({class:"cm-merge-a"}),Bh.of(i),r]}),s=[Pi.of({side:"b",sibling:()=>this.a,highlightChanges:e.highlightChanges!==!1,markGutter:e.gutter!==!1})];e.gutter!==!1&&s.push(Lh);let a=Fe.EditorState.create({doc:e.b.doc,selection:e.b.selection,extensions:[e.b.extensions||[],Oe.EditorView.editorAttributes.of({class:"cm-merge-b"}),Bh.of(s),r]});this.chunks=is.build(n.doc,a.doc,this.diffConf);let o=[Tn.init(()=>this.chunks),T2.of(e.collapseUnchanged?A2(e.collapseUnchanged):[])];n=n.update({effects:Fe.StateEffect.appendConfig.of(o)}).state,a=a.update({effects:Fe.StateEffect.appendConfig.of(o)}).state,this.dom=document.createElement("div"),this.dom.className="cm-mergeView",this.editorDOM=this.dom.appendChild(document.createElement("div")),this.editorDOM.className="cm-mergeViewEditors";let l=e.orientation||"a-b",c=document.createElement("div");c.className="cm-mergeViewEditor";let u=document.createElement("div");u.className="cm-mergeViewEditor",this.editorDOM.appendChild(l=="a-b"?c:u),this.editorDOM.appendChild(l=="a-b"?u:c),this.a=new Oe.EditorView({state:n,parent:c,root:e.root,dispatchTransactions:f=>this.dispatch(f,this.a)}),this.b=new Oe.EditorView({state:a,parent:u,root:e.root,dispatchTransactions:f=>this.dispatch(f,this.b)}),this.setupRevertControls(!!e.revertControls,e.revertControls=="b-to-a",e.renderRevertControl),e.parent&&e.parent.appendChild(this.dom),this.scheduleMeasure()}dispatch(e,r){if(e.some(i=>i.docChanged)){let i=e[e.length-1],n=e.reduce((a,o)=>a.compose(o.changes),Fe.ChangeSet.empty(e[0].startState.doc.length));this.chunks=r==this.a?is.updateA(this.chunks,i.newDoc,this.b.state.doc,n,this.diffConf):is.updateB(this.chunks,this.a.state.doc,i.newDoc,n,this.diffConf),r.update([...e,i.state.update({effects:$w.of(this.chunks)})]);let s=r==this.a?this.b:this.a;s.update([s.state.update({effects:$w.of(this.chunks)})]),this.scheduleMeasure()}else r.update(e)}reconfigure(e){if("diffConfig"in e&&(this.diffConf=e.diffConfig),"orientation"in e){let s=e.orientation!="b-a";if(s!=(this.editorDOM.firstChild==this.a.dom.parentNode)){let a=this.a.dom.parentNode,o=this.b.dom.parentNode;a.remove(),o.remove(),this.editorDOM.insertBefore(s?a:o,this.editorDOM.firstChild),this.editorDOM.appendChild(s?o:a),this.revertToLeft=!this.revertToLeft,this.revertDOM&&(this.revertDOM.textContent="")}}if("revertControls"in e||"renderRevertControl"in e){let s=!!this.revertDOM,a=this.revertToA,o=this.renderRevert;"revertControls"in e&&(s=!!e.revertControls,a=e.revertControls=="b-to-a"),"renderRevertControl"in e&&(o=e.renderRevertControl),this.setupRevertControls(s,a,o)}let r="highlightChanges"in e,i="gutter"in e,n="collapseUnchanged"in e;if(r||i||n){let s=[],a=[];if(r||i){let o=this.a.state.facet(Pi),l=i?e.gutter!==!1:o.markGutter,c=r?e.highlightChanges!==!1:o.highlightChanges;s.push(Bh.reconfigure([Pi.of({side:"a",sibling:()=>this.b,highlightChanges:c,markGutter:l}),l?Lh:[]])),a.push(Bh.reconfigure([Pi.of({side:"b",sibling:()=>this.a,highlightChanges:c,markGutter:l}),l?Lh:[]]))}if(n){let o=T2.reconfigure(e.collapseUnchanged?A2(e.collapseUnchanged):[]);s.push(o),a.push(o)}this.a.dispatch({effects:s}),this.b.dispatch({effects:a})}this.scheduleMeasure()}setupRevertControls(e,r,i){this.revertToA=r,this.revertToLeft=this.revertToA==(this.editorDOM.firstChild==this.a.dom.parentNode),this.renderRevert=i,!e&&this.revertDOM?(this.revertDOM.remove(),this.revertDOM=null):e&&!this.revertDOM?(this.revertDOM=this.editorDOM.insertBefore(document.createElement("div"),this.editorDOM.firstChild.nextSibling),this.revertDOM.addEventListener("mousedown",n=>this.revertClicked(n)),this.revertDOM.className="cm-merge-revert"):this.revertDOM&&(this.revertDOM.textContent="")}scheduleMeasure(){if(this.measuring<0){let e=this.dom.ownerDocument.defaultView||window;this.measuring=e.requestAnimationFrame(()=>{this.measuring=-1,this.measure()})}}measure(){c4(this.a,this.b,this.chunks),this.revertDOM&&this.updateRevertButtons()}updateRevertButtons(){let e=this.revertDOM,r=e.firstChild,i=this.a.viewport,n=this.b.viewport;for(let s=0;si.to||a.fromB>n.to)break;if(a.fromA-1&&(this.dom.ownerDocument.defaultView||window).cancelAnimationFrame(this.measuring),this.dom.remove()}};function P2(t){let e=t.nextSibling;return t.remove(),e}var Nw=require("@codemirror/state");function jh(t,e){let r=t.lineAt(e);return!(r.text.length==0&&r.number==t.lines)?r.number:r.number-1}function Bw(t,e,r){let i=[],n=t.split(` +`),s=e.split(` +`);for(let a of r){let{oldStart:o,oldLines:l,newStart:c,newLines:u}=a,f=qt.createHunk(o,l,c,u);if(a.oldLines>0){for(let d=o;dn.length&&n.last()!=""&&(f.removed.no_nl_at_eof=!0)}if(a.newLines>0){for(let d=c;ds.length&&s.last()!=""&&(f.added.no_nl_at_eof=!0)}i.push(f)}return i}function Hw(t,e,r){let i=e.lineAt(t.fromA).number,n=t.fromA==t.toA?0:jh(e,t.endA)-i+1,s=r.lineAt(t.fromB).number,a=t.fromB==t.toB?0:jh(r,t.endB)-s+1,o={oldStart:i,oldLines:n,newStart:s,newLines:a};return o.oldLines==0&&(o.oldStart-=1),o.newLines==0&&(o.newStart-=1),o}var V2={scanLimit:1e3,timeout:200};function m4(t,e,r,i){let n=Nw.Text.of(t.split(` +`)),s=Nw.Text.of(e.split(` +`)),a=r&&i?is.updateB(r,n,s,i,V2):is.build(n,s,V2),o=[];for(let l=0;lh.vend&&(f=f-(h.added.count-h.removed.count)),o>h.vend&&(d=d-(h.added.count-h.removed.count));c.added.lines=u.compareText.split(` +`).slice(f-1,d),u.compareTextHead?c.removed.lines=u.compareTextHead.split(` +`).slice(c.removed.start-1,c.removed.start-1+c.removed.count):c.removed.lines=[]}else c.added.lines=e.doc.toString().split(` +`).slice(a-1,o),o===e.doc.lines&&!e.doc.toString().endsWith(` +`)&&(c.added.no_nl_at_eof=!0),c.removed.lines=u.compareText.split(` +`).slice(c.removed.start-1,c.removed.start-1+c.removed.count),c.removed.start+c.removed.count-1===u.compareText.split(` +`).length&&!u.compareText.endsWith(` +`)&&(c.removed.no_nl_at_eof=!0);return c}},Wr=Il.StateField.define({create:t=>{},update:(t,e)=>{var n,s,a;let r=t?{...t}:{maxDiffTimeMs:0,hunks:[],stagedHunks:[],chunks:void 0,isDirty:!1},i=!1;for(let o of e.effects)if(o.is(Ml)&&(r.compareText=o.value.compareText,r.compareTextHead=o.value.compareTextHead,i=(t==null?void 0:t.compareText)!==o.value.compareText,i&&(r.chunks=void 0,r.changeDesc=void 0)),o.is(Vh)){let l=(n=e.startState.field(ju,!1))==null?void 0:n.revision;if(o.value.revision!==l)continue;W2(r,o.value.result,e.state),r.changeDesc=void 0}if(e.docChanged){let o=!r.changeDesc||r.changeDesc.newLength===e.changes.length;console.assert(o,"Git: Hunk changes belong to different document histories."),o||(r.chunks=void 0),r.changeDesc=g4(r.changeDesc,e.changes)}if(r.compareText!==void 0){if(i||e.docChanged){r.isDirty=!0;let o=v4(e,r.compareText,r.chunks,r.changeDesc,r.maxDiffTimeMs);o&&(W2(r,o,e.state),r.changeDesc=void 0)}}else{r.compareText=void 0,r.compareTextHead=void 0,r.chunks=void 0,r.hunks=[],r.stagedHunks=[],r.isDirty=!1;let o=e.state.field(ns.editorInfoField).file;(a=(s=Et.plugin)==null?void 0:s.editorIntegration.signsFeature.changeStatusBar)==null||a.display(r.hunks,o)}return r}});function W2(t,e,r){var n,s;t.hunks=e.hunks,t.chunks=e.chunks,t.isDirty=!1,t.maxDiffTimeMs=Math.max(.95*t.maxDiffTimeMs,e.diffDuration);let i=r.field(ns.editorInfoField).file;(s=(n=Et.plugin)==null?void 0:n.editorIntegration.signsFeature.changeStatusBar)==null||s.display(t.hunks,i)}var ju=Il.StateField.define({create:t=>{var e,r;return{debouncer:(0,ns.debounce)(i=>{let{state:n,compareText:s,previousChunks:a,changeDesc:o,revision:l}=i,c=n.field(ns.editorEditorField,!1);if(!c)return;let u=c.state.field(ju,!1);if((u==null?void 0:u.revision)!==l)return;let f=q2(n,s,a,o);c.dispatch({effects:Vh.of({result:f,revision:l})})},1e3,!0),revision:{},filePath:(r=(e=t.field(ns.editorInfoField,!1))==null?void 0:e.file)==null?void 0:r.path}},update:(t,e)=>{var i,n;let r=(n=(i=e.state.field(ns.editorInfoField,!1))==null?void 0:i.file)==null?void 0:n.path;return e.docChanged||r!==t.filePath?{...t,revision:{},filePath:r}:t}});function g4(t,e){return!t||t.newLength!==e.length?e:t.composeDesc(e)}function q2(t,e,r,i){let n=t.doc.toString(),s=performance.now(),{hunks:a,chunks:o}=z2(e,n,r,i),l=performance.now()-s;return{hunks:a,chunks:o,diffDuration:l}}function v4(t,e,r,i,n){let s=t.state,a=Math.abs(t.changes.length-t.changes.newLength),o=s.field(ju);if(a>1e3||n>16){o.debouncer({state:s,compareText:e,previousChunks:r,changeDesc:i,revision:o.revision});return}else return q2(s,e,r,i)}var Ml=Il.StateEffect.define(),Vh=Il.StateEffect.define();function Y2(t,e){return e.update({effects:Ml.of(t)})}m();m();m();var ut;(function(t){t.INSERT="insert",t.DELETE="delete",t.CONTEXT="context"})(ut||(ut={}));var Z2={LINE_BY_LINE:"line-by-line",SIDE_BY_SIDE:"side-by-side"},K2={LINES:"lines",WORDS:"words",NONE:"none"},X2={WORD:"word",CHAR:"char"},Ua;(function(t){t.AUTO="auto",t.DARK="dark",t.LIGHT="light"})(Ua||(Ua={}));m();var w4=["-","[","]","/","{","}","(",")","*","+","?",".","\\","^","$","|"],b4=RegExp("["+w4.join("\\")+"]","g");function Q2(t){return t.replace(b4,"\\$&")}function Uw(t){return t&&t.replace(/\\/g,"/")}function J2(t){let e,r,i,n=0;for(e=0,i=t.length;e1?r[r.length-1]:e}function tP(t,e){return e.reduce((r,i)=>r||t.startsWith(i),!1)}var rP=["a/","b/","i/","w/","c/","o/"];function qs(t,e,r){let i=r!==void 0?[...rP,r]:rP,n=e?new RegExp(`^${Q2(e)} "?(.+?)"?$`):new RegExp('^"?(.+?)"?$'),[,s=""]=n.exec(t)||[],a=i.find(l=>s.indexOf(l)===0);return(a?s.slice(a.length):s).replace(/\s+\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d+)? [+-]\d{4}.*$/,"")}function _4(t,e){return qs(t,"---",e)}function y4(t,e){return qs(t,"+++",e)}function iP(t,e={}){let r=[],i=null,n=null,s=null,a=null,o=null,l=null,c=null,u="--- ",f="+++ ",d="@@",h=/^old mode (\d{6})/,p=/^new mode (\d{6})/,g=/^deleted file mode (\d{6})/,v=/^new file mode (\d{6})/,b=/^copy from "?(.+)"?/,_=/^copy to "?(.+)"?/,C=/^rename from "?(.+)"?/,x=/^rename to "?(.+)"?/,E=/^similarity index (\d+)%/,A=/^dissimilarity index (\d+)%/,w=/^index ([\da-z]+)\.\.([\da-z]+)\s*(\d{6})?/,S=/^Binary files (.*) and (.*) differ/,y=/^GIT binary patch/,P=/^index ([\da-z]+),([\da-z]+)\.\.([\da-z]+)/,T=/^mode (\d{6}),(\d{6})\.\.(\d{6})/,I=/^new file mode (\d{6})/,M=/^deleted file mode (\d{6}),(\d{6})/,B=t.replace(/\\ No newline at end of file/g,"").replace(/\r\n?/g,` +`).split(` +`);function re(){n!==null&&i!==null&&(i.blocks.push(n),n=null)}function Ae(){i!==null&&(!i.oldName&&l!==null&&(i.oldName=l),!i.newName&&c!==null&&(i.newName=c),i.newName&&(r.push(i),i=null)),l=null,c=null}function K(){re(),Ae(),i={blocks:[],deletedLines:0,addedLines:0}}function Q(z){re();let X;i!==null&&((X=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@.*/.exec(z))?(i.isCombined=!1,s=parseInt(X[1],10),o=parseInt(X[2],10)):(X=/^@@@ -(\d+)(?:,\d+)? -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@@.*/.exec(z))?(i.isCombined=!0,s=parseInt(X[1],10),a=parseInt(X[2],10),o=parseInt(X[3],10)):(z.startsWith(d)&&console.error("Failed to parse lines, starting in 0!"),s=0,o=0,i.isCombined=!1)),n={lines:[],oldStartLine:s,oldStartLine2:a,newStartLine:o,header:z}}function fe(z){if(i===null||n===null||s===null||o===null)return;let X={content:z},j=i.isCombined?["+ "," +","++"]:["+"],Ze=i.isCombined?["- "," -","--"]:["-"];tP(z,j)?(i.addedLines++,X.type=ut.INSERT,X.oldNumber=void 0,X.newNumber=o++):tP(z,Ze)?(i.deletedLines++,X.type=ut.DELETE,X.oldNumber=s++,X.newNumber=void 0):(X.type=ut.CONTEXT,X.oldNumber=s++,X.newNumber=o++),n.lines.push(X)}function ce(z,X){let j=X;for(;j{if(!z||z.startsWith("*"))return;let j,Ze=B[X-1],$r=B[X+1],cr=B[X+2];if(z.startsWith("diff --git")||z.startsWith("diff --combined")){if(K(),(j=/^diff --git "?([a-ciow]\/.+)"? "?([a-ciow]\/.+)"?/.exec(z))&&(l=qs(j[1],void 0,e.dstPrefix),c=qs(j[2],void 0,e.srcPrefix)),i===null)throw new Error("Where is my file !!!");i.isGitDiff=!0;return}if(z.startsWith("Binary files")&&!(i!=null&&i.isGitDiff)){if(K(),(j=/^Binary files "?([a-ciow]\/.+)"? and "?([a-ciow]\/.+)"? differ/.exec(z))&&(l=qs(j[1],void 0,e.dstPrefix),c=qs(j[2],void 0,e.srcPrefix)),i===null)throw new Error("Where is my file !!!");i.isBinary=!0;return}if((!i||!i.isGitDiff&&i&&z.startsWith(u)&&$r.startsWith(f)&&cr.startsWith(d))&&K(),i!=null&&i.isTooBig)return;if(i&&(typeof e.diffMaxChanges=="number"&&i.addedLines+i.deletedLines>e.diffMaxChanges||typeof e.diffMaxLineLength=="number"&&z.length>e.diffMaxLineLength)){i.isTooBig=!0,i.addedLines=0,i.deletedLines=0,i.blocks=[],n=null;let yt=typeof e.diffTooBigMessage=="function"?e.diffTooBigMessage(r.length):"Diff too big to be displayed";Q(yt);return}if(z.startsWith(u)&&$r.startsWith(f)||z.startsWith(f)&&Ze.startsWith(u)){if(i&&!i.oldName&&z.startsWith("--- ")&&(j=_4(z,e.srcPrefix))){i.oldName=j,i.language=eP(i.oldName,i.language);return}if(i&&!i.newName&&z.startsWith("+++ ")&&(j=y4(z,e.dstPrefix))){i.newName=j,i.language=eP(i.newName,i.language);return}}if(i&&(z.startsWith(d)||i.isGitDiff&&i.oldName&&i.newName&&!n)){Q(z);return}if(n&&(z.startsWith("+")||z.startsWith("-")||z.startsWith(" "))){fe(z);return}let Ie=!ce(z,X);if(i===null)throw new Error("Where is my file !!!");(j=h.exec(z))?i.oldMode=j[1]:(j=p.exec(z))?i.newMode=j[1]:(j=g.exec(z))?(i.deletedFileMode=j[1],i.isDeleted=!0):(j=v.exec(z))?(i.newFileMode=j[1],i.isNew=!0):(j=b.exec(z))?(Ie&&(i.oldName=j[1]),i.isCopy=!0):(j=_.exec(z))?(Ie&&(i.newName=j[1]),i.isCopy=!0):(j=C.exec(z))?(Ie&&(i.oldName=j[1]),i.isRename=!0):(j=x.exec(z))?(Ie&&(i.newName=j[1]),i.isRename=!0):(j=S.exec(z))?(i.isBinary=!0,i.oldName=qs(j[1],void 0,e.srcPrefix),i.newName=qs(j[2],void 0,e.dstPrefix),Q("Binary file")):y.test(z)?(i.isBinary=!0,Q(z)):(j=E.exec(z))?i.unchangedPercentage=parseInt(j[1],10):(j=A.exec(z))?i.changedPercentage=parseInt(j[1],10):(j=w.exec(z))?(i.checksumBefore=j[1],i.checksumAfter=j[2],j[3]&&(i.mode=j[3])):(j=P.exec(z))?(i.checksumBefore=[j[2],j[3]],i.checksumAfter=j[1]):(j=T.exec(z))?(i.oldMode=[j[2],j[3]],i.newMode=j[1]):(j=I.exec(z))?(i.newFileMode=j[1],i.isNew=!0):(j=M.exec(z))&&(i.deletedFileMode=j[1],i.isDeleted=!0)}),re(),Ae(),r}m();m();m();m();var Ys=class{diff(e,r,i={}){let n;typeof i=="function"?(n=i,i={}):"callback"in i&&(n=i.callback);let s=this.castInput(e,i),a=this.castInput(r,i),o=this.removeEmpty(this.tokenize(s,i)),l=this.removeEmpty(this.tokenize(a,i));return this.diffWithOptionsObj(o,l,i,n)}diffWithOptionsObj(e,r,i,n){var s;let a=_=>{if(_=this.postProcess(_,i),n){setTimeout(function(){n(_)},0);return}else return _},o=r.length,l=e.length,c=1,u=o+l;i.maxEditLength!=null&&(u=Math.min(u,i.maxEditLength));let f=(s=i.timeout)!==null&&s!==void 0?s:1/0,d=Date.now()+f,h=[{oldPos:-1,lastComponent:void 0}],p=this.extractCommon(h[0],r,e,0,i);if(h[0].oldPos+1>=l&&p+1>=o)return a(this.buildValues(h[0].lastComponent,r,e));let g=-1/0,v=1/0,b=()=>{for(let _=Math.max(g,-c);_<=Math.min(v,c);_+=2){let C,x=h[_-1],E=h[_+1];x&&(h[_-1]=void 0);let A=!1;if(E){let S=E.oldPos-_;A=E&&0<=S&&S=l&&p+1>=o)return a(this.buildValues(C.lastComponent,r,e))||!0;h[_]=C,C.oldPos+1>=l&&(v=Math.min(v,_-1)),p+1>=o&&(g=Math.max(g,_+1))}c++};if(n)(function _(){setTimeout(function(){if(c>u||Date.now()>d)return n(void 0);b()||_()},0)})();else for(;c<=u&&Date.now()<=d;){let _=b();if(_)return _}}addToPath(e,r,i,n,s){let a=e.lastComponent;return a&&!s.oneChangePerToken&&a.added===r&&a.removed===i?{oldPos:e.oldPos+n,lastComponent:{count:a.count+1,added:r,removed:i,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+n,lastComponent:{count:1,added:r,removed:i,previousComponent:a}}}extractCommon(e,r,i,n,s){let a=r.length,o=i.length,l=e.oldPos,c=l-n,u=0;for(;c+1d.length?p:d}),u.value=this.join(f)}else u.value=this.join(r.slice(l,l+u.count));l+=u.count,u.added||(c+=u.count)}}return n}};m();var Gw=class extends Ys{},nP=new Gw;function jw(t,e,r){return nP.diff(t,e,r)}m();m();function Vw(t,e){let r;for(r=0;re.length&&(r=t.length-e.length);let i=e.length;t.length0&&e[a]!=e[s];)s=n[s];e[a]==e[s]&&s++}s=0;for(let a=r;a0&&t[a]!=e[s];)s=n[s];t[a]==e[s]&&s++}return s}function qw(t,e){let r=[];for(let i of Array.from(e.segment(t))){let n=i.segment;r.length&&/\s/.test(r[r.length-1])&&/\s/.test(n)?r[r.length-1]+=n:r.push(n)}return r}function Yh(t,e){if(e)return Ol(t,e)[1];let r;for(r=t.length-1;r>=0&&t[r].match(/\s/);r--);return t.substring(r+1)}function Ga(t,e){if(e)return Ol(t,e)[0];let r=t.match(/^\s*/);return r?r[0]:""}function Ol(t,e){if(!e)return[Ga(t),Yh(t)];if(e.resolvedOptions().granularity!="word")throw new Error('The segmenter passed must have a granularity of "word"');let r=qw(t,e),i=r[0],n=r[r.length-1],s=/\s/.test(i)?i:"",a=/\s/.test(n)?n:"";return[s,a]}var Zh="a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}",S4=new RegExp(`[${Zh}]+|\\s+|[^${Zh}]`,"ug"),Yw=class extends Ys{equals(e,r,i){return i.ignoreCase&&(e=e.toLowerCase(),r=r.toLowerCase()),e.trim()===r.trim()}tokenize(e,r={}){let i;if(r.intlSegmenter){let a=r.intlSegmenter;if(a.resolvedOptions().granularity!="word")throw new Error('The segmenter passed must have a granularity of "word"');i=qw(e,a)}else i=e.match(S4)||[];let n=[],s=null;return i.forEach(a=>{/\s/.test(a)?s==null?n.push(a):n.push(n.pop()+a):s!=null&&/\s/.test(s)?n[n.length-1]==s?n.push(n.pop()+a):n.push(s+a):n.push(a),s=a}),n}join(e){return e.map((r,i)=>i==0?r:r.replace(/^\s+/,"")).join("")}postProcess(e,r){if(!e||r.oneChangePerToken)return e;let i=null,n=null,s=null;return e.forEach(a=>{a.added?n=a:a.removed?s=a:((n||s)&&sP(i,s,n,a,r.intlSegmenter),i=a,n=null,s=null)}),(n||s)&&sP(i,s,n,null,r.intlSegmenter),e}},k4=new Yw;function sP(t,e,r,i,n){if(e&&r){let[s,a]=Ol(e.value,n),[o,l]=Ol(r.value,n);if(t){let c=Vw(s,o);t.value=qh(t.value,o,c),e.value=Dl(e.value,c),r.value=Dl(r.value,c)}if(i){let c=zw(a,l);i.value=Wh(i.value,l,c),e.value=Vu(e.value,c),r.value=Vu(r.value,c)}}else if(r){if(t){let s=Ga(r.value,n);r.value=r.value.substring(s.length)}if(i){let s=Ga(i.value,n);i.value=i.value.substring(s.length)}}else if(t&&i){let s=Ga(i.value,n),[a,o]=Ol(e.value,n),l=Vw(s,a);e.value=Dl(e.value,l);let c=zw(Dl(s,l),o);e.value=Vu(e.value,c),i.value=Wh(i.value,s,c),t.value=qh(t.value,s,s.slice(0,s.length-c.length))}else if(i){let s=Ga(i.value,n),a=Yh(e.value,n),o=Ww(a,s);e.value=Vu(e.value,o)}else if(t){let s=Yh(t.value,n),a=Ga(e.value,n),o=Ww(s,a);e.value=Dl(e.value,o)}}var Zw=class extends Ys{tokenize(e){let r=new RegExp(`(\\r?\\n)|[${Zh}]+|[^\\S\\n\\r]+|[^${Zh}]`,"ug");return e.match(r)||[]}},aP=new Zw;function Kw(t,e,r){return aP.diff(t,e,r)}m();function A4(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=[],i;for(i=0;i<=e.length;i++)r[i]=[i];let n;for(n=0;n<=t.length;n++)r[0][n]=n;for(i=1;i<=e.length;i++)for(n=1;n<=t.length;n++)e.charAt(i-1)===t.charAt(n-1)?r[i][n]=r[i-1][n-1]:r[i][n]=Math.min(r[i-1][n-1]+1,Math.min(r[i][n-1]+1,r[i-1][n]+1));return r[e.length][t.length]}function Ll(t){return(e,r)=>{let i=t(e).trim(),n=t(r).trim();return A4(i,n)/(i.length+n.length)}}function Nl(t){function e(i,n,s=new Map){let a=1/0,o;for(let l=0;l0||o.indexB>0)&&(C=v.concat(C)),(i.length>d||n.length>h)&&(C=C.concat(_)),C}return r}var tr={INSERTS:"d2h-ins",DELETES:"d2h-del",CONTEXT:"d2h-cntx",INFO:"d2h-info",INSERT_CHANGES:"d2h-ins d2h-change",DELETE_CHANGES:"d2h-del d2h-change"},ja={matching:K2.NONE,matchWordsThreshold:.25,maxLineLengthHighlight:1e4,diffStyle:X2.WORD,colorScheme:Ua.LIGHT},Pn="/",oP=Ll(t=>t.value),T4=Nl(oP);function Qw(t){return t.indexOf("dev/null")!==-1}function P4(t){return t.replace(/(]*>((.|\n)*?)<\/ins>)/g,"")}function R4(t){return t.replace(/(]*>((.|\n)*?)<\/del>)/g,"")}function Bl(t){switch(t){case ut.CONTEXT:return tr.CONTEXT;case ut.INSERT:return tr.INSERTS;case ut.DELETE:return tr.DELETES}}function Hl(t){switch(t){case Ua.DARK:return"d2h-dark-color-scheme";case Ua.AUTO:return"d2h-auto-color-scheme";case Ua.LIGHT:default:return"d2h-light-color-scheme"}}function $4(t){return t?2:1}function Zs(t){return t.slice(0).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")}function Ri(t,e,r=!0){let i=$4(e);return{prefix:t.substring(0,i),content:r?Zs(t.substring(i)):t.substring(i)}}function Va(t){let e=Uw(t.oldName),r=Uw(t.newName);if(e!==r&&!Qw(e)&&!Qw(r)){let i=[],n=[],s=e.split(Pn),a=r.split(Pn),o=s.length,l=a.length,c=0,u=o-1,f=l-1;for(;cc&&f>c&&s[u]===a[f];)n.unshift(a[f]),u-=1,f-=1;let d=i.join(Pn),h=n.join(Pn),p=s.slice(c,u+1).join(Pn),g=a.slice(c,f+1).join(Pn);return d.length&&h.length?d+Pn+"{"+p+" \u2192 "+g+"}"+Pn+h:d.length?d+Pn+"{"+p+" \u2192 "+g+"}":h.length?"{"+p+" \u2192 "+g+"}"+Pn+h:e+" \u2192 "+r}else return Qw(r)?e:r}function Ul(t){return`d2h-${J2(Va(t)).toString().slice(-6)}`}function Gl(t){let e="file-changed";return t.isRename||t.isCopy?e="file-renamed":t.isNew?e="file-added":t.isDeleted?e="file-deleted":t.newName!==t.oldName&&(e="file-renamed"),e}function Kh(t,e,r,i={}){let{matching:n,maxLineLengthHighlight:s,matchWordsThreshold:a,diffStyle:o}=Object.assign(Object.assign({},ja),i),l=Ri(t,r,!1),c=Ri(e,r,!1);if(l.content.length>s||c.content.length>s)return{oldLine:{prefix:l.prefix,content:Zs(l.content)},newLine:{prefix:c.prefix,content:Zs(c.content)}};let u=o==="char"?jw(l.content,c.content):Kw(l.content,c.content),f=[];if(o==="word"&&n==="words"){let h=u.filter(v=>v.removed),p=u.filter(v=>v.added);T4(p,h).forEach(v=>{v[0].length===1&&v[1].length===1&&oP(v[0][0],v[1][0]){let g=p.added?"ins":p.removed?"del":null,v=f.indexOf(p)>-1?' class="d2h-change"':"",b=Zs(p.value);return g!==null?`${h}<${g}${v}>${b}`:`${h}${b}`},"");return{oldLine:{prefix:l.prefix,content:P4(d)},newLine:{prefix:c.prefix,content:R4(d)}}}var lP="file-summary",F4="icon",I4={colorScheme:ja.colorScheme},Xh=class{constructor(e,r={}){this.hoganUtils=e,this.config=Object.assign(Object.assign({},I4),r)}render(e){let r=e.map(i=>this.hoganUtils.render(lP,"line",{fileHtmlId:Ul(i),oldName:i.oldName,newName:i.newName,fileName:Va(i),deletedLines:"-"+i.deletedLines,addedLines:"+"+i.addedLines},{fileIcon:this.hoganUtils.template(F4,Gl(i))})).join(` +`);return this.hoganUtils.render(lP,"wrapper",{colorScheme:Hl(this.config.colorScheme),filesNumber:e.length,files:r})}};m();var e0=Object.assign(Object.assign({},ja),{renderNothingWhenEmpty:!1,matchingMaxComparisons:2500,maxLineSizeInBlockForComparison:200}),zu="generic",cP="line-by-line",M4="icon",D4="tag",Wu=class{constructor(e,r={}){this.hoganUtils=e,this.config=Object.assign(Object.assign({},e0),r)}render(e){let r=e.map(i=>{let n;return i.blocks.length?n=this.generateFileHtml(i):n=this.generateEmptyDiff(),this.makeFileDiffHtml(i,n)}).join(` +`);return this.hoganUtils.render(zu,"wrapper",{colorScheme:Hl(this.config.colorScheme),content:r})}makeFileDiffHtml(e,r){if(this.config.renderNothingWhenEmpty&&Array.isArray(e.blocks)&&e.blocks.length===0)return"";let i=this.hoganUtils.template(cP,"file-diff"),n=this.hoganUtils.template(zu,"file-path"),s=this.hoganUtils.template(M4,"file"),a=this.hoganUtils.template(D4,Gl(e));return i.render({file:e,fileHtmlId:Ul(e),diffs:r,filePath:n.render({fileDiffName:Va(e)},{fileIcon:s,fileTag:a})})}generateEmptyDiff(){return this.hoganUtils.render(zu,"empty-diff",{contentClass:"d2h-code-line",CSSLineClass:tr})}generateFileHtml(e){let r=Nl(Ll(i=>Ri(i.content,e.isCombined).content));return e.blocks.map(i=>{let n=this.hoganUtils.render(zu,"block-header",{CSSLineClass:tr,blockHeader:e.isTooBig?i.header:Zs(i.header),lineClass:"d2h-code-linenumber",contentClass:"d2h-code-line"});return this.applyLineGroupping(i).forEach(([s,a,o])=>{if(a.length&&o.length&&!s.length)this.applyRematchMatching(a,o,r).map(([l,c])=>{let{left:u,right:f}=this.processChangedLines(e,e.isCombined,l,c);n+=u,n+=f});else if(s.length)s.forEach(l=>{let{prefix:c,content:u}=Ri(l.content,e.isCombined);n+=this.generateSingleLineHtml(e,{type:tr.CONTEXT,prefix:c,content:u,oldNumber:l.oldNumber,newNumber:l.newNumber})});else if(a.length||o.length){let{left:l,right:c}=this.processChangedLines(e,e.isCombined,a,o);n+=l,n+=c}else console.error("Unknown state reached while processing groups of lines",s,a,o)}),n}).join(` +`)}applyLineGroupping(e){let r=[],i=[],n=[];for(let s=0;s0)&&(r.push([[],i,n]),i=[],n=[]),a.type===ut.CONTEXT?r.push([[a],[],[]]):a.type===ut.INSERT&&i.length===0?r.push([[],[],[a]]):a.type===ut.INSERT&&i.length>0?n.push(a):a.type===ut.DELETE&&i.push(a)}return(i.length||n.length)&&(r.push([[],i,n]),i=[],n=[]),r}applyRematchMatching(e,r,i){let n=e.length*r.length,s=zh(e.concat(r).map(o=>o.content.length));return n{let n;return i.blocks.length?n=this.generateFileHtml(i):n=this.generateEmptyDiff(),this.makeFileDiffHtml(i,n)}).join(` +`);return this.hoganUtils.render(qu,"wrapper",{colorScheme:Hl(this.config.colorScheme),content:r})}makeFileDiffHtml(e,r){if(this.config.renderNothingWhenEmpty&&Array.isArray(e.blocks)&&e.blocks.length===0)return"";let i=this.hoganUtils.template(O4,"file-diff"),n=this.hoganUtils.template(qu,"file-path"),s=this.hoganUtils.template(L4,"file"),a=this.hoganUtils.template(N4,Gl(e));return i.render({file:e,fileHtmlId:Ul(e),diffs:r,filePath:n.render({fileDiffName:Va(e)},{fileIcon:s,fileTag:a})})}generateEmptyDiff(){return{right:"",left:this.hoganUtils.render(qu,"empty-diff",{contentClass:"d2h-code-side-line",CSSLineClass:tr})}}generateFileHtml(e){let r=Nl(Ll(i=>Ri(i.content,e.isCombined).content));return e.blocks.map(i=>{let n={left:this.makeHeaderHtml(i.header,e),right:this.makeHeaderHtml("")};return this.applyLineGroupping(i).forEach(([s,a,o])=>{if(a.length&&o.length&&!s.length)this.applyRematchMatching(a,o,r).map(([l,c])=>{let{left:u,right:f}=this.processChangedLines(e.isCombined,l,c);n.left+=u,n.right+=f});else if(s.length)s.forEach(l=>{let{prefix:c,content:u}=Ri(l.content,e.isCombined),{left:f,right:d}=this.generateLineHtml({type:tr.CONTEXT,prefix:c,content:u,number:l.oldNumber},{type:tr.CONTEXT,prefix:c,content:u,number:l.newNumber});n.left+=f,n.right+=d});else if(a.length||o.length){let{left:l,right:c}=this.processChangedLines(e.isCombined,a,o);n.left+=l,n.right+=c}else console.error("Unknown state reached while processing groups of lines",s,a,o)}),n}).reduce((i,n)=>({left:i.left+n.left,right:i.right+n.right}),{left:"",right:""})}applyLineGroupping(e){let r=[],i=[],n=[];for(let s=0;s0)&&(r.push([[],i,n]),i=[],n=[]),a.type===ut.CONTEXT?r.push([[a],[],[]]):a.type===ut.INSERT&&i.length===0?r.push([[],[],[a]]):a.type===ut.INSERT&&i.length>0?n.push(a):a.type===ut.DELETE&&i.push(a)}return(i.length||n.length)&&(r.push([[],i,n]),i=[],n=[]),r}applyRematchMatching(e,r,i){let n=e.length*r.length,s=zh(e.concat(r).map(o=>o.content.length));return n'),i.b(` +`+r),i.b(' '),i.b(` +`+r),i.b(i.rp("'),i.b(i.v(i.f("fileName",t,e,0))),i.b(""),i.b(` +`+r),i.b(' '),i.b(` +`+r),i.b(' '),i.b(i.v(i.f("addedLines",t,e,0))),i.b(""),i.b(` +`+r),i.b(' '),i.b(i.v(i.f("deletedLines",t,e,0))),i.b(""),i.b(` +`+r),i.b(" "),i.b(` +`+r),i.b(" "),i.b(` +`+r),i.b(""),i.fl()},partials:{"'),i.b(` +`+r),i.b('
'),i.b(` +`+r),i.b(' Files changed ('),i.b(i.v(i.f("filesNumber",t,e,0))),i.b(")"),i.b(` +`+r),i.b(' hide'),i.b(` +`+r),i.b(' show'),i.b(` +`+r),i.b("
"),i.b(` +`+r),i.b('
    '),i.b(` +`+r),i.b(" "),i.b(i.t(i.f("files",t,e,0))),i.b(` +`+r),i.b("
"),i.b(` +`+r),i.b(""),i.fl()},partials:{},subs:{}});Ct["generic-block-header"]=new $t.Template({code:function(t,e,r){var i=this;return i.b(r=r||""),i.b(""),i.b(` +`+r),i.b(' '),i.b(` +`+r),i.b(' '),i.b(` +`+r),i.b('
'),i.s(i.f("blockHeader",t,e,1),t,e,0,156,173,"{{ }}")&&(i.rs(t,e,function(n,s,a){a.b(a.t(a.f("blockHeader",n,s,0)))}),t.pop()),i.s(i.f("blockHeader",t,e,1),t,e,1,0,0,"")||i.b(" "),i.b("
"),i.b(` +`+r),i.b(" "),i.b(` +`+r),i.b(""),i.fl()},partials:{},subs:{}});Ct["generic-empty-diff"]=new $t.Template({code:function(t,e,r){var i=this;return i.b(r=r||""),i.b(""),i.b(` +`+r),i.b(' '),i.b(` +`+r),i.b('
'),i.b(` +`+r),i.b(" File without changes"),i.b(` +`+r),i.b("
"),i.b(` +`+r),i.b(" "),i.b(` +`+r),i.b(""),i.fl()},partials:{},subs:{}});Ct["generic-file-path"]=new $t.Template({code:function(t,e,r){var i=this;return i.b(r=r||""),i.b(''),i.b(` +`+r),i.b(i.rp("'),i.b(i.v(i.f("fileDiffName",t,e,0))),i.b(""),i.b(` +`+r),i.b(i.rp(""),i.b(` +`+r),i.b('"),i.fl()},partials:{""),i.b(` +`+r),i.b(' '),i.b(` +`+r),i.b(" "),i.b(i.t(i.f("lineNumber",t,e,0))),i.b(` +`+r),i.b(" "),i.b(` +`+r),i.b(' '),i.b(` +`+r),i.b('
'),i.b(` +`+r),i.s(i.f("prefix",t,e,1),t,e,0,162,238,"{{ }}")&&(i.rs(t,e,function(n,s,a){a.b(' '),a.b(a.t(a.f("prefix",n,s,0))),a.b(""),a.b(` +`+r)}),t.pop()),i.s(i.f("prefix",t,e,1),t,e,1,0,0,"")||(i.b('  '),i.b(` +`+r)),i.s(i.f("content",t,e,1),t,e,0,371,445,"{{ }}")&&(i.rs(t,e,function(n,s,a){a.b(' '),a.b(a.t(a.f("content",n,s,0))),a.b(""),a.b(` +`+r)}),t.pop()),i.s(i.f("content",t,e,1),t,e,1,0,0,"")||(i.b('
'),i.b(` +`+r)),i.b("
"),i.b(` +`+r),i.b(" "),i.b(` +`+r),i.b(""),i.fl()},partials:{},subs:{}});Ct["generic-wrapper"]=new $t.Template({code:function(t,e,r){var i=this;return i.b(r=r||""),i.b('
'),i.b(` +`+r),i.b(" "),i.b(i.t(i.f("content",t,e,0))),i.b(` +`+r),i.b("
"),i.fl()},partials:{},subs:{}});Ct["icon-file-added"]=new $t.Template({code:function(t,e,r){var i=this;return i.b(r=r||""),i.b('"),i.fl()},partials:{},subs:{}});Ct["icon-file-changed"]=new $t.Template({code:function(t,e,r){var i=this;return i.b(r=r||""),i.b('"),i.fl()},partials:{},subs:{}});Ct["icon-file-deleted"]=new $t.Template({code:function(t,e,r){var i=this;return i.b(r=r||""),i.b('"),i.fl()},partials:{},subs:{}});Ct["icon-file-renamed"]=new $t.Template({code:function(t,e,r){var i=this;return i.b(r=r||""),i.b('"),i.fl()},partials:{},subs:{}});Ct["icon-file"]=new $t.Template({code:function(t,e,r){var i=this;return i.b(r=r||""),i.b('"),i.fl()},partials:{},subs:{}});Ct["line-by-line-file-diff"]=new $t.Template({code:function(t,e,r){var i=this;return i.b(r=r||""),i.b('
'),i.b(` +`+r),i.b('
'),i.b(` +`+r),i.b(" "),i.b(i.t(i.f("filePath",t,e,0))),i.b(` +`+r),i.b("
"),i.b(` +`+r),i.b('
'),i.b(` +`+r),i.b('
'),i.b(` +`+r),i.b(' '),i.b(` +`+r),i.b(' '),i.b(` +`+r),i.b(" "),i.b(i.t(i.f("diffs",t,e,0))),i.b(` +`+r),i.b(" "),i.b(` +`+r),i.b("
"),i.b(` +`+r),i.b("
"),i.b(` +`+r),i.b("
"),i.b(` +`+r),i.b("
"),i.fl()},partials:{},subs:{}});Ct["line-by-line-numbers"]=new $t.Template({code:function(t,e,r){var i=this;return i.b(r=r||""),i.b('
'),i.b(i.v(i.f("oldNumber",t,e,0))),i.b("
"),i.b(` +`+r),i.b('
'),i.b(i.v(i.f("newNumber",t,e,0))),i.b("
"),i.fl()},partials:{},subs:{}});Ct["side-by-side-file-diff"]=new $t.Template({code:function(t,e,r){var i=this;return i.b(r=r||""),i.b('
'),i.b(` +`+r),i.b('
'),i.b(` +`+r),i.b(" "),i.b(i.t(i.f("filePath",t,e,0))),i.b(` +`+r),i.b("
"),i.b(` +`+r),i.b('
'),i.b(` +`+r),i.b('
'),i.b(` +`+r),i.b('
'),i.b(` +`+r),i.b(' '),i.b(` +`+r),i.b(' '),i.b(` +`+r),i.b(" "),i.b(i.t(i.d("diffs.left",t,e,0))),i.b(` +`+r),i.b(" "),i.b(` +`+r),i.b("
"),i.b(` +`+r),i.b("
"),i.b(` +`+r),i.b("
"),i.b(` +`+r),i.b('
'),i.b(` +`+r),i.b('
'),i.b(` +`+r),i.b(' '),i.b(` +`+r),i.b(' '),i.b(` +`+r),i.b(" "),i.b(i.t(i.d("diffs.right",t,e,0))),i.b(` +`+r),i.b(" "),i.b(` +`+r),i.b("
"),i.b(` +`+r),i.b("
"),i.b(` +`+r),i.b("
"),i.b(` +`+r),i.b("
"),i.b(` +`+r),i.b("
"),i.fl()},partials:{},subs:{}});Ct["tag-file-added"]=new $t.Template({code:function(t,e,r){var i=this;return i.b(r=r||""),i.b('ADDED'),i.fl()},partials:{},subs:{}});Ct["tag-file-changed"]=new $t.Template({code:function(t,e,r){var i=this;return i.b(r=r||""),i.b('CHANGED'),i.fl()},partials:{},subs:{}});Ct["tag-file-deleted"]=new $t.Template({code:function(t,e,r){var i=this;return i.b(r=r||""),i.b('DELETED'),i.fl()},partials:{},subs:{}});Ct["tag-file-renamed"]=new $t.Template({code:function(t,e,r){var i=this;return i.b(r=r||""),i.b('RENAMED'),i.fl()},partials:{},subs:{}});var Zu=class{constructor({compiledTemplates:e={},rawTemplates:r={}}){let i=Object.entries(r).reduce((n,[s,a])=>{let o=s0.compile(a,{asString:!1});return Object.assign(Object.assign({},n),{[s]:o})},{});this.preCompiledTemplates=Object.assign(Object.assign(Object.assign({},Ct),e),i)}static compile(e){return s0.compile(e,{asString:!1})}render(e,r,i,n,s){let a=this.templateKey(e,r);try{return this.preCompiledTemplates[a].render(i,n,s)}catch(o){throw new Error(`Could not find template to render '${a}'`)}}template(e,r){return this.preCompiledTemplates[this.templateKey(e,r)]}templateKey(e,r){return`${e}-${r}`}};var H4=Object.assign(Object.assign(Object.assign({},e0),t0),{outputFormat:Z2.LINE_BY_LINE,drawFileList:!0});function Jh(t,e={}){let r=Object.assign(Object.assign({},H4),e),i=typeof t=="string"?iP(t,r):t,n=new Zu(r),{colorScheme:s}=r,a={colorScheme:s},o=r.drawFileList?new Xh(n,a).render(i):"",l=r.outputFormat==="side-by-side"?new Yu(n,r).render(i):new Wu(n,r).render(i);return o+l}var vP=mt(mP(),1);var za=require("obsidian"),a0=Ku.StateEffect.define();function Ks(t,e){let r=t.state,i=r.field(tp),n=r.field(Wr),s=r.doc.lineAt(e!=null?e:r.selection.main.head).number,a=qt.findHunk(s,n==null?void 0:n.hunks)[0];if(!a)return;let o=r.doc.line(Math.max(1,a.added.start)).from,l=i.has(o);return r.field(za.editorEditorField).dispatch({effects:a0.of({pos:o,add:!l})})}var tp=Ku.StateField.define({create:()=>new Set,update(t,e){let r=new Set;for(let i of e.effects)i.is(a0)&&(i.value.add?t.add(i.value.pos):t.delete(i.value.pos));for(let i of t)r.add(e.changes.mapPos(i));return r}}),wP=Ku.StateField.define({create:t=>gP(t),update(t,e){return e.docChanged||e.effects.some(r=>r.is(Ml)||r.is(a0))?gP(e.state):t},provide:t=>ep.showTooltip.computeN([t],e=>e.field(t))}),bP=ep.EditorView.baseTheme({".cm-tooltip.git-diff-tooltip":{"z-index":"var(--layer-popover)",backgroundColor:"var(--background-primary-alt)",border:"var(--border-width) solid var(--background-primary-alt)",borderRadius:"var(--radius-s)"},".cm-tooltip.git-diff-tooltip .tooltip-toolbar":{display:"flex",padding:"var(--size-2-1)"}});function gP(t){let e=t.field(Wr);return e?[...t.field(tp)].map(i=>{let n=t.doc.lineAt(i),s=qt.findHunk(n.number,e.hunks)[0];if(s)return{pos:i,above:!1,arrow:!1,strictSide:!0,clip:!1,create:()=>U4(s,t,i)}}).filter(i=>i!==void 0):[]}function U4(t,e,r){var g,v;let i=qt.createPatch("file",[t],"10064",!1).join(` +`)+` +`,n=Jh(i,{colorScheme:vP.ColorSchemeType.AUTO,diffStyle:"word",drawFileList:!1}),s=new DOMParser().parseFromString(n,"text/html").querySelector(".d2h-file-diff"),a=createDiv();a.addClass("tooltip-toolbar");let o=(b,_)=>{let C=createDiv();return(0,za.setIcon)(C,b),C.setAttr("aria-label",_),C.addClass("clickable-icon"),C},l=o("x","Close hunk"),c=o("plus","Stage hunk"),u=o("undo","Reset hunk");a.appendChild(l),a.appendChild(c),a.appendChild(u);let f=createDiv();f.appendChild(a),f.appendChild(s),f.addClass("git-diff-tooltip","git-diff");let d=e.field(za.editorEditorField);l.onclick=()=>{Ks(d,r)},c.onclick=()=>{let b=Et.plugin;b&&(b.promiseQueue.addTask(()=>b.hunkActions.stageHunk(r)),Ks(d,r))},u.onclick=()=>{let b=Et.plugin;b&&(b.hunkActions.resetHunk(r),Ks(d,r))};let h=(v=(g=Et.plugin)==null?void 0:g.app.workspace.getActiveViewOfType(za.MarkdownView))==null?void 0:v.scope,p=h==null?void 0:h.register(null,"Escape",(b,_)=>{Ks(d,r)});return{dom:f,destroy:()=>{p&&(h==null||h.unregister(p))},update:b=>{r=b.changes.mapPos(r)}}}function _P(t){let e=t.app;t.addCommand({id:"edit-gitignore",name:"Edit .gitignore",callback:async()=>{let r=t.gitManager.getRelativeVaultPath(".gitignore");await e.vault.adapter.exists(r)||await e.vault.adapter.write(r,"");let i=await e.vault.adapter.read(r),s=await new Mh(e,i).openAndGetReslt();s!==void 0&&(await e.vault.adapter.write(r,s),await t.refresh())}}),t.addCommand({id:"open-git-view",name:"Open source control view",callback:async()=>{var n;let r=e.workspace.getLeavesOfType(er.type),i;r.length===0?(i=(n=e.workspace.getRightLeaf(!1))!=null?n:e.workspace.getLeaf(),await i.setViewState({type:er.type})):i=r.first(),await e.workspace.revealLeaf(i),e.workspace.trigger("obsidian-git:refresh")}}),t.addCommand({id:"open-history-view",name:"Open history view",callback:async()=>{var n;let r=e.workspace.getLeavesOfType(Ei.type),i;r.length===0?(i=(n=e.workspace.getRightLeaf(!1))!=null?n:e.workspace.getLeaf(),await i.setViewState({type:Ei.type})):i=r.first(),await e.workspace.revealLeaf(i),e.workspace.trigger("obsidian-git:refresh")}}),t.addCommand({id:"open-diff-view",name:"Open diff view",checkCallback:r=>{let i=e.workspace.getActiveFile();if(r)return i!==null;{let n=t.gitManager.getRelativeRepoPath(i.path,!0);return t.tools.openDiff({aFile:n,aRef:""}),!0}}}),t.addCommand({id:"view-file-on-github",name:"Open file on GitHub",editorCallback:(r,{file:i})=>{if(i)return s2(r,i,t.gitManager)}}),t.addCommand({id:"view-history-on-github",name:"Open file history on GitHub",editorCallback:(r,{file:i})=>{if(i)return a2(i,t.gitManager)}}),t.addCommand({id:"pull",name:"Pull",callback:()=>t.promiseQueue.addTask(()=>t.pullChangesFromRemote())}),t.addCommand({id:"fetch",name:"Fetch",callback:()=>t.promiseQueue.addTask(()=>t.fetch())}),t.addCommand({id:"switch-to-remote-branch",name:"Switch to remote branch",callback:()=>t.promiseQueue.addTask(()=>t.switchRemoteBranch())}),t.addCommand({id:"add-to-gitignore",name:"Add file to .gitignore",checkCallback:r=>{let i=e.workspace.getActiveFile();return r?i!==null:(t.addFileToGitignore(i.path,i instanceof Xi.TFolder).catch(n=>t.displayError(n)),!0)}}),t.addCommand({id:"push",name:"Commit-and-sync",callback:()=>t.promiseQueue.addTask(()=>t.commitAndSync({fromAutoBackup:!1}))}),t.addCommand({id:"backup-and-close",name:"Commit-and-sync and then close Obsidian",callback:()=>t.promiseQueue.addTask(async()=>{await t.commitAndSync({fromAutoBackup:!1}),window.close()})}),t.addCommand({id:"commit-push-specified-message",name:"Commit-and-sync with specific message",callback:()=>t.promiseQueue.addTask(()=>t.commitAndSync({fromAutoBackup:!1,requestCustomMessage:!0}))}),t.addCommand({id:"commit",name:"Commit all changes",callback:()=>t.promiseQueue.addTask(()=>t.commit({fromAuto:!1,mode:"all"}))}),t.addCommand({id:"commit-specified-message",name:"Commit all changes with specific message",callback:()=>t.promiseQueue.addTask(()=>t.commit({fromAuto:!1,requestCustomMessage:!0,mode:"all"}))}),t.addCommand({id:"commit-smart",name:"Commit",callback:()=>t.promiseQueue.addTask(()=>t.commit({fromAuto:!1,requestCustomMessage:!1,mode:"smart"}))}),t.addCommand({id:"commit-staged",name:"Commit staged",callback:()=>t.promiseQueue.addTask(()=>t.commit({fromAuto:!1,requestCustomMessage:!1,mode:"staged"}))}),Xi.Platform.isDesktopApp&&t.addCommand({id:"commit-amend-staged-specified-message",name:"Amend staged",callback:()=>t.promiseQueue.addTask(()=>t.commit({fromAuto:!1,requestCustomMessage:!0,mode:"staged",amend:!0}))}),t.addCommand({id:"commit-smart-specified-message",name:"Commit with specific message",callback:()=>t.promiseQueue.addTask(()=>t.commit({fromAuto:!1,requestCustomMessage:!0,mode:"smart"}))}),t.addCommand({id:"commit-staged-specified-message",name:"Commit staged with specific message",callback:()=>t.promiseQueue.addTask(()=>t.commit({fromAuto:!1,requestCustomMessage:!0,mode:"staged"}))}),t.addCommand({id:"push2",name:"Push",callback:()=>t.promiseQueue.addTask(()=>t.push())}),t.addCommand({id:"stage-current-file",name:"Stage current file",checkCallback:r=>{let i=e.workspace.getActiveFile();return r?i!==null:(t.promiseQueue.addTask(()=>t.stageFile(i)),!0)}}),t.addCommand({id:"unstage-current-file",name:"Unstage current file",checkCallback:r=>{let i=e.workspace.getActiveFile();return r?i!==null:(t.promiseQueue.addTask(()=>t.unstageFile(i)),!0)}}),t.addCommand({id:"edit-remotes",name:"Edit remotes",callback:()=>t.editRemotes().catch(r=>t.displayError(r))}),t.addCommand({id:"remove-remote",name:"Remove remote",callback:()=>t.removeRemote().catch(r=>t.displayError(r))}),t.addCommand({id:"set-upstream-branch",name:"Set upstream branch",callback:()=>t.setUpstreamBranch().catch(r=>t.displayError(r))}),t.addCommand({id:"delete-repo",name:"CAUTION: Delete repository",callback:async()=>{await e.vault.adapter.exists(`${t.settings.basePath}/.git`)?await new at(t,{options:["NO","YES"],placeholder:"Do you really want to delete the repository (.git directory)? plugin action cannot be undone.",onlySelection:!0}).openAndGetResult()==="YES"&&(await e.vault.adapter.rmdir(`${t.settings.basePath}/.git`,!0),new Xi.Notice("Successfully deleted repository. Reloading plugin..."),t.unloadPlugin(),await t.init({fromReload:!0})):new Xi.Notice("No repository found")}}),t.addCommand({id:"init-repo",name:"Initialize a new repo",callback:()=>t.createNewRepo().catch(r=>t.displayError(r))}),t.addCommand({id:"clone-repo",name:"Clone an existing remote repo",callback:()=>t.cloneNewRepo().catch(r=>t.displayError(r))}),t.addCommand({id:"list-changed-files",name:"List changed files",callback:async()=>{if(await t.isAllInitialized())try{let r=await t.updateCachedStatus();if(r.changed.length+r.staged.length>500){t.displayError("Too many changes to display");return}new Ih(t,r.all).open()}catch(r){t.displayError(r)}}}),t.addCommand({id:"switch-branch",name:"Switch branch",callback:()=>{t.switchBranch().catch(r=>t.displayError(r))}}),t.addCommand({id:"create-branch",name:"Create new branch",callback:()=>{t.createBranch().catch(r=>t.displayError(r))}}),t.addCommand({id:"delete-branch",name:"Delete branch",callback:()=>{t.deleteBranch().catch(r=>t.displayError(r))}}),t.addCommand({id:"discard-all",name:"CAUTION: Discard all changes",callback:async()=>{let r=await t.discardAll();switch(r){case"discard":new Xi.Notice("Discarded all changes in tracked files.");break;case"delete":new Xi.Notice("Discarded all files.");break;case!1:break;default:zd(r)}}}),t.addCommand({id:"pause-automatic-routines",name:"Pause/Resume automatic routines",callback:()=>{let r=!t.localStorage.getPausedAutomatics();t.localStorage.setPausedAutomatics(r),r?(t.automaticsManager.unload(),new Xi.Notice("Paused automatic routines.")):(t.automaticsManager.reload("commit","push","pull"),new Xi.Notice("Resumed automatic routines."))}}),t.addCommand({id:"raw-command",name:"Raw command",checkCallback:r=>{let i=t.gitManager;return r?i instanceof ke:(t.tools.runRawCommand().catch(n=>t.displayError(n)),!0)}}),t.addCommand({id:"toggle-line-author-info",name:"Toggle line author information",callback:()=>{var r;return(r=t.settingsTab)==null?void 0:r.configureLineAuthorShowStatus(!t.settings.lineAuthor.show)}}),t.addCommand({id:"reset-hunk",name:"Reset hunk",editorCheckCallback(r,i,n){return r?t.settings.hunks.hunkCommands&&t.hunkActions.editor!==void 0:(t.hunkActions.resetHunk(),!0)}}),t.addCommand({id:"stage-hunk",name:"Stage hunk",editorCheckCallback:(r,i,n)=>r?t.settings.hunks.hunkCommands&&t.hunkActions.editor!==void 0:(t.promiseQueue.addTask(()=>t.hunkActions.stageHunk()),!0)}),t.addCommand({id:"preview-hunk",name:"Preview hunk",editorCheckCallback:(r,i,n)=>{if(r)return t.settings.hunks.hunkCommands&&t.hunkActions.editor!==void 0;let s=t.hunkActions.editor.editor;return Ks(s),!0}}),t.addCommand({id:"next-hunk",name:"Go to next hunk",editorCheckCallback:(r,i,n)=>r?t.settings.hunks.hunkCommands&&t.hunkActions.editor!==void 0:(t.hunkActions.goToHunk("next"),!0)}),t.addCommand({id:"prev-hunk",name:"Go to previous hunk",editorCheckCallback:(r,i,n)=>r?t.settings.hunks.hunkCommands&&t.hunkActions.editor!==void 0:(t.hunkActions.goToHunk("prev"),!0)})}m();var rp=class{constructor(e){this.plugin=e;this.prefix=this.plugin.manifest.id+":",this.app=e.app}migrate(){let e=["password","hostname","conflict","lastAutoPull","lastAutoBackup","lastAutoPush","gitPath","pluginDisabled"];for(let r of e){let i=localStorage.getItem(this.prefix+r);this.app.loadLocalStorage(this.prefix+r)==null&&i!=null&&i!=null&&(this.app.saveLocalStorage(this.prefix+r,i),localStorage.removeItem(this.prefix+r))}}getPassword(){return this.app.loadLocalStorage(this.prefix+"password")}setPassword(e){return this.app.saveLocalStorage(this.prefix+"password",e)}getUsername(){return this.app.loadLocalStorage(this.prefix+"username")}setUsername(e){return this.app.saveLocalStorage(this.prefix+"username",e)}getHostname(){return this.app.loadLocalStorage(this.prefix+"hostname")}setHostname(e){return this.app.saveLocalStorage(this.prefix+"hostname",e)}getConflict(){return this.app.loadLocalStorage(this.prefix+"conflict")=="true"}setConflict(e){return this.app.saveLocalStorage(this.prefix+"conflict",`${e}`)}getLastAutoPull(){return this.app.loadLocalStorage(this.prefix+"lastAutoPull")}setLastAutoPull(e){return this.app.saveLocalStorage(this.prefix+"lastAutoPull",e)}getLastAutoBackup(){return this.app.loadLocalStorage(this.prefix+"lastAutoBackup")}setLastAutoBackup(e){return this.app.saveLocalStorage(this.prefix+"lastAutoBackup",e)}getLastAutoPush(){return this.app.loadLocalStorage(this.prefix+"lastAutoPush")}setLastAutoPush(e){return this.app.saveLocalStorage(this.prefix+"lastAutoPush",e)}getGitPath(){return this.app.loadLocalStorage(this.prefix+"gitPath")}setGitPath(e){return this.app.saveLocalStorage(this.prefix+"gitPath",e)}getPATHPaths(){var e,r;return(r=(e=this.app.loadLocalStorage(this.prefix+"PATHPaths"))==null?void 0:e.split(":"))!=null?r:[]}setPATHPaths(e){return this.app.saveLocalStorage(this.prefix+"PATHPaths",e.join(":"))}getEnvVars(){var e;return JSON.parse((e=this.app.loadLocalStorage(this.prefix+"envVars"))!=null?e:"[]")}setEnvVars(e){return this.app.saveLocalStorage(this.prefix+"envVars",JSON.stringify(e))}getPluginDisabled(){return this.app.loadLocalStorage(this.prefix+"pluginDisabled")=="true"}setPluginDisabled(e){return this.app.saveLocalStorage(this.prefix+"pluginDisabled",`${e}`)}getPausedAutomatics(){return this.app.loadLocalStorage(this.prefix+"pausedAutomatics")=="true"}setPausedAutomatics(e){return this.app.saveLocalStorage(this.prefix+"pausedAutomatics",`${e}`)}getGutterSpacingFallbackLength(){var e;return(e=this.app.loadLocalStorage(this.prefix+"gutterSpacingFallbackLength"))!=null?e:5}setGutterSpacingFallbackLength(e){return this.app.saveLocalStorage(this.prefix+"gutterSpacingFallbackLength",e)}};m();var jl=require("obsidian");var Xu=class{constructor(e){this.plugin=e}async hasTooBigFiles(e){let r=await this.plugin.gitManager.branchInfo(),i=r.tracking?Vs(r.tracking)[0]:null;if(!i)return!1;let n=await this.plugin.gitManager.getRemoteUrl(i);if(n!=null&&n.includes("github.com")){let s=[],a=this.plugin.gitManager;for(let o of e){let l=this.plugin.app.vault.getAbstractFileByPath(o.vaultPath),c=!1;if(l instanceof jl.TFile)l.stat.size>=1e8&&(c=!0);else{let u=await this.plugin.app.vault.adapter.stat(o.vaultPath);u&&u.size>=1e8&&(c=!0)}if(c){let u=!1;a instanceof ke&&(u=await a.isFileTrackedByLFS(o.path)),u||s.push(o)}}if(s.length>0)return this.plugin.displayError(`Aborted commit, because the following files are too big: +- ${s.map(o=>o.vaultPath).join(` +- `)} +Please remove them or add to .gitignore.`),!0}return!1}async writeAndOpenFile(e){e!==void 0&&await this.plugin.app.vault.adapter.write(ol,e);let r=!1;this.plugin.app.workspace.iterateAllLeaves(i=>{i.getDisplayText()!=""&&ol.startsWith(i.getDisplayText())&&(r=!0)}),r||await this.plugin.app.workspace.openLinkText(ol,"/",!0)}openDiff({aFile:e,bFile:r,aRef:i,bRef:n,event:s}){var l,c;let a=this.plugin.settings.diffStyle;jl.Platform.isMobileApp&&(a="git_unified");let o={aFile:e,bFile:r!=null?r:e,aRef:i,bRef:n};a=="split"?(l=Yi(this.plugin.app,s))==null||l.setViewState({type:Hs.type,active:!0,state:o}):a=="git_unified"&&((c=Yi(this.plugin.app,s))==null||c.setViewState({type:Us.type,active:!0,state:o}))}async runRawCommand(){let e=this.plugin.gitManager;if(!(e instanceof ke))return;let i=await new at(this.plugin,{placeholder:"push origin master",allowEmpty:!1}).openAndGetResult();i!==void 0&&this.plugin.promiseQueue.addTask(async()=>{let n=new jl.Notice(`Running '${i}'...`,999999);try{let s=await e.rawCommand(i);s?(n.setMessage(s),window.setTimeout(()=>n.hide(),5e3)):n.hide()}catch(s){throw n.hide(),s}})}};m();var ip=require("obsidian");var Wa=class extends ip.ItemView{constructor(r,i){super(r);this.plugin=i;this.gettingDiff=!1;this.parser=new DOMParser,this.navigation=!0,this.contentEl.addClass("git-diff"),this.gitRefreshRef=this.app.workspace.on("obsidian-git:status-changed",()=>{this.refresh().catch(console.error)})}getViewType(){return Us.type}getDisplayText(){var r;if(((r=this.state)==null?void 0:r.bFile)!=null){let i=this.state.bFile.split("/").last();return i!=null&&i.endsWith(".md")&&(i=i.slice(0,-3)),`Diff: ${i}`}return Us.name}getIcon(){return Us.icon}async setState(r,i){this.state=r,ip.Platform.isMobile&&(this.leaf.view.titleEl.textContent=this.getDisplayText()),await this.refresh()}getState(){return this.state}onClose(){return this.app.workspace.offref(this.gitRefreshRef),this.app.workspace.offref(this.gitViewRefreshRef),super.onClose()}async onOpen(){return await this.refresh(),super.onOpen()}async refresh(){var r;if((r=this.state)!=null&&r.bFile&&!this.gettingDiff&&this.plugin.gitManager){this.gettingDiff=!0;try{let i=await this.plugin.gitManager.getDiffString(this.state.bFile,this.state.aRef=="HEAD",this.state.bRef);this.contentEl.empty();let n=this.plugin.gitManager.getRelativeVaultPath(this.state.bFile);if(!i){if(this.plugin.gitManager instanceof ke&&await this.plugin.gitManager.isTracked(this.state.bFile))i=[`--- ${this.state.aFile}`,`+++ ${this.state.bFile}`,""].join(` +`);else if(await this.app.vault.adapter.exists(n)){let s=await this.app.vault.adapter.read(n);i=[...`--- /dev/null ++++ ${this.state.bFile} +@@ -0,0 +1,${s.split(` +`).length} @@`.split(` +`),...s.split(` +`).map(o=>`+${o}`)].join(` +`)}}if(i){let s=this.parser.parseFromString(Jh(i),"text/html").querySelector(".d2h-file-diff");this.contentEl.append(s)}else{let s=this.contentEl.createDiv({cls:"obsidian-git-center"});s.createSpan({text:"\u26A0\uFE0F",attr:{style:"font-size: 2em"}}),s.createEl("br"),s.createSpan({text:"File not found: "+this.state.bFile})}}finally{this.gettingDiff=!1}}}};m();var ss=require("obsidian");var zl=require("@codemirror/commands");var sp=require("@codemirror/search"),Vl=require("@codemirror/state"),Qi=require("@codemirror/view");m();var np=require("obsidian"),o0=require("@codemirror/view");function G4(t){return t.selection.ranges.filter(e=>!e.empty).map(e=>t.sliceDoc(e.from,e.to)).join(t.lineBreak)}function j4(t){t.dispatch({...t.state.replaceSelection(""),userEvent:"delete.cut"})}function yP(t,e){t.dispatch({...t.state.replaceSelection(e),scrollIntoView:!0,userEvent:"input.paste"})}async function xP(t){if(!t&&navigator.clipboard.read){let e=await navigator.clipboard.read();for(let r of e)if(r.types.includes("text/html")){let i=await(await r.getType("text/html")).text();return(0,np.htmlToMarkdown)(i)}}return navigator.clipboard.readText()}var EP=o0.EditorView.domEventHandlers({contextmenu(t,e){t.preventDefault();let r=G4(e.state),i=!e.state.readOnly&&e.state.facet(o0.EditorView.editable),n=np.Menu.forEvent(t);return n.addItem(s=>s.setTitle("Cut").setIcon("scissors").setDisabled(!i||r.length===0).onClick(async()=>{await navigator.clipboard.writeText(r),j4(e)})),n.addItem(s=>s.setTitle("Copy").setIcon("copy").setDisabled(r.length===0).onClick(()=>navigator.clipboard.writeText(r))),n.addItem(s=>s.setTitle("Paste").setIcon("clipboard-paste").setDisabled(!i).onClick(async()=>yP(e,await xP(!1)))),n.addItem(s=>s.setTitle("Paste as plain text").setIcon("clipboard-type").setDisabled(!i).onClick(async()=>yP(e,await xP(!0)))),n.addItem(s=>s.setTitle("Select all").setIcon("scan").onClick(()=>e.dispatch({selection:{anchor:0,head:e.state.doc.length}}))),n.showAtMouseEvent(t),!0}});var SP=Qi.EditorView.theme({"& .cm-content":{caretColor:"transparent !important"},"&.cm-focused .cm-cursor, & .cm-dropCursor":{display:"none !important"}}),V4=10;function z4(t,e){let r=Number.isInteger(t)&&t>0?t:tt.diffTimeout;return e?r:r*V4}var qa=class extends ss.ItemView{constructor(r,i){super(r);this.plugin=i;this.refreshing=!1;this.ignoreNextModification=!1;this.navigation=!0,this.registerEvent(this.app.workspace.on("obsidian-git:status-changed",()=>{this.mergeView?this.updateRefEditors().catch(console.error):this.createMergeView().catch(console.error)})),this.intervalRef=window.setInterval(()=>{this.mergeView&&this.updateRefEditors().catch(console.error)},30*1e3),this.registerEvent(this.app.vault.on("modify",n=>{this.state.bRef==null&&n.path===this.state.bFile&&(this.ignoreNextModification?this.ignoreNextModification=!1:this.updateModifiableEditor().catch(console.error))})),this.registerEvent(this.app.vault.on("delete",n=>{this.state.bRef==null&&n.path===this.state.bFile&&this.createMergeView().catch(console.error)})),this.registerEvent(this.app.vault.on("create",n=>{this.state.bRef==null&&n.path===this.state.bFile&&this.createMergeView().catch(console.error)})),this.registerEvent(this.app.vault.on("rename",(n,s)=>{this.state.bRef==null&&(n.path===this.state.bFile||s===this.state.bFile)&&this.createMergeView().catch(console.error)})),this.fileSaveDebouncer=(0,ss.debounce)(n=>{let s=this.state.bFile;s&&(this.ignoreNextModification=!0,this.plugin.app.vault.adapter.write(this.plugin.gitManager.getRelativeVaultPath(s),n).catch(a=>this.plugin.displayError(a)))},1e3,!1)}getViewType(){return Hs.type}getDisplayText(){var r;if(((r=this.state)==null?void 0:r.bFile)!=null){let i=this.state.bFile.split("/").last();i!=null&&i.endsWith(".md")&&(i=i.slice(0,-3));let n;return this.state.bRef==null?n=" (Working Tree)":this.state.bRef==""?n=" (Index)":n="("+this.state.bRef.substring(0,7)+")",`Diff: ${i} ${n}`}return Hs.name}getIcon(){return Hs.icon}async setState(r,i){this.state=r,ss.Platform.isMobile&&(this.leaf.view.titleEl.textContent=this.getDisplayText()),await super.setState(r,i),await this.createMergeView()}getState(){return this.state}onClose(){return window.clearInterval(this.intervalRef),super.onClose()}async onOpen(){return await this.createMergeView(),super.onOpen()}async gitShow(r,i){try{return await this.plugin.gitManager.show(r,i,!1)}catch(n){if(n instanceof jr&&(n.message.includes("does not exist")||n.message.includes("unknown revision or path")||n.message.includes("exists on disk, but not in")||n.message.includes("fatal: bad object")))return n.message.includes("fatal: bad object")&&this.plugin.displayError(n.message),"";throw n}}async bShouldBeEditable(){if(this.state.bRef!=null)return!1;let r=this.plugin.gitManager.getRelativeVaultPath(this.state.bFile);return await this.app.vault.adapter.exists(r)}async updateModifiableEditor(){if(!this.mergeView||this.refreshing)return;let r=this.mergeView.b;this.refreshing=!0;let i=await this.app.vault.adapter.read(this.state.bFile);if(i!=r.state.doc.toString()){let n=r.state.update({changes:{from:0,to:r.state.doc.length,insert:i},annotations:[Vl.Transaction.remote.of(!0)]});r.dispatch(n)}this.refreshing=!1}async updateRefEditors(){if(!this.mergeView||this.refreshing)return;let r=this.mergeView.a,i=this.mergeView.b;this.refreshing=!0;let n=await this.gitShow(this.state.aRef,this.state.aFile),s;if(this.state.bRef!=null&&(s=await this.gitShow(this.state.bRef,this.state.bFile)),n!=r.state.doc.toString()){let a=r.state.update({changes:{from:0,to:r.state.doc.length,insert:n}});r.dispatch(a)}if(s!=null&&s!=i.state.doc.toString()){let a=i.state.update({changes:{from:0,to:i.state.doc.length,insert:s}});i.dispatch(a)}this.refreshing=!1}renderButtons(r){let i=r.createDiv(),n=i.createDiv();if(n.addClass("clickable-icon"),n.setAttr("aria-label",this.state.bRef==null?"Stage hunk":"Unstage hunk"),(0,ss.setIcon)(n,this.state.bRef==null?"plus":"minus"),n.onmousedown=async s=>{var p;let a=this.mergeView.b,o=this.mergeView.a,l=Lw(a.state),c=(p=i.parentElement)==null?void 0:p.indexOf(i),u=l.chunks[c],f=Hw(u,o.state.doc,a.state.doc),d=Bw(this.mergeView.a.state.doc.toString(),this.mergeView.b.state.doc.toString(),[f])[0],h=qt.createPatch(this.state.bFile,[d],"100644",this.state.bRef!=null).join(` +`)+` +`;await this.plugin.gitManager.applyPatch(h),this.plugin.app.workspace.trigger("obsidian-git:refresh")},this.state.bRef==null){let s=i.createDiv();s.addClass("clickable-icon"),s.setAttr("aria-label","Reset hunk"),(0,ss.setIcon)(s,"undo"),s.onmousedown=a=>{var d;let o=this.mergeView.a,l=this.mergeView.b,c=Lw(l.state),u=(d=i.parentElement)==null?void 0:d.indexOf(i),f=c.chunks[u];if(f){let h=f.fromA,p=f.toA,g=f.fromB,v=f.toB,b=o.state.sliceDoc(h,Math.max(h,p-1));h!=p&&v<=l.state.doc.length&&(b+=o.state.lineBreak),l.dispatch({changes:{from:g,to:Math.min(l.state.doc.length,v),insert:b},userEvent:"revert"})}}}return i.onmousedown=s=>{s.preventDefault(),s.stopPropagation()},i}async createMergeView(){var r,i,n;if((r=this.state)!=null&&r.aFile&&((i=this.state)!=null&&i.bFile)&&!this.refreshing&&this.plugin.gitManager){this.refreshing=!0,(n=this.mergeView)==null||n.destroy();let s=this.containerEl.children[1];s.empty(),this.contentEl.addClass("git-split-diff-view","git-diff"),this.bIsEditable=await this.bShouldBeEditable();let a=await this.gitShow(this.state.aRef,this.state.aFile),o;if(this.state.bRef!=null)o=await this.gitShow(this.state.bRef,this.state.bFile);else{let p=this.plugin.gitManager.getRelativeVaultPath(this.state.bFile);await this.app.vault.adapter.exists(p)?o=await this.app.vault.adapter.read(p):o=""}let l=[(0,Qi.lineNumbers)(),(0,sp.highlightSelectionMatches)(),(0,Qi.drawSelection)(),Qi.keymap.of([...zl.standardKeymap,zl.indentWithTab]),(0,zl.history)(),(0,sp.search)(),Qi.EditorView.lineWrapping,EP],c=Qi.ViewPlugin.define(p=>({update:g=>{if(g.docChanged&&!g.transactions.some(v=>v.annotation(Vl.Transaction.remote))){let v=p.state.doc.toString();this.fileSaveDebouncer(v)}}})),u={doc:a,extensions:[...l,Vl.EditorState.readOnly.of(!0),SP]},f=[...l];this.bIsEditable?f.push(c):f.push(Vl.EditorState.readOnly.of(!0),SP);let d={doc:o,extensions:f};s.addClasses(["cm-s-obsidian","mod-cm6","markdown-source-view","cm-content"]);let h=this.plugin.gitManager instanceof ke&&(this.state.bRef===void 0||this.state.bRef==="");this.mergeView=new Gh({b:d,a:u,collapseUnchanged:{minSize:6,margin:4},renderRevertControl:h?()=>this.renderButtons(s):void 0,revertControls:h?"a-to-b":void 0,diffConfig:{timeout:z4(this.plugin.settings.diffTimeout,this.bIsEditable)},parent:s}),this.refreshing=!1}}};m();var p$=require("obsidian");m();m();m();var kP,CP,AP;typeof window!="undefined"&&((AP=(CP=(kP=window.__svelte)!=null?kP:window.__svelte={}).v)!=null?AP:CP.v=new Set).add("5");m();m();m();var as={};var Qe=Symbol("uninitialized"),Fi=Symbol("filename");var ap="http://www.w3.org/1999/xhtml";m();m();m();m();var op=!0;m();var O=!1;m();var os=Array.isArray,TP=Array.prototype.indexOf,Xs=Array.prototype.includes,Wl=Array.from,l0=Object.keys,fr=Object.defineProperty,qr=Object.getOwnPropertyDescriptor,c0=Object.getOwnPropertyDescriptors,u0=Object.prototype,PP=Array.prototype,ql=Object.getPrototypeOf,f0=Object.isExtensible;function d0(t){return typeof t=="function"}var dr=()=>{};function lp(t){for(var e=0;e{t=i,e=n});return{promise:r,resolve:t,reject:e}}m();m();var rr=Symbol("$state"),Qu=Symbol("legacy props"),$P=Symbol(""),up=Symbol("proxy path"),fp=Symbol("attributes"),Ju=Symbol("class"),h0=Symbol("style"),ef=Symbol("text"),Ya=Symbol("form reset"),p0=Symbol("hmr anchor"),ls=new class extends Error{constructor(){super(...arguments);Ue(this,"name","StaleReactionError");Ue(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}},RP,m0=!!((RP=globalThis.document)!=null&&RP.contentType)&&globalThis.document.contentType.includes("xml");var Yl=3,Ii=8;m();m();function FP(t){if(O){let e=new Error(`invariant_violation +An invariant violation occurred, meaning Svelte's internal assumptions were flawed. This is a bug in Svelte, not your app \u2014 please open an issue at https://github.com/sveltejs/svelte, citing the following message: "${t}" +https://svelte.dev/e/invariant_violation`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/invariant_violation")}function dp(t){if(O){let e=new Error(`lifecycle_outside_component +\`${t}(...)\` can only be used during component initialisation +https://svelte.dev/e/lifecycle_outside_component`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function MP(){if(O){let t=new Error("async_derived_orphan\nCannot create a `$derived(...)` with an `await` expression outside of an effect tree\nhttps://svelte.dev/e/async_derived_orphan");throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/async_derived_orphan")}function g0(){if(O){let t=new Error("bind_invalid_checkbox_value\nUsing `bind:value` together with a checkbox input is not allowed. Use `bind:checked` instead\nhttps://svelte.dev/e/bind_invalid_checkbox_value");throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/bind_invalid_checkbox_value")}function DP(){if(O){let t=new Error(`derived_references_self +A derived value cannot reference itself recursively +https://svelte.dev/e/derived_references_self`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/derived_references_self")}function v0(t,e,r){if(O){let i=new Error(`each_key_duplicate +${r?`Keyed each block has duplicate key \`${r}\` at indexes ${t} and ${e}`:`Keyed each block has duplicate key at indexes ${t} and ${e}`} +https://svelte.dev/e/each_key_duplicate`);throw i.name="Svelte error",i}else throw new Error("https://svelte.dev/e/each_key_duplicate")}function OP(t,e,r){if(O){let i=new Error(`each_key_volatile +Keyed each block has key that is not idempotent \u2014 the key for item at index ${t} was \`${e}\` but is now \`${r}\`. Keys must be the same each time for a given item +https://svelte.dev/e/each_key_volatile`);throw i.name="Svelte error",i}else throw new Error("https://svelte.dev/e/each_key_volatile")}function LP(t){if(O){let e=new Error(`effect_in_teardown +\`${t}\` cannot be used inside an effect cleanup function +https://svelte.dev/e/effect_in_teardown`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/effect_in_teardown")}function NP(){if(O){let t=new Error("effect_in_unowned_derived\nEffect cannot be created inside a `$derived` value that was not itself created inside an effect\nhttps://svelte.dev/e/effect_in_unowned_derived");throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function BP(t){if(O){let e=new Error(`effect_orphan +\`${t}\` can only be used inside an effect (e.g. during component initialisation) +https://svelte.dev/e/effect_orphan`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/effect_orphan")}function HP(){if(O){let t=new Error(`effect_update_depth_exceeded +Maximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state +https://svelte.dev/e/effect_update_depth_exceeded`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function UP(){if(O){let t=new Error(`hydration_failed +Failed to hydrate the application +https://svelte.dev/e/hydration_failed`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/hydration_failed")}function GP(t){if(O){let e=new Error(`props_invalid_value +Cannot do \`bind:${t}={undefined}\` when \`${t}\` has a fallback value +https://svelte.dev/e/props_invalid_value`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/props_invalid_value")}function jP(t){if(O){let e=new Error(`rune_outside_svelte +The \`${t}\` rune is only available inside \`.svelte\` and \`.svelte.js/ts\` files +https://svelte.dev/e/rune_outside_svelte`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/rune_outside_svelte")}function VP(){if(O){let t=new Error("state_descriptors_fixed\nProperty descriptors defined on `$state` objects must contain `value` and always be `enumerable`, `configurable` and `writable`.\nhttps://svelte.dev/e/state_descriptors_fixed");throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function zP(){if(O){let t=new Error("state_prototype_fixed\nCannot set prototype of `$state` object\nhttps://svelte.dev/e/state_prototype_fixed");throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/state_prototype_fixed")}function WP(){if(O){let t=new Error("state_unsafe_mutation\nUpdating state inside `$derived(...)`, `$inspect(...)` or a template expression is forbidden. If the value should not be reactive, declare it without `$state`\nhttps://svelte.dev/e/state_unsafe_mutation");throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function qP(){if(O){let t=new Error("svelte_boundary_reset_onerror\nA `` `reset` function cannot be called while an error is still being handled\nhttps://svelte.dev/e/svelte_boundary_reset_onerror");throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}m();m();m();var Rn="font-weight: bold",$n="font-weight: normal";function YP(t){O?console.warn(`%c[svelte] await_reactivity_loss +%cDetected reactivity loss when reading \`${t}\`. This happens when state is read in an async function after an earlier \`await\` +https://svelte.dev/e/await_reactivity_loss`,Rn,$n):console.warn("https://svelte.dev/e/await_reactivity_loss")}function ZP(t,e){O?console.warn(`%c[svelte] await_waterfall +%cAn async derived, \`${t}\` (${e}) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app +https://svelte.dev/e/await_waterfall`,Rn,$n):console.warn("https://svelte.dev/e/await_waterfall")}function KP(){O?console.warn(`%c[svelte] derived_inert +%cReading a derived belonging to a now-destroyed effect may result in stale values +https://svelte.dev/e/derived_inert`,Rn,$n):console.warn("https://svelte.dev/e/derived_inert")}function XP(t,e,r){O?console.warn(`%c[svelte] hydration_attribute_changed +%cThe \`${t}\` attribute on \`${e}\` changed its value between server and client renders. The client value, \`${r}\`, will be ignored in favour of the server value +https://svelte.dev/e/hydration_attribute_changed`,Rn,$n):console.warn("https://svelte.dev/e/hydration_attribute_changed")}function Za(t){O?console.warn(`%c[svelte] hydration_mismatch +%c${t?`Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near ${t}`:"Hydration failed because the initial UI does not match what was rendered on the server"} +https://svelte.dev/e/hydration_mismatch`,Rn,$n):console.warn("https://svelte.dev/e/hydration_mismatch")}function QP(){O?console.warn(`%c[svelte] lifecycle_double_unmount +%cTried to unmount a component that was not mounted +https://svelte.dev/e/lifecycle_double_unmount`,Rn,$n):console.warn("https://svelte.dev/e/lifecycle_double_unmount")}function hp(t){O?console.warn(`%c[svelte] state_proxy_equality_mismatch +%cReactive \`$state(...)\` proxies and the values they proxy have different identities. Because of this, comparisons with \`${t}\` will produce unexpected results +https://svelte.dev/e/state_proxy_equality_mismatch`,Rn,$n):console.warn("https://svelte.dev/e/state_proxy_equality_mismatch")}function JP(){O?console.warn(`%c[svelte] state_proxy_unmount +%cTried to unmount a state proxy, rather than a component +https://svelte.dev/e/state_proxy_unmount`,Rn,$n):console.warn("https://svelte.dev/e/state_proxy_unmount")}function eR(){O?console.warn("%c[svelte] svelte_boundary_reset_noop\n%cA `` `reset` function only resets the boundary the first time it is called\nhttps://svelte.dev/e/svelte_boundary_reset_noop",Rn,$n):console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}function tR(t){O?console.warn(`%c[svelte] transition_slide_display +%cThe \`slide\` transition does not work correctly for elements with \`display: ${t}\` +https://svelte.dev/e/transition_slide_display`,Rn,$n):console.warn("https://svelte.dev/e/transition_slide_display")}var se=!1;function Lt(t){se=t}var we;function We(t){if(t===null)throw Za(),as;return we=t}function hr(){return We(nr(we))}function G(t){if(se){if(nr(we)!==null)throw Za(),as;we=t}}function Ka(t=1){if(se){for(var e=t,r=we;e--;)r=nr(r);we=r}}function Fn(t=!0){for(var e=0,r=we;;){if(r.nodeType===Ii){var i=r.data;if(i==="]"){if(e===0)return r;e-=1}else(i==="["||i==="[!"||i[0]==="["&&!isNaN(Number(i.slice(1))))&&(e+=1)}var n=nr(r);t&&r.remove(),r=n}}function rf(t){if(!t||t.nodeType!==Ii)throw Za(),as;return t.data}m();m();m();m();function pp(t){return t===this.v}function w0(t,e){return t!=t?e==e:t!==e||t!==null&&typeof t=="object"||typeof t=="function"}function mp(t){return!w0(t,this.v)}m();var Ft=!1,cs=!1,Ji=!1;m();m();m();var nf=null;function pr(t,e){return t.label=e,vp(t.v,e),t}function vp(t,e){var r;return(r=t==null?void 0:t[up])==null||r.call(t,e),t}m();function en(t){let e=new Error,r=q4();return r.length===0?null:(r.unshift(` +`),fr(e,"stack",{value:r.join(` +`)}),fr(e,"name",{value:t}),e)}function q4(){let t=Error.stackTraceLimit;Error.stackTraceLimit=1/0;let e=new Error().stack;if(Error.stackTraceLimit=t,!e)return[];let r=e.split(` +`),i=[];for(let n=0;n{e===Xa&&nR()})}Xa.push(t)}function sR(){for(;Xa.length>0;)nR()}m();var _0=new WeakMap;function bp(t){var e=ee;if(e===null)return oe.f|=8388608,t;if(O&&t instanceof Error&&!_0.has(t)&&_0.set(t,Y4(t,e)),(e.f&32768)===0&&(e.f&4)===0)throw O&&!e.parent&&t instanceof Error&&aR(t),t;nn(t,e)}function nn(t,e){if(!(e!==null&&(e.f&16384)!==0)){for(;e!==null;){if((e.f&128)!==0){if((e.f&32768)===0)throw t;try{e.b.error(t);return}catch(r){t=r}}e=e.parent}throw O&&t instanceof Error&&aR(t),t}}function Y4(t,e){var a,o,l;let r=qr(t,"message");if(!(r&&!r.configurable)){for(var i=af?" ":" ",n=` +${i}in ${((a=e.fn)==null?void 0:a.name)||""}`,s=e.ctx;s!==null;)n+=` +${i}in ${(o=s.function)==null?void 0:o[Fi].split("/").pop()}`,s=s.p;return{message:t.message+` +${n} +`,stack:(l=t.stack)==null?void 0:l.split(` +`).filter(c=>!c.includes("svelte/src/internal")).join(` +`)}}}function aR(t){let e=_0.get(t);e&&(fr(t,"message",{value:e.message}),fr(t,"stack",{value:e.stack}))}m();m();var Z4=-7169;function Ge(t,e){t.f=t.f&Z4|e}function Ql(t){(t.f&512)!==0||t.deps===null?Ge(t,1024):Ge(t,4096)}function oR(t){if(t!==null)for(let e of t)(e.f&2)===0||(e.f&65536)===0||(e.f^=65536,oR(e.deps))}function _p(t,e,r){(t.f&2048)!==0?e.add(t):(t.f&4096)!==0&&r.add(t),oR(t.deps),Ge(t,1024)}m();m();m();var lR=!1,yp=!1;function y0(t){var e=yp;try{return yp=!1,[t(),yp]}finally{yp=e}}m();m();m();m();function x0(t){se&&or(t)!==null&&ec(t)}var cR=!1;function E0(){cR||(cR=!0,document.addEventListener("reset",t=>{Promise.resolve().then(()=>{var e;if(!t.defaultPrevented)for(let r of t.target.elements)(e=r[Ya])==null||e.call(r)})},{capture:!0}))}function Zr(t){var e=oe,r=ee;Ht(null),Ut(null);try{return t()}finally{Ht(e),Ut(r)}}function S0(t,e,r,i=r){t.addEventListener(e,()=>Zr(r));let n=t[Ya];n?t[Ya]=()=>{n(),i(!0)}:t[Ya]=()=>i(!0),E0()}m();m();m();function uR(t){let e=0,r=gr(0),i;return O&&pr(r,"createSubscriber version"),()=>{Qs()&&(F(r),lr(()=>(e===0&&(i=Je(()=>t(()=>to(r)))),e+=1,()=>{At(()=>{e-=1,e===0&&(i==null||i(),i=void 0,to(r))})})))}}var X4=589824;function R0(t,e,r,i){new k0(t,e,r,i)}var li,of,Oi,ro,Kr,Li,Ar,ci,ds,io,Js,tc,lf,cf,Dn,Sp,qe,dR,hR,C0,pR,A0,xp,Ep,T0,P0,k0=class{constructor(e,r,i,n){ge(this,qe);Ue(this,"parent");Ue(this,"is_pending",!1);Ue(this,"transform_error");ge(this,li);ge(this,of,se?we:null);ge(this,Oi);ge(this,ro);ge(this,Kr);ge(this,Li,null);ge(this,Ar,null);ge(this,ci,null);ge(this,ds,null);ge(this,io,0);ge(this,Js,0);ge(this,tc,!1);ge(this,lf,new Set);ge(this,cf,new Set);ge(this,Dn,null);ge(this,Sp,uR(()=>(de(this,Dn,gr($(this,io))),O&&pr($(this,Dn),"$effect.pending()"),()=>{de(this,Dn,null)})));var s,a;de(this,li,e),de(this,Oi,r),de(this,ro,o=>{var l=ee;l.b=this,l.f|=128,i(o)}),this.parent=ee.b,this.transform_error=(a=n!=null?n:(s=this.parent)==null?void 0:s.transform_error)!=null?a:(o=>o),de(this,Kr,fi(()=>{if(se){let o=$(this,of);hr();let l=o.data==="[!";if(o.data.startsWith("[?")){let u=JSON.parse(o.data.slice("[?".length));Se(this,qe,hR).call(this,u)}else l?Se(this,qe,pR).call(this):Se(this,qe,dR).call(this)}else Se(this,qe,A0).call(this)},X4)),se&&de(this,li,we)}defer_effect(e){_p(e,$(this,lf),$(this,cf))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!$(this,Oi).pending}update_pending_count(e,r){Se(this,qe,T0).call(this,e,r),de(this,io,$(this,io)+e),!(!$(this,Dn)||$(this,tc))&&(de(this,tc,!0),At(()=>{de(this,tc,!1),$(this,Dn)&&sn($(this,Dn),$(this,io))}))}get_effect_pending(){return $(this,Sp).call(this),F($(this,Dn))}error(e){var r;if(!$(this,Oi).onerror&&!$(this,Oi).failed)throw e;(r=le)!=null&&r.is_fork?($(this,Li)&&le.skip_effect($(this,Li)),$(this,Ar)&&le.skip_effect($(this,Ar)),$(this,ci)&&le.skip_effect($(this,ci)),le.oncommit(()=>{Se(this,qe,P0).call(this,e)})):Se(this,qe,P0).call(this,e)}};li=new WeakMap,of=new WeakMap,Oi=new WeakMap,ro=new WeakMap,Kr=new WeakMap,Li=new WeakMap,Ar=new WeakMap,ci=new WeakMap,ds=new WeakMap,io=new WeakMap,Js=new WeakMap,tc=new WeakMap,lf=new WeakMap,cf=new WeakMap,Dn=new WeakMap,Sp=new WeakMap,qe=new WeakSet,dR=function(){try{de(this,Li,Gt(()=>$(this,ro).call(this,$(this,li))))}catch(e){this.error(e)}},hR=function(e){let r=$(this,Oi).failed,{reset:i,invoke_onerror:n}=Se(this,qe,C0).call(this,e);At(n),r&&de(this,ci,Gt(()=>{r($(this,li),()=>e,()=>i)}))},C0=function(e){var r=!1,i=!1;let n=()=>{if(r){eR();return}r=!0,i&&qP(),$(this,ci)!==null&&On($(this,ci),()=>{de(this,ci,null)}),Se(this,qe,Ep).call(this,()=>{Se(this,qe,A0).call(this)})};return{reset:n,invoke_onerror:()=>{var a,o;try{i=!0,(o=(a=$(this,Oi)).onerror)==null||o.call(a,e,n),i=!1}catch(l){nn(l,$(this,Kr)&&$(this,Kr).parent)}}}},pR=function(){let e=$(this,Oi).pending;e&&(this.is_pending=!0,de(this,Ar,Gt(()=>e($(this,li)))),At(()=>{var r=de(this,ds,document.createDocumentFragment()),i=jt();r.append(i),de(this,Li,Se(this,qe,Ep).call(this,()=>Gt(()=>$(this,ro).call(this,i)))),$(this,Js)===0&&($(this,li).before(r),de(this,ds,null),On($(this,Ar),()=>{de(this,Ar,null)}),Se(this,qe,xp).call(this,le))}))},A0=function(){try{if(this.is_pending=this.has_pending_snippet(),de(this,Js,0),de(this,io,0),de(this,Li,Gt(()=>{$(this,ro).call(this,$(this,li))})),$(this,Js)>0){var e=de(this,ds,document.createDocumentFragment());rc($(this,Li),e);let r=$(this,Oi).pending;de(this,Ar,Gt(()=>r($(this,li))))}else Se(this,qe,xp).call(this,le)}catch(r){this.error(r)}},xp=function(e){this.is_pending=!1,e.transfer_effects($(this,lf),$(this,cf))},Ep=function(e){var r=ee,i=oe,n=Ee;Ut($(this,Kr)),Ht($(this,Kr)),us($(this,Kr).ctx);try{return ui.ensure(),e()}catch(s){return bp(s),null}finally{Ut(r),Ht(i),us(n)}},T0=function(e,r){var i;if(!this.has_pending_snippet()){this.parent&&Se(i=this.parent,qe,T0).call(i,e,r);return}de(this,Js,$(this,Js)+e),$(this,Js)===0&&(Se(this,qe,xp).call(this,r),$(this,Ar)&&On($(this,Ar),()=>{de(this,Ar,null)}),$(this,ds)&&($(this,li).before($(this,ds)),de(this,ds,null)))},P0=function(e){$(this,Li)&&(_t($(this,Li)),de(this,Li,null)),$(this,Ar)&&(_t($(this,Ar)),de(this,Ar,null)),$(this,ci)&&(_t($(this,ci)),de(this,ci,null)),se&&(We($(this,of)),Ka(),We(Fn()));let r=$(this,Oi).failed,i=n=>{let{reset:s,invoke_onerror:a}=Se(this,qe,C0).call(this,n);a(),r&&de(this,ci,Se(this,qe,Ep).call(this,()=>{try{return Gt(()=>{var o=ee;o.b=this,o.f|=128,r($(this,li),()=>n,()=>s)})}catch(o){return nn(o,$(this,Kr).parent),null}}))};At(()=>{var n;try{n=this.transform_error(e)}catch(s){nn(s,$(this,Kr)&&$(this,Kr).parent);return}n!==null&&typeof n=="object"&&typeof n.then=="function"?n.then(i,s=>nn(s,$(this,Kr)&&$(this,Kr).parent)):i(n)})};function kp(t,e,r,i){let n=Mn()?ea:no;var s=t.filter(h=>!h.settled),a=e.map(n);if(O&&a.forEach((h,p)=>{h.label=e[p].toString().replace("() => ","").replaceAll("$.eager(() => ","$state.eager(").replace(/\$\.get\((.+?)\)/g,(g,v)=>v)}),r.length===0&&s.length===0){i(a);return}var o=ee,l=mR(),c=s.length===1?s[0].promise:s.length>1?Promise.all(s.map(h=>h.promise)):null;function u(h){if((o.f&16384)===0){l();try{i([...a,...h])}catch(p){nn(p,o)}ic()}}var f=$0();if(r.length===0){c.then(()=>u([])).finally(f);return}function d(){Promise.all(r.map(h=>I0(h))).then(u).catch(h=>nn(h,o)).finally(f)}c?c.then(()=>{l(),d(),ic()}):d()}function mR(){var t=ee,e=oe,r=Ee,i=le;if(O)var n=In;return function(a=!0){Ut(t),Ht(e),us(r),a&&(t.f&16384)===0&&(i==null||i.activate(),i==null||i.apply()),O&&(F0(null),Xl(n))}}function ic(t=!0){var e;Ut(null),Ht(null),us(null),t&&((e=le)==null||e.deactivate()),O&&(F0(null),Xl(null))}function $0(){var t=ee,e=t.b,r=le,i=!!(e!=null&&e.is_rendered());return e==null||e.update_pending_count(1,r),r.increment(i,t),()=>{e==null||e.update_pending_count(-1,r),r.decrement(i,t)}}var Qr=null;function F0(t){Qr=t}var uf=new Set;function ea(t){var e=2050;ee!==null&&(ee.f|=524288);let r={ctx:Ee,deps:null,effects:null,equals:pp,f:e,fn:t,reactions:null,rv:0,v:Qe,wv:0,parent:ee,ac:null};return O&&Ji&&(r.created=en("created at")),r}var nc=Symbol("obsolete");function I0(t,e,r){let i=ee;i===null&&MP();var n=void 0,s=gr(Qe);O&&(s.label=e!=null?e:t.toString());var a=!oe,o=new Set;return wR(()=>{var h,p;var l=ee;O&&(Qr={effect:l,effect_deps:new Set,warned:!1});var c=cp();n=c.promise;try{Promise.resolve(t()).then(c.resolve,g=>{g!==ls&&c.reject(g)}).finally(ic)}catch(g){c.reject(g),ic()}if(O){if(Qr){if(l.deps!==null)for(let g=0;g{O&&(Qr=null),f==null||f(),o.delete(c),v!==nc&&(u.activate(),v?(s.f|=8388608,sn(s,v)):((s.f&8388608)!==0&&(s.f^=8388608),O&&r!==void 0&&!s.equals(g)&&(uf.add(s),setTimeout(()=>{uf.has(s)&&(l.f&16384)===0&&(ZP(s.label,r),uf.delete(s))})),sn(s,g)),u.deactivate())};c.promise.then(d,g=>d(null,g||"unknown"))}),sr(()=>{for(let l of o)l.reject(nc)}),O&&(s.f|=4194304),new Promise(l=>{function c(u){function f(){u===n?l(s):c(n)}u.then(f,f)}c(n)})}function Le(t){let e=ea(t);return Ft||Tp(e),e}function no(t){let e=ea(t);return e.equals=mp,e}function gR(t){var e=t.effects;if(e!==null){t.effects=null;for(var r=0;r{r.ac.abort(ls),r.ac=null}),r.fn!==null&&(r.teardown=dr),ao(r,0),df(r))}function O0(t){if(t.effects!==null)for(let e of t.effects)e.teardown&&e.fn!==null&&Ln(e)}var Pp=null,ac=null,le=null,ps=null,It=null,B0=null,Qa=!1,L0=!1,oo=null,mf=null,bR=0,N0=new Set,eU=1,lc,ms,gs,cc,uc,fc,vs,dc,Pr,gf,ws,an,Nn,hc,ta,He,H0,hf,U0,yR,xR,oc,ER,pf,Rp=class Rp{constructor(){ge(this,He);Ue(this,"id",eU++);ge(this,lc,!1);Ue(this,"linked",!0);ge(this,ms,null);ge(this,gs,null);Ue(this,"async_deriveds",new Map);Ue(this,"current",new Map);Ue(this,"previous",new Map);ge(this,cc,new Set);ge(this,uc,new Set);ge(this,fc,0);ge(this,vs,new Map);ge(this,dc,null);ge(this,Pr,[]);ge(this,gf,[]);ge(this,ws,new Set);ge(this,an,new Set);ge(this,Nn,new Map);ge(this,hc,new Set);Ue(this,"is_fork",!1);ge(this,ta,!1);ac===null?Pp=ac=this:(de(ac,gs,this),de(this,ms,ac)),ac=this}skip_effect(e){$(this,Nn).has(e)||$(this,Nn).set(e,{d:[],m:[]}),$(this,hc).delete(e)}unskip_effect(e,r=i=>this.schedule(i)){var i=$(this,Nn).get(e);if(i){$(this,Nn).delete(e);for(var n of i.d)Ge(n,2048),r(n);for(n of i.m)Ge(n,4096),r(n)}$(this,hc).add(e)}capture(e,r,i=!1){e.v!==Qe&&!this.previous.has(e)&&this.previous.set(e,e.v),(e.f&8388608)===0&&(this.current.set(e,[r,i]),It==null||It.set(e,r)),this.is_fork||(e.v=r)}activate(){le=this}deactivate(){le=null,It=null}flush(){try{O&&N0.clear(),L0=!0,le=this,Se(this,He,hf).call(this)}finally{if(bR=0,B0=null,oo=null,mf=null,L0=!1,le=null,It=null,bs.clear(),O)for(let e of N0)e.updated=null}}discard(){var e;for(let r of $(this,uc))r(this);$(this,uc).clear();for(let r of this.async_deriveds.values())r.reject(nc);Se(this,He,pf).call(this),(e=$(this,dc))==null||e.resolve()}register_created_effect(e){$(this,gf).push(e)}increment(e,r){var i;if(de(this,fc,$(this,fc)+1),e){let n=(i=$(this,vs).get(r))!=null?i:0;$(this,vs).set(r,n+1)}}decrement(e,r){var i;if(de(this,fc,$(this,fc)-1),e){let n=(i=$(this,vs).get(r))!=null?i:0;n===1?$(this,vs).delete(r):$(this,vs).set(r,n-1)}$(this,ta)||(de(this,ta,!0),At(()=>{de(this,ta,!1),this.linked&&this.flush()}))}transfer_effects(e,r){for(let i of e)$(this,ws).add(i);for(let i of r)$(this,an).add(i);e.clear(),r.clear()}oncommit(e){$(this,cc).add(e)}ondiscard(e){$(this,uc).add(e)}settled(){var e;return((e=$(this,dc))!=null?e:de(this,dc,cp())).promise}static ensure(){if(le===null){let e=le=new Rp;!L0&&!Qa&&At(()=>{$(e,lc)||e.flush()})}return le}apply(){if(!Ft||!this.is_fork&&$(this,ms)===null&&$(this,gs)===null){It=null;return}It=new Map;for(let[r,[i]]of this.current)It.set(r,i);for(let r=Pp;r!==null;r=$(r,gs))if(!(r===this||r.is_fork)){var e=!1;if(r.id1e3&&(Se(this,He,pf).call(this),tU()),O)for(let d of this.current.keys())N0.add(d);for(let d of $(this,ws))$(this,an).delete(d),Ge(d,2048),this.schedule(d);for(let d of $(this,an))Ge(d,4096),this.schedule(d);let e=$(this,Pr);de(this,Pr,[]),this.apply();var r=oo=[],i=[],n=mf=[];for(let d of e)try{Se(this,He,U0).call(this,d,r,i)}catch(h){throw CR(d),Se(this,He,H0).call(this)||this.discard(),h}if(le=null,n.length>0){var s=Rp.ensure();for(let d of n)s.schedule(d)}if(oo=null,mf=null,Se(this,He,H0).call(this)){Se(this,He,oc).call(this,i),Se(this,He,oc).call(this,r);for(let[d,h]of $(this,Nn))kR(d,h);n.length>0&&Se(l=le,He,hf).call(l);return}let a=Se(this,He,yR).call(this);if(a){Se(this,He,oc).call(this,i),Se(this,He,oc).call(this,r),Se(c=a,He,xR).call(c,this);return}$(this,ws).clear(),$(this,an).clear();for(let d of $(this,cc))d(this);$(this,cc).clear(),ps=this,_R(i),_R(r),ps=null,(u=$(this,dc))==null||u.resolve();var o=le;if($(this,fc)===0&&($(this,Pr).length===0||o!==null)&&(Se(this,He,pf).call(this),Ft&&(Se(this,He,ER).call(this),le=o)),$(this,Pr).length>0)if(o!==null){let d=o;$(d,Pr).push(...$(this,Pr).filter(h=>!$(d,Pr).includes(h)))}else o=this;o!==null&&Se(f=o,He,hf).call(f)},U0=function(e,r,i){e.f^=1024;for(var n=e.first;n!==null;){var s=n.f,a=(s&96)!==0,o=a&&(s&1024)!==0,l=o||(s&8192)!==0||$(this,Nn).has(n);if(!l&&n.fn!==null){a?n.f^=1024:(s&4)!==0?r.push(n):Ft&&(s&16777224)!==0?i.push(n):ra(n)&&((s&16)!==0&&$(this,an).add(n),Ln(n));var c=n.first;if(c!==null){n=c;continue}}for(;n!==null;){var u=n.next;if(u!==null){n=u;break}n=n.parent}}},yR=function(){for(var e=$(this,ms);e!==null;){if(!e.is_fork){for(let[r,[,i]]of this.current)if(e.current.has(r)&&!i)return e}e=$(e,ms)}return null},xR=function(e){var i;for(let[n,s]of e.current)!this.previous.has(n)&&e.previous.has(n)&&this.previous.set(n,e.previous.get(n)),this.current.set(n,s);for(let[n,s]of e.async_deriveds){let a=this.async_deriveds.get(n);a&&s.promise.then(a.resolve).catch(a.reject)}e.async_deriveds.clear(),this.transfer_effects($(e,ws),$(e,an));let r=n=>{var s=n.reactions;if(s!==null&&!((n.f&2)!==0&&(n.f&6144)===0))for(let l of s){var a=l.f;if((a&2)!==0)r(l);else{var o=l;a&4194320&&!this.async_deriveds.has(o)&&($(this,an).delete(o),Ge(o,2048),this.schedule(o))}}};for(let n of this.current.keys())r(n);this.oncommit(()=>e.discard()),Se(i=e,He,pf).call(i),le=this,Se(this,He,hf).call(this)},oc=function(e){for(var r=0;r!d.current.get(h)[1]);if(!(!$(d,lc)||n.length===0)){var s=n.filter(h=>!this.current.has(h));if(s.length===0)e&&d.discard();else if(r.length>0){if(O&&!$(d,ta)&&iR($(d,Pr).length===0,"Batch has scheduled roots"),e)for(let h of $(this,hc))d.unskip_effect(h,p=>{var g;(p.f&4194320)!==0?d.schedule(p):Se(g=d,He,oc).call(g,[p])});d.activate();var a=new Set,o=new Map;for(var l of r)SR(l,s,a,o);o=new Map;var c=[...d.current].filter(([h,p])=>{let g=this.current.get(h);return g?g[0]!==p[0]||g[1]!==p[1]:!0}).map(([h])=>h);if(c.length>0)for(let h of $(this,gf))(h.f&155648)===0&&G0(h,c,o)&&((h.f&4194320)!==0?(Ge(h,2048),d.schedule(h)):$(d,ws).add(h));if($(d,Pr).length>0&&!$(d,ta)){d.apply();for(var u of $(d,Pr))Se(f=d,He,U0).call(f,u,[],[]);de(d,Pr,[])}d.deactivate()}}}},pf=function(){if(this.linked){var e=$(this,ms),r=$(this,gs);e===null?Pp=r:de(e,gs,r),r===null?ac=e:de(r,ms,e),this.linked=!1}};var ui=Rp;function co(t){var e=Qa;Qa=!0;try{var r;for(t&&(le!==null&&!le.is_fork&&le.flush(),r=t());;){if(sR(),le===null)return r;le.flush()}}finally{Qa=e}}function tU(){var r;if(O){var t=new Map;for(let i of le.current.keys())for(let[n,s]of(r=i.updated)!=null?r:[]){var e=t.get(n);e||(e={error:s.error,count:0},t.set(n,e)),e.count+=s.count}for(let i of t.values())i.error&&console.error(i.error)}try{HP()}catch(i){O&&fr(i,"stack",{value:""}),nn(i,B0)}}var Jr=null;function _R(t){var e=t.length;if(e!==0){for(var r=0;r0)){bs.clear();for(let n of Jr){if((n.f&24576)!==0)continue;let s=[n],a=n.parent;for(;a!==null;)Jr.has(a)&&(Jr.delete(a),s.push(a)),a=a.parent;for(let o=s.length-1;o>=0;o--){let l=s[o];(l.f&24576)===0&&Ln(l)}}Jr.clear()}}Jr=null}}function SR(t,e,r,i){if(!r.has(t)&&(r.add(t),t.reactions!==null))for(let n of t.reactions){let s=n.f;(s&2)!==0?SR(n,e,r,i):(s&4194320)!==0&&(s&2048)===0&&G0(n,e,i)&&(Ge(n,2048),wf(n))}}function G0(t,e,r){let i=r.get(t);if(i!==void 0)return i;if(t.deps!==null)for(let n of t.deps){if(Xs.call(e,n))return!0;if((n.f&2)!==0&&G0(n,e,r))return r.set(n,!0),!0}return r.set(t,!1),!1}function wf(t){le.schedule(t)}function kR(t,e){if(!((t.f&32)!==0&&(t.f&1024)!==0)){(t.f&2048)!==0?e.d.push(t):(t.f&4096)!==0&&e.m.push(t),Ge(t,1024);for(var r=t.first;r!==null;)kR(r,e),r=r.next}}function CR(t){Ge(t,1024);for(var e=t.first;e!==null;)CR(e),e=e.next}var so=new Set,bs=new Map;function Cp(t){so=t}var V0=!1;function TR(){V0=!0}function gr(t,e){var r={f:0,v:t,reactions:null,equals:pp,rv:0,wv:0};return O&&Ji&&(r.created=e!=null?e:en("created at"),r.updated=null,r.set_during_effect=!1,r.trace=null),r}function Ne(t,e){let r=gr(t,e);return Tp(r),r}function Ja(t,e=!1,r=!0){var n,s;let i=gr(t);return e||(i.equals=mp),cs&&r&&Ee!==null&&Ee.l!==null&&((s=(n=Ee.l).s)!=null?s:n.s=[]).push(i),i}function ae(t,e,r=!1){oe!==null&&(!Rr||(oe.f&131072)!==0)&&Mn()&&(oe.f&4325394)!==0&&(hi===null||!hi.has(t))&&WP();let i=r?nt(e):e;return O&&vp(i,t.label),sn(t,i,mf)}function sn(t,e,r=null){var n,s,a;if(!t.equals(e)){bs.set(t,di?e:t.v);var i=ui.ensure();if(i.capture(t,e),O){if(Ji||ee!==null){(n=t.updated)!=null||(t.updated=new Map);let o=((a=(s=t.updated.get(""))==null?void 0:s.count)!=null?a:0)+1;if(t.updated.set("",{error:null,count:o}),Ji||o>5){let l=en("updated at");if(l!==null){let c=t.updated.get(l.stack);c||(c={error:l,count:0},t.updated.set(l.stack,c)),c.count++}}}ee!==null&&(t.set_during_effect=!0)}if((t.f&2)!==0){let o=t;(t.f&2048)!==0&&ff(o),It===null&&Ql(o)}t.wv=sc(),PR(t,2048,r),Mn()&&ee!==null&&(ee.f&1024)!==0&&(ee.f&96)===0&&(pi===null?RR([t]):pi.push(t)),!i.is_fork&&so.size>0&&!V0&&$p()}return e}function $p(){V0=!1;for(let t of so){(t.f&1024)!==0&&Ge(t,4096);let e;try{e=ra(t)}catch(r){e=!0}e&&Ln(t)}so.clear()}function to(t){ae(t,t.v+1)}function PR(t,e,r){var d;var i=t.reactions;if(i!==null)for(var n=Mn(),s=i.length,a=0;a{if(ia===a)return f();var d=oe,h=ia;Ht(null),z0(a);var p=f();return Ht(d),z0(h),p};i&&(r.set("length",Ne(t.length,s)),O&&(t=sU(t)));var l="";let c=!1;function u(f){if(!c){c=!0,l=f,pr(n,`${l} version`);for(let[d,h]of r)pr(h,uo(l,d));c=!1}}return new Proxy(t,{defineProperty(f,d,h){(!("value"in h)||h.configurable===!1||h.enumerable===!1||h.writable===!1)&&VP();var p=r.get(d);return p===void 0?o(()=>{var g=Ne(h.value,s);return r.set(d,g),O&&typeof d=="string"&&pr(g,uo(l,d)),g}):ae(p,h.value,!0),!0},deleteProperty(f,d){var h=r.get(d);if(h===void 0){if(d in f){let p=o(()=>Ne(Qe,s));r.set(d,p),to(n),O&&pr(p,uo(l,d))}}else ae(h,Qe),to(n);return!0},get(f,d,h){var b;if(d===rr)return t;if(O&&d===up)return u;var p=r.get(d),g=d in f;if(p===void 0&&(!g||(b=qr(f,d))!=null&&b.writable)&&(p=o(()=>{var _=nt(g?f[d]:Qe),C=Ne(_,s);return O&&pr(C,uo(l,d)),C}),r.set(d,p)),p!==void 0){var v=F(p);return v===Qe?void 0:v}return Reflect.get(f,d,h)},getOwnPropertyDescriptor(f,d){var h=Reflect.getOwnPropertyDescriptor(f,d);if(h&&"value"in h){var p=r.get(d);p&&(h.value=F(p))}else if(h===void 0){var g=r.get(d),v=g==null?void 0:g.v;if(g!==void 0&&v!==Qe)return{enumerable:!0,configurable:!0,value:v,writable:!0}}return h},has(f,d){var v;if(d===rr)return!0;var h=r.get(d),p=h!==void 0&&h.v!==Qe||Reflect.has(f,d);if(h!==void 0||ee!==null&&(!p||(v=qr(f,d))!=null&&v.writable)){h===void 0&&(h=o(()=>{var b=p?nt(f[d]):Qe,_=Ne(b,s);return O&&pr(_,uo(l,d)),_}),r.set(d,h));var g=F(h);if(g===Qe)return!1}return p},set(f,d,h,p){var w;var g=r.get(d),v=d in f;if(i&&d==="length")for(var b=h;bNe(Qe,s)),r.set(b+"",_),O&&pr(_,uo(l,b)))}if(g===void 0)(!v||(w=qr(f,d))!=null&&w.writable)&&(g=o(()=>Ne(void 0,s)),O&&pr(g,uo(l,d)),ae(g,nt(h)),r.set(d,g));else{v=g.v!==Qe;var C=o(()=>nt(h));ae(g,C)}var x=Reflect.getOwnPropertyDescriptor(f,d);if(x!=null&&x.set&&x.set.call(p,h),!v){if(i&&typeof d=="string"){var E=r.get("length"),A=Number(d);Number.isInteger(A)&&A>=E.v&&ae(E,A+1)}to(n)}return!0},ownKeys(f){F(n);var d=Reflect.ownKeys(f).filter(g=>{var v=r.get(g);return v===void 0||v.v!==Qe});for(var[h,p]of r)p.v!==Qe&&!(h in f)&&d.push(h);return d},setPrototypeOf(){zP()}})}function uo(t,e){var r;return typeof e=="symbol"?`${t}[Symbol(${(r=e.description)!=null?r:""})]`:iU.test(e)?`${t}.${e}`:/^\d+$/.test(e)?`${t}[${e}]`:`${t}['${e}']`}function Fp(t){try{if(t!==null&&typeof t=="object"&&rr in t)return t[rr]}catch(e){}return t}var nU=new Set(["copyWithin","fill","pop","push","reverse","shift","sort","splice","unshift"]);function sU(t){return new Proxy(t,{get(e,r,i){var n=Reflect.get(e,r,i);return nU.has(r)?function(...s){TR();var a=n.apply(this,s);return $p(),a}:n}})}function $R(){let t=Array.prototype,e=Array.__svelte_cleanup;e&&e();let{indexOf:r,lastIndexOf:i,includes:n}=t;t.indexOf=function(s,a){let o=r.call(this,s,a);if(o===-1){for(let l=a!=null?a:0;l{t.indexOf=r,t.lastIndexOf=i,t.includes=n}}var W0,FR,af,IR,MR;function Ip(){if(W0===void 0){W0=window,FR=document,af=/Firefox/.test(navigator.userAgent);var t=Element.prototype,e=Node.prototype,r=Text.prototype;IR=qr(e,"firstChild").get,MR=qr(e,"nextSibling").get,f0(t)&&(t[Ju]=void 0,t[fp]=null,t[h0]=void 0,t.__e=void 0),f0(r)&&(r[ef]=void 0),O&&(t.__svelte_meta=null,$R())}}function jt(t=""){return document.createTextNode(t)}function or(t){return IR.call(t)}function nr(t){return MR.call(t)}function V(t,e){if(!se)return or(t);var r=or(we);if(r===null)r=we.appendChild(jt());else if(e&&r.nodeType!==Yl){var i=jt();return r==null||r.before(i),We(i),i}return e&&Dp(r),We(r),r}function Ni(t,e=!1){var n,s;if(!se){var r=or(t);return r instanceof Comment&&r.data===""?nr(r):r}if(e){if(((n=we)==null?void 0:n.nodeType)!==Yl){var i=jt();return(s=we)==null||s.before(i),We(i),i}Dp(we)}return we}function ne(t,e=1,r=!1){let i=se?we:t;for(var n;e--;)n=i,i=nr(i);if(!se)return i;if(r){if((i==null?void 0:i.nodeType)!==Yl){var s=jt();return i===null?n==null||n.after(s):i.before(s),We(s),s}Dp(i)}return We(i),i}function ec(t){t.textContent=""}function Mp(){if(!Ft||Jr!==null)return!1;var t=ee.f;return(t&32768)!==0}function Bn(t,e,r){return e==null||e===ap?r?document.createElement(t,{is:r}):document.createElement(t):r?document.createElementNS(e,t,{is:r}):document.createElementNS(e,t)}function Dp(t){if(t.nodeValue.length<65536)return;let e=t.nextSibling;for(;e!==null&&e.nodeType===Yl;)e.remove(),t.nodeValue+=e.nodeValue,e=t.nextSibling}function OR(t){ee===null&&(oe===null&&BP(t),NP()),di&&LP(t)}function oU(t,e){var r=e.last;r===null?e.last=e.first=t:(r.next=t,t.prev=r,e.last=t)}function Hn(t,e){var a,o;var r=ee;if(O)for(;r!==null&&(r.f&131072)!==0;)r=r.parent;r!==null&&(r.f&8192)!==0&&(t|=8192);var i={ctx:Ee,deps:null,nodes:null,f:t|2048|512,first:null,fn:e,last:null,next:null,parent:r,b:r&&r.b,prev:null,teardown:null,wv:0,ac:null};O&&(i.component_function=tn),(a=le)==null||a.register_created_effect(i);var n=i;if((t&4)!==0)oo!==null?oo.push(i):ui.ensure().schedule(i);else if(e!==null){try{Ln(i)}catch(l){throw _t(i),l}n.deps===null&&n.teardown===null&&n.nodes===null&&n.first===n.last&&(n.f&524288)===0&&(n=n.first,(t&16)!==0&&(t&65536)!==0&&n!==null&&(n.f|=65536))}if(n!==null&&(n.parent=r,r!==null&&oU(n,r),oe!==null&&(oe.f&2)!==0&&(t&64)===0)){var s=oe;((o=s.effects)!=null?o:s.effects=[]).push(n)}return i}function Qs(){return oe!==null&&!Rr}function sr(t){let e=Hn(8,null);return Ge(e,1024),e.teardown=t,e}function vr(t){var n;OR("$effect"),O&&fr(t,"name",{value:"$effect"});var e=ee.f,r=!oe&&(e&32)!==0&&Ee!==null&&!Ee.i;if(r){var i=Ee;((n=i.e)!=null?n:i.e=[]).push(t)}else return b0(t)}function b0(t){return Hn(1048580,t)}function Y0(t){ui.ensure();let e=Hn(524352,t);return()=>{_t(e)}}function LR(t){ui.ensure();let e=Hn(524352,t);return(r={})=>new Promise(i=>{r.outro?On(e,()=>{_t(e),i(void 0)}):(_t(e),i(void 0))})}function ei(t){return Hn(4,t)}function wR(t){return Hn(4718592,t)}function lr(t,e=0){return Hn(8|e,t)}function Ve(t,e=[],r=[],i=[]){kp(i,e,r,n=>{Hn(8,()=>{t(...n.map(F))})})}function fi(t,e=0){var r=Hn(16|e,t);return O&&(r.dev_stack=In),r}function Gt(t){return Hn(524320,t)}function Z0(t){var e=t.teardown;if(e!==null){let r=di,i=oe;q0(!0),Ht(null);try{e.call(null)}finally{q0(r),Ht(i)}}}function df(t,e=!1){var r=t.first;for(t.first=t.last=null;r!==null;){let n=r.ac;n!==null&&Zr(()=>{n.abort(ls)});var i=r.next;(r.f&64)!==0?r.parent=null:_t(r,e),r=i}}function NR(t){for(var e=t.first;e!==null;){var r=e.next;(e.f&32)===0&&_t(e),e=r}}function _t(t,e=!0){var r=!1;(e||(t.f&262144)!==0)&&t.nodes!==null&&t.nodes.end!==null&&(BR(t.nodes.start,t.nodes.end),r=!0),t.f|=33554432,df(t,e&&!r),ao(t,0);var i=t.nodes&&t.nodes.t;if(i!==null)for(let s of i)s.stop();Z0(t),t.f^=33554432,t.f|=16384;var n=t.parent;n!==null&&n.first!==null&&j0(t),O&&(t.component_function=null),t.next=t.prev=t.teardown=t.ctx=t.deps=t.fn=t.nodes=t.ac=t.b=null}function BR(t,e){for(;t!==null;){var r=t===e?null:nr(t);t.remove(),t=r}}function j0(t){var e=t.parent,r=t.prev,i=t.next;r!==null&&(r.next=i),i!==null&&(i.prev=r),e!==null&&(e.first===t&&(e.first=i),e.last===t&&(e.last=r))}function On(t,e,r=!0){var i=[];HR(t,i,!0);var n=()=>{r&&_t(t),e&&e()},s=i.length;if(s>0){var a=()=>--s||n();for(var o of i)o.out(a)}else n()}function HR(t,e,r){if((t.f&8192)===0){t.f^=8192;var i=t.nodes&&t.nodes.t;if(i!==null)for(let o of i)(o.is_global||r)&&e.push(o);for(var n=t.first;n!==null;){var s=n.next;if((n.f&64)===0){var a=(n.f&65536)!==0||(n.f&32)!==0&&(t.f&16)!==0;HR(n,e,a?r:!1)}n=s}}}function mc(t){UR(t,!0)}function UR(t,e){if((t.f&8192)!==0){t.f^=8192,(t.f&1024)===0&&(Ge(t,2048),ui.ensure().schedule(t));for(var r=t.first;r!==null;){var i=r.next,n=(r.f&65536)!==0||(r.f&32)!==0;UR(r,n?e:!1),r=i}var s=t.nodes&&t.nodes.t;if(s!==null)for(let a of s)(a.is_global||e)&&a.in()}}function rc(t,e){if(t.nodes)for(var r=t.nodes.start,i=t.nodes.end;r!==null;){var n=r===i?null:nr(r);e.append(r),r=n}}m();var GR=null;var Op=!1,di=!1;function q0(t){di=t}var oe=null,Rr=!1;function Ht(t){oe=t}var ee=null;function Ut(t){ee=t}var hi=null;function Tp(t){oe!==null&&(!Ft||(oe.f&2)!==0)&&(hi!=null?hi:hi=new Set).add(t)}var Kt=null,Tr=0,pi=null;function RR(t){pi=t}var jR=1,fo=0,ia=fo;function z0(t){ia=t}function sc(){return++jR}function ra(t){var e=t.f;if((e&2048)!==0)return!0;if(e&2&&(t.f&=-65537),(e&4096)!==0){for(var r=t.deps,i=r.length,n=0;nt.wv)return!0}(e&512)!==0&&It===null&&Ge(t,1024)}return!1}function VR(t,e,r=!0){var i=t.reactions;if(i!==null&&!(!Ft&&hi!==null&&hi.has(t)))for(var n=0;n{t.ac.abort(ls)}),t.ac=null);try{t.f|=2097152;var u=t.fn,f=u();t.f|=32768;var d=t.deps,h=(g=le)==null?void 0:g.is_fork;if(Kt!==null){var p;if(h||ao(t,Tr),d!==null&&Tr>0)for(d.length=Tr+Kt.length,p=0;p{s.ac.abort(ls),s.ac=null,Ge(s,2048)}),vR(s),ao(s,0)}}function ao(t,e){var r=t.deps;if(r!==null)for(var i=e;i{requestAnimationFrame(()=>t()),setTimeout(()=>t())});await Promise.resolve(),co()}function F(t){var h,p,g;var e=t.f,r=(e&2)!==0;if((h=GR)==null||h.add(t),oe!==null&&!Rr){var i=ee!==null&&(ee.f&16384)!==0;if(!i&&(hi===null||!hi.has(t))){var n=oe.deps;if((oe.f&2097152)!==0)t.rvr==null?void 0:r.call(this,s))}return t.startsWith("pointer")||t.startsWith("touch")||t==="wheel"?At(()=>{e.addEventListener(t,n,i)}):e.addEventListener(t,n,i),n}function mi(t,e,r,i,n){var s={capture:i,passive:n},a=YR(t,e,r,s);(e===document.body||e===window||e===document||e instanceof HTMLMediaElement)&&sr(()=>{e.removeEventListener(t,a,s)})}function me(t,e,r){var i;((i=e[ho])!=null?i:e[ho]={})[t]=r}function Mt(t){for(var e=0;e{throw b});throw d}}finally{t[ho]=e,delete t.currentTarget,Ht(u),Ut(f)}}}m();m();var ZR,X0=((ZR=globalThis==null?void 0:globalThis.window)==null?void 0:ZR.trustedTypes)&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:t=>t});function KR(t){var e;return(e=X0==null?void 0:X0.createHTML(t))!=null?e:t}function Q0(t){var e=Bn("template");return e.innerHTML=KR(t.replaceAll("","")),e.content}function on(t,e){var r=ee;r.nodes===null&&(r.nodes={start:t,end:e,a:null,t:null})}function _e(t,e){var r=(e&1)!==0,i=(e&2)!==0,n,s=!t.startsWith("");return()=>{if(se)return on(we,null),we;n===void 0&&(n=Q0(s?t:""+t),r||(n=or(n)));var a=i||af?document.importNode(n,!0):n.cloneNode(!0);if(r){var o=or(a),l=a.lastChild;on(o,l)}else on(a,a);return a}}function po(){if(se)return on(we,null),we;var t=document.createDocumentFragment(),e=document.createComment(""),r=jt();return t.append(e,r),on(e,r),t}function ue(t,e){if(se){var r=ee;((r.f&32768)===0||r.nodes.end===null)&&(r.nodes.end=we),hr();return}t!==null&&t.before(e)}m();var pU=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","disabled","formnovalidate","indeterminate","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","seamless","selected","webkitdirectory","defer","disablepictureinpicture","disableremoteplayback"];var Ote=[...pU,"formNoValidate","isMap","noModule","playsInline","readOnly","value","volume","defaultValue","defaultChecked","srcObject","noValidate","allowFullscreen","disablePictureInPicture","disableRemotePlayback"];var mU=["touchstart","touchmove"];function XR(t){return mU.includes(t)}var gU=["$state","$state.raw","$derived","$derived.by"],Lte=[...gU,"$state.eager","$state.snapshot","$props","$props.id","$bindable","$effect","$effect.pre","$effect.tracking","$effect.root","$effect.pending","$inspect","$inspect().with","$inspect.trace","$host"];var Up=!0;function Ye(t,e){var i,n;var r=e==null?"":typeof e=="object"?`${e}`:e;r!==((n=t[i=ef])!=null?n:t[i]=t.nodeValue)&&(t[ef]=r,t.nodeValue=`${r}`)}function na(t,e){return QR(t,e)}function tb(t,e){var a;Ip(),e.intro=(a=e.intro)!=null?a:!1;let r=e.target,i=se,n=we;try{for(var s=or(r);s&&(s.nodeType!==Ii||s.data!=="[");)s=nr(s);if(!s)throw as;Lt(!0),We(s);let o=QR(t,{...e,anchor:s});return Lt(!1),o}catch(o){if(o instanceof Error&&o.message.split(` +`).some(l=>l.startsWith("https://svelte.dev/e/")))throw o;return o!==as&&console.warn("Failed to hydrate: ",o),e.recover===!1&&UP(),Ip(),ec(r),Lt(!1),na(t,e)}finally{Lt(i),We(n)}}var Hp=new Map;function QR(t,{target:e,anchor:r,props:i={},events:n,context:s,intro:a=!0,transformError:o}){Ip();var l=void 0,c=LR(()=>{var u=r!=null?r:e.appendChild(jt());R0(u,{pending:()=>{}},h=>{ht({});var p=Ee;if(s&&(p.c=s),n&&(i.$$events=n),se&&on(h,null),Up=a,l=t(h,i)||{},Up=!0,se&&(ee.nodes.end=we,we===null||we.nodeType!==Ii||we.data!=="]"))throw Za(),as;pt()},o);var f=new Set,d=h=>{for(var p=0;p{var v;for(var h of f)for(let b of[e,document]){var p=Hp.get(b),g=p.get(h);--g==0?(b.removeEventListener(h,Bp),p.delete(h),p.size===0&&Hp.delete(b)):p.set(h,g)}Np.delete(d),u!==r&&((v=u.parentNode)==null||v.removeChild(u))}});return eb.set(l,c),l}var eb=new WeakMap;function _s(t,e){let r=eb.get(t);return r?(eb.delete(t),r(e)):(O&&(rr in t?JP():QP()),Promise.resolve())}m();m();m();var ln,Un,gi,mo,bf,_f,Gp,ys=class{constructor(e,r=!0){Ue(this,"anchor");ge(this,ln,new Map);ge(this,Un,new Map);ge(this,gi,new Map);ge(this,mo,new Set);ge(this,bf,!0);ge(this,_f,e=>{if($(this,ln).has(e)){var r=$(this,ln).get(e),i=$(this,Un).get(r);if(i)mc(i),$(this,mo).delete(r);else{var n=$(this,gi).get(r);n&&(mc(n.effect),$(this,Un).set(r,n.effect),$(this,gi).delete(r),O&&(n.fragment.lastChild[p0]=this.anchor),n.fragment.lastChild.remove(),this.anchor.before(n.fragment),i=n.effect)}for(let[s,a]of $(this,ln)){if($(this,ln).delete(s),s===e)break;let o=$(this,gi).get(a);o&&(_t(o.effect),$(this,gi).delete(a))}for(let[s,a]of $(this,Un)){if(s===r||$(this,mo).has(s))continue;let o=()=>{if(Array.from($(this,ln).values()).includes(s)){var c=document.createDocumentFragment();rc(a,c),c.append(jt()),$(this,gi).set(s,{effect:a,fragment:c})}else _t(a);$(this,mo).delete(s),$(this,Un).delete(s)};$(this,bf)||!i?($(this,mo).add(s),On(a,o,!1)):o()}}});ge(this,Gp,e=>{$(this,ln).delete(e);let r=Array.from($(this,ln).values());for(let[i,n]of $(this,gi))r.includes(i)||(_t(n.effect),$(this,gi).delete(i))});this.anchor=e,de(this,bf,r)}ensure(e,r){var i=le,n=Mp();if(r&&!$(this,Un).has(e)&&!$(this,gi).has(e))if(n){var s=document.createDocumentFragment(),a=jt();s.append(a),$(this,gi).set(e,{effect:Gt(()=>r(a)),fragment:s})}else $(this,Un).set(e,Gt(()=>r(this.anchor)));if($(this,ln).set(i,e),n){for(let[o,l]of $(this,Un))o===e?i.unskip_effect(l):i.skip_effect(l);for(let[o,l]of $(this,gi))o===e?i.unskip_effect(l.effect):i.skip_effect(l.effect);i.oncommit($(this,_f)),i.ondiscard($(this,Gp))}else se&&(this.anchor=we),$(this,_f).call(this,i)}};ln=new WeakMap,Un=new WeakMap,gi=new WeakMap,mo=new WeakMap,bf=new WeakMap,_f=new WeakMap,Gp=new WeakMap;if(O){let t=function(e){if(!(e in globalThis)){let r;Object.defineProperty(globalThis,e,{configurable:!0,get:()=>{if(r!==void 0)return r;jP(e)},set:i=>{r=i}})}};t("$state"),t("$effect"),t("$derived"),t("$inspect"),t("$props"),t("$bindable")}function go(t){Ee===null&&dp("onMount"),cs&&Ee.l!==null?bU(Ee).m.push(t):vr(()=>{let e=Je(t);if(typeof e=="function")return e})}function bU(t){var r;var e=t.l;return(r=e.u)!=null?r:e.u={a:[],b:[],m:[]}}m();m();var t$=new Map;function r$(t,e){var r=t$.get(t);r||(r=new Set,t$.set(t,r)),r.add(e)}m();m();m();m();m();m();m();m();m();function $e(t,e,r=!1){var i;se&&(i=we,hr());var n=new ys(t),s=r?65536:0;function a(o,l){if(se){var c=rf(i);if(o!==parseInt(c.substring(1))){var u=Fn();We(u),n.anchor=u,Lt(!1),n.ensure(o,l),Lt(!0);return}}n.ensure(o,l)}fi(()=>{var o=!1;e((l,c=0)=>{o=!0,a(c,l)}),o||a(-1,null)},s)}m();m();m();function vi(t,e){return e}function AU(t,e,r){var f;for(var i=[],n=e.length,s,a=e.length,o=0;o{if(s){if(s.pending.delete(d),s.done.add(d),s.pending.size===0){var h=t.outrogroups;rb(t,Wl(s.done)),h.delete(s),h.size===0&&(t.outrogroups=null)}}else a-=1},!1)}if(a===0){var l=i.length===0&&r!==null;if(l){var c=r,u=c.parentNode;ec(u),u.append(c),t.items.clear()}rb(t,e,!l)}else s={pending:new Set(e),done:new Set},((f=t.outrogroups)!=null?f:t.outrogroups=new Set).add(s)}function rb(t,e,r=!0){var i;if(t.pending.size>0){i=new Set;for(let a of t.pending.values())for(let o of a)i.add(t.items.get(o).e)}for(var n=0;n{var C=r();return os(C)?C:C==null?[]:Wl(C)});O&&pr(f,"{#each ...}");var d,h=new Map,p=!0;function g(C){(_.effect.f&16384)===0&&(_.pending.delete(C),_.fallback=u,TU(_,d,a,e,i),u!==null&&(d.length===0?(u.f&33554432)===0?mc(u):(u.f^=33554432,xf(u,null,a)):On(u,()=>{u=null})))}function v(C){_.pending.delete(C)}var b=fi(()=>{d=F(f);var C=d.length;let x=!1;if(se){var E=rf(a)==="[!";E!==(C===0)&&(a=Fn(),We(a),Lt(!1),x=!0)}for(var A=new Set,w=le,S=Mp(),y=0;ys(a)):(u=Gt(()=>s(gc!=null?gc:gc=jt())),u.f|=33554432)),C>A.size&&(O?RU(d,i):v0("","","")),se&&C>0&&We(Fn()),!p)if(h.set(w,A),S){for(let[B,re]of o)A.has(B)||w.skip_effect(re.e);w.oncommit(g),w.ondiscard(v)}else g(w);x&&Lt(!0),F(f)}),_={effect:b,flags:e,items:o,pending:h,outrogroups:null,fallback:u};p=!1,se&&(a=we)}function yf(t){for(;t!==null&&(t.f&32)===0;)t=t.next;return t}function TU(t,e,r,i,n){var P,T,I,M,B,re,Ae,K,Q;var s=(i&8)!==0,a=e.length,o=t.items,l=yf(t.effect.first),c,u=null,f,d=[],h=[],p,g,v,b;if(s)for(b=0;b0){var y=(i&4)!==0&&a===0?r:null;if(s){for(b=0;b{var fe,ce;if(f!==void 0)for(v of f)(ce=(fe=v.nodes)==null?void 0:fe.a)==null||ce.apply()})}function PU(t,e,r,i,n,s,a,o){var l=(a&1)!==0?(a&16)===0?Ja(r,!1,!1):gr(r):null,c=(a&2)!==0?gr(n):null;return O&&l&&(l.trace=()=>{var u;o()[(u=c==null?void 0:c.v)!=null?u:n]}),{v:l,i:c,e:Gt(()=>(s(e,l!=null?l:r,c!=null?c:n,o),()=>{t.delete(i)}))}}function xf(t,e,r){if(t.nodes)for(var i=t.nodes.start,n=t.nodes.end,s=e&&(e.f&33554432)===0?e.nodes.start:r;i!==null;){var a=nr(i);if(s.before(i),i===n)return;i=a}}function sa(t,e,r){e===null?t.effect.first=r:e.next=r,r===null?t.effect.last=e:r.prev=e}function RU(t,e){let r=new Map,i=t.length;for(let n=0;nperformance.now():()=>Date.now(),cn={tick:t=>(op?requestAnimationFrame:dr)(t),now:()=>$U(),tasks:new Set};function n$(){let t=cn.now();cn.tasks.forEach(e=>{e.c(t)||(cn.tasks.delete(e),e.f())}),cn.tasks.size!==0&&cn.tick(n$)}function s$(t){let e;return cn.tasks.size===0&&cn.tick(n$),{promise:new Promise(r=>{cn.tasks.add(e={c:t,f:r})}),abort(){cn.tasks.delete(e)}}}function jp(t,e){Zr(()=>{t.dispatchEvent(new CustomEvent(e))})}function DU(t){if(t==="float")return"cssFloat";if(t==="offset")return"cssOffset";if(t.startsWith("--"))return t;let e=t.split("-");return e.length===1?e[0]:e[0]+e.slice(1).map(r=>r[0].toUpperCase()+r.slice(1)).join("")}function a$(t){let e={},r=t.split(";");for(let i of r){let[n,s]=i.split(":");if(!n||s===void 0)break;let a=DU(n.trim());e[a]=s.trim()}return e}var OU=t=>t;function un(t,e,r,i){var C,x;var n=(t&1)!==0,s=(t&2)!==0,a=n&&s,o=(t&4)!==0,l=a?"both":n?"in":"out",c,u=e.inert,f=e.style.overflow,d,h;function p(){return Zr(()=>{var E;return c!=null?c:c=r()(e,(E=i==null?void 0:i())!=null?E:{},{direction:l})})}var g={is_global:o,in(){var E;if(e.inert=u,!n){h==null||h.abort(),(E=h==null?void 0:h.reset)==null||E.call(h);return}s||d==null||d.abort(),d=ib(e,p(),h,1,()=>{jp(e,"introstart")},()=>{jp(e,"introend"),d==null||d.abort(),d=c=void 0,e.style.overflow=f})},out(E){if(!s){E==null||E(),c=void 0;return}e.inert=!0,h=ib(e,p(),d,0,()=>{jp(e,"outrostart")},()=>{jp(e,"outroend"),E==null||E()})},stop:()=>{d==null||d.abort(),h==null||h.abort()}},v=ee;if(((x=(C=v.nodes).t)!=null?x:C.t=[]).push(g),n&&Up){var b=o;if(!b){for(var _=v.parent;_&&(_.f&65536)!==0;)for(;(_=_.parent)&&(_.f&16)===0;);b=!_||(_.f&32768)!==0}b&&ei(()=>{Je(()=>g.in())})}}function ib(t,e,r,i,n,s){var a=i===1;if(d0(e)){var o,l=!1;return At(()=>{if(!l){var b=e({direction:a?"in":"out"});o=ib(t,b,r,i,n,s)}}),{abort:()=>{l=!0,o==null||o.abort()},deactivate:()=>o.deactivate(),reset:()=>o.reset(),t:()=>o.t()}}if(r==null||r.deactivate(),!(e!=null&&e.duration)&&!(e!=null&&e.delay))return n(),s(),{abort:dr,deactivate:dr,reset:dr,t:()=>i};let{delay:c=0,css:u,tick:f,easing:d=OU}=e;var h=[];if(a&&r===void 0&&(f&&f(0,1),u)){var p=a$(u(0,1));h.push(p,p)}var g=()=>1-i,v=t.animate(h,{duration:c,fill:"forwards"});return v.onfinish=()=>{var P;v.cancel(),n();var b=(P=r==null?void 0:r.t())!=null?P:1-i;r==null||r.abort();var _=i-b,C=e.duration*Math.abs(_),x=[];if(C>0){var E=!1;if(u)for(var A=Math.ceil(C/16.666666666666668),w=0;w<=A;w+=1){var S=b+_*d(w/A),y=a$(u(S,1-S));x.push(y),E||(E=y.overflow==="hidden")}E&&(t.style.overflow="hidden"),g=()=>{var T=v.currentTime;return b+_*d(T/C)},f&&s$(()=>{if(v.playState!=="running")return!1;var T=g();return f(T,1-T),!0})}v=t.animate(x,{duration:C,fill:"forwards"}),v.onfinish=()=>{g=()=>i,f==null||f(i,1-i),s()}},{abort:()=>{v&&(v.cancel(),v.effect=null,v.onfinish=dr)},deactivate:()=>{s=dr},reset:()=>{i===0&&(f==null||f(1,0))},t:()=>g()}}m();m();function fn(t,e){ei(()=>{var n;var r=t.getRootNode(),i=r.host?r:(n=r.head)!=null?n:r.ownerDocument.head;if(!i.querySelector("#"+e.hash)){let s=Bn("style");s.id=e.hash,s.textContent=e.code,i.appendChild(s),O&&r$(e.hash,s)}})}m();m();m();m();m();m();var l$=[...` +\r\f\xA0\v\uFEFF`];function c$(t,e,r){var i=t==null?"":""+t;if(e&&(i=i?i+" "+e:e),r){for(var n of Object.keys(r))if(r[n])i=i?i+" "+n:n;else if(i.length)for(var s=n.length,a=0;(a=i.indexOf(n,a))>=0;){var o=a+s;(a===0||l$.includes(i[a-1]))&&(o===i.length||l$.includes(i[o]))?i=(a===0?"":i.substring(0,a))+i.substring(o+1):a=o}}return i===""?null:i}m();function ft(t,e,r,i,n,s){var a=t[Ju];if(se||a!==r||a===void 0){var o=c$(r,i,s);(!se||o!==t.getAttribute("class"))&&(o==null?t.removeAttribute("class"):e?t.className=o:t.setAttribute("class",o)),t[Ju]=r}else if(s&&n!==s)for(var l in s){var c=!!s[l];(n==null||c!==!!n[l])&&t.classList.toggle(l,c)}return s}m();m();var VU=Symbol("is custom element"),zU=Symbol("is html"),WU=m0?"link":"LINK";function ye(t,e,r,i){var n=qU(t);if(se&&(n[e]=t.getAttribute(e),e==="src"||e==="srcset"||e==="href"&&t.nodeName===WU)){i||ZU(t,e,r!=null?r:"");return}n[e]!==(n[e]=r)&&(e==="loading"&&(t[$P]=r),r==null?t.removeAttribute(e):typeof r!="string"&&YU(t).includes(e)?t[e]=r:t.setAttribute(e,r))}function qU(t){var e,r;return(r=t[e=fp])!=null?r:t[e]={[VU]:t.nodeName.includes("-"),[zU]:t.namespaceURI===ap}}var u$=new Map;function YU(t){var e=t.getAttribute("is")||t.nodeName,r=u$.get(e);if(r)return r;u$.set(e,r=[]);for(var i,n=t,s=Element.prototype;s!==n;){i=c0(n);for(var a in i)i[a].set&&a!=="innerHTML"&&a!=="textContent"&&a!=="innerText"&&r.push(a);n=ql(n)}return r}function ZU(t,e,r){var i;O&&(e==="srcset"&&KU(t,r)||nb((i=t.getAttribute(e))!=null?i:"",r)||XP(e,t.outerHTML.replace(t.innerHTML,t.innerHTML&&"..."),String(r)))}function nb(t,e){return t===e?!0:new URL(t,document.baseURI).href===new URL(e,document.baseURI).href}function f$(t){return t.split(",").map(e=>e.trim().split(" ").filter(Boolean))}function KU(t,e){var r=f$(t.srcset),i=f$(e);return i.length===r.length&&i.every(([n,s],a)=>s===r[a][1]&&(nb(r[a][0],n)||nb(n,r[a][0])))}m();m();m();function ob(t,e,r=e){var i=new WeakSet;S0(t,"input",async n=>{O&&t.type==="checkbox"&&g0();var s=n?t.defaultValue:t.value;if(s=sb(t)?ab(s):s,r(s),le!==null&&i.add(le),await Lp(),s!==(s=e())){var a=t.selectionStart,o=t.selectionEnd,l=t.value.length;if(t.value=s!=null?s:"",o!==null){var c=t.value.length;a===o&&o===l&&c>l?(t.selectionStart=c,t.selectionEnd=c):(t.selectionStart=a,t.selectionEnd=Math.min(o,c))}}}),(se&&t.defaultValue!==t.value||Je(e)==null&&t.value)&&(r(sb(t)?ab(t.value):t.value),le!==null&&i.add(le)),lr(()=>{O&&t.type==="checkbox"&&g0();var n=e();if(t===document.activeElement){var s=Ft?ps:le;if(i.has(s))return}sb(t)&&n===ab(t.value)||t.type==="date"&&!n&&!t.value||n!==t.value&&(t.value=n!=null?n:"")})}function sb(t){var e=t.type;return e==="number"||e==="range"}function ab(t){return t===""?null:+t}m();m();m();m();m();function lb(t,e){return t===e||(t==null?void 0:t[rr])===e}function ot(t={},e,r,i){var n=Ee.r,s=ee;return ei(()=>{var a,o;return lr(()=>{a=o,o=(i==null?void 0:i())||[],Je(()=>{lb(r(...o),t)||(e(t,...o),a&&lb(r(...a),t)&&e(null,...a))})}),()=>{let l=s;for(;l!==n&&l.parent!==null&&l.parent.f&33554432;)l=l.parent;let c=()=>{o&&lb(r(...o),t)&&e(null,...o)},u=l.teardown;l.teardown=()=>{c(),u==null||u()}}}),t}m();m();m();m();m();m();function Bi(t,e,r,i){var x,E;var n=!cs||(r&2)!==0,s=(r&8)!==0,a=(r&16)!==0,o=i,l=!0,c=void 0,u=()=>a&&n?(c!=null||(c=ea(i)),F(c)):(l&&(l=!1,o=a?Je(i):i),o);let f;if(s){var d=rr in t||Qu in t;f=(E=(x=qr(t,e))==null?void 0:x.set)!=null?E:d&&e in t?A=>t[e]=A:void 0}var h,p=!1;s?[h,p]=y0(()=>t[e]):h=t[e],h===void 0&&i!==void 0&&(h=u(),f&&(n&&GP(e),f(h)));var g;if(n?g=()=>{var A=t[e];return A===void 0?u():(l=!0,A)}:g=()=>{var A=t[e];return A!==void 0&&(o=void 0),A===void 0?o:A},n&&(r&4)===0)return g;if(f){var v=t.$$legacy;return(function(A,w){return arguments.length>0?((!n||!w||v||p)&&f(w?g():A),A):g()})}var b=!1,_=((r&1)!==0?ea:no)(()=>(b=!1,g()));O&&(_.label=e),s&&F(_);var C=ee;return(function(A,w){if(arguments.length>0){let S=w?F(_):n&&s?nt(A):A;return ae(_,S),b=!0,o!==void 0&&(o=S),A}return di&&b||(C.f&16384)!==0?_.v:F(_)})}m();m();m();function h$(t){return new ub(t)}var xs,Hi,ub=class{constructor(e){ge(this,xs);ge(this,Hi);var s,a;var r=new Map,i=(o,l)=>{var c=Ja(l,!1,!1);return r.set(o,c),c};let n=new Proxy({...e.props||{},$$events:{}},{get(o,l){var c;return F((c=r.get(l))!=null?c:i(l,Reflect.get(o,l)))},has(o,l){var c;return l===Qu?!0:(F((c=r.get(l))!=null?c:i(l,Reflect.get(o,l))),Reflect.has(o,l))},set(o,l,c){var u;return ae((u=r.get(l))!=null?u:i(l,c),c),Reflect.set(o,l,c)}});de(this,Hi,(e.hydrate?tb:na)(e.component,{target:e.target,anchor:e.anchor,props:n,context:e.context,intro:(s=e.intro)!=null?s:!1,recover:e.recover,transformError:e.transformError})),!Ft&&(!((a=e==null?void 0:e.props)!=null&&a.$$host)||e.sync===!1)&&co(),de(this,xs,n.$$events);for(let o of Object.keys($(this,Hi)))o==="$set"||o==="$destroy"||o==="$on"||fr(this,o,{get(){return $(this,Hi)[o]},set(l){$(this,Hi)[o]=l},enumerable:!0});$(this,Hi).$set=o=>{Object.assign(n,o)},$(this,Hi).$destroy=()=>{_s($(this,Hi))}}$set(e){$(this,Hi).$set(e)}$on(e,r){$(this,xs)[e]=$(this,xs)[e]||[];let i=(...n)=>r.call(this,...n);return $(this,xs)[e].push(i),()=>{$(this,xs)[e]=$(this,xs)[e].filter(n=>n!==i)}}$destroy(){$(this,Hi).$destroy()}};xs=new WeakMap,Hi=new WeakMap;var cG;typeof HTMLElement=="function"&&(cG=class extends HTMLElement{constructor(e,r,i){super();Ue(this,"$$ctor");Ue(this,"$$s");Ue(this,"$$c");Ue(this,"$$cn",!1);Ue(this,"$$d",{});Ue(this,"$$r",!1);Ue(this,"$$p_d",{});Ue(this,"$$l",{});Ue(this,"$$l_u",new Map);Ue(this,"$$me");Ue(this,"$$shadowRoot",null);this.$$ctor=e,this.$$s=r,i&&(this.$$shadowRoot=this.attachShadow(i))}addEventListener(e,r,i){if(this.$$l[e]=this.$$l[e]||[],this.$$l[e].push(r),this.$$c){let n=this.$$c.$on(e,r);this.$$l_u.set(r,n)}super.addEventListener(e,r,i)}removeEventListener(e,r,i){if(super.removeEventListener(e,r,i),this.$$c){let n=this.$$l_u.get(r);n&&(n(),this.$$l_u.delete(r))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let e=function(n){return s=>{let a=Bn("slot");n!=="default"&&(a.name=n),ue(s,a)}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;let r={},i=uG(this);for(let n of this.$$s)n in i&&(n==="default"&&!this.$$d.children?(this.$$d.children=e(n),r.default=!0):r[n]=e(n));for(let n of this.attributes){let s=this.$$g_p(n.name);s in this.$$d||(this.$$d[s]=fb(s,n.value,this.$$p_d,"toProp"))}for(let n in this.$$p_d)!(n in this.$$d)&&this[n]!==void 0&&(this.$$d[n]=this[n],delete this[n]);this.$$c=h$({component:this.$$ctor,target:this.$$shadowRoot||this,props:{...this.$$d,$$slots:r,$$host:this}}),this.$$me=Y0(()=>{lr(()=>{var n;this.$$r=!0;for(let s of l0(this.$$c)){if(!((n=this.$$p_d[s])!=null&&n.reflect))continue;this.$$d[s]=this.$$c[s];let a=fb(s,this.$$d[s],this.$$p_d,"toAttribute");a==null?this.removeAttribute(this.$$p_d[s].attribute||s):this.setAttribute(this.$$p_d[s].attribute||s,a)}this.$$r=!1})});for(let n in this.$$l)for(let s of this.$$l[n]){let a=this.$$c.$on(n,s);this.$$l_u.set(s,a)}this.$$l={}}}attributeChangedCallback(e,r,i){var n;this.$$r||(e=this.$$g_p(e),this.$$d[e]=fb(e,i,this.$$p_d,"toProp"),(n=this.$$c)==null||n.$set({[e]:this.$$d[e]}))}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{!this.$$cn&&this.$$c&&(this.$$c.$destroy(),this.$$me(),this.$$c=void 0)})}$$g_p(e){return l0(this.$$p_d).find(r=>this.$$p_d[r].attribute===e||!this.$$p_d[r].attribute&&r.toLowerCase()===e)||e}});function fb(t,e,r,i){var s;let n=(s=r[t])==null?void 0:s.type;if(e=n==="Boolean"&&typeof e!="boolean"?e!=null:e,!i||!r[t])return e;if(i==="toAttribute")switch(n){case"Object":case"Array":return e==null?null:JSON.stringify(e);case"Boolean":return e?"":null;case"Number":return e==null?null:e;default:return e}else switch(n){case"Object":case"Array":return e&&JSON.parse(e);case"Boolean":return e;case"Number":return e!=null?+e:e;default:return e}}function uG(t){let e={};return t.childNodes.forEach(r=>{e[r.slot||"default"]=!0}),e}m();var mb=require("obsidian");m();var hb=require("obsidian");m();function fG(t){let e=t-1;return e*e*e+1}var db=!1;function Vn(t,{delay:e=0,duration:r=400,easing:i=fG,axis:n="y"}={}){let s=getComputedStyle(t);O&&!db&&/(contents|inline|table)/.test(s.display)&&(db=!0,Promise.resolve().then(()=>db=!1),tR(s.display));let a=+s.opacity,o=n==="y"?"height":"width",l=parseFloat(s[o]),c=n==="y"?["top","bottom"]:["left","right"],u=c.map(b=>`${b[0].toUpperCase()}${b.slice(1)}`),f=parseFloat(s[`padding${u[0]}`]),d=parseFloat(s[`padding${u[1]}`]),h=parseFloat(s[`margin${u[0]}`]),p=parseFloat(s[`margin${u[1]}`]),g=parseFloat(s[`border${u[0]}Width`]),v=parseFloat(s[`border${u[1]}Width`]);return{delay:e,duration:r,easing:i,css:b=>`overflow: hidden;opacity: ${Math.min(b*20,1)*a};${o}: ${b*l}px;padding-${c[0]}: ${b*f}px;padding-${c[1]}: ${b*d}px;margin-${c[0]}: ${b*h}px;margin-${c[1]}: ${b*p}px;border-${c[0]}-width: ${b*g}px;border-${c[1]}-width: ${b*v}px;min-${o}: 0`}}m();var zp=require("obsidian");var dG=_e('
'),hG=_e('
'),pG={hash:"svelte-1c0jiav",code:"main.svelte-1c0jiav .nav-file-title:where(.svelte-1c0jiav) {align-items:center;}"};function Ef(t,e){ht(e,!0),fn(t,pG);let r=nt([]),i=Le(()=>Hr(e.view.leaf));vr(()=>{for(let _ of r)_&&(0,zp.setIcon)(_,_.getAttr("data-icon"))});function n(_){_.stopPropagation(),ul(e.diff.path)?s(_):a(_)}function s(_){var x;_.stopPropagation();let C=e.view.app.vault.getAbstractFileByPath(e.diff.vaultPath);C instanceof zp.TFile&&((x=Yi(e.view.app,_))==null||x.openFile(C).catch(E=>e.view.plugin.displayError(E)))}function a(_){var C;e.view.plugin.tools.openDiff({event:_,aFile:(C=e.diff.fromPath)!=null?C:e.diff.path,aRef:`${e.diff.hash}^`,bFile:e.diff.path,bRef:e.diff.hash})}var o=hG(),l=V(o),c=V(l),u=V(c,!0);G(c);var f=ne(c,2),d=V(f),h=V(d);{var p=_=>{var C=dG();ot(C,x=>r[0]=x,()=>r==null?void 0:r[0]),mi("auxclick",C,s),me("click",C,s),ue(_,C)},g=Le(()=>fl(e.diff.vaultPath,e.view.app));$e(h,_=>{F(g)&&_(p)})}G(d);var v=ne(d,2),b=V(v,!0);G(v),G(f),G(l),G(o),Ve(_=>{ye(l,"data-path",e.diff.vaultPath),ye(l,"data-tooltip-position",F(i)),ye(l,"aria-label",e.diff.vaultPath),Ye(u,_),ye(v,"data-type",e.diff.status),Ye(b,e.diff.status)},[()=>kn(e.diff.vaultPath)]),me("click",o,n),mi("auxclick",o,_=>{_.stopPropagation(),_.button==2?Sn(e.view.app,_,e.diff.vaultPath,e.view.leaf,"git-history"):n(_)}),ue(t,o),pt()}Mt(["click"]);m();var mG=_e("
"),gG=_e(''),vG=_e('
'),wG=_e("
"),bG={hash:"svelte-d9h7mp",code:"main.svelte-d9h7mp .nav-folder-title-content:where(.svelte-d9h7mp) {display:flex;align-items:center;}"};function Sf(t,e){ht(e,!0),fn(t,bG);let r=Bi(e,"topLevel",3,!1),i=Bi(e,"closed",15),n=Le(()=>Hr(e.view.leaf));function s(l,c){l.stopPropagation(),i(i()[c.path]=!i()[c.path],!0)}var a=wG();let o;wi(a,21,()=>e.hierarchy.children,vi,(l,c)=>{var u=po(),f=Ni(u);{var d=p=>{var g=mG(),v=V(g);Ef(v,{get diff(){return F(c).data},get view(){return e.view}}),G(g),ue(p,g)},h=p=>{var g=vG();let v;var b=V(g),_=ne(V(b),2);let C;var x=ne(_,2),E=V(x,!0);G(x),G(b);var A=ne(b,2);{var w=S=>{var y=gG(),P=V(y);Sf(P,{get hierarchy(){return F(c)},get plugin(){return e.plugin},get view(){return e.view},get closed(){return i()},set closed(T){i(T)}}),G(y),un(3,y,()=>Vn,()=>({duration:150})),ue(S,y)};$e(A,S=>{i()[F(c).path]||S(w)})}G(g),Ve(()=>{v=ft(g,1,"tree-item nav-folder",null,v,{"is-collapsed":i()[F(c).path]}),ye(b,"data-tooltip-position",F(n)),ye(b,"aria-label",F(c).vaultPath),C=ft(_,1,"tree-item-icon nav-folder-collapse-indicator collapse-icon",null,C,{"is-collapsed":i()[F(c).path]}),Ye(E,F(c).title)}),me("click",b,S=>s(S,F(c))),ue(p,g)};$e(f,p=>{F(c).data?p(d):p(h,-1)})}ue(l,u)}),G(a),Ve(()=>o=ft(a,1,"svelte-d9h7mp",null,o,{topLevel:r()})),ue(t,a),pt()}Mt(["click"]);var _G=_e('
'),yG=_e('
'),xG=_e('
'),EG=_e(''),SG=_e('
'),kG={hash:"svelte-1edsiy5",code:""};function pb(t,e){ht(e,!0),fn(t,kG);let r=Le(()=>({title:"",path:"",vaultPath:"",children:e.plugin.gitManager.getTreeStructure(e.log.diff.files)})),i=Le(()=>Hr(e.view.leaf)),n=Ne(!0),s=Ne(nt({}));function a(S){let y=S.author.name;return e.plugin.settings.authorInHistoryView=="full"?y:e.plugin.settings.authorInHistoryView=="initials"?y.split(" ").filter(T=>T.length>0).map(T=>T[0].toUpperCase()).join(""):""}var o=SG(),l=V(o);let c;var u=V(l),f=V(u);let d;var h=ne(f,2),p=V(h);{var g=S=>{var y=_G(),P=V(y,!0);G(y),Ve(T=>Ye(P,T),[()=>e.log.refs.join(", ")]),ue(S,y)};$e(p,S=>{e.log.refs.length>0&&S(g)})}var v=ne(p,2);{var b=S=>{var y=yG(),P=V(y,!0);G(y),Ve(T=>Ye(P,T),[()=>a(e.log)]),ue(S,y)};$e(v,S=>{var y;e.plugin.settings.authorInHistoryView!="hide"&&((y=e.log.author)!=null&&y.name)&&S(b)})}var _=ne(v,2);{var C=S=>{var y=xG(),P=V(y,!0);G(y),Ve(T=>Ye(P,T),[()=>(0,hb.moment)(e.log.date).format(e.plugin.settings.commitDateFormat)]),ue(S,y)};$e(_,S=>{e.plugin.settings.dateInHistoryView&&S(C)})}var x=ne(_,2),E=V(x,!0);G(x),G(h),G(u);var A=ne(u,2);{var w=S=>{var y=EG(),P=V(y);{var T=M=>{Sf(M,{get hierarchy(){return F(r)},get plugin(){return e.plugin},get view(){return e.view},topLevel:!0,get closed(){return F(s)},set closed(B){ae(s,B,!0)}})},I=M=>{var B=po(),re=Ni(B);wi(re,17,()=>e.log.diff.files,vi,(Ae,K)=>{Ef(Ae,{get view(){return e.view},get diff(){return F(K)}})}),ue(M,B)};$e(P,M=>{e.showTree?M(T):M(I,-1)})}G(y),un(3,y,()=>Vn,()=>({duration:150})),ue(S,y)};$e(A,S=>{F(n)||S(w)})}G(l),G(o),Ve(S=>{c=ft(l,1,"tree-item nav-folder",null,c,{"is-collapsed":F(n)}),ye(u,"aria-label",S),ye(u,"data-tooltip-position",F(i)),d=ft(f,1,"tree-item-icon nav-folder-collapse-indicator collapse-icon",null,d,{"is-collapsed":F(n)}),Ye(E,e.log.message)},[()=>{var S;return`${e.log.refs.length>0?e.log.refs.join(", ")+` +`:""}${(S=e.log.author)==null?void 0:S.name} +${(0,hb.moment)(e.log.date).format(e.plugin.settings.commitDateFormat)} +${e.log.message}`}]),me("click",u,()=>ae(n,!F(n))),ue(t,o),pt()}Mt(["click"]);var CG=_e(''),AG=_e('
'),TG={hash:"svelte-12n6twc",code:""};function gb(t,e){ht(e,!0),fn(t,TG);let r=Bi(e,"plugin",15),i=Ne(!1),n=nt([]),s=Ne(void 0),a=Ne(nt(r().settings.treeStructure)),o;vr(()=>{o&&o.empty()}),go(()=>{e.view.registerEvent(e.view.app.workspace.on("obsidian-git:head-change",()=>{c().catch(console.error)}))}),vr(()=>{n.forEach(x=>(0,mb.setIcon)(x,x.getAttr("data-icon")))}),go(()=>{let x=new IntersectionObserver(A=>{var w;(w=A[0])!=null&&w.isIntersecting&&!F(i)&&u().catch(console.error)}),E=activeDocument.querySelector("#sentinel");return E&&x.observe(E),()=>{x.disconnect()}}),c().catch(console.error);function l(){c().catch(console.error)}async function c(){var A,w;if(!r().gitReady){ae(s,void 0);return}ae(i,!0);let x=r().gitManager instanceof ke,E;((w=(A=F(s))==null?void 0:A.length)!=null?w:0)==0?E=x?50:10:E=F(s).length,ae(s,await r().gitManager.log(void 0,!1,E),!0),ae(i,!1)}async function u(){var w;if(!r().gitReady||F(s)===void 0)return;ae(i,!0);let E=r().gitManager instanceof ke?50:10,A=await r().gitManager.log(void 0,!1,E,(w=F(s).last())==null?void 0:w.hash);F(s).push(...A.slice(1)),ae(i,!1)}var f=AG(),d=V(f),h=V(d),p=V(h);ot(p,x=>n[0]=x,()=>n==null?void 0:n[0]);var g=ne(p,2);let v;ot(g,x=>n[1]=x,()=>n==null?void 0:n[1]),G(h),G(d);var b=ne(d,2),_=V(b);{var C=x=>{var E=CG();wi(E,21,()=>F(s),vi,(A,w)=>{pb(A,{get view(){return e.view},get showTree(){return F(a)},get log(){return F(w)},get plugin(){return r()}})}),G(E),ue(x,E)};$e(_,x=>{F(s)&&x(C)})}Ka(4),G(b),G(f),Ve(()=>{ye(p,"data-icon",F(a)?"list":"folder"),v=ft(g,1,"clickable-icon nav-action-button",null,v,{loading:F(i)})}),me("click",p,()=>{ae(a,!F(a)),(0,mb.setIcon)(n[0],F(a)?"list":"folder"),r(r().settings.treeStructure=F(a),!0),r().saveSettings()}),me("click",g,l),ue(t,f),pt()}Mt(["click"]);var kf=class extends p$.ItemView{constructor(e,r){super(e),this.plugin=r,this.hoverPopover=null}getViewType(){return Ei.type}getDisplayText(){return Ei.name}getIcon(){return Ei.icon}async onClose(){return this._view&&await _s(this._view),super.onClose()}async reload(){this._view&&await _s(this._view),this._view=na(gb,{target:this.contentEl,props:{plugin:this.plugin,view:this}})}async onOpen(){return await this.reload(),super.onOpen()}};m();var m$=require("obsidian"),Wp=class extends m$.FuzzySuggestModal{constructor(r,i){super(r.app);this.branches=i;this.setPlaceholder("Select branch to checkout")}getItems(){return this.branches}getItemText(r){return r}onChooseItem(r,i){this.resolve(r)}openAndGetReslt(){return new Promise(r=>{this.resolve=r,this.open()})}onClose(){new Promise(r=>window.setTimeout(r,10)).then(()=>{this.resolve&&this.resolve(void 0)})}};m();var w$=require("obsidian");m();var zn=require("obsidian");m();var Cf=require("obsidian");m();var g$=require("obsidian");var vc=class extends g$.Modal{constructor({app:r,path:i,filesToDeleteCount:n,filesToDiscardCount:s}){super(r);this.resolve=null;this.path=i,this.deleteCount=n,this.discardCount=s}openAndGetResult(){return this.open(),new Promise(r=>{this.resolve=r})}onOpen(){let r=this.deleteCount+this.discardCount,{contentEl:i,titleEl:n}=this,s="";this.path!=""&&(r>1?s=`files in "${this.path}"`:s=`"${this.path}"`),n.setText(`${this.discardCount==0?"Delete":"Discard"} ${s}`),this.deleteCount>0&&i.createEl("p").setText(`Are you sure you want to DELETE the ${xu(this.deleteCount,"untracked file")}? They are deleted according to your Obsidian trash settting.`),this.discardCount>0&&i.createEl("p").setText(`Are you sure you want to discard ALL changes in ${xu(this.discardCount,"tracked file")}?`);let a=i.createDiv({cls:"modal-button-container"});if(this.deleteCount>0){let l=a.createEl("button",{cls:"mod-warning",text:`${this.discardCount>0?"Discard":"Delete"} all ${xu(r,"file")}`});l.addEventListener("click",()=>{this.resolve&&this.resolve("delete"),this.close()}),l.addEventListener("keypress",()=>{this.resolve&&this.resolve("delete"),this.close()})}if(this.discardCount>0){let l=a.createEl("button",{cls:"mod-warning",text:`Discard all ${xu(this.discardCount,"tracked file")}`});l.addEventListener("click",()=>{this.resolve&&this.resolve("discard"),this.close()}),l.addEventListener("keypress",()=>{this.resolve&&this.resolve("discard"),this.close()})}let o=a.createEl("button",{text:"Cancel"});o.addEventListener("click",()=>(this.resolve&&this.resolve(!1),this.close())),o.addEventListener("keypress",()=>(this.resolve&&this.resolve(!1),this.close()))}onClose(){let{contentEl:r}=this;r.empty()}};var PG=_e('
'),RG=_e('
');function Af(t,e){ht(e,!0);let r=nt([]),i=Le(()=>Hr(e.view.leaf));vr(()=>{for(let w of r)w&&(0,Cf.setIcon)(w,w.getAttr("data-icon"))});function n(w){w.stopPropagation(),ul(e.change.path)?a(w):l(w)}function s(w){e.view.app.vault.getAbstractFileByPath(e.change.vaultPath)&&dl(e.view.app,w,e.view,e.change.vaultPath)}function a(w){var y;w.stopPropagation();let S=e.view.app.vault.getAbstractFileByPath(e.change.vaultPath);S instanceof Cf.TFile&&((y=Yi(e.view.app,w))==null||y.openFile(S).catch(P=>e.view.plugin.displayError(P)))}function o(w){w.stopPropagation(),e.manager.stage(e.change.path,!1).catch(S=>e.view.plugin.displayError(S)).finally(()=>{e.view.app.workspace.trigger("obsidian-git:refresh")})}function l(w){w.stopPropagation(),e.view.plugin.tools.openDiff({aFile:e.change.path,aRef:"",event:w})}function c(w){w.stopPropagation();let S=e.change.workingDir=="U";new vc({app:e.view.app,filesToDeleteCount:S?1:0,filesToDiscardCount:S?0:1,path:e.change.vaultPath}).openAndGetResult().then(async y=>{if(y=="delete"){let P=e.view.app.vault.getAbstractFileByPath(e.change.vaultPath);P instanceof Cf.TFile?await e.view.app.fileManager.trashFile(P):await e.view.app.vault.adapter.remove(e.change.vaultPath)}else y=="discard"&&await e.manager.discard(e.change.path).finally(()=>{e.view.app.workspace.trigger("obsidian-git:refresh")});e.view.app.workspace.trigger("obsidian-git:refresh")},y=>e.view.plugin.displayError(y))}var u=RG(),f=V(u),d=V(f),h=V(d,!0);G(d);var p=ne(d,2),g=V(p),v=V(g);{var b=w=>{var S=PG();ot(S,y=>r[0]=y,()=>r==null?void 0:r[0]),mi("auxclick",S,a),me("click",S,a),ue(w,S)},_=Le(()=>fl(e.change.vaultPath,e.view.app));$e(v,w=>{F(_)&&w(b)})}var C=ne(v,2);ot(C,w=>r[1]=w,()=>r==null?void 0:r[1]);var x=ne(C,2);ot(x,w=>r[2]=w,()=>r==null?void 0:r[2]),G(g);var E=ne(g,2),A=V(E,!0);G(E),G(p),G(f),G(u),Ve(w=>{ye(f,"data-path",e.change.vaultPath),ye(f,"data-tooltip-position",F(i)),ye(f,"aria-label",e.change.vaultPath),Ye(h,w),ye(E,"data-type",e.change.workingDir),Ye(A,e.change.workingDir)},[()=>kn(e.change.vaultPath)]),me("mouseover",u,s),me("click",u,n),mi("auxclick",u,w=>{w.stopPropagation(),w.button==2?Sn(e.view.app,w,e.change.vaultPath,e.view.leaf,"git-source-control"):n(w)}),me("click",C,c),me("click",x,o),ue(t,u),pt()}Mt(["mouseover","click"]);m();var v$=require("obsidian");var $G=_e('
');function Tf(t,e){ht(e,!0);let r=Le(()=>Hr(e.view.leaf));function i(d){e.view.app.vault.getAbstractFileByPath(e.change.vaultPath)&&dl(e.view.app,d,e.view,e.change.vaultPath)}function n(d){var p;d.stopPropagation();let h=e.view.app.vault.getAbstractFileByPath(e.change.vaultPath);h instanceof v$.TFile&&((p=Yi(e.view.app,d))==null||p.openFile(h).catch(g=>e.view.plugin.displayError(g)))}var s=$G(),a=V(s),o=V(a),l=V(o,!0);G(o);var c=ne(o,2),u=V(c),f=V(u,!0);G(u),G(c),G(a),G(s),Ve(d=>{ye(a,"data-path",e.change.vaultPath),ye(a,"data-tooltip-position",F(r)),ye(a,"aria-label",e.change.vaultPath),Ye(l,d),ye(u,"data-type",e.change.workingDir),Ye(f,e.change.workingDir)},[()=>kn(e.change.vaultPath)]),me("mouseover",s,i),me("click",s,n),mi("auxclick",s,d=>{d.stopPropagation(),d.button==2?Sn(e.view.app,d,e.change.vaultPath,e.view.leaf,"git-source-control"):n(d)}),ue(t,s),pt()}Mt(["mouseover","click"]);m();var qp=require("obsidian");var FG=_e('
'),IG=_e('
');function Pf(t,e){ht(e,!0);let r=nt([]),i=Le(()=>Hr(e.view.leaf));vr(()=>{for(let E of r)E&&(0,qp.setIcon)(E,E.getAttr("data-icon"))});function n(E){E.stopPropagation(),ul(e.change.path)?a(E):o(E)}function s(E){e.view.app.vault.getFileByPath(e.change.vaultPath)&&dl(e.view.app,E,e.view,e.change.vaultPath)}function a(E){var w;E.stopPropagation();let A=e.view.app.vault.getAbstractFileByPath(e.change.vaultPath);A instanceof qp.TFile&&((w=Yi(e.view.app,E))==null||w.openFile(A).catch(S=>e.view.plugin.displayError(S)))}function o(E){var A;E.stopPropagation(),e.view.plugin.tools.openDiff({aFile:(A=e.change.from)!=null?A:e.change.path,bFile:e.change.path,aRef:"HEAD",bRef:"",event:E})}function l(E){E.stopPropagation(),e.manager.unstage(e.change.path,!1).catch(A=>e.view.plugin.displayError(A)).finally(()=>{e.view.app.workspace.trigger("obsidian-git:refresh")})}var c=IG(),u=V(c),f=V(u),d=V(f,!0);G(f);var h=ne(f,2),p=V(h),g=V(p);{var v=E=>{var A=FG();ot(A,w=>r[0]=w,()=>r==null?void 0:r[0]),me("click",A,a),ue(E,A)},b=Le(()=>fl(e.change.vaultPath,e.view.app));$e(g,E=>{F(b)&&E(v)})}var _=ne(g,2);ot(_,E=>r[1]=E,()=>r==null?void 0:r[1]),G(p);var C=ne(p,2),x=V(C,!0);G(C),G(h),G(u),G(c),Ve(E=>{ye(u,"data-path",e.change.vaultPath),ye(u,"data-tooltip-position",F(i)),ye(u,"aria-label",e.change.vaultPath),Ye(d,E),ye(C,"data-type",e.change.index),Ye(x,e.change.index)},[()=>kn(e.change.vaultPath)]),me("mouseover",c,s),me("click",c,n),mi("auxclick",c,E=>{E.stopPropagation(),E.button==2?Sn(e.view.app,E,e.change.vaultPath,e.view.leaf,"git-source-control"):n(E)}),me("click",_,l),ue(t,c),pt()}Mt(["mouseover","click"]);m();m();var MG=_e(''),DG=_e("
");function vo(t,e){ht(e,!0);var r=DG(),i=V(r);{var n=s=>{var a=MG(),o=V(a),l=V(o),c=V(l,!0);G(l),G(o),G(a),Ve(()=>{ye(o,"aria-label","And "+(e.files.length-500)+" more files"),Ye(c,"And "+(e.files.length-500)+" more files")}),ue(s,a)};$e(i,s=>{e.files.length>500&&s(n)})}G(r),ue(t,r),pt()}var LG=_e("
"),NG=_e('
'),BG=_e('
',1),HG=_e(''),UG=_e('
'),GG=_e("
");function wo(t,e){ht(e,!0);let r=Bi(e,"topLevel",3,!1),i=Bi(e,"closed",15);go(()=>{var h,p;for(let g of e.hierarchy.children)((p=(h=g.children)==null?void 0:h.length)!=null?p:0)>100&&i(i()[g.title]=!0,!0)});let n=Le(()=>Hr(e.view.leaf));function s(h,p){h.stopPropagation(),e.plugin.gitManager.stageAll({dir:p}).catch(g=>e.plugin.displayError(g)).finally(()=>{e.view.app.workspace.trigger("obsidian-git:refresh")})}function a(h,p){h.stopPropagation(),e.plugin.gitManager.unstageAll({dir:p}).catch(g=>e.plugin.displayError(g)).finally(()=>{e.view.app.workspace.trigger("obsidian-git:refresh")})}function o(h,p){h.stopPropagation(),e.plugin.discardAll(p.vaultPath)}function l(h,p){h.stopPropagation(),i(i()[p.path]=!i()[p.path],!0)}var c=GG();let u;var f=V(c);wi(f,17,()=>Eu(e.hierarchy.children,500),vi,(h,p)=>{var g=po(),v=Ni(g);{var b=C=>{var x=LG(),E=V(x);{var A=y=>{Pf(y,{get change(){return F(p).data},get manager(){return e.plugin.gitManager},get view(){return e.view}})},w=y=>{Af(y,{get change(){return F(p).data},get manager(){return e.plugin.gitManager},get view(){return e.view}})},S=y=>{Tf(y,{get change(){return F(p).data},get view(){return e.view}})};$e(E,y=>{e.fileType==0?y(A):e.fileType==1?y(w,1):e.fileType==2&&y(S,2)})}G(x),ue(C,x)},_=C=>{var x=UG();let E;var A=V(x),w=ne(V(A),2);let S;var y=ne(w,2),P=V(y,!0);G(y);var T=ne(y,2),I=V(T),M=V(I);{var B=Q=>{var fe=NG();me("click",fe,ce=>a(ce,F(p).path)),ue(Q,fe)},re=Q=>{var fe=BG(),ce=Ni(fe),z=ne(ce,2);me("click",ce,X=>o(X,F(p))),me("click",z,X=>s(X,F(p).path)),ue(Q,fe)};$e(M,Q=>{e.fileType==0?Q(B):Q(re,-1)})}Ka(2),G(I),G(T),G(A);var Ae=ne(A,2);{var K=Q=>{var fe=HG(),ce=V(fe);wo(ce,{get hierarchy(){return F(p)},get plugin(){return e.plugin},get view(){return e.view},get fileType(){return e.fileType},get closed(){return i()},set closed(z){i(z)}}),G(fe),un(3,fe,()=>Vn,()=>({duration:150})),ue(Q,fe)};$e(Ae,Q=>{i()[F(p).path]||Q(K)})}G(x),Ve(()=>{E=ft(x,1,"tree-item nav-folder",null,E,{"is-collapsed":i()[F(p).path]}),ye(A,"data-tooltip-position",F(n)),ye(A,"aria-label",F(p).vaultPath),S=ft(w,1,"tree-item-icon nav-folder-collapse-indicator collapse-icon",null,S,{"is-collapsed":i()[F(p).path]}),Ye(P,F(p).title)}),mi("auxclick",x,Q=>Sn(e.view.app,Q,F(p).vaultPath,e.view.leaf,"git-source-control")),me("click",A,Q=>l(Q,F(p))),ue(C,x)};$e(v,C=>{F(p).data?C(b):C(_,-1)})}ue(h,g)});var d=ne(f,2);vo(d,{get files(){return e.hierarchy.children}}),G(c),Ve(()=>u=ft(c,1,"",null,u,{topLevel:r()})),ue(t,c),pt()}Mt(["click"]);var jG=_e('
'),vb=_e(" ",1),wb=_e(''),VG=_e('
'),zG=_e(''),WG=_e('
'),qG={hash:"svelte-5wq9p",code:`.commit-action-group.svelte-5wq9p {display:inline-flex;flex:0 0 auto;gap:0;overflow:hidden;border:1px solid var(--background-modifier-border);border-radius:var(--radius-s);}.commit-action-group.svelte-5wq9p .nav-action-button:where(.svelte-5wq9p) {margin:0;border-radius:0;}.commit-action-group.svelte-5wq9p .nav-action-button:where(.svelte-5wq9p) + .nav-action-button:where(.svelte-5wq9p) {border-left:1px solid var(--background-modifier-border);}.commit-action-group.svelte-5wq9p #commit-menu:where(.svelte-5wq9p) {width:var(--size-4-5);padding-right:0;padding-left:0;}.commit-msg-input.svelte-5wq9p {width:100%;overflow:hidden;resize:none;padding:7px 5px;background-color:var(--background-modifier-form-field);}.git-commit-msg.svelte-5wq9p {position:relative;padding:0;width:calc(100% - var(--size-4-8));margin:4px auto;}main.svelte-5wq9p .git-tools:where(.svelte-5wq9p) .files-count:where(.svelte-5wq9p) {padding-left:var(--size-2-1);width:11px;display:flex;align-items:center;justify-content:center;}.nav-folder-title.svelte-5wq9p {align-items:center;}.git-commit-msg-clear-button.svelte-5wq9p {position:absolute;background:transparent;border-radius:50%;color:var(--search-clear-button-color);cursor:var(--cursor);top:-4px;right:2px;bottom:0px;line-height:0;height:var(--input-height);width:28px;margin:auto;padding:0 0;text-align:center;display:flex;justify-content:center;align-items:center;transition:color 0.15s ease-in-out;}.git-commit-msg-clear-button.svelte-5wq9p:after {content:"";height:var(--search-clear-button-size);width:var(--search-clear-button-size);display:block;background-color:currentColor;mask-image:url("data:image/svg+xml,");mask-repeat:no-repeat;-webkit-mask-image:url("data:image/svg+xml,");-webkit-mask-repeat:no-repeat;}`};function bb(t,e){ht(e,!0),fn(t,qG);let r=Bi(e,"plugin",7),i=Bi(e,"view",7),n=Ne(!1),s=Ne(void 0),a=Ne(nt([])),o=Le(()=>r().settings.commitMessage),l=nt([]),c=Ne(void 0),u=Ne(void 0),f=Ne(void 0),d=Ne(!0),h=Ne(!0),p=Ne(!0),g=Ne(0),v=Ne(nt({})),b=Ne(nt({})),_=Ne(nt({})),C=Le(()=>{var Z,De;return(De=(Z=F(s))==null?void 0:Z.staged.length)!=null?De:0}),x=Le(()=>{var Z,De;return(De=(Z=F(s))==null?void 0:Z.changed.length)!=null?De:0}),E=Le(()=>{var Z,De;return((De=(Z=F(s))==null?void 0:Z.conflicted.length)!=null?De:0)>0}),A=Le(()=>F(C)+F(x)>0),w=Le(()=>!M("smart")),S=Le(()=>!B("all")),y=Le(()=>I(!1)),P=Le(()=>I(!0)),T=Le(()=>r().settings.treeStructure);go(()=>{i().registerEvent(i().app.workspace.on("obsidian-git:loading-status",()=>ae(n,!0))),i().registerEvent(i().app.workspace.on("obsidian-git:status-changed",()=>{fe().catch(console.error)})),i().plugin.cachedStatus==null?i().plugin.refresh().catch(console.error):fe().catch(console.error),i().scope=new zn.Scope(r().app.scope),i().scope.register(["Ctrl"],"Enter",Z=>K())}),vr(()=>{l.forEach(Z=>(0,zn.setIcon)(Z,Z.getAttr("data-icon")))}),vr(()=>{l.forEach(Z=>{var De,Xt;!Z||Z.id!="push"||(zn.Platform.isMobile?(Z.removeClass("button-border"),F(g)>0&&Z.addClass("button-border")):((De=Z.firstElementChild)==null||De.removeAttribute("color"),F(g)>0&&((Xt=Z.firstElementChild)==null||Xt.setAttr("color","var(--text-accent)"))))})});function I(Z){let De=Z?" and sync":"";return F(E)?"Resolve conflicts before committing":F(A)?Z?"Commit all changes and sync":F(C)>0?`Commit ${F(C)} staged ${F(C)===1?"file":"files"}${De}`:r().settings.autoStageOnEmptyIndex?`Stage and commit all ${F(x)} changed ${F(x)===1?"file":"files"}${De}`:"Nothing staged \u2014 stage changes before committing":Z?"Sync (no changes to commit)":"No changes to commit"}function M(Z){return F(E)?!1:Z==="staged"?F(C)>0:Z==="all"?F(A):F(C)>0||r().settings.autoStageOnEmptyIndex&&F(x)>0}function B(Z){return F(E)?!1:Z==="all"||F(C)>0}function re(Z="smart"){M(Z)&&(ae(n,!0),F(s)&&r().promiseQueue.addTask(()=>r().commit({fromAuto:!1,commitMessage:F(o),mode:Z}).then(()=>ae(o,r().settings.commitMessage)).finally(ce)))}function Ae(){M("staged")&&(ae(n,!0),r().promiseQueue.addTask(()=>r().commit({fromAuto:!1,commitMessage:F(o),mode:"staged",amend:!0}).then(()=>ae(o,r().settings.commitMessage)).finally(ce)))}function K(Z="all"){B(Z)&&(ae(n,!0),F(s)&&r().promiseQueue.addTask(()=>r().commitAndSync({fromAutoBackup:!1,commitMessage:F(o),mode:Z}).then(()=>{ae(o,r().settings.commitMessage)}).finally(ce)))}function Q(Z){Z.stopPropagation();let De=zn.Menu.forEvent(Z);De.addItem(Xt=>Xt.setTitle("Commit staged").setIcon("git-commit").setDisabled(!M("staged")).onClick(()=>re("staged"))),De.addItem(Xt=>Xt.setTitle("Stage all and commit").setIcon("list-plus").setDisabled(!M("all")).onClick(()=>re("all"))),zn.Platform.isDesktopApp&&De.addItem(Xt=>Xt.setTitle("Amend staged").setIcon("git-commit").setDisabled(!M("staged")).onClick(Ae)),De.addSeparator(),De.addItem(Xt=>Xt.setTitle("Commit staged and sync").setIcon("arrow-up-circle").setDisabled(!M("staged")).onClick(()=>K("staged"))),De.showAtMouseEvent(Z)}async function fe(){if(!r().gitReady){ae(s,void 0);return}if(ae(g,await r().gitManager.getUnpushedCommits(),!0),ae(s,r().cachedStatus,!0),ae(n,!1),r().lastPulledFiles&&r().lastPulledFiles!=F(a)&&(ae(a,r().lastPulledFiles,!0),ae(f,{title:"",path:"",vaultPath:"",children:r().gitManager.getTreeStructure(F(a))},!0)),F(s)){let Z=(De,Xt)=>De.vaultPath.split("/").last().localeCompare(kn(Xt.vaultPath));F(s).changed.sort(Z),F(s).staged.sort(Z),ae(c,{title:"",path:"",vaultPath:"",children:r().gitManager.getTreeStructure(F(s).changed)},!0),ae(u,{title:"",path:"",vaultPath:"",children:r().gitManager.getTreeStructure(F(s).staged)},!0)}else ae(c,void 0),ae(u,void 0)}function ce(){i().app.workspace.trigger("obsidian-git:refresh")}function z(Z){Z.stopPropagation(),ae(n,!0),r().promiseQueue.addTask(()=>r().gitManager.stageAll({status:F(s)}).finally(ce))}function X(Z){Z.stopPropagation(),ae(n,!0),r().promiseQueue.addTask(()=>r().gitManager.unstageAll({status:F(s)}).finally(ce))}function j(){ae(n,!0),r().promiseQueue.addTask(()=>r().push().finally(ce))}function Ze(){ae(n,!0),r().promiseQueue.addTask(()=>r().pullChangesFromRemote().finally(ce))}function $r(Z){Z.stopPropagation(),r().discardAll()}let cr=Le(()=>(F(o).match(/\n/g)||[]).length+1||1);var Ie=WG(),yt=V(Ie),Tt=V(yt),Ke=V(Tt),J=V(Ke);let L;ot(J,Z=>l[0]=Z,()=>l==null?void 0:l[0]);var W=ne(J,2);let xe;ot(W,Z=>l[1]=Z,()=>l==null?void 0:l[1]);var Xe=ne(W,2);ot(Xe,Z=>l[10]=Z,()=>l==null?void 0:l[10]),G(Ke);var Dt=ne(Ke,2);ot(Dt,Z=>l[2]=Z,()=>l==null?void 0:l[2]);var ti=ne(Dt,2);ot(ti,Z=>l[3]=Z,()=>l==null?void 0:l[3]);var aa=ne(ti,2);ot(aa,Z=>l[4]=Z,()=>l==null?void 0:l[4]);var om=ne(aa,2);ot(om,Z=>l[5]=Z,()=>l==null?void 0:l[5]);var $f=ne(om,2);ot($f,Z=>l[6]=Z,()=>l==null?void 0:l[6]);var lm=ne($f,2);let Eb;ot(lm,Z=>l[7]=Z,()=>l==null?void 0:l[7]),G(Tt),G(yt);var cm=ne(yt,2),Ff=V(cm);x0(Ff);var C$=ne(Ff,2);{var A$=Z=>{var De=jG();ye(De,"aria-label","Clear"),me("click",De,()=>ae(o,"")),ue(Z,De)};$e(C$,Z=>{F(o)&&Z(A$)})}G(cm);var Sb=ne(cm,2),T$=V(Sb);{var P$=Z=>{var De=zG(),Xt=V(De);let kb;var If=V(Xt),Cb=V(If);let Ab;var Tb=ne(Cb,4),um=V(Tb),Pb=V(um);ot(Pb,wr=>l[8]=wr,()=>l==null?void 0:l[8]),G(um);var Rb=ne(um,2),R$=V(Rb,!0);G(Rb),G(Tb),G(If);var $$=ne(If,2);{var F$=wr=>{var Fr=wb(),yo=V(Fr);{var Es=br=>{wo(br,{get hierarchy(){return F(u)},get plugin(){return r()},get view(){return i()},get fileType(){return 0},topLevel:!0,get closed(){return F(v)},set closed(Ui){ae(v,Ui,!0)}})},xo=br=>{var Ui=vb(),oa=Ni(Ui);wi(oa,17,()=>Eu(F(s).staged,500),vi,(Ss,bc)=>{Pf(Ss,{get change(){return F(bc)},get view(){return i()},get manager(){return r().gitManager}})});var la=ne(oa,2);vo(la,{get files(){return F(s).staged}}),ue(br,Ui)};$e(yo,br=>{F(T)?br(Es):br(xo,-1)})}G(Fr),un(3,Fr,()=>Vn,()=>({duration:150})),ue(wr,Fr)};$e($$,wr=>{F(h)&&wr(F$)})}G(Xt);var Mf=ne(Xt,2);let $b;var Df=V(Mf),Fb=V(Df);let Ib;var Mb=ne(Fb,4),fm=V(Mb),Db=V(fm),Ob=ne(Db,2);ot(Ob,wr=>l[9]=wr,()=>l==null?void 0:l[9]),G(fm);var Lb=ne(fm,2),I$=V(Lb,!0);G(Lb),G(Mb),G(Df);var M$=ne(Df,2);{var D$=wr=>{var Fr=wb(),yo=V(Fr);{var Es=br=>{wo(br,{get hierarchy(){return F(c)},get plugin(){return r()},get view(){return i()},get fileType(){return 1},topLevel:!0,get closed(){return F(b)},set closed(Ui){ae(b,Ui,!0)}})},xo=br=>{var Ui=vb(),oa=Ni(Ui);wi(oa,17,()=>Eu(F(s).changed,500),vi,(Ss,bc)=>{Af(Ss,{get change(){return F(bc)},get view(){return i()},get manager(){return r().gitManager}})});var la=ne(oa,2);vo(la,{get files(){return F(s).changed}}),ue(br,Ui)};$e(yo,br=>{F(T)?br(Es):br(xo,-1)})}G(Fr),un(3,Fr,()=>Vn,()=>({duration:150})),ue(wr,Fr)};$e(M$,wr=>{F(d)&&wr(D$)})}G(Mf);var O$=ne(Mf,2);{var L$=wr=>{var Fr=VG();let yo;var Es=V(Fr),xo=ne(V(Es),4),br=V(xo,!0);G(xo),G(Es);var Ui=ne(Es,2);{var oa=la=>{var Ss=wb(),bc=V(Ss);{var N$=Eo=>{wo(Eo,{get hierarchy(){return F(f)},get plugin(){return r()},get view(){return i()},get fileType(){return 2},topLevel:!0,get closed(){return F(_)},set closed(Of){ae(_,Of,!0)}})},B$=Eo=>{var Of=vb(),Nb=Ni(Of);wi(Nb,17,()=>F(a),vi,(U$,G$)=>{Tf(U$,{get change(){return F(G$)},get view(){return i()}})});var H$=ne(Nb,2);vo(H$,{get files(){return F(a)}}),ue(Eo,Of)};$e(bc,Eo=>{F(T)?Eo(N$):Eo(B$,-1)})}G(Ss),un(3,Ss,()=>Vn,()=>({duration:150})),ue(la,Ss)};$e(Ui,la=>{F(p)&&la(oa)})}G(Fr),Ve(()=>{yo=ft(Fr,1,"pulled nav-folder",null,yo,{"is-collapsed":!F(p)}),Ye(br,F(a).length)}),me("click",Es,()=>ae(p,!F(p))),ue(wr,Fr)};$e(O$,wr=>{F(a).length>0&&F(f)&&wr(L$)})}G(De),Ve(()=>{kb=ft(Xt,1,"staged tree-item nav-folder",null,kb,{"is-collapsed":!F(h)}),Ab=ft(Cb,1,"tree-item-icon nav-folder-collapse-indicator collapse-icon",null,Ab,{"is-collapsed":!F(h)}),Ye(R$,F(s).staged.length),$b=ft(Mf,1,"changes tree-item nav-folder",null,$b,{"is-collapsed":!F(d)}),Ib=ft(Fb,1,"tree-item-icon nav-folder-collapse-indicator collapse-icon",null,Ib,{"is-collapsed":!F(d)}),Ye(I$,F(s).changed.length)}),me("click",If,()=>ae(h,!F(h))),me("click",Pb,X),me("click",Df,()=>ae(d,!F(d))),me("click",Db,$r),me("click",Ob,z),ue(Z,De)};$e(T$,Z=>{F(s)&&F(u)&&F(c)&&Z(P$)})}G(Sb),G(Ie),Ve(()=>{ye(Ie,"data-type",er.type),L=ft(J,1,"clickable-icon nav-action-button svelte-5wq9p",null,L,{"is-disabled":F(S)}),ye(J,"aria-label",F(P)),ye(J,"aria-disabled",F(S)),xe=ft(W,1,"clickable-icon nav-action-button svelte-5wq9p",null,xe,{"is-disabled":F(w)}),ye(W,"aria-label",F(y)),ye(W,"aria-disabled",F(w)),ye($f,"data-icon",F(T)?"list":"folder"),Eb=ft(lm,1,"clickable-icon nav-action-button",null,Eb,{loading:F(n)}),ye(Ff,"rows",F(cr))}),me("click",J,()=>K()),me("click",W,()=>re()),me("click",Xe,Q),me("click",Dt,z),me("click",ti,X),me("click",aa,j),me("click",om,Ze),me("click",$f,()=>{ae(T,!F(T)),(0,zn.setIcon)(l[6],F(T)?"list":"folder"),r().settings.treeStructure=F(T),r().saveSettings()}),me("click",lm,ce),ob(Ff,()=>F(o),Z=>ae(o,Z)),ue(t,Ie),pt()}Mt(["click"]);var Rf=class extends w$.ItemView{constructor(e,r){super(e),this.plugin=r,this.hoverPopover=null}getViewType(){return er.type}getDisplayText(){return er.name}getIcon(){return er.icon}async onClose(){return this._view&&await _s(this._view),super.onClose()}async reload(){this._view&&await _s(this._view),this._view=na(bb,{target:this.contentEl,props:{plugin:this.plugin,view:this}})}async onOpen(){return await this.reload(),super.onOpen()}};m();var Yp=class{constructor(e,r){this.statusBarEl=e;this.plugin=r;this.statusBarEl.addClass("mod-clickable"),this.statusBarEl.onClickEvent(i=>{this.plugin.switchBranch().catch(n=>r.displayError(n))})}async display(){if(this.plugin.gitReady){let e=await this.plugin.gitManager.branchInfo();e.current!=null?this.statusBarEl.setText(e.current):this.statusBarEl.empty()}else this.statusBarEl.empty()}remove(){this.statusBarEl.remove()}};m();var b$=require("obsidian");var Zp=class{constructor(e){this.plugin=e}get editor(){var i;let e=(i=this.plugin.app.workspace.activeEditor)==null?void 0:i.editor,r=e==null?void 0:e.cm;if(!(!e||!Ki.hasHunksData(r.state)))return{editor:r,obEditor:e}}get gitManager(){return this.plugin.gitManager}resetHunk(e){if(!this.editor)return;let{editor:r,obEditor:i}=this.editor,n=Ki.getHunk(r.state,!1,e);if(n){let s,a;n.type==="delete"?(s=n.added.start+1,a=n.added.start+1):(s=n.added.start-0,a=n.added.start-1+n.added.count);let o=r.state.doc.line(s).from,l=n.type==="delete"?r.state.doc.line(a).from:r.state.doc.line(a).to+1,c=n.removed.lines.join(` +`);n.removed.lines.length>0&&!n.removed.no_nl_at_eof&&(c+=` +`),i.replaceRange(c,i.offsetToPos(o),i.offsetToPos(l)),i.setSelection(i.offsetToPos(o))}}async stageHunk(e){if(!await this.plugin.isAllInitialized()||!this.editor)return;let{editor:r}=this.editor,i=Ki.getHunk(r.state,!1,e),n=!1;if(i||(i=Ki.getHunk(r.state,!0,e),n=!0),!i)return;let s=r.state.field(b$.editorInfoField).file.path,a=qt.createPatch(s,[i],"100644",n).join(` +`)+` +`;await this.gitManager.applyPatch(a),this.plugin.app.workspace.trigger("obsidian-git:refresh")}goToHunk(e){if(!this.editor)return;let{editor:r,obEditor:i}=this.editor,n=Ki.getHunks(r.state,!1),s=i.getCursor().line+1,a=qt.findNearestHunk(s,n,e,!0);if(a==null)return;let o=n[a];if(o){let l=o.added.start-1;i.setCursor(l,0),i.scrollIntoView({from:{line:l,ch:0},to:{line:l+1,ch:0}},!0)}}};m();m();var bo=require("obsidian");var Kp=class{constructor(e){this.plg=e;this.codeMirrorExtensions=[];this.handleWorkspaceLeaf=e=>{if(!this.lineAuthorInfoProvider){console.warn("Git: undefined lineAuthorInfoProvider. Unexpected situation.");return}let r=e==null?void 0:e.view;!(r instanceof bo.MarkdownView)||r.file==null||(r==null?void 0:r.allowNoFile)===!0||this.lineAuthorInfoProvider.trackChanged(r.file).catch(console.error)}}onLoadPlugin(){this.plg.registerEditorExtension(this.codeMirrorExtensions),DT(()=>this.plg.settings.lineAuthor,e=>{this.plg.settings.lineAuthor=e,this.plg.saveSettings()})}conditionallyActivateBySettings(){this.plg.settings.lineAuthor.show&&this.activateFeature()}activateFeature(){try{if(!this.isAvailableOnCurrentPlatform().available)return;zT(this.plg.settings.lineAuthor),this.lineAuthorInfoProvider=new Th(this.plg),this.createEventHandlers(),this.activateCodeMirrorExtensions(),console.log(this.plg.manifest.name+": Enabled line authoring.")}catch(e){console.warn("Git: Error while loading line authoring feature.",e),this.deactivateFeature()}}deactivateFeature(){var e;this.destroyEventHandlers(),this.deactivateCodeMirrorExtensions(),(e=this.lineAuthorInfoProvider)==null||e.destroy(),this.lineAuthorInfoProvider=void 0,console.log(this.plg.manifest.name+": Disabled line authoring.")}isAvailableOnCurrentPlatform(){return{available:this.plg.useSimpleGit&&bo.Platform.isDesktopApp,gitManager:this.plg.gitManager instanceof ke?this.plg.gitManager:void 0}}refreshLineAuthorViews(){this.plg.settings.lineAuthor.show&&(this.deactivateFeature(),this.activateFeature())}activateCodeMirrorExtensions(){this.codeMirrorExtensions.push(r2),this.plg.app.workspace.updateOptions(),this.plg.app.workspace.iterateAllLeaves(this.handleWorkspaceLeaf)}deactivateCodeMirrorExtensions(){for(let e of this.codeMirrorExtensions)this.codeMirrorExtensions.remove(e);this.plg.app.workspace.updateOptions()}createEventHandlers(){this.gutterContextMenuEvent=this.createGutterContextMenuHandler(),this.fileOpenEvent=this.createFileOpenEvent(),this.workspaceLeafChangeEvent=this.createWorkspaceLeafChangeEvent(),this.fileModificationEvent=this.createVaultFileModificationHandler(),this.headChangeEvent=this.createHeadChangeEvent(),this.refreshOnCssChangeEvent=this.createCssRefreshHandler(),this.fileRenameEvent=this.createFileRenameEvent(),HT(),this.plg.registerEvent(this.gutterContextMenuEvent),this.plg.registerEvent(this.refreshOnCssChangeEvent),this.plg.registerEvent(this.fileOpenEvent),this.plg.registerEvent(this.workspaceLeafChangeEvent),this.plg.registerEvent(this.fileModificationEvent),this.plg.registerEvent(this.headChangeEvent),this.plg.registerEvent(this.fileRenameEvent)}destroyEventHandlers(){this.plg.app.workspace.offref(this.gutterContextMenuEvent),this.plg.app.workspace.offref(this.refreshOnCssChangeEvent),this.plg.app.workspace.offref(this.fileOpenEvent),this.plg.app.workspace.offref(this.workspaceLeafChangeEvent),this.plg.app.vault.offref(this.fileModificationEvent),this.plg.app.workspace.offref(this.headChangeEvent),this.plg.app.vault.offref(this.fileRenameEvent)}createFileOpenEvent(){return this.plg.app.workspace.on("file-open",e=>{var r;e&&((r=this.lineAuthorInfoProvider)==null||r.trackChanged(e).catch(console.error))})}createWorkspaceLeafChangeEvent(){return this.plg.app.workspace.on("active-leaf-change",this.handleWorkspaceLeaf)}createFileRenameEvent(){return this.plg.app.vault.on("rename",(e,r)=>{var i;return e instanceof bo.TFile&&((i=this.lineAuthorInfoProvider)==null?void 0:i.trackChanged(e))})}createVaultFileModificationHandler(){return this.plg.app.vault.on("modify",e=>{var r;return e instanceof bo.TFile&&((r=this.lineAuthorInfoProvider)==null?void 0:r.trackChanged(e))})}createHeadChangeEvent(){return this.plg.app.workspace.on("obsidian-git:head-change",()=>{this.refreshLineAuthorViews()})}createCssRefreshHandler(){return this.plg.app.workspace.on("css-change",()=>this.refreshLineAuthorViews())}createGutterContextMenuHandler(){return this.plg.app.workspace.on("editor-menu",jT)}};m();var wc=require("obsidian");m();m();var _o=require("@codemirror/state"),Qp=require("@codemirror/view");var Xp=class extends Qp.GutterMarker{constructor(r,i){super();this.type=r;this.staged=i}toDOM(r){let i=createDiv();return i.className=`git-gutter-marker git-${this.type} ${this.staged?"staged":"unstaged"}`,this.type=="changedelete"&&i.setText("~"),i}},_b=_o.StateField.define({create:()=>_o.RangeSet.empty,update:(t,e)=>{let r=e.state.field(Wr,!1);if(!r)return _o.RangeSet.empty;let i=e.effects.some(s=>s.is(Vh)),n=e.effects.some(s=>s.is(Ml));if(i||n||(e.docChanged||t.size==0)&&r.isDirty==!1){let s=new Set,a=_$(e,r.hunks,!1,s),o=_$(e,r.stagedHunks,!0,s);return t=_o.RangeSet.of([...a,...o],!0),t}else e.docChanged&&(t=t.map(e.changes));return t}});function _$(t,e,r,i){let n=[];for(let a=0;a0?e[a-1]:void 0,l=a{var e;return(e=t.state.field(_b,!1))!=null?e:_o.RangeSet.empty},initialSpacer:t=>new Xp("delete",!1),domEventHandlers:{click:(t,e,r)=>{var n;return((n=Ki.getHunkAtPos(t.state,e.from,!1))!=null?n:Ki.getHunkAtPos(t.state,e.from,!0))&&(Ks(t,e.from),r.preventDefault()),!1}}});var Jp=class{constructor(e){this.plugin=e}async trackChanged(e){try{await this.trackChangedHelper(e)}catch(r){throw console.warn("Git: Error in trackChanged.",r),r}}async trackChangedHelper(e){if(e){if(e.path===void 0){console.warn("Git: Attempted to track change of undefined filepath. Unforeseen situation.");return}return this.computeSigns(e.path)}}destroy(){}async computeSigns(e){let i=await this.plugin.editorIntegration.lineAuthoringFeature.isAvailableOnCurrentPlatform().gitManager.show("",e).catch(()=>{});this.notifySignComputationResultToSubscribers(e,{compareText:i,compareTextHead:void 0})}notifySignComputationResultToSubscribers(e,r){Ti.ifFilepathDefinedTransformSubscribers(e,i=>i.forEach(n=>n.notifyGitCompare(r)))}},x$=[wP,bP,y$,_b,tp],E$=[Wr,ju];m();var em=require("obsidian"),tm=class{constructor(e,r){this.statusBarEl=e;this.plugin=r;var i;e.addClass("git-changes-status-bar"),r.settings.hunks.statusBar==="colored"&&e.addClass("git-changes-status-bar-colored"),e.setAttr("aria-label","Git diff of the current editor"),this.statusBarEl.setAttribute("data-tooltip-position","top"),this.view=(i=r.app.workspace.getActiveViewOfType(em.MarkdownView))!=null?i:void 0,r.app.workspace.on("active-leaf-change",n=>{!n||n.getRoot()==r.app.workspace.rootSplit&&!(n.view instanceof em.MarkdownView)?this.statusBarEl.empty():n.view instanceof em.MarkdownView&&(this.view=n.view)})}display(e,r){var a;if(!this.view||((a=this.view.file)==null?void 0:a.path)!==(r==null?void 0:r.path))return;let i=0,n=0,s=0;for(let o of e)i+=Math.max(0,o.added.count-o.removed.count),n+=Math.min(o.added.count,o.removed.count),s+=Math.max(0,o.removed.count-o.added.count);this.statusBarEl.empty(),i>0&&this.statusBarEl.createSpan({text:`+${i} `,cls:"git-add"}),n>0&&this.statusBarEl.createSpan({text:`~${n} `,cls:"git-change"}),s>0&&this.statusBarEl.createSpan({text:`-${s}`,cls:"git-delete"})}remove(){this.statusBarEl.remove()}};var rm=class{constructor(e){this.plg=e;this.codeMirrorExtensions=[];this.handleWorkspaceLeaf=e=>{if(!this.signsProvider){console.warn("Git: undefined signsProvider. Unexpected situation.");return}let r=e==null?void 0:e.view;!(r instanceof wc.MarkdownView)||r.file==null||(r==null?void 0:r.allowNoFile)===!0||this.signsProvider.trackChanged(r.file).catch(console.error)}}onLoadPlugin(){this.plg.registerEditorExtension(this.codeMirrorExtensions)}conditionallyActivateBySettings(){(this.plg.settings.hunks.showSigns||this.plg.settings.hunks.statusBar!="disabled"||this.plg.settings.hunks.hunkCommands)&&this.activateFeature()}activateFeature(){try{if(!this.isAvailableOnCurrentPlatform().available)return;if(this.signsProvider=new Jp(this.plg),this.createEventHandlers(),this.activateCodeMirrorExtensions(),this.plg.settings.hunks.statusBar!="disabled"){let e=this.plg.addStatusBarItem();this.changeStatusBar=new tm(e,this.plg)}}catch(e){console.warn("Git: Error while loading signs feature.",e),this.deactivateFeature()}}deactivateFeature(){var e,r;this.destroyEventHandlers(),this.deactivateCodeMirrorExtensions(),(e=this.signsProvider)==null||e.destroy(),this.signsProvider=void 0,(r=this.changeStatusBar)==null||r.remove(),this.changeStatusBar=void 0}isAvailableOnCurrentPlatform(){return{available:this.plg.useSimpleGit&&wc.Platform.isDesktopApp,gitManager:this.plg.gitManager instanceof ke?this.plg.gitManager:void 0}}refresh(){this.signsProvider&&this.plg.app.workspace.iterateAllLeaves(this.handleWorkspaceLeaf)}activateCodeMirrorExtensions(){this.codeMirrorExtensions.push(E$),this.plg.settings.hunks.showSigns&&this.codeMirrorExtensions.push(...x$),this.plg.app.workspace.updateOptions(),this.plg.app.workspace.iterateAllLeaves(this.handleWorkspaceLeaf)}deactivateCodeMirrorExtensions(){for(let e of this.codeMirrorExtensions)this.codeMirrorExtensions.remove(e);this.plg.app.workspace.updateOptions()}createEventHandlers(){this.workspaceLeafChangeEvent=this.createWorkspaceLeafChangeEvent(),this.fileRenameEvent=this.createFileRenameEvent(),this.pluginRefreshedEvent=this.createPluginRefreshedEvent(),this.intervalRefreshEvent=this.createIntervalRefreshEvent(),this.plg.registerEvent(this.workspaceLeafChangeEvent),this.plg.registerEvent(this.fileRenameEvent),this.plg.registerEvent(this.pluginRefreshedEvent),this.plg.registerInterval(this.intervalRefreshEvent)}destroyEventHandlers(){this.plg.app.workspace.offref(this.workspaceLeafChangeEvent),this.plg.app.vault.offref(this.fileRenameEvent),this.plg.app.workspace.offref(this.pluginRefreshedEvent),window.clearInterval(this.intervalRefreshEvent)}createWorkspaceLeafChangeEvent(){return this.plg.app.workspace.on("active-leaf-change",this.handleWorkspaceLeaf)}createFileRenameEvent(){return this.plg.app.vault.on("rename",(e,r)=>{var i;return Ti.ifFilepathDefinedTransformSubscribers(r,n=>n.forEach(s=>{s.changeToNewFilepath(e.path)})),e instanceof wc.TFile&&((i=this.signsProvider)==null?void 0:i.trackChanged(e))})}createPluginRefreshedEvent(){return this.plg.app.workspace.on("obsidian-git:refreshed",()=>{this.refresh()})}createIntervalRefreshEvent(){return window.setInterval(()=>{var e,r;(e=this.plg.app.workspace.activeEditor)!=null&&e.file&&((r=this.signsProvider)==null||r.trackChanged(this.plg.app.workspace.activeEditor.file).catch(console.error))},10*1e3)}};m();var S$=require("@codemirror/state"),im=require("obsidian");var yb=class{constructor(e){this.state=e;this.subscribeMe()}notifyLineAuthoring(e,r){if(this.view===void 0){console.warn(`Git: View is not defined for editor cache key. Unforeseen situation. id: ${e}`);return}let i=this.view.state,n=MT(e,r,i);this.view.dispatch(n)}notifyGitCompare(e){if(this.view===void 0){console.warn("Git: View is not defined for editor cache key. Unforeseen situation. id: ");return}if(this.removeIfStale())return;let r=this.view.state,i=r.field(Wr);if(!i||i.compareText!=e.compareText||i.compareTextHead!=e.compareTextHead){let n=Y2(e,r);this.view.dispatch(n)}}updateToNewState(e){return this.state=e,!this.lastSeenPath&&this.filepath&&this.subscribeMe(),this}removeIfStale(){var e;return((e=this.view)==null?void 0:e.state.field(xb,!1))!=this||this.view.destroyed?(this.unsubscribeMe(this.lastSeenPath),!0):!1}changeToNewFilepath(e){this.unsubscribeMe(this.lastSeenPath),this.subscribeMe(e)}subscribeMe(e){e!=null||(e=this.filepath),e!==void 0&&(Ti.ifFilepathDefinedTransformSubscribers(e,r=>r.add(this)),this.lastSeenPath=e)}unsubscribeMe(e){Ti.ifFilepathDefinedTransformSubscribers(e,r=>r.delete(this))}get filepath(){var e,r;return(r=(e=this.state.field(im.editorInfoField))==null?void 0:e.file)==null?void 0:r.path}get view(){return this.state.field(im.editorEditorField)}},xb=S$.StateField.define({create:t=>new yb(t),update:(t,e)=>t.updateToNewState(e.state),compare:(t,e)=>t===e});var nm=class{constructor(e){this.plg=e;this.lineAuthoringFeature=new Kp(this.plg);this.signsFeature=new rm(this.plg)}onUnloadPlugin(){this.lineAuthoringFeature.deactivateFeature(),this.signsFeature.deactivateFeature(),Ti.clear()}onLoadPlugin(){Ti.init(),this.plg.registerEditorExtension(xb),this.lineAuthoringFeature.onLoadPlugin(),this.signsFeature.onLoadPlugin()}onReady(){this.lineAuthoringFeature.conditionallyActivateBySettings(),this.signsFeature.conditionallyActivateBySettings()}activateLineAuthoring(){this.lineAuthoringFeature.activateFeature()}deactiveLineAuthoring(){this.lineAuthoringFeature.deactivateFeature()}refreshSignsSettings(){let e=this.plg.settings.hunks;e.showSigns||e.statusBar!="disabled"||e.hunkCommands?(this.signsFeature.deactivateFeature(),this.signsFeature.activateFeature()):this.signsFeature.deactivateFeature()}};var sm=class extends Ce.Plugin{constructor(){super(...arguments);this.automaticsManager=new Nu(this);this.tools=new Xu(this);this.localStorage=new rp(this);this.state={operation:0,offlineMode:!1};this.gitReady=!1;this.promiseQueue=new Nd(this);this.intervalsToClear=[];this.editorIntegration=new nm(this);this.hunkActions=new Zp(this)}setPluginState(r){var i;this.state=Object.assign(this.state,r),(i=this.statusBar)==null||i.display()}async updateCachedStatus(){var r,i;return this.app.workspace.trigger("obsidian-git:loading-status"),this.cachedStatus=await this.gitManager.status(),this.cachedStatus.conflicted.length>0?(this.localStorage.setConflict(!0),await((r=this.branchBar)==null?void 0:r.display())):(this.localStorage.setConflict(!1),await((i=this.branchBar)==null?void 0:i.display())),this.app.workspace.trigger("obsidian-git:status-changed",this.cachedStatus),this.cachedStatus}async refresh(){if(!this.gitReady)return;let r=this.app.workspace.getLeavesOfType(er.type),i=this.app.workspace.getLeavesOfType(Ei.type);(this.settings.changedFilesInStatusBar||r.some(n=>{var s;return!((s=n.isDeferred)!=null&&s)})||i.some(n=>{var s;return!((s=n.isDeferred)!=null&&s)}))&&await this.updateCachedStatus().catch(n=>this.displayError(n)),this.app.workspace.trigger("obsidian-git:refreshed")}refreshUpdatedHead(){}async onload(){console.log("loading "+this.manifest.name+" plugin: v"+this.manifest.version),Et.plugin=this,this.localStorage.migrate(),await this.loadSettings(),await this.migrateSettings(),this.settingsTab=new Ph(this.app,this),this.addSettingTab(this.settingsTab),this.localStorage.getPluginDisabled()||(this.registerStuff(),this.app.workspace.onLayoutReady(()=>this.init({fromReload:!1}).catch(r=>this.displayError(r))))}onExternalSettingsChange(){this.reloadSettings().catch(r=>this.displayError(r))}async reloadSettings(){var n,s;let r=JSON.stringify(this.settings);await this.loadSettings();let i=JSON.stringify(this.settings);if(r!==i){this.log("Reloading settings"),this.unloadPlugin(),await this.init({fromReload:!0});for(let a of this.app.workspace.getLeavesOfType(er.type))(n=a.isDeferred)!=null&&n||await a.view.reload();for(let a of this.app.workspace.getLeavesOfType(Ei.type))(s=a.isDeferred)!=null&&s||await a.view.reload()}}registerStuff(){this.registerEvent(this.app.workspace.on("obsidian-git:refresh",()=>{this.refresh().catch(r=>this.displayError(r))})),this.registerEvent(this.app.workspace.on("obsidian-git:head-change",()=>{this.refreshUpdatedHead()})),this.registerEvent(this.app.workspace.on("file-menu",(r,i,n)=>{this.handleFileMenu(r,i,n,"file-manu")})),this.registerEvent(this.app.workspace.on("obsidian-git:menu",(r,i,n)=>{this.handleFileMenu(r,i,n,"obsidian-git:menu")})),this.registerEvent(this.app.workspace.on("active-leaf-change",r=>{this.onActiveLeafChange(r)})),this.registerEvent(this.app.vault.on("modify",()=>{var r;this.debRefresh(),(r=this.autoCommitDebouncer)==null||r.call(this)})),this.registerEvent(this.app.vault.on("delete",()=>{var r;this.debRefresh(),(r=this.autoCommitDebouncer)==null||r.call(this)})),this.registerEvent(this.app.vault.on("create",()=>{var r;this.debRefresh(),(r=this.autoCommitDebouncer)==null||r.call(this)})),this.registerEvent(this.app.vault.on("rename",()=>{var r;this.debRefresh(),(r=this.autoCommitDebouncer)==null||r.call(this)})),this.registerView(er.type,r=>new Rf(r,this)),this.registerView(Ei.type,r=>new kf(r,this)),this.registerView(Us.type,r=>new Wa(r,this)),this.registerView(Hs.type,r=>new qa(r,this)),this.addRibbonIcon("git-pull-request","Open Git source control",async()=>{var n;let r=this.app.workspace.getLeavesOfType(er.type),i;r.length===0?(i=(n=this.app.workspace.getRightLeaf(!1))!=null?n:this.app.workspace.getLeaf(),await i.setViewState({type:er.type})):i=r.first(),await this.app.workspace.revealLeaf(i)}),this.registerHoverLinkSource(er.type,{display:"Git View",defaultMod:!0}),this.editorIntegration.onLoadPlugin(),this.setRefreshDebouncer(),_P(this)}setRefreshDebouncer(){var r;(r=this.debRefresh)==null||r.cancel(),this.debRefresh=(0,Ce.debounce)(()=>{this.settings.refreshSourceControl&&this.refresh().catch(console.error)},this.settings.refreshSourceControlTimer,!0)}async addFileToGitignore(r,i){let n=this.gitManager.getRelativeRepoPath(r,!0),s=kk({isFolder:i,gitRelativePath:n});await this.app.vault.adapter.append(this.gitManager.getRelativeVaultPath(".gitignore"),` +`+s),this.app.workspace.trigger("obsidian-git:refresh")}handleFileMenu(r,i,n,s){if(!this.gitReady||!this.settings.showFileMenu||!i)return;let a;if(typeof i=="string"?a=i:a=i.path,n=="file-explorer-context-menu"&&(r.addItem(o=>{o.setTitle("Git: Stage").setIcon("plus-circle").setSection("action").onClick(l=>{this.promiseQueue.addTask(async()=>{i instanceof Ce.TFile?await this.stageFile(i):(await this.gitManager.stageAll({dir:this.gitManager.getRelativeRepoPath(a,!0)}),this.app.workspace.trigger("obsidian-git:refresh"))})})}),r.addItem(o=>{o.setTitle("Git: Unstage").setIcon("minus-circle").setSection("action").onClick(l=>{this.promiseQueue.addTask(async()=>{i instanceof Ce.TFile?await this.unstageFile(i):(await this.gitManager.unstageAll({dir:this.gitManager.getRelativeRepoPath(a,!0)}),this.app.workspace.trigger("obsidian-git:refresh"))})})}),r.addItem(o=>{o.setTitle("Git: Add to .gitignore").setIcon("file-x").setSection("action").onClick(l=>{this.addFileToGitignore(a,i instanceof Ce.TFolder).catch(c=>this.displayError(c))})})),n=="git-source-control"){r.addItem(l=>{l.setTitle("Git: Add to .gitignore").setIcon("file-x").setSection("action").onClick(c=>{this.addFileToGitignore(a,i instanceof Ce.TFolder).catch(u=>this.displayError(u))})});let o=this.app.vault.adapter;s==="obsidian-git:menu"&&o instanceof Ce.FileSystemAdapter&&(r.addItem(l=>{l.setTitle("Open in default app").setIcon("arrow-up-right").setSection("action").onClick(c=>{this.app.openWithDefaultApp(a)})}),r.addItem(l=>{l.setTitle("Show in system explorer").setIcon("arrow-up-right").setSection("action").onClick(c=>{window.electron.shell.showItemInFolder(k$.join(o.getBasePath(),a))})}))}}async migrateSettings(){this.settings.mergeOnPull!=null&&(this.settings.syncMethod=this.settings.mergeOnPull?"merge":"rebase",this.settings.mergeOnPull=void 0,await this.saveSettings()),this.settings.autoCommitMessage===void 0&&(this.settings.autoCommitMessage=this.settings.commitMessage,await this.saveSettings()),this.settings.gitPath!=null&&(this.localStorage.setGitPath(this.settings.gitPath),this.settings.gitPath=void 0,await this.saveSettings()),this.settings.username!=null&&(this.localStorage.setPassword(this.settings.username),this.settings.username=void 0,await this.saveSettings())}unloadPlugin(){var r,i;this.gitReady=!1,this.editorIntegration.onUnloadPlugin(),this.automaticsManager.unload(),(r=this.branchBar)==null||r.remove(),(i=this.statusBar)==null||i.remove(),this.statusBar=void 0,this.branchBar=void 0,this.gitManager.unload(),this.promiseQueue.clear();for(let n of this.intervalsToClear)window.clearInterval(n);this.intervalsToClear=[],this.debRefresh.cancel()}onunload(){this.unloadPlugin(),console.log("unloading "+this.manifest.name+" plugin")}async loadSettings(){let r=await this.loadData();r==null&&(r={showedMobileNotice:!0}),this.settings=XS(tt,r)}async saveSettings(){var r;(r=this.settingsTab)==null||r.beforeSaveSettings(),await this.saveData(this.settings)}get useSimpleGit(){return Ce.Platform.isDesktopApp}async init({fromReload:r=!1}){var i;if(!this.localStorage.getPluginDisabled()){if(this.settings.showStatusBar&&!this.statusBar){let n=this.addStatusBarItem();this.statusBar=new Rh(n,this),this.intervalsToClear.push(window.setInterval(()=>{var s;return(s=this.statusBar)==null?void 0:s.display()},1e3))}try{this.useSimpleGit?(this.gitManager=new ke(this),await this.gitManager.setGitInstance()):this.gitManager=new Zi(this);let n=await this.gitManager.checkRequirements(),s=this.localStorage.getPausedAutomatics();switch(n){case"missing-git":this.displayError(`Cannot run git command. Trying to run: '${this.localStorage.getGitPath()||"git"}' .`);break;case"missing-repo":new Ce.Notice("Can't find a valid git repository. Please create one via the given command or clone an existing repo.",1e4);break;case"valid":if(this.gitReady=!0,Ce.Platform.isDesktop&&this.settings.showBranchStatusBar&&!this.branchBar){let a=this.addStatusBarItem();this.branchBar=new Yp(a,this),this.intervalsToClear.push(window.setInterval(()=>{var o;(o=this.branchBar)==null?void 0:o.display().catch(console.error)},6e4))}await((i=this.branchBar)==null?void 0:i.display()),this.editorIntegration.onReady(),this.app.workspace.trigger("obsidian-git:refresh"),this.app.workspace.trigger("obsidian-git:head-change"),!r&&this.settings.autoPullOnBoot&&!s&&this.promiseQueue.addTask(()=>this.pullChangesFromRemote()),s||await this.automaticsManager.init(),s&&new Ce.Notice("Automatic routines are currently paused.");break;default:this.log("Something weird happened. The 'checkRequirements' result is "+String(n))}}catch(n){this.displayError(n),console.error(n)}}}async createNewRepo(){try{await this.gitManager.init(),new Ce.Notice("Initialized new repo"),await this.init({fromReload:!0})}catch(r){this.displayError(r)}}async cloneNewRepo(){let i=await new at(this,{placeholder:"Enter remote URL"}).openAndGetResult();if(i){let n="Vault Root",s=await new at(this,{options:this.gitManager instanceof Zi?[n]:[],placeholder:"Enter directory for clone. It needs to be empty or not existent.",allowEmpty:this.gitManager instanceof Zi}).openAndGetResult();if(s==null)return;if(s===n&&(s="."),s=(0,Ce.normalizePath)(s),s==="/"&&(s="."),s==="."){let f=await new at(this,{options:["NO","YES"],placeholder:`Does your remote repo contain a ${this.app.vault.configDir} directory at the root?`,onlySelection:!0}).openAndGetResult();if(f===void 0){new Ce.Notice("Aborted clone");return}else if(f==="YES"){let d="DELETE ALL YOUR LOCAL CONFIG AND PLUGINS";if(await new at(this,{options:["Abort clone",d],placeholder:`To avoid conflicts, the local ${this.app.vault.configDir} directory needs to be deleted.`,onlySelection:!0}).openAndGetResult()===d)await this.app.vault.adapter.rmdir(this.app.vault.configDir,!0);else{new Ce.Notice("Aborted clone");return}}}let a=await new at(this,{placeholder:"Specify depth of clone. Leave empty for full clone.",allowEmpty:!0}).openAndGetResult(),o;if(a===void 0){new Ce.Notice("Aborted clone");return}if(a!==""&&(o=parseInt(a),isNaN(o))){new Ce.Notice("Invalid depth. Aborting clone.");return}new Ce.Notice(`Cloning new repo into "${s}"`);let l=this.settings.basePath,c=s&&s!==".";c&&(this.settings.basePath=s);try{await this.gitManager.clone(yv(i),s,o),new Ce.Notice("Cloned new repo."),new Ce.Notice("Please restart Obsidian"),c&&await this.saveSettings()}catch(u){this.displayError(u),this.settings.basePath=l,await this.saveSettings()}}}async isAllInitialized(){return this.gitReady||await this.init({fromReload:!0}),this.gitReady}async pullChangesFromRemote(){if(!await this.isAllInitialized())return;let r=await this.pull();if(r!==!1){if(r||this.displayMessage("Pull: Everything is up-to-date"),this.gitManager instanceof ke){let i=await this.updateCachedStatus();i.conflicted.length>0&&(this.displayError(`You have conflicts in ${i.conflicted.length} ${i.conflicted.length==1?"file":"files"}`),await this.handleConflict(i.conflicted))}this.app.workspace.trigger("obsidian-git:refresh")}}resolveCommitMode(r,i){return r==="all"?"all":i>0?"staged":r==="staged"?"nothing":this.settings.autoStageOnEmptyIndex?"all":"nothing"}async commitAndSync({fromAutoBackup:r,requestCustomMessage:i=!1,commitMessage:n,mode:s="all"}){!await this.isAllInitialized()||(this.settings.syncMethod=="reset"&&this.settings.pullBeforePush&&await this.pull(),!await this.commit({fromAuto:r,requestCustomMessage:i,commitMessage:n,mode:s}))||(this.settings.syncMethod!="reset"&&this.settings.pullBeforePush&&await this.pull(),this.settings.disablePush||(await this.remotesAreSet()&&await this.gitManager.canPush()?await this.push():this.displayMessage("No commits to push")))}async commit({fromAuto:r,requestCustomMessage:i=!1,mode:n="all",commitMessage:s,amend:a=!1}){if(!await this.isAllInitialized())return!1;try{let o=this.localStorage.getConflict(),l,c=[],u=[],f=n==="smart"?"nothing":n;if(this.gitManager instanceof ke){if(await this.mayDeleteConflictFile(),l=await this.updateCachedStatus(),l.conflicted.length==0&&(o=!1),r&&l.conflicted.length>0)return this.displayError(`Did not commit, because you have conflicts in ${l.conflicted.length} ${l.conflicted.length==1?"file":"files"}. Please resolve them and commit per command.`),await this.handleConflict(l.conflicted),!1;c=l.staged,u=l.changed,f=this.resolveCommitMode(n,c.length)}else{if(r&&o)return this.displayError("Did not commit, because you have conflicts. Please resolve them and commit per command."),!1;{o&&await this.mayDeleteConflictFile();let p=this.gitManager;c=await p.getStagedFiles(),f=this.resolveCommitMode(n,c.length),f==="all"&&(u=(await p.getUnstagedFiles()).map(({path:v,type:b})=>({vaultPath:this.gitManager.getRelativeVaultPath(v),path:v,type:b})))}}if(f==="nothing")return this.displayMessage("Nothing staged. Stage changes first or use Commit all changes."),!0;let d=f==="staged";if(await this.tools.hasTooBigFiles(d?c:[...c,...u]))return!1;if((d?0:u.length)+c.length!==0||o){let p=s!=null?s:s=r?this.settings.autoCommitMessage:this.settings.commitMessage;if(r&&this.settings.customMessageOnAutoBackup||i){!this.settings.disablePopups&&r&&new Ce.Notice("Auto backup: Please enter a custom commit message. Leave empty to abort");let b=await new $h(this).openAndGetResult();if(b!=null&&b!=""&&b!="...")p=b;else return!1}else if(this.gitManager instanceof ke&&this.settings.commitMessageScript){let b=this.settings.commitMessageScript,_=this.localStorage.getHostname()||"",C=b.replace("{{hostname}}",_);C=C.replace("{{date}}",(0,Ce.moment)().format(this.settings.commitDateFormat));let x="sh";if(Ce.Platform.isWin){x=process.env.PROGRAMFILES+"\\Git\\bin\\sh.exe";let A=!1;try{await am.access(x,am.constants.X_OK),A=!0}catch(w){A=!1}if(!A)return this.displayError(`Cannot find sh.exe at ${x}. Please make sure Git is properly installed.`),!1}let E=await Su(x,["-c",C],{cwd:this.gitManager.absoluteRepoPath});E.code!=0?this.displayError(E.stderr):E.stdout.trim().length==0?this.displayMessage("Stdout from commit message script is empty. Using default message."):p=E.stdout}if(!p||p.trim()==="")return new Ce.Notice("Commit aborted: No commit message provided"),!1;let g;d?g=await this.gitManager.commit({message:p,amend:a}):g=await this.gitManager.commitAll({message:p,status:l,unstagedFiles:u,amend:a}),this.gitManager instanceof ke&&await this.updateCachedStatus();let v=!1;g===void 0&&(v=!0,g=u.length+c.length||0),g===0?this.displayMessage("No changes to commit"):this.displayMessage(`Committed${v?" approx.":""} ${g} ${g==1?"file":"files"}`)}else this.displayMessage("No changes to commit");return this.app.workspace.trigger("obsidian-git:refresh"),!0}catch(o){return this.displayError(o),!1}}async push(){if(!await this.isAllInitialized()||!await this.remotesAreSet())return!1;let r=this.localStorage.getConflict();try{this.gitManager instanceof ke&&await this.mayDeleteConflictFile();let i;if(this.gitManager instanceof ke&&(i=await this.updateCachedStatus()).conflicted.length>0)return this.displayError(`Cannot push. You have conflicts in ${i.conflicted.length} ${i.conflicted.length==1?"file":"files"}`),await this.handleConflict(i.conflicted),!1;if(this.gitManager instanceof Zi&&r)return this.displayError("Cannot push. You have conflicts"),!1;this.settings.squashCommitsBeforePush&&this.gitManager instanceof ke&&await this.gitManager.squashAllUnpushedCommits(),this.log("Pushing....");let n=await this.gitManager.push();return n!==void 0&&(n===null?this.displayMessage("Pushed to remote"):n>0?this.displayMessage(`Pushed ${n} ${n==1?"file":"files"} to remote`):this.displayMessage("No commits to push")),this.setPluginState({offlineMode:!1}),this.app.workspace.trigger("obsidian-git:refresh"),!0}catch(i){return i instanceof ll?this.handleNoNetworkError(i):this.displayError(i),!1}}async pull(){if(!await this.remotesAreSet())return!1;try{this.log("Pulling....");let r=await this.gitManager.pull()||[];return this.setPluginState({offlineMode:!1}),r.length>0&&(this.displayMessage(`Pulled ${r.length} ${r.length==1?"file":"files"} from remote`),this.lastPulledFiles=r),r.length}catch(r){return this.displayError(r),!1}}async fetch(){if(await this.remotesAreSet())try{await this.gitManager.fetch(),this.displayMessage("Fetched from remote"),this.setPluginState({offlineMode:!1}),this.app.workspace.trigger("obsidian-git:refresh")}catch(r){this.displayError(r)}}async mayDeleteConflictFile(){let r=this.app.vault.getAbstractFileByPath(ol);r&&(this.app.workspace.iterateAllLeaves(i=>{var n;i.view instanceof Ce.MarkdownView&&((n=i.view.file)==null?void 0:n.path)==r.path&&i.detach()}),await this.app.vault.delete(r))}async stageFile(r){return await this.isAllInitialized()?(await this.gitManager.stage(r.path,!0),this.app.workspace.trigger("obsidian-git:refresh"),!0):!1}async unstageFile(r){return await this.isAllInitialized()?(await this.gitManager.unstage(r.path,!0),this.app.workspace.trigger("obsidian-git:refresh"),!0):!1}async switchBranch(){var n;if(!await this.isAllInitialized())return;let r=await this.gitManager.branchInfo(),i=await new Wp(this,r.branches).openAndGetReslt();if(i!=null)return await this.gitManager.checkout(i),this.displayMessage(`Switched to ${i}`),this.app.workspace.trigger("obsidian-git:refresh"),await((n=this.branchBar)==null?void 0:n.display()),i}async switchRemoteBranch(){var s;if(!await this.isAllInitialized())return;let r=await this.selectRemoteBranch()||"",[i,n]=Vs(r);if(n!=null&&i!=null)return await this.gitManager.checkout(n,i),this.displayMessage(`Switched to ${r}`),await((s=this.branchBar)==null?void 0:s.display()),r}async createBranch(){var i;if(!await this.isAllInitialized())return;let r=await new at(this,{placeholder:"Create new branch"}).openAndGetResult();if(r!=null)return await this.gitManager.createBranch(r),this.displayMessage(`Created new branch ${r}`),await((i=this.branchBar)==null?void 0:i.display()),r}async deleteBranch(){var n;if(!await this.isAllInitialized())return;let r=await this.gitManager.branchInfo();r.current&&r.branches.remove(r.current);let i=await new at(this,{options:r.branches,placeholder:"Delete branch",onlySelection:!0}).openAndGetResult();if(i!=null){let s=!1;if(!await this.gitManager.branchIsMerged(i)){let o=await new at(this,{options:["YES","NO"],placeholder:"This branch isn't merged into HEAD. Force delete?",onlySelection:!0}).openAndGetResult();if(o!=="YES")return;s=o==="YES"}return await this.gitManager.deleteBranch(i,s),this.displayMessage(`Deleted branch ${i}`),await((n=this.branchBar)==null?void 0:n.display()),i}}async remotesAreSet(){return this.settings.updateSubmodules||this.gitManager instanceof ke&&await this.gitManager.getConfig("push.autoSetupRemote","all")=="true"||(await this.gitManager.branchInfo()).tracking?!0:(new Ce.Notice("No upstream branch is set. Please select one."),await this.setUpstreamBranch())}async setUpstreamBranch(){let r=await this.selectRemoteBranch();return r==null?(this.displayError("Aborted. No upstream-branch is set!",1e4),!1):(await this.gitManager.updateUpstreamBranch(r),this.displayMessage(`Set upstream branch to ${r}`),!0)}async discardAll(r){if(!await this.isAllInitialized())return!1;let i=await this.gitManager.status({path:r}),n=0,s=0;for(let o of i.changed)o.workingDir=="U"?n++:s++;if(n+s==0)return!1;let a=await new vc({app:this.app,filesToDeleteCount:n,filesToDiscardCount:s,path:r!=null?r:""}).openAndGetResult();switch(a){case!1:return a;case"discard":await this.gitManager.discardAll({dir:r,status:this.cachedStatus});break;case"delete":{await this.gitManager.discardAll({dir:r,status:this.cachedStatus});let o=await this.gitManager.getUntrackedPaths({path:r,status:this.cachedStatus});for(let l of o){let c=this.gitManager.getRelativeVaultPath(l),u=this.app.vault.getAbstractFileByPath(c);u?await this.app.fileManager.trashFile(u):l.endsWith("/")?await this.app.vault.adapter.rmdir(c,!0):await this.app.vault.adapter.remove(c)}break}default:zd(a)}return this.app.workspace.trigger("obsidian-git:refresh"),a}async handleConflict(r){this.localStorage.setConflict(!0);let i;r!==void 0&&(i=["# Conflicts","Please resolve them and commit them using the commands `Git: Commit all changes` followed by `Git: Push`","(This file will automatically be deleted before commit)","[[#Additional Instructions]] available below file list","",...r.map(n=>{let s=this.app.vault.getAbstractFileByPath(n);return s instanceof Ce.TFile?`- [[${this.app.metadataCache.fileToLinktext(s,"/")}]]`:`- Not a file: ${n}`}),` +# Additional Instructions +I strongly recommend to use "Source mode" for viewing the conflicted files. For simple conflicts, in each file listed above replace every occurrence of the following text blocks with the desired text. + +\`\`\`diff +<<<<<<< HEAD + File changes in local repository +======= + File changes in remote repository +>>>>>>> origin/main +\`\`\``]),await this.tools.writeAndOpenFile(i==null?void 0:i.join(` +`))}async editRemotes(){if(!await this.isAllInitialized())return;let r=await this.gitManager.getRemotes(),n=await new at(this,{options:r,placeholder:"Select or create a new remote by typing its name and selecting it"}).openAndGetResult();if(n){let s=await this.gitManager.getRemoteUrl(n),o=await new at(this,{initialValue:s,placeholder:"Enter remote URL"}).openAndGetResult();if(o)return await this.gitManager.setRemote(n,yv(o)),n}}async selectRemoteBranch(){let r=await this.gitManager.getRemotes(),i;r.length===0&&(i=await this.editRemotes(),i==null&&(r=await this.gitManager.getRemotes()));let n=new at(this,{options:r,placeholder:"Select or create a new remote by typing its name and selecting it"}),s=i!=null?i:await n.openAndGetResult();if(s){this.displayMessage("Fetching remote branches"),await this.gitManager.fetch(s);let a=await this.gitManager.getRemoteBranches(s),l=await new at(this,{options:a,placeholder:"Select or create a new remote branch by typing its name and selecting it"}).openAndGetResult();return l==null?void 0:l.startsWith(s+"/")?l:`${s}/${l}`}}async removeRemote(){if(!await this.isAllInitialized())return;let r=await this.gitManager.getRemotes(),n=await new at(this,{options:r,placeholder:"Select a remote"}).openAndGetResult();n&&await this.gitManager.removeRemote(n)}onActiveLeafChange(r){var a,o;let i=r==null?void 0:r.view;if(!(i!=null&&i.getState().file)&&!(i instanceof Wa||i instanceof qa))return;let n=this.app.workspace.getLeavesOfType(er.type).first(),s=this.app.workspace.getLeavesOfType(Ei.type).first();if((a=n==null?void 0:n.view.containerEl.querySelector("div.tree-item-self.is-active"))==null||a.removeClass("is-active"),(o=s==null?void 0:s.view.containerEl.querySelector("div.tree-item-self.is-active"))==null||o.removeClass("is-active"),(r==null?void 0:r.view)instanceof Wa||(r==null?void 0:r.view)instanceof qa){let c=r.view.state.bFile.replace(/["\\]/g,"\\$&");this.lastDiffViewState=r.view.getState();let u;n&&r.view.state.aRef=="HEAD"?u=n.view.containerEl.querySelector(`div.staged div.tree-item-self[data-path="${c}"]`):n&&r.view.state.aRef==""?u=n.view.containerEl.querySelector(`div.changes div.tree-item-self[data-path="${c}"]`):s&&(u=s.view.containerEl.querySelector(`div.tree-item-self[data-path='${c}']`)),u==null||u.addClass("is-active")}else this.lastDiffViewState=void 0}handleNoNetworkError(r){this.state.offlineMode?this.log("Encountered network error, but already in offline mode"):this.displayError("Git: Going into offline mode. Future network errors will no longer be displayed.",2e3),this.setPluginState({offlineMode:!0})}displayMessage(r,i=4*1e3){var n;(n=this.statusBar)==null||n.displayMessage(r.toLowerCase(),i),this.settings.disablePopups||(!this.settings.disablePopupsForNoChanges||!r.startsWith("No changes"))&&new Ce.Notice(r,5*1e3),this.log(r)}displayError(r,i=10*1e3){var s;if(r instanceof du.UserCanceledError){new Ce.Notice("Aborted");return}let n;r instanceof Error?n=r:n=new Error(String(r)),this.settings.showErrorNotices&&new Ce.Notice(n.message,i),console.error(`${this.manifest.id}:`,n.stack),(s=this.statusBar)==null||s.displayMessage(n.message.toLowerCase(),i)}log(...r){console.log(`${this.manifest.id}:`,...r)}}; +/*! Bundled license information: + +ieee754/index.js: + (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *) + +buffer/index.js: + (*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + *) + +safe-buffer/index.js: + (*! safe-buffer. MIT License. Feross Aboukhadijeh *) + +crc-32/crc32.js: + (*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com *) + +isomorphic-git/index.js: + (*! + * This code for `path.join` is directly copied from @zenfs/core/path for bundle size improvements. + * SPDX-License-Identifier: LGPL-3.0-or-later + * Copyright (c) James Prevett and other ZenFS contributors. + * + * Windows support added: + * - Backslashes are normalised to forward slashes before processing. + * - Drive-letter prefixes (e.g. "C:") are detected and preserved through + * normalisation, so absolute Windows paths are handled correctly. + * - An absolute argument passed to join() resets the accumulated path, + * matching Node behaviour and handling worktree gitdir paths properly. + * + * Limitation: UNC paths (e.g. \\server\share) are not supported. The leading + * backslashes are normalised to forward slashes and then collapsed by + * normalizeString, losing the UNC root. Git on Windows works with + * drive-letter paths, so this is not expected to be a practical issue. + *) + +js-sha256/build/sha256.mjs: + (** + * [js-sha256]{@link https://github.com/emn178/js-sha256} + * + * @version 0.12.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2014-2026 + * @license MIT + *) +*/ + +/* nosourcemap */ \ No newline at end of file diff --git a/.obsidian/plugins/obsidian-git/manifest.json b/.obsidian/plugins/obsidian-git/manifest.json new file mode 100644 index 0000000..3281673 --- /dev/null +++ b/.obsidian/plugins/obsidian-git/manifest.json @@ -0,0 +1,10 @@ +{ + "author": "Vinzent", + "authorUrl": "https://github.com/Vinzent03", + "id": "obsidian-git", + "name": "Git", + "description": "Integrate Git version control with automatic backup and other advanced features.", + "isDesktopOnly": false, + "fundingUrl": "https://ko-fi.com/vinzent", + "version": "2.40.0" +} diff --git a/.obsidian/plugins/obsidian-git/styles.css b/.obsidian/plugins/obsidian-git/styles.css new file mode 100644 index 0000000..7dee885 --- /dev/null +++ b/.obsidian/plugins/obsidian-git/styles.css @@ -0,0 +1,705 @@ +@keyframes loading { + 0% { + transform: rotate(0deg); + } + + 100% { + transform: rotate(360deg); + } +} + +.workspace-leaf-content[data-type="git-view"] .button-border { + border: 2px solid var(--interactive-accent); + border-radius: var(--radius-s); +} + +.workspace-leaf-content[data-type="git-view"] .view-content { + padding-left: 0; + padding-top: 0; + padding-right: 0; +} + +.workspace-leaf-content[data-type="git-history-view"] .view-content { + padding-left: 0; + padding-top: 0; + padding-right: 0; +} + +.loading { + overflow: hidden; +} + +.loading > svg { + animation: 2s linear infinite loading; + transform-origin: 50% 50%; + display: inline-block; +} + +.obsidian-git-center { + margin: auto; + text-align: center; + width: 50%; +} + +.obsidian-git-textarea { + display: block; + margin-left: auto; + margin-right: auto; +} + +.obsidian-git-disabled { + opacity: 0.5; +} + +.obsidian-git-center-button { + display: block; + margin: 20px auto; +} + +.tooltip.mod-left { + overflow-wrap: break-word; +} + +.tooltip.mod-right { + overflow-wrap: break-word; +} + +/* Limits the scrollbar to the view body */ +.git-view { + display: flex; + flex-direction: column; + position: relative; + height: 100%; +} + +/* Re-enable wrapping of nav buttns to prevent overflow on smaller screens #*/ +.workspace-drawer .git-view .nav-buttons-container { + flex-wrap: wrap; +} + +.git-tools { + display: flex; + margin-left: auto; +} +.git-tools .type { + padding-left: var(--size-2-1); + display: flex; + align-items: center; + justify-content: center; + width: 11px; +} + +.git-tools .type[data-type="M"] { + color: orange; +} +.git-tools .type[data-type="D"] { + color: red; +} +.git-tools .buttons { + display: flex; +} +.git-tools .buttons > * { + padding: 0; + height: auto; +} + +.workspace-leaf-content[data-type="git-view"] .tree-item-self, +.workspace-leaf-content[data-type="git-history-view"] .tree-item-self { + align-items: center; +} + +.workspace-leaf-content[data-type="git-view"] + .tree-item-self:hover + .clickable-icon, +.workspace-leaf-content[data-type="git-history-view"] + .tree-item-self:hover + .clickable-icon { + color: var(--icon-color-hover); +} + +/* Highlight an item as active if it's diff is currently opened */ +.is-active .git-tools .buttons > * { + color: var(--nav-item-color-active); +} + +.git-author { + color: var(--text-accent); +} + +.git-date { + color: var(--text-accent); +} + +.git-ref { + color: var(--text-accent); +} + +/* ====== diff2html ====== +The following styles are adapted from the obsidian-version-history plugin by +@kometenstaub https://github.com/kometenstaub/obsidian-version-history-diff/blob/main/src/styles.scss +which itself is adapted from the diff2html library with the following original license: + + https://github.com/rtfpessoa/diff2html/blob/master/LICENSE.md + + Copyright 2014-2016 Rodrigo Fernandes https://rtfpessoa.github.io/ + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + documentation files (the "Software"), to deal in the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +.theme-dark, +.theme-light { + --git-delete-bg: #ff475040; + --git-delete-hl: #96050a75; + --git-insert-bg: #68d36840; + --git-insert-hl: #23c02350; + --git-change-bg: #ffd55840; + --git-selected: #3572b0; + + --git-delete: #cc3333; + --git-insert: #399839; + --git-change: #d0b44c; + --git-move: #3572b0; +} + +.git-diff { + .d2h-d-none { + display: none; + } + .d2h-wrapper { + text-align: left; + border-radius: 0.25em; + overflow: auto; + } + .d2h-file-header.d2h-file-header { + background-color: var(--background-secondary); + border-bottom: 1px solid var(--background-modifier-border); + font-family: + Source Sans Pro, + Helvetica Neue, + Helvetica, + Arial, + sans-serif; + height: 35px; + padding: 5px 10px; + } + .d2h-file-header, + .d2h-file-stats { + display: -webkit-box; + display: -ms-flexbox; + display: flex; + } + .d2h-file-header { + display: none; + } + .d2h-file-stats { + font-size: 14px; + margin-left: auto; + } + .d2h-lines-added { + border: 1px solid var(--color-green); + border-radius: 5px 0 0 5px; + color: var(--color-green); + padding: 2px; + text-align: right; + vertical-align: middle; + } + .d2h-lines-deleted { + border: 1px solid var(--color-red); + border-radius: 0 5px 5px 0; + color: var(--color-red); + margin-left: 1px; + padding: 2px; + text-align: left; + vertical-align: middle; + } + .d2h-file-name-wrapper { + -webkit-box-align: center; + -ms-flex-align: center; + align-items: center; + display: -webkit-box; + display: -ms-flexbox; + display: flex; + font-size: 15px; + width: 100%; + } + .d2h-file-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--text-normal); + font-size: var(--h5-size); + } + .d2h-file-wrapper { + border: 1px solid var(--background-secondary-alt); + border-radius: 3px; + margin-bottom: 1em; + max-height: 100%; + } + .d2h-file-collapse { + -webkit-box-pack: end; + -ms-flex-pack: end; + -webkit-box-align: center; + -ms-flex-align: center; + align-items: center; + border: 1px solid var(--background-secondary-alt); + border-radius: 3px; + cursor: pointer; + display: none; + font-size: 12px; + justify-content: flex-end; + padding: 4px 8px; + } + .d2h-file-collapse.d2h-selected { + background-color: var(--git-selected); + } + .d2h-file-collapse-input { + margin: 0 4px 0 0; + } + .d2h-diff-table { + border-collapse: collapse; + font-family: var(--font-monospace); + font-size: var(--code-size); + width: 100%; + } + .d2h-files-diff { + width: 100%; + } + .d2h-file-diff { + /* + overflow-y: scroll; + */ + border-radius: 5px; + font-size: var(--font-text-size); + line-height: var(--line-height-normal); + } + .d2h-file-side-diff { + display: inline-block; + margin-bottom: -8px; + margin-right: -4px; + overflow-x: scroll; + overflow-y: hidden; + width: 50%; + } + .d2h-code-line { + padding-left: 6em; + padding-right: 1.5em; + } + .d2h-code-line, + .d2h-code-side-line { + display: inline-block; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + white-space: nowrap; + width: 100%; + } + .d2h-code-side-line { + /* needed to be changed */ + padding-left: 0.5em; + padding-right: 0.5em; + } + .d2h-code-line-ctn { + word-wrap: normal; + background: none; + display: inline-block; + padding: 0; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + vertical-align: middle; + width: 100%; + /* only works for line-by-line */ + white-space: pre-wrap; + } + .d2h-code-line del, + .d2h-code-side-line del { + background-color: var(--git-delete-hl); + color: var(--text-normal); + } + .d2h-code-line del, + .d2h-code-line ins, + .d2h-code-side-line del, + .d2h-code-side-line ins { + border-radius: 0.2em; + display: inline-block; + margin-top: -1px; + text-decoration: none; + vertical-align: middle; + } + .d2h-code-line ins, + .d2h-code-side-line ins { + background-color: var(--git-insert-hl); + text-align: left; + } + .d2h-code-line-prefix { + word-wrap: normal; + background: none; + display: inline; + padding: 0; + white-space: pre; + } + .line-num1 { + float: left; + } + .line-num1, + .line-num2 { + -webkit-box-sizing: border-box; + box-sizing: border-box; + overflow: hidden; + /* + padding: 0 0.5em; + */ + text-overflow: ellipsis; + width: 2.5em; + padding-left: 0; + } + .line-num2 { + float: right; + } + .d2h-code-linenumber { + background-color: var(--background-primary); + border: solid var(--background-modifier-border); + border-width: 0 1px; + -webkit-box-sizing: border-box; + box-sizing: border-box; + color: var(--text-faint); + cursor: pointer; + display: inline-block; + position: absolute; + text-align: right; + width: 5.5em; + } + .d2h-code-linenumber:after { + content: "\200b"; + } + .d2h-code-side-linenumber { + background-color: var(--background-primary); + border: solid var(--background-modifier-border); + border-width: 0 1px; + -webkit-box-sizing: border-box; + box-sizing: border-box; + color: var(--text-faint); + cursor: pointer; + overflow: hidden; + padding: 0 0.5em; + text-align: right; + text-overflow: ellipsis; + width: 4em; + /* needed to be changed */ + display: table-cell; + position: relative; + } + .d2h-code-side-linenumber:after { + content: "\200b"; + } + .d2h-code-side-emptyplaceholder, + .d2h-emptyplaceholder { + background-color: var(--background-primary); + border-color: var(--background-modifier-border); + } + .d2h-code-line-prefix, + .d2h-code-linenumber, + .d2h-code-side-linenumber, + .d2h-emptyplaceholder { + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + } + .d2h-code-linenumber, + .d2h-code-side-linenumber { + direction: rtl; + } + .d2h-del { + background-color: var(--git-delete-bg); + border-color: var(--git-delete-hl); + } + .d2h-ins { + background-color: var(--git-insert-bg); + border-color: var(--git-insert-hl); + } + .d2h-info { + background-color: var(--background-primary); + border-color: var(--background-modifier-border); + color: var(--text-faint); + } + .d2h-del, + .d2h-ins, + .d2h-file-diff .d2h-change { + color: var(--text-normal); + } + .d2h-file-diff .d2h-del.d2h-change { + background-color: var(--git-change-bg); + } + .d2h-file-diff .d2h-ins.d2h-change { + background-color: var(--git-insert-bg); + } + .d2h-file-list-wrapper { + a { + text-decoration: none; + cursor: default; + -webkit-user-drag: none; + } + + svg { + display: none; + } + } + .d2h-file-list-header { + text-align: left; + } + .d2h-file-list-title { + display: none; + } + .d2h-file-list-line { + display: -webkit-box; + display: -ms-flexbox; + display: flex; + text-align: left; + } + .d2h-file-list { + } + .d2h-file-list > li { + border-bottom: 1px solid var(--background-modifier-border); + margin: 0; + padding: 5px 10px; + } + .d2h-file-list > li:last-child { + border-bottom: none; + } + .d2h-file-switch { + cursor: pointer; + display: none; + font-size: 10px; + } + .d2h-icon { + fill: currentColor; + margin-right: 10px; + vertical-align: middle; + } + .d2h-deleted { + color: var(--git-delete); + } + .d2h-added { + color: var(--git-insert); + } + .d2h-changed { + color: var(--git-change); + } + .d2h-moved { + color: var(--git-move); + } + .d2h-tag { + background-color: var(--background-secondary); + display: -webkit-box; + display: -ms-flexbox; + display: flex; + font-size: 10px; + margin-left: 5px; + padding: 0 2px; + } + .d2h-deleted-tag { + border: 1px solid var(--git-delete); + } + .d2h-added-tag { + border: 1px solid var(--git-insert); + } + .d2h-changed-tag { + border: 1px solid var(--git-change); + } + .d2h-moved-tag { + border: 1px solid var(--git-move); + } + + /* needed for line-by-line*/ + + .d2h-diff-tbody { + position: relative; + } + + /* My additions */ + .cm-merge-revert { + width: 4em; + } + /* Ensure that merge revert markers are positioned correctly */ + .cm-merge-revert > * { + position: absolute; + background-color: var(--background-secondary); + display: flex; + } +} + +/* ====================== Line Authoring Information ====================== */ + +.cm-gutterElement.obs-git-blame-gutter { + /* Add background color to spacing inbetween and around the gutter for better aesthetics */ + border-width: 0px 2px 0.2px; + border-style: solid; + border-color: var(--background-secondary); + background-color: var(--background-secondary); +} + +.cm-gutterElement.obs-git-blame-gutter > div, +.line-author-settings-preview { + /* delegate text color to settings */ + color: var(--obs-git-gutter-text); + font-family: monospace; + height: 100%; /* ensure, that age-based background color occupies entire parent */ + text-align: right; + padding: 0px 6px; + white-space: pre; /* Keep spaces and do not collapse them. */ +} + +@media (max-width: 800px) { + /* hide git blame gutter not to superpose text */ + .cm-gutterElement.obs-git-blame-gutter { + display: none; + } +} + +.git-unified-diff-view, +.git-split-diff-view .cm-deletedLine .cm-changedText { + background-color: #ee443330; +} + +.git-unified-diff-view, +.git-split-diff-view .cm-insertedLine .cm-changedText { + background-color: #22bb2230; +} + +.git-obscure-prompt[git-is-obscured="true"] #git-show-password:after { + -webkit-mask-image: url('data:image/svg+xml,'); +} + +.git-obscure-prompt[git-is-obscured="false"] #git-show-password:after { + -webkit-mask-image: url('data:image/svg+xml,'); +} + +/* Override styling of Codemirror merge view "collapsed lines" indicator */ +.git-split-diff-view .ͼ2 .cm-collapsedLines { + background: var(--interactive-normal); + border-radius: var(--radius-m); + color: var(--text-accent); + font-size: var(--font-small); + padding: var(--size-4-1) var(--size-4-1); +} +.git-split-diff-view .ͼ2 .cm-collapsedLines:hover { + background: var(--interactive-hover); + color: var(--text-accent-hover); +} + +.git-signs-gutter { + .cm-gutterElement { + display: grid; + + /* Needed to align the sign properly for different line heigts. Such as + * when having a heading or list item. + */ + padding-top: 0 !important; + } +} + +.git-gutter-marker:hover { + border-radius: 2px; +} + +.git-gutter-marker.git-add { + background-color: var(--color-green); + justify-self: center; + height: inherit; + width: 0.2rem; +} + +.git-gutter-marker.git-change { + background-color: var(--color-yellow); + justify-self: center; + height: inherit; + width: 0.2rem; +} + +.git-gutter-marker.git-changedelete { + color: var(--color-yellow); + font-weight: var(--font-bold); + font-size: 1rem; + justify-self: center; + height: inherit; +} + +.git-gutter-marker.git-delete { + background-color: var(--color-red); + height: 0.2rem; + width: 0.8rem; + align-self: end; +} + +.git-gutter-marker.git-topdelete { + background-color: var(--color-red); + height: 0.2rem; + width: 0.8rem; + align-self: start; +} + +div:hover > .git-gutter-marker.git-change { + width: 0.6rem; +} + +div:hover > .git-gutter-marker.git-add { + width: 0.6rem; +} + +div:hover > .git-gutter-marker.git-delete { + height: 0.6rem; +} + +div:hover > .git-gutter-marker.git-topdelete { + height: 0.6rem; +} + +div:hover > .git-gutter-marker.git-changedelete { + font-weight: var(--font-bold); +} + +.git-gutter-marker.staged { + opacity: 0.5; +} + +/* Prevent shifting of the editor when git signs gutter is the only gutter present */ +.cm-gutters.cm-gutters-before:has(> .git-signs-gutter:only-child) { + margin-inline-end: 0; + .git-signs-gutter { + margin-inline-start: -1rem; + } +} + +.git-changes-status-bar-colored { + .git-add { + color: var(--color-green); + } + .git-change { + color: var(--color-yellow); + } + .git-delete { + color: var(--color-red); + } +} + +.git-changes-status-bar .git-add { + margin-right: 0.3em; +} + +.git-changes-status-bar .git-change { + margin-right: 0.3em; +} diff --git a/.obsidian/plugins/obsidian-icon-folder/data.json b/.obsidian/plugins/obsidian-icon-folder/data.json new file mode 100644 index 0000000..5d514dd --- /dev/null +++ b/.obsidian/plugins/obsidian-icon-folder/data.json @@ -0,0 +1,39 @@ +{ + "settings": { + "migrated": 6, + "iconPacksPath": ".obsidian/icons", + "fontSize": 16, + "emojiStyle": "native", + "iconColor": null, + "recentlyUsedIcons": [ + "LiCheck", + "LiTasknotesSimple", + "LiBookMarked", + "LiInfo" + ], + "recentlyUsedIconsSize": 5, + "rules": [], + "extraMargin": { + "top": 0, + "right": 4, + "bottom": 0, + "left": 0 + }, + "iconInTabsEnabled": false, + "iconInTitleEnabled": false, + "iconInTitlePosition": "above", + "iconInFrontmatterEnabled": false, + "iconInFrontmatterFieldName": "icon", + "iconColorInFrontmatterFieldName": "iconColor", + "iconsBackgroundCheckEnabled": false, + "iconsInNotesEnabled": true, + "iconsInLinksEnabled": true, + "iconIdentifier": ":", + "lucideIconPackType": "native", + "debugMode": false, + "useInternalPlugins": false + }, + "00 About": "LiInfo", + "01 Project docs": "LiBookMarked", + "TaskNotes": "LiCheck" +} \ No newline at end of file diff --git a/.obsidian/plugins/obsidian-icon-folder/main.js b/.obsidian/plugins/obsidian-icon-folder/main.js new file mode 100644 index 0000000..271b2ff --- /dev/null +++ b/.obsidian/plugins/obsidian-icon-folder/main.js @@ -0,0 +1,7158 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ROLLUP +if you want to view the source visit the plugins github repository +*/ + +'use strict'; + +var obsidian = require('obsidian'); +var view = require('@codemirror/view'); +var state = require('@codemirror/state'); +var language = require('@codemirror/language'); + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +const iconPacks$1 = { + faBrands: { + name: 'font-awesome-brands', + displayName: 'FontAwesome Brands', + path: 'fontawesome-free-6.5.1-web/svgs/brands/', + downloadLink: 'https://github.com/FortAwesome/Font-Awesome/releases/download/6.5.1/fontawesome-free-6.5.1-web.zip', + }, + faRegular: { + name: 'font-awesome-regular', + displayName: 'FontAwesome Regular', + path: 'fontawesome-free-6.5.1-web/svgs/regular/', + downloadLink: 'https://github.com/FortAwesome/Font-Awesome/releases/download/6.5.1/fontawesome-free-6.5.1-web.zip', + }, + faSolid: { + name: 'font-awesome-solid', + displayName: 'FontAwesome Solid', + path: 'fontawesome-free-6.5.1-web/svgs/solid/', + downloadLink: 'https://github.com/FortAwesome/Font-Awesome/releases/download/6.5.1/fontawesome-free-6.5.1-web.zip', + }, + remixIcons: { + name: 'remix-icons', + displayName: 'Remix Icons', + path: '', + downloadLink: 'https://github.com/Remix-Design/RemixIcon/releases/download/v4.2.0/RemixIcon_Svg_v4.2.0.zip', + }, + iconBrew: { + name: 'icon-brew', + displayName: 'Icon Brew', + path: '', + downloadLink: 'https://github.com/FlorianWoelki/obsidian-iconize/raw/main/iconPacks/icon-brew.zip', + }, + /** @source https://simpleicons.org/ */ + simpleIcons: { + name: 'simple-icons', + displayName: 'Simple Icons', + path: 'simple-icons-11.10.0/icons/', + downloadLink: 'https://github.com/simple-icons/simple-icons/archive/refs/tags/11.10.0.zip', + }, + lucide: { + name: 'lucide-icons', + displayName: 'Lucide', + path: '', + downloadLink: 'https://github.com/lucide-icons/lucide/releases/download/0.363.0/lucide-icons-0.363.0.zip', + }, + tablerIcons: { + name: 'tabler-icons', + displayName: 'Tabler Icons', + path: 'svg', + downloadLink: 'https://github.com/tabler/tabler-icons/releases/download/v3.1.0/tabler-icons-3.1.0.zip', + }, + /** @source https://boxicons.com/ */ + boxicons: { + name: 'boxicons', + displayName: 'Boxicons', + path: 'svg', + downloadLink: 'https://github.com/FlorianWoelki/obsidian-iconize/raw/main/iconPacks/boxicons.zip', + }, + /** @source http://nagoshiashumari.github.io/Rpg-Awesome/ */ + rpgAwesome: { + name: 'rpg-awesome', + displayName: 'RPG Awesome', + path: '', + downloadLink: 'https://github.com/FlorianWoelki/obsidian-iconize/raw/main/iconPacks/rpg-awesome.zip', + }, + /** @source https://coolicons.cool/ */ + coolicons: { + name: 'coolicons', + displayName: 'Coolicons', + path: 'cooliocns SVG', + downloadLink: 'https://github.com/krystonschwarze/coolicons/releases/download/v4.1/coolicons.v4.1.zip', + }, + /** @source https://feathericons.com/ */ + feathericons: { + name: 'feather-icons', + displayName: 'Feather Icons', + path: 'feather-4.29.1/icons/', + downloadLink: 'https://github.com/feathericons/feather/archive/refs/tags/v4.29.1.zip', + }, + /** @source https://github.com/primer/octicons */ + octicons: { + name: 'octicons', + displayName: 'Octicons', + path: 'octicons-19.8.0/icons/', + downloadLink: 'https://github.com/primer/octicons/archive/refs/tags/v19.8.0.zip', + }, +}; +/** + * Returns a possible path to the icon pack. + * @param name String of the icon pack name. + * @returns String of the path to the icon pack or undefined if the icon pack does not + * exist. + */ +const getExtraPath = (iconPackName) => { + var _a; + const path = (_a = Object.values(iconPacks$1).find((iconPack) => iconPack.name === iconPackName)) === null || _a === void 0 ? void 0 : _a.path; + return (path === null || path === void 0 ? void 0 : path.length) === 0 ? undefined : path; +}; + +// This library file does not include any other dependency and is a standalone file that +// only include utility functions for manipulating or extracting svg information. +/** + * Extracts an SVG string from a given input string and returns a cleaned up and + * formatted SVG string. + * @param svgString SVG string to extract from. + * @returns Cleaned up and formatted SVG string. + */ +const extract = (svgString) => { + var _a, _b; + // Removes unnecessary spaces and newlines. + svgString = svgString.replace(/(\r\n|\n|\r)/gm, ''); + svgString = svgString.replace(/>\s+<'); + // Create a parser for better parsing of HTML. + const parser = new DOMParser(); + const svg = parser + .parseFromString(svgString, 'text/html') + .querySelector('svg'); + // Removes `width` and `height` from the `style` attribute. + if (svg.hasAttribute('style')) { + svg.style.width = ''; + svg.style.height = ''; + } + // Add `viewbox`, if it is not already a attribute. + if (svg.viewBox.baseVal.width === 0 && svg.viewBox.baseVal.height === 0) { + const width = (_a = svg.width.baseVal.value) !== null && _a !== void 0 ? _a : 16; + const height = (_b = svg.height.baseVal.value) !== null && _b !== void 0 ? _b : 16; + svg.viewBox.baseVal.width = width; + svg.viewBox.baseVal.height = height; + } + if (!svg.hasAttribute('fill')) { + svg.setAttribute('fill', 'currentColor'); + } + const possibleTitle = svg.querySelector('title'); + if (possibleTitle) { + possibleTitle.remove(); + } + svg.setAttribute('width', '16px'); + svg.setAttribute('height', '16px'); + return svg.outerHTML; +}; +/** + * Sets the font size of an SVG string by modifying its width and/or height attributes. + * The font size will be always set in pixels. + * @param svgString SVG string to modify. + * @param fontSize Font size in pixels to set. + * @returns Modified SVG string. + */ +const setFontSize = (svgString, fontSize) => { + const widthRe = new RegExp(/width="[\d.]+(px)?"/); + const heightRe = new RegExp(/height="[\d.]+(px)?"/); + if (svgString.match(widthRe)) { + svgString = svgString.replace(widthRe, `width="${fontSize}px"`); + } + if (svgString.match(heightRe)) { + svgString = svgString.replace(heightRe, `height="${fontSize}px"`); + } + return svgString; +}; +/** + * Replaces the fill or stroke color of an SVG string with a given color. + * @param svgString SVG string to modify. + * @param color Color to set. Defaults to 'currentColor'. + * @returns The modified SVG string. + */ +const colorize = (svgString, color) => { + if (!color) { + color = 'currentColor'; + } + const parser = new DOMParser(); + // Tries to parse the string into a HTML node. + const parsedNode = parser.parseFromString(svgString, 'text/html'); + const svg = parsedNode.querySelector('svg'); + if (svg) { + if (svg.hasAttribute('fill') && svg.getAttribute('fill') !== 'none') { + svg.setAttribute('fill', color); + } + else if (svg.hasAttribute('stroke') && + svg.getAttribute('stroke') !== 'none') { + svg.setAttribute('stroke', color); + } + return svg.outerHTML; + } + return svgString; +}; +var svg = { + extract, + colorize, + setFontSize, +}; + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function commonjsRequire(path) { + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'); +} + +var jszip_min = {exports: {}}; + +/*! + +JSZip v3.10.1 - A JavaScript class for generating and reading zip files + + +(c) 2009-2016 Stuart Knightley +Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. + +JSZip uses the library pako released under the MIT license : +https://github.com/nodeca/pako/blob/main/LICENSE +*/ + +var hasRequiredJszip_min; + +function requireJszip_min () { + if (hasRequiredJszip_min) return jszip_min.exports; + hasRequiredJszip_min = 1; + (function (module, exports) { + !function(e){module.exports=e();}(function(){return function s(a,o,h){function u(r,e){if(!o[r]){if(!a[r]){var t="function"==typeof commonjsRequire&&commonjsRequire;if(!e&&t)return t(r,!0);if(l)return l(r,!0);var n=new Error("Cannot find module '"+r+"'");throw n.code="MODULE_NOT_FOUND",n}var i=o[r]={exports:{}};a[r][0].call(i.exports,function(e){var t=a[r][1][e];return u(t||e)},i,i.exports,s,a,o,h);}return o[r].exports}for(var l="function"==typeof commonjsRequire&&commonjsRequire,e=0;e>2,s=(3&t)<<4|r>>4,a=1>6:64,o=2>4,r=(15&i)<<4|(s=p.indexOf(e.charAt(o++)))>>2,n=(3&s)<<6|(a=p.indexOf(e.charAt(o++))),l[h++]=t,64!==s&&(l[h++]=r),64!==a&&(l[h++]=n);return l};},{"./support":30,"./utils":32}],2:[function(e,t,r){var n=e("./external"),i=e("./stream/DataWorker"),s=e("./stream/Crc32Probe"),a=e("./stream/DataLengthProbe");function o(e,t,r,n,i){this.compressedSize=e,this.uncompressedSize=t,this.crc32=r,this.compression=n,this.compressedContent=i;}o.prototype={getContentWorker:function(){var e=new i(n.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new a("data_length")),t=this;return e.on("end",function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),e},getCompressedWorker:function(){return new i(n.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},o.createWorkerFrom=function(e,t,r){return e.pipe(new s).pipe(new a("uncompressedSize")).pipe(t.compressWorker(r)).pipe(new a("compressedSize")).withStreamInfo("compression",t)},t.exports=o;},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,r){var n=e("./stream/GenericWorker");r.STORE={magic:"\0\0",compressWorker:function(){return new n("STORE compression")},uncompressWorker:function(){return new n("STORE decompression")}},r.DEFLATE=e("./flate");},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,r){var n=e("./utils");var o=function(){for(var e,t=[],r=0;r<256;r++){e=r;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[r]=e;}return t}();t.exports=function(e,t){return void 0!==e&&e.length?"string"!==n.getTypeOf(e)?function(e,t,r,n){var i=o,s=n+r;e^=-1;for(var a=n;a>>8^i[255&(e^t[a])];return -1^e}(0|t,e,e.length,0):function(e,t,r,n){var i=o,s=n+r;e^=-1;for(var a=n;a>>8^i[255&(e^t.charCodeAt(a))];return -1^e}(0|t,e,e.length,0):0};},{"./utils":32}],5:[function(e,t,r){r.base64=!1,r.binary=!1,r.dir=!1,r.createFolders=!0,r.date=null,r.compression=null,r.compressionOptions=null,r.comment=null,r.unixPermissions=null,r.dosPermissions=null;},{}],6:[function(e,t,r){var n=null;n="undefined"!=typeof Promise?Promise:e("lie"),t.exports={Promise:n};},{lie:37}],7:[function(e,t,r){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,i=e("pako"),s=e("./utils"),a=e("./stream/GenericWorker"),o=n?"uint8array":"array";function h(e,t){a.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={};}r.magic="\b\0",s.inherits(h,a),h.prototype.processChunk=function(e){this.meta=e.meta,null===this._pako&&this._createPako(),this._pako.push(s.transformTo(o,e.data),!1);},h.prototype.flush=function(){a.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0);},h.prototype.cleanUp=function(){a.prototype.cleanUp.call(this),this._pako=null;},h.prototype._createPako=function(){this._pako=new i[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var t=this;this._pako.onData=function(e){t.push({data:e,meta:t.meta});};},r.compressWorker=function(e){return new h("Deflate",e)},r.uncompressWorker=function(){return new h("Inflate",{})};},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,r){function A(e,t){var r,n="";for(r=0;r>>=8;return n}function n(e,t,r,n,i,s){var a,o,h=e.file,u=e.compression,l=s!==O.utf8encode,f=I.transformTo("string",s(h.name)),c=I.transformTo("string",O.utf8encode(h.name)),d=h.comment,p=I.transformTo("string",s(d)),m=I.transformTo("string",O.utf8encode(d)),_=c.length!==h.name.length,g=m.length!==d.length,b="",v="",y="",w=h.dir,k=h.date,x={crc32:0,compressedSize:0,uncompressedSize:0};t&&!r||(x.crc32=e.crc32,x.compressedSize=e.compressedSize,x.uncompressedSize=e.uncompressedSize);var S=0;t&&(S|=8),l||!_&&!g||(S|=2048);var z=0,C=0;w&&(z|=16),"UNIX"===i?(C=798,z|=function(e,t){var r=e;return e||(r=t?16893:33204),(65535&r)<<16}(h.unixPermissions,w)):(C=20,z|=function(e){return 63&(e||0)}(h.dosPermissions)),a=k.getUTCHours(),a<<=6,a|=k.getUTCMinutes(),a<<=5,a|=k.getUTCSeconds()/2,o=k.getUTCFullYear()-1980,o<<=4,o|=k.getUTCMonth()+1,o<<=5,o|=k.getUTCDate(),_&&(v=A(1,1)+A(B(f),4)+c,b+="up"+A(v.length,2)+v),g&&(y=A(1,1)+A(B(p),4)+m,b+="uc"+A(y.length,2)+y);var E="";return E+="\n\0",E+=A(S,2),E+=u.magic,E+=A(a,2),E+=A(o,2),E+=A(x.crc32,4),E+=A(x.compressedSize,4),E+=A(x.uncompressedSize,4),E+=A(f.length,2),E+=A(b.length,2),{fileRecord:R.LOCAL_FILE_HEADER+E+f+b,dirRecord:R.CENTRAL_FILE_HEADER+A(C,2)+E+A(p.length,2)+"\0\0\0\0"+A(z,4)+A(n,4)+f+b+p}}var I=e("../utils"),i=e("../stream/GenericWorker"),O=e("../utf8"),B=e("../crc32"),R=e("../signature");function s(e,t,r,n){i.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=r,this.encodeFileName=n,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[];}I.inherits(s,i),s.prototype.push=function(e){var t=e.meta.percent||0,r=this.entriesCount,n=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,i.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:r?(t+100*(r-n-1))/r:100}}));},s.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var r=n(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:r.fileRecord,meta:{percent:0}});}else this.accumulate=!0;},s.prototype.closedSource=function(e){this.accumulate=!1;var t=this.streamFiles&&!e.file.dir,r=n(e,t,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(r.dirRecord),t)this.push({data:function(e){return R.DATA_DESCRIPTOR+A(e.crc32,4)+A(e.compressedSize,4)+A(e.uncompressedSize,4)}(e),meta:{percent:100}});else for(this.push({data:r.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null;},s.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t=this.index;t--)r=(r<<8)+this.byteAt(t);return this.index+=e,r},readString:function(e){return n.transformTo("string",this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},t.exports=i;},{"../utils":32}],19:[function(e,t,r){var n=e("./Uint8ArrayReader");function i(e){n.call(this,e);}e("../utils").inherits(i,n),i.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=i;},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,r){var n=e("./DataReader");function i(e){n.call(this,e);}e("../utils").inherits(i,n),i.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)},i.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero},i.prototype.readAndCheckSignature=function(e){return e===this.readData(4)},i.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=i;},{"../utils":32,"./DataReader":18}],21:[function(e,t,r){var n=e("./ArrayReader");function i(e){n.call(this,e);}e("../utils").inherits(i,n),i.prototype.readData=function(e){if(this.checkOffset(e),0===e)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=i;},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,r){var n=e("../utils"),i=e("../support"),s=e("./ArrayReader"),a=e("./StringReader"),o=e("./NodeBufferReader"),h=e("./Uint8ArrayReader");t.exports=function(e){var t=n.getTypeOf(e);return n.checkSupport(t),"string"!==t||i.uint8array?"nodebuffer"===t?new o(e):i.uint8array?new h(n.transformTo("uint8array",e)):new s(n.transformTo("array",e)):new a(e)};},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,t,r){r.LOCAL_FILE_HEADER="PK",r.CENTRAL_FILE_HEADER="PK",r.CENTRAL_DIRECTORY_END="PK",r.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",r.ZIP64_CENTRAL_DIRECTORY_END="PK",r.DATA_DESCRIPTOR="PK\b";},{}],24:[function(e,t,r){var n=e("./GenericWorker"),i=e("../utils");function s(e){n.call(this,"ConvertWorker to "+e),this.destType=e;}i.inherits(s,n),s.prototype.processChunk=function(e){this.push({data:i.transformTo(this.destType,e.data),meta:e.meta});},t.exports=s;},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,r){var n=e("./GenericWorker"),i=e("../crc32");function s(){n.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0);}e("../utils").inherits(s,n),s.prototype.processChunk=function(e){this.streamInfo.crc32=i(e.data,this.streamInfo.crc32||0),this.push(e);},t.exports=s;},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,r){var n=e("../utils"),i=e("./GenericWorker");function s(e){i.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0);}n.inherits(s,i),s.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length;}i.prototype.processChunk.call(this,e);},t.exports=s;},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,r){var n=e("../utils"),i=e("./GenericWorker");function s(e){i.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then(function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=n.getTypeOf(e),t.isPaused||t._tickAndRepeat();},function(e){t.error(e);});}n.inherits(s,i),s.prototype.cleanUp=function(){i.prototype.cleanUp.call(this),this.data=null;},s.prototype.resume=function(){return !!i.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,n.delay(this._tickAndRepeat,[],this)),!0)},s.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(n.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0));},s.prototype._tick=function(){if(this.isPaused||this.isFinished)return !1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":e=this.data.substring(this.index,t);break;case"uint8array":e=this.data.subarray(this.index,t);break;case"array":case"nodebuffer":e=this.data.slice(this.index,t);}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=s;},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,r){function n(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null;}n.prototype={push:function(e){this.emit("data",e);},end:function(){if(this.isFinished)return !1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0;}catch(e){this.emit("error",e);}return !0},error:function(e){return !this.isFinished&&(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[];},emit:function(e,t){if(this._listeners[e])for(var r=0;r "+e:e}},t.exports=n;},{}],29:[function(e,t,r){var h=e("../utils"),i=e("./ConvertWorker"),s=e("./GenericWorker"),u=e("../base64"),n=e("../support"),a=e("../external"),o=null;if(n.nodestream)try{o=e("../nodejs/NodejsStreamOutputAdapter");}catch(e){}function l(e,o){return new a.Promise(function(t,r){var n=[],i=e._internalType,s=e._outputType,a=e._mimeType;e.on("data",function(e,t){n.push(e),o&&o(t);}).on("error",function(e){n=[],r(e);}).on("end",function(){try{var e=function(e,t,r){switch(e){case"blob":return h.newBlob(h.transformTo("arraybuffer",t),r);case"base64":return u.encode(t);default:return h.transformTo(e,t)}}(s,function(e,t){var r,n=0,i=null,s=0;for(r=0;r>>6:(r<65536?t[s++]=224|r>>>12:(t[s++]=240|r>>>18,t[s++]=128|r>>>12&63),t[s++]=128|r>>>6&63),t[s++]=128|63&r);return t}(e)},s.utf8decode=function(e){return h.nodebuffer?o.transformTo("nodebuffer",e).toString("utf-8"):function(e){var t,r,n,i,s=e.length,a=new Array(2*s);for(t=r=0;t>10&1023,a[r++]=56320|1023&n);}return a.length!==r&&(a.subarray?a=a.subarray(0,r):a.length=r),o.applyFromCharCode(a)}(e=o.transformTo(h.uint8array?"uint8array":"array",e))},o.inherits(a,n),a.prototype.processChunk=function(e){var t=o.transformTo(h.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(h.uint8array){var r=t;(t=new Uint8Array(r.length+this.leftOver.length)).set(this.leftOver,0),t.set(r,this.leftOver.length);}else t=this.leftOver.concat(t);this.leftOver=null;}var n=function(e,t){var r;for((t=t||e.length)>e.length&&(t=e.length),r=t-1;0<=r&&128==(192&e[r]);)r--;return r<0?t:0===r?t:r+u[e[r]]>t?r:t}(t),i=t;n!==t.length&&(h.uint8array?(i=t.subarray(0,n),this.leftOver=t.subarray(n,t.length)):(i=t.slice(0,n),this.leftOver=t.slice(n,t.length))),this.push({data:s.utf8decode(i),meta:e.meta});},a.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:s.utf8decode(this.leftOver),meta:{}}),this.leftOver=null);},s.Utf8DecodeWorker=a,o.inherits(l,n),l.prototype.processChunk=function(e){this.push({data:s.utf8encode(e.data),meta:e.meta});},s.Utf8EncodeWorker=l;},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,t,a){var o=e("./support"),h=e("./base64"),r=e("./nodejsUtils"),u=e("./external");function n(e){return e}function l(e,t){for(var r=0;r>8;this.dir=!!(16&this.externalFileAttributes),0==e&&(this.dosPermissions=63&this.externalFileAttributes),3==e&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0);},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=n(this.extraFields[1].value);this.uncompressedSize===s.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===s.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===s.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===s.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4));}},readExtraFields:function(e){var t,r,n,i=e.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});e.index+4>>6:(r<65536?t[s++]=224|r>>>12:(t[s++]=240|r>>>18,t[s++]=128|r>>>12&63),t[s++]=128|r>>>6&63),t[s++]=128|63&r);return t},r.buf2binstring=function(e){return l(e,e.length)},r.binstring2buf=function(e){for(var t=new h.Buf8(e.length),r=0,n=t.length;r>10&1023,o[n++]=56320|1023&i);}return l(o,n)},r.utf8border=function(e,t){var r;for((t=t||e.length)>e.length&&(t=e.length),r=t-1;0<=r&&128==(192&e[r]);)r--;return r<0?t:0===r?t:r+u[e[r]]>t?r:t};},{"./common":41}],43:[function(e,t,r){t.exports=function(e,t,r,n){for(var i=65535&e|0,s=e>>>16&65535|0,a=0;0!==r;){for(r-=a=2e3>>1:e>>>1;t[r]=e;}return t}();t.exports=function(e,t,r,n){var i=o,s=n+r;e^=-1;for(var a=n;a>>8^i[255&(e^t[a])];return -1^e};},{}],46:[function(e,t,r){var h,c=e("../utils/common"),u=e("./trees"),d=e("./adler32"),p=e("./crc32"),n=e("./messages"),l=0,f=4,m=0,_=-2,g=-1,b=4,i=2,v=8,y=9,s=286,a=30,o=19,w=2*s+1,k=15,x=3,S=258,z=S+x+1,C=42,E=113,A=1,I=2,O=3,B=4;function R(e,t){return e.msg=n[t],t}function T(e){return (e<<1)-(4e.avail_out&&(r=e.avail_out),0!==r&&(c.arraySet(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,0===t.pending&&(t.pending_out=0));}function N(e,t){u._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,F(e.strm);}function U(e,t){e.pending_buf[e.pending++]=t;}function P(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t;}function L(e,t){var r,n,i=e.max_chain_length,s=e.strstart,a=e.prev_length,o=e.nice_match,h=e.strstart>e.w_size-z?e.strstart-(e.w_size-z):0,u=e.window,l=e.w_mask,f=e.prev,c=e.strstart+S,d=u[s+a-1],p=u[s+a];e.prev_length>=e.good_match&&(i>>=2),o>e.lookahead&&(o=e.lookahead);do{if(u[(r=t)+a]===p&&u[r+a-1]===d&&u[r]===u[s]&&u[++r]===u[s+1]){s+=2,r++;do{}while(u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&sh&&0!=--i);return a<=e.lookahead?a:e.lookahead}function j(e){var t,r,n,i,s,a,o,h,u,l,f=e.w_size;do{if(i=e.window_size-e.lookahead-e.strstart,e.strstart>=f+(f-z)){for(c.arraySet(e.window,e.window,f,f,0),e.match_start-=f,e.strstart-=f,e.block_start-=f,t=r=e.hash_size;n=e.head[--t],e.head[t]=f<=n?n-f:0,--r;);for(t=r=f;n=e.prev[--t],e.prev[t]=f<=n?n-f:0,--r;);i+=f;}if(0===e.strm.avail_in)break;if(a=e.strm,o=e.window,h=e.strstart+e.lookahead,u=i,l=void 0,l=a.avail_in,u=x)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<=x&&(e.ins_h=(e.ins_h<=x)if(n=u._tr_tally(e,e.strstart-e.match_start,e.match_length-x),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=x){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<=x&&(e.ins_h=(e.ins_h<=x&&e.match_length<=e.prev_length){for(i=e.strstart+e.lookahead-x,n=u._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-x),e.lookahead-=e.prev_length-1,e.prev_length-=2;++e.strstart<=i&&(e.ins_h=(e.ins_h<e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(j(e),0===e.lookahead&&t===l)return A;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+r;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,N(e,!1),0===e.strm.avail_out))return A;if(e.strstart-e.block_start>=e.w_size-z&&(N(e,!1),0===e.strm.avail_out))return A}return e.insert=0,t===f?(N(e,!0),0===e.strm.avail_out?O:B):(e.strstart>e.block_start&&(N(e,!1),e.strm.avail_out),A)}),new M(4,4,8,4,Z),new M(4,5,16,8,Z),new M(4,6,32,32,Z),new M(4,4,16,16,W),new M(8,16,32,32,W),new M(8,16,128,128,W),new M(8,32,128,256,W),new M(32,128,258,1024,W),new M(32,258,258,4096,W)],r.deflateInit=function(e,t){return Y(e,t,v,15,8,0)},r.deflateInit2=Y,r.deflateReset=K,r.deflateResetKeep=G,r.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?_:(e.state.gzhead=t,m):_},r.deflate=function(e,t){var r,n,i,s;if(!e||!e.state||5>8&255),U(n,n.gzhead.time>>16&255),U(n,n.gzhead.time>>24&255),U(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),U(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(U(n,255&n.gzhead.extra.length),U(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=p(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(U(n,0),U(n,0),U(n,0),U(n,0),U(n,0),U(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),U(n,3),n.status=E);else {var a=v+(n.w_bits-8<<4)<<8;a|=(2<=n.strategy||n.level<2?0:n.level<6?1:6===n.level?2:3)<<6,0!==n.strstart&&(a|=32),a+=31-a%31,n.status=E,P(n,a),0!==n.strstart&&(P(n,e.adler>>>16),P(n,65535&e.adler)),e.adler=1;}if(69===n.status)if(n.gzhead.extra){for(i=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>i&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),F(e),i=n.pending,n.pending!==n.pending_buf_size));)U(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>i&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=73);}else n.status=73;if(73===n.status)if(n.gzhead.name){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),F(e),i=n.pending,n.pending===n.pending_buf_size)){s=1;break}s=n.gzindexi&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),0===s&&(n.gzindex=0,n.status=91);}else n.status=91;if(91===n.status)if(n.gzhead.comment){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),F(e),i=n.pending,n.pending===n.pending_buf_size)){s=1;break}s=n.gzindexi&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),0===s&&(n.status=103);}else n.status=103;if(103===n.status&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&F(e),n.pending+2<=n.pending_buf_size&&(U(n,255&e.adler),U(n,e.adler>>8&255),e.adler=0,n.status=E)):n.status=E),0!==n.pending){if(F(e),0===e.avail_out)return n.last_flush=-1,m}else if(0===e.avail_in&&T(t)<=T(r)&&t!==f)return R(e,-5);if(666===n.status&&0!==e.avail_in)return R(e,-5);if(0!==e.avail_in||0!==n.lookahead||t!==l&&666!==n.status){var o=2===n.strategy?function(e,t){for(var r;;){if(0===e.lookahead&&(j(e),0===e.lookahead)){if(t===l)return A;break}if(e.match_length=0,r=u._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(N(e,!1),0===e.strm.avail_out))return A}return e.insert=0,t===f?(N(e,!0),0===e.strm.avail_out?O:B):e.last_lit&&(N(e,!1),0===e.strm.avail_out)?A:I}(n,t):3===n.strategy?function(e,t){for(var r,n,i,s,a=e.window;;){if(e.lookahead<=S){if(j(e),e.lookahead<=S&&t===l)return A;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=x&&0e.lookahead&&(e.match_length=e.lookahead);}if(e.match_length>=x?(r=u._tr_tally(e,1,e.match_length-x),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=u._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(N(e,!1),0===e.strm.avail_out))return A}return e.insert=0,t===f?(N(e,!0),0===e.strm.avail_out?O:B):e.last_lit&&(N(e,!1),0===e.strm.avail_out)?A:I}(n,t):h[n.level].func(n,t);if(o!==O&&o!==B||(n.status=666),o===A||o===O)return 0===e.avail_out&&(n.last_flush=-1),m;if(o===I&&(1===t?u._tr_align(n):5!==t&&(u._tr_stored_block(n,0,0,!1),3===t&&(D(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),F(e),0===e.avail_out))return n.last_flush=-1,m}return t!==f?m:n.wrap<=0?1:(2===n.wrap?(U(n,255&e.adler),U(n,e.adler>>8&255),U(n,e.adler>>16&255),U(n,e.adler>>24&255),U(n,255&e.total_in),U(n,e.total_in>>8&255),U(n,e.total_in>>16&255),U(n,e.total_in>>24&255)):(P(n,e.adler>>>16),P(n,65535&e.adler)),F(e),0=r.w_size&&(0===s&&(D(r.head),r.strstart=0,r.block_start=0,r.insert=0),u=new c.Buf8(r.w_size),c.arraySet(u,t,l-r.w_size,r.w_size,0),t=u,l=r.w_size),a=e.avail_in,o=e.next_in,h=e.input,e.avail_in=l,e.next_in=0,e.input=t,j(r);r.lookahead>=x;){for(n=r.strstart,i=r.lookahead-(x-1);r.ins_h=(r.ins_h<>>=y=v>>>24,p-=y,0===(y=v>>>16&255))C[s++]=65535&v;else {if(!(16&y)){if(0==(64&y)){v=m[(65535&v)+(d&(1<>>=y,p-=y),p<15&&(d+=z[n++]<>>=y=v>>>24,p-=y,!(16&(y=v>>>16&255))){if(0==(64&y)){v=_[(65535&v)+(d&(1<>>=y,p-=y,(y=s-a)>3,d&=(1<<(p-=w<<3))-1,e.next_in=n,e.next_out=s,e.avail_in=n>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function s(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new I.Buf16(320),this.work=new I.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0;}function a(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=P,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new I.Buf32(n),t.distcode=t.distdyn=new I.Buf32(i),t.sane=1,t.back=-1,N):U}function o(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,a(e)):U}function h(e,t){var r,n;return e&&e.state?(n=e.state,t<0?(r=0,t=-t):(r=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15=s.wsize?(I.arraySet(s.window,t,r-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):(n<(i=s.wsize-s.wnext)&&(i=n),I.arraySet(s.window,t,r-n,i,s.wnext),(n-=i)?(I.arraySet(s.window,t,r-n,n,0),s.wnext=n,s.whave=s.wsize):(s.wnext+=i,s.wnext===s.wsize&&(s.wnext=0),s.whave>>8&255,r.check=B(r.check,E,2,0),l=u=0,r.mode=2;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&u)<<8)+(u>>8))%31){e.msg="incorrect header check",r.mode=30;break}if(8!=(15&u)){e.msg="unknown compression method",r.mode=30;break}if(l-=4,k=8+(15&(u>>>=4)),0===r.wbits)r.wbits=k;else if(k>r.wbits){e.msg="invalid window size",r.mode=30;break}r.dmax=1<>8&1),512&r.flags&&(E[0]=255&u,E[1]=u>>>8&255,r.check=B(r.check,E,2,0)),l=u=0,r.mode=3;case 3:for(;l<32;){if(0===o)break e;o--,u+=n[s++]<>>8&255,E[2]=u>>>16&255,E[3]=u>>>24&255,r.check=B(r.check,E,4,0)),l=u=0,r.mode=4;case 4:for(;l<16;){if(0===o)break e;o--,u+=n[s++]<>8),512&r.flags&&(E[0]=255&u,E[1]=u>>>8&255,r.check=B(r.check,E,2,0)),l=u=0,r.mode=5;case 5:if(1024&r.flags){for(;l<16;){if(0===o)break e;o--,u+=n[s++]<>>8&255,r.check=B(r.check,E,2,0)),l=u=0;}else r.head&&(r.head.extra=null);r.mode=6;case 6:if(1024&r.flags&&(o<(d=r.length)&&(d=o),d&&(r.head&&(k=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),I.arraySet(r.head.extra,n,s,d,k)),512&r.flags&&(r.check=B(r.check,n,d,s)),o-=d,s+=d,r.length-=d),r.length))break e;r.length=0,r.mode=7;case 7:if(2048&r.flags){if(0===o)break e;for(d=0;k=n[s+d++],r.head&&k&&r.length<65536&&(r.head.name+=String.fromCharCode(k)),k&&d>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=12;break;case 10:for(;l<32;){if(0===o)break e;o--,u+=n[s++]<>>=7&l,l-=7&l,r.mode=27;break}for(;l<3;){if(0===o)break e;o--,u+=n[s++]<>>=1)){case 0:r.mode=14;break;case 1:if(j(r),r.mode=20,6!==t)break;u>>>=2,l-=2;break e;case 2:r.mode=17;break;case 3:e.msg="invalid block type",r.mode=30;}u>>>=2,l-=2;break;case 14:for(u>>>=7&l,l-=7&l;l<32;){if(0===o)break e;o--,u+=n[s++]<>>16^65535)){e.msg="invalid stored block lengths",r.mode=30;break}if(r.length=65535&u,l=u=0,r.mode=15,6===t)break e;case 15:r.mode=16;case 16:if(d=r.length){if(o>>=5,l-=5,r.ndist=1+(31&u),u>>>=5,l-=5,r.ncode=4+(15&u),u>>>=4,l-=4,286>>=3,l-=3;}for(;r.have<19;)r.lens[A[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,S={bits:r.lenbits},x=T(0,r.lens,0,19,r.lencode,0,r.work,S),r.lenbits=S.bits,x){e.msg="invalid code lengths set",r.mode=30;break}r.have=0,r.mode=19;case 19:for(;r.have>>16&255,b=65535&C,!((_=C>>>24)<=l);){if(0===o)break e;o--,u+=n[s++]<>>=_,l-=_,r.lens[r.have++]=b;else {if(16===b){for(z=_+2;l>>=_,l-=_,0===r.have){e.msg="invalid bit length repeat",r.mode=30;break}k=r.lens[r.have-1],d=3+(3&u),u>>>=2,l-=2;}else if(17===b){for(z=_+3;l>>=_)),u>>>=3,l-=3;}else {for(z=_+7;l>>=_)),u>>>=7,l-=7;}if(r.have+d>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=30;break}for(;d--;)r.lens[r.have++]=k;}}if(30===r.mode)break;if(0===r.lens[256]){e.msg="invalid code -- missing end-of-block",r.mode=30;break}if(r.lenbits=9,S={bits:r.lenbits},x=T(D,r.lens,0,r.nlen,r.lencode,0,r.work,S),r.lenbits=S.bits,x){e.msg="invalid literal/lengths set",r.mode=30;break}if(r.distbits=6,r.distcode=r.distdyn,S={bits:r.distbits},x=T(F,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,S),r.distbits=S.bits,x){e.msg="invalid distances set",r.mode=30;break}if(r.mode=20,6===t)break e;case 20:r.mode=21;case 21:if(6<=o&&258<=h){e.next_out=a,e.avail_out=h,e.next_in=s,e.avail_in=o,r.hold=u,r.bits=l,R(e,c),a=e.next_out,i=e.output,h=e.avail_out,s=e.next_in,n=e.input,o=e.avail_in,u=r.hold,l=r.bits,12===r.mode&&(r.back=-1);break}for(r.back=0;g=(C=r.lencode[u&(1<>>16&255,b=65535&C,!((_=C>>>24)<=l);){if(0===o)break e;o--,u+=n[s++]<>v)])>>>16&255,b=65535&C,!(v+(_=C>>>24)<=l);){if(0===o)break e;o--,u+=n[s++]<>>=v,l-=v,r.back+=v;}if(u>>>=_,l-=_,r.back+=_,r.length=b,0===g){r.mode=26;break}if(32&g){r.back=-1,r.mode=12;break}if(64&g){e.msg="invalid literal/length code",r.mode=30;break}r.extra=15&g,r.mode=22;case 22:if(r.extra){for(z=r.extra;l>>=r.extra,l-=r.extra,r.back+=r.extra;}r.was=r.length,r.mode=23;case 23:for(;g=(C=r.distcode[u&(1<>>16&255,b=65535&C,!((_=C>>>24)<=l);){if(0===o)break e;o--,u+=n[s++]<>v)])>>>16&255,b=65535&C,!(v+(_=C>>>24)<=l);){if(0===o)break e;o--,u+=n[s++]<>>=v,l-=v,r.back+=v;}if(u>>>=_,l-=_,r.back+=_,64&g){e.msg="invalid distance code",r.mode=30;break}r.offset=b,r.extra=15&g,r.mode=24;case 24:if(r.extra){for(z=r.extra;l>>=r.extra,l-=r.extra,r.back+=r.extra;}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=30;break}r.mode=25;case 25:if(0===h)break e;if(d=c-h,r.offset>d){if((d=r.offset-d)>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=30;break}p=d>r.wnext?(d-=r.wnext,r.wsize-d):r.wnext-d,d>r.length&&(d=r.length),m=r.window;}else m=i,p=a-r.offset,d=r.length;for(hd?(m=R[T+a[v]],A[I+a[v]]):(m=96,0),h=1<>S)+(u-=h)]=p<<24|m<<16|_|0,0!==u;);for(h=1<>=1;if(0!==h?(E&=h-1,E+=h):E=0,v++,0==--O[b]){if(b===w)break;b=t[r+a[v]];}if(k>>7)]}function U(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255;}function P(e,t,r){e.bi_valid>d-r?(e.bi_buf|=t<>d-e.bi_valid,e.bi_valid+=r-d):(e.bi_buf|=t<>>=1,r<<=1,0<--t;);return r>>>1}function Z(e,t,r){var n,i,s=new Array(g+1),a=0;for(n=1;n<=g;n++)s[n]=a=a+r[n-1]<<1;for(i=0;i<=t;i++){var o=e[2*i+1];0!==o&&(e[2*i]=j(s[o]++,o));}}function W(e){var t;for(t=0;t>1;1<=r;r--)G(e,s,r);for(i=h;r=e.heap[1],e.heap[1]=e.heap[e.heap_len--],G(e,s,1),n=e.heap[1],e.heap[--e.heap_max]=r,e.heap[--e.heap_max]=n,s[2*i]=s[2*r]+s[2*n],e.depth[i]=(e.depth[r]>=e.depth[n]?e.depth[r]:e.depth[n])+1,s[2*r+1]=s[2*n+1]=i,e.heap[1]=i++,G(e,s,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(e,t){var r,n,i,s,a,o,h=t.dyn_tree,u=t.max_code,l=t.stat_desc.static_tree,f=t.stat_desc.has_stree,c=t.stat_desc.extra_bits,d=t.stat_desc.extra_base,p=t.stat_desc.max_length,m=0;for(s=0;s<=g;s++)e.bl_count[s]=0;for(h[2*e.heap[e.heap_max]+1]=0,r=e.heap_max+1;r<_;r++)p<(s=h[2*h[2*(n=e.heap[r])+1]+1]+1)&&(s=p,m++),h[2*n+1]=s,u>=7;n>>=1)if(1&r&&0!==e.dyn_ltree[2*t])return o;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return h;for(t=32;t>>3,(s=e.static_len+3+7>>>3)<=i&&(i=s)):i=s=r+5,r+4<=i&&-1!==t?J(e,t,r,n):4===e.strategy||s===i?(P(e,2+(n?1:0),3),K(e,z,C)):(P(e,4+(n?1:0),3),function(e,t,r,n){var i;for(P(e,t-257,5),P(e,r-1,5),P(e,n-4,4),i=0;i>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&r,e.last_lit++,0===t?e.dyn_ltree[2*r]++:(e.matches++,t--,e.dyn_ltree[2*(A[r]+u+1)]++,e.dyn_dtree[2*N(t)]++),e.last_lit===e.lit_bufsize-1},r._tr_align=function(e){P(e,2,3),L(e,m,z),function(e){16===e.bi_valid?(U(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):8<=e.bi_valid&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8);}(e);};},{"../utils/common":41}],53:[function(e,t,r){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0;};},{}],54:[function(e,t,r){(function(e){!function(r,n){if(!r.setImmediate){var i,s,t,a,o=1,h={},u=!1,l=r.document,e=Object.getPrototypeOf&&Object.getPrototypeOf(r);e=e&&e.setTimeout?e:r,i="[object process]"==={}.toString.call(r.process)?function(e){process.nextTick(function(){c(e);});}:function(){if(r.postMessage&&!r.importScripts){var e=!0,t=r.onmessage;return r.onmessage=function(){e=!1;},r.postMessage("","*"),r.onmessage=t,e}}()?(a="setImmediate$"+Math.random()+"$",r.addEventListener?r.addEventListener("message",d,!1):r.attachEvent("onmessage",d),function(e){r.postMessage(a+e,"*");}):r.MessageChannel?((t=new MessageChannel).port1.onmessage=function(e){c(e.data);},function(e){t.port2.postMessage(e);}):l&&"onreadystatechange"in l.createElement("script")?(s=l.documentElement,function(e){var t=l.createElement("script");t.onreadystatechange=function(){c(e),t.onreadystatechange=null,s.removeChild(t),t=null;},s.appendChild(t);}):function(e){setTimeout(c,0,e);},e.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),r=0;r __awaiter(void 0, void 0, void 0, function* () { + const fetched = yield obsidian.requestUrl({ url }); + const bytes = fetched.arrayBuffer; + return bytes; +}); +/** + * Transforms a JSZip file into a File object. + * @param file JSZip file to transform. + * @returns File object of the JSZip file. + */ +const getFileFromJSZipFile = (file) => __awaiter(void 0, void 0, void 0, function* () { + const fileData = yield file.async('blob'); + const filename = file.name.split('/').pop(); + return new File([fileData], filename); +}); +/** + * Read a zip file and return the files inside it. + * @param bytes ArrayBuffer of the zip file. + * @param extraPath String path to filter the files inside the zip file. This can be used + * to set an extra path (like a directory inside the zip file) to filter the files. + * @returns Array of loaded files inside the zip file. + */ +const readZipFile = (bytes_1, ...args_1) => __awaiter(void 0, [bytes_1, ...args_1], void 0, function* (bytes, extraPath = '') { + const unzippedFiles = yield jszip_minExports.loadAsync(bytes); + return Promise.resolve(unzippedFiles).then((unzipped) => { + if (!Object.keys(unzipped.files).length) { + return Promise.reject('No file was found'); + } + const files = []; + // Regex for retrieving the files inside the zip file or inside the directory of a + // zip file. + const regex = new RegExp(extraPath + '(.+)\\.svg', 'g'); + Object.entries(unzippedFiles.files).forEach(([_, v]) => { + const matched = v.name.match(regex); + if (!v.dir && matched && matched.length > 0) { + files.push(v); + } + }); + return files; + }); +}); + +const PLUGIN_NAME = 'iconize'; +const TITLE_ICON_CLASS = 'iconize-title-icon'; +const INLINE_TITLE_WRAPPER_CLASS = 'iconize-inline-title-wrapper'; +/** + * The name of the attribute that is used to store the icon name in the node. + * The value of this attributes contains the prefix and the name of the icon. + */ +const ICON_ATTRIBUTE_NAME = 'data-icon'; +var config = { + PLUGIN_NAME, + TITLE_ICON_CLASS, + INLINE_TITLE_WRAPPER_CLASS, + ICON_ATTRIBUTE_NAME, +}; + +var LoggerPrefix; +(function (LoggerPrefix) { + LoggerPrefix["Outline"] = "Outline"; +})(LoggerPrefix || (LoggerPrefix = {})); +class ConsoleLogger { + constructor(projectPrefix, enabled = false) { + this.logLevels = { + log: { label: 'LOG:' }, + info: { label: 'INFO:' }, + warn: { label: 'WARN:' }, + error: { label: 'ERROR:' }, + }; + this.projectPrefix = projectPrefix; + this.enabled = enabled; + } + formatMessage(level, message, prefix, optionalParams) { + const timestamp = new Date().toISOString(); + const { label } = this.logLevels[level]; + const prefixAsStr = !prefix ? '' : `/${prefix}`; + return [ + `${this.projectPrefix}${prefixAsStr}: [${timestamp}] ${label} ${message}`, + ...optionalParams, + ]; + } + log(message, prefix, ...optionalParams) { + if (this.enabled) { + console.log(...this.formatMessage('log', message, prefix, optionalParams)); + } + } + info(message, prefix, ...optionalParams) { + if (this.enabled) { + console.info(...this.formatMessage('info', message, prefix, optionalParams)); + } + } + warn(message, prefix, ...optionalParams) { + if (this.enabled) { + console.warn(...this.formatMessage('warn', message, prefix, optionalParams)); + } + } + error(message, prefix, ...optionalParams) { + if (this.enabled) { + console.error(...this.formatMessage('error', message, prefix, optionalParams)); + } + } + toggleLogging(enabled) { + this.enabled = enabled; + } +} +const logger = new ConsoleLogger(config.PLUGIN_NAME); + +const LUCIDE_ICON_PACK_NAME = 'lucide-icons'; +let path; +const getPath = () => { + return path; +}; +const setPath = (newPath) => { + if (newPath === 'plugins/obsidian-icon-folder/icons') { + newPath = '.obsidian/plugins/obsidian-icon-folder/icons'; + new obsidian.Notice(`[${config.PLUGIN_NAME}] Due to a change in version v1.2.2, the icon pack folder changed. Please change it in the settings to not be directly in /plugins.`, 8000); + } + path = newPath; +}; +let preloadedIcons = []; +const getPreloadedIcons = () => { + return preloadedIcons; +}; +const resetPreloadedIcons = () => { + preloadedIcons = []; +}; +let iconPacks = []; +const addLucideIconsPack = (plugin) => { + iconPacks.push({ + name: LUCIDE_ICON_PACK_NAME, + prefix: 'Li', + custom: false, + icons: plugin.doesUseNativeLucideIconPack() + ? obsidian.getIconIds() + .map((iconId) => iconId.replace(/^lucide-/, '')) + .map((iconId) => { + const iconEl = obsidian.getIcon(iconId); + iconEl.removeClass('svg-icon'); // Removes native `svg-icon` class. + return { + name: getNormalizedName(iconId), + filename: iconId, + prefix: 'Li', + svgElement: iconEl === null || iconEl === void 0 ? void 0 : iconEl.outerHTML, + svgContent: iconEl === null || iconEl === void 0 ? void 0 : iconEl.innerHTML, + svgViewbox: '', + iconPackName: LUCIDE_ICON_PACK_NAME, + }; + }) + : [], + }); +}; +const addCustomLucideIconPack = (plugin) => __awaiter(void 0, void 0, void 0, function* () { + const iconPackIndex = iconPacks.findIndex((iconPack) => iconPack.name === LUCIDE_ICON_PACK_NAME); + if (iconPackIndex > -1) { + iconPacks.splice(iconPackIndex); + } + const iconPack = iconPacks$1['lucide']; + const arrayBuffer = yield downloadZipFile(iconPack.downloadLink); + yield createZipFile(plugin, `${iconPack.name}.zip`, arrayBuffer); + yield registerIconPack(iconPack.name, arrayBuffer); +}); +const removeCustomLucideIconPack = (plugin) => __awaiter(void 0, void 0, void 0, function* () { + const iconPackIndex = iconPacks.findIndex((iconPack) => iconPack.name === LUCIDE_ICON_PACK_NAME); + if (iconPackIndex > -1) { + iconPacks.splice(iconPackIndex); + } + yield deleteIconPack(plugin, LUCIDE_ICON_PACK_NAME); +}); +const moveIconPackDirectories = (plugin, from, to) => __awaiter(void 0, void 0, void 0, function* () { + // Tries to move all icon packs to the new folder. + for (let i = 0; i < iconPacks.length; i++) { + const iconPack = iconPacks[i]; + if (yield plugin.app.vault.adapter.exists(`${from}/${iconPack.name}`)) { + // Tries to create a new directory in the new path. + const doesDirExist = yield createDirectory(plugin, iconPack.name); + if (doesDirExist) { + new obsidian.Notice(`Directory with name ${iconPack.name} already exists.`); + continue; + } + } + new obsidian.Notice(`Moving ${iconPack.name}...`); + // Move the zip file. + if (yield plugin.app.vault.adapter.exists(`${from}/${iconPack.name}.zip`)) { + yield plugin.app.vault.adapter.copy(`${from}/${iconPack.name}.zip`, `${to}/${iconPack.name}.zip`); + } + // Move all other files inside of the iconpack directory. + const filesInDirectory = yield getFilesInDirectory(plugin, `${from}/${iconPack.name}`); + for (const file of filesInDirectory) { + const fileName = file.split('/').pop(); + yield plugin.app.vault.adapter.copy(`${from}/${iconPack.name}/${fileName}`, `${to}/${iconPack.name}/${fileName}`); + } + new obsidian.Notice(`...moved ${iconPack.name}`); + } + // Removes all the existing icon packs in the `from` directory. + for (let i = 0; i < iconPacks.length; i++) { + const iconPack = iconPacks[i]; + if (yield plugin.app.vault.adapter.exists(`${from}/${iconPack.name}`)) { + yield plugin.app.vault.adapter.rmdir(`${from}/${iconPack.name}`, true); + } + } + // Remove root directory that contains all the icon packs. + if (!to.startsWith(from)) { + yield plugin.app.vault.adapter.rmdir(`${from}`, true); + } +}); +const createCustomIconPackDirectory = (plugin, dir) => __awaiter(void 0, void 0, void 0, function* () { + yield createDirectory(plugin, dir); + const prefix = createIconPackPrefix(dir); + iconPacks.push({ name: dir, icons: [], prefix, custom: true }); +}); +const deleteIconPack = (plugin, dir) => __awaiter(void 0, void 0, void 0, function* () { + iconPacks = iconPacks.filter((iconPack) => iconPack.name !== dir); + // Check for the icon pack directory and delete it. + if (yield plugin.app.vault.adapter.exists(`${path}/${dir}`)) { + yield plugin.app.vault.adapter.rmdir(`${path}/${dir}`, true); + } + // Check for the icon pack zip file and delete it. + if (yield plugin.app.vault.adapter.exists(`${path}/${dir}.zip`)) { + yield plugin.app.vault.adapter.remove(`${path}/${dir}.zip`); + } +}); +const doesIconPackExist = (plugin, iconPackName) => { + return plugin.app.vault.adapter.exists(`${path}/${iconPackName}`); +}; +const createDirectory = (plugin, dir) => __awaiter(void 0, void 0, void 0, function* () { + const doesDirExist = yield plugin.app.vault.adapter.exists(`${path}/${dir}`); + if (!doesDirExist) { + yield plugin.app.vault.adapter.mkdir(`${path}/${dir}`); + } + return doesDirExist; +}); +const getNormalizedName = (s) => { + return s + .split(/[ -]|[ _]/g) + .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) + .join(''); +}; +// export const normalizeFileName = async (plugin: Plugin, oldPath: string) => { +// const fileName = oldPath.split('/').pop(); +// const newPath = oldPath.substring(0, oldPath.indexOf(fileName)) + getNormalizedName(fileName); +// await plugin.app.vault.adapter.rename(oldPath, newPath); +// }; +const createZipFile = (plugin, filename, buffer) => __awaiter(void 0, void 0, void 0, function* () { + yield plugin.app.vault.adapter.writeBinary(`${path}/${filename}`, buffer); +}); +const createFile = (plugin, iconPackName, filename, content, absoluteFilename) => __awaiter(void 0, void 0, void 0, function* () { + const normalizedFilename = getNormalizedName(filename); + const exists = yield plugin.app.vault.adapter.exists(`${path}/${iconPackName}/${normalizedFilename}`); + if (exists) { + const folderSplit = absoluteFilename.split('/'); + if (folderSplit.length >= 2) { + const folderName = folderSplit[folderSplit.length - 2]; + const newFilename = folderName + normalizedFilename; + yield plugin.app.vault.adapter.write(`${path}/${iconPackName}/${newFilename}`, content); + logger.info(`Renamed old file ${normalizedFilename} to ${newFilename} due to duplication`); + new obsidian.Notice(`[${config.PLUGIN_NAME}] Renamed ${normalizedFilename} to ${newFilename} to avoid duplication.`, 8000); + } + else { + logger.warn(`Could not create icons with duplicated file names (file name: ${normalizedFilename})`); + new obsidian.Notice(`[${config.PLUGIN_NAME}] Could not create duplicated icon name (${normalizedFilename})`, 8000); + } + } + else { + yield plugin.app.vault.adapter.write(`${path}/${iconPackName}/${normalizedFilename}`, content); + } +}); +const createDefaultDirectory = (plugin) => __awaiter(void 0, void 0, void 0, function* () { + yield createDirectory(plugin, ''); +}); +const getAllIconPacks = () => { + return iconPacks; +}; +const getFilesInDirectory = (plugin, dir) => __awaiter(void 0, void 0, void 0, function* () { + if (!(yield plugin.app.vault.adapter.exists(dir))) { + return []; + } + return (yield plugin.app.vault.adapter.list(dir)).files; +}); +const validIconName = /^[(A-Z)|(0-9)]/; +const svgViewboxRegex = /viewBox="([^"]*)"/g; +const svgContentRegex = /(.*?)<\/svg>/g; +const generateIcon = (iconPackName, iconName, content) => { + if (content.length === 0) { + return; + } + content = content.replace(/(\r\n|\n|\r)/gm, ''); + content = content.replace(/>\s+<'); + const normalizedName = iconName.charAt(0).toUpperCase() + iconName.substring(1); + if (!validIconName.exec(normalizedName)) { + logger.info(`Skipping icon with invalid name: ${iconName}`); + return null; + } + const svgViewboxMatch = content.match(svgViewboxRegex); + let svgViewbox = ''; + if (svgViewboxMatch && svgViewboxMatch.length !== 0) { + svgViewbox = svgViewboxMatch[0]; + } + const svgContentMatch = content.match(svgContentRegex); + if (!svgContentMatch) { + logger.info(`Skipping icon with invalid svg content: ${iconName}`); + return null; + } + const svgContent = svgContentMatch.map((val) => val.replace(/<\/?svg>/g, '').replace(//g, ''))[0]; + const iconPackPrefix = createIconPackPrefix(iconPackName); + const icon = { + name: normalizedName.split('.svg')[0], + prefix: iconPackPrefix, + iconPackName, + filename: iconName, + svgContent, + svgViewbox, + svgElement: svg.extract(content), + }; + return icon; +}; +const createIconPackPrefix = (iconPackName) => { + if (iconPackName.includes('-')) { + const splitted = iconPackName.split('-'); + let result = splitted[0].charAt(0).toUpperCase(); + for (let i = 1; i < splitted.length; i++) { + result += splitted[i].charAt(0).toLowerCase(); + } + return result; + } + return (iconPackName.charAt(0).toUpperCase() + iconPackName.charAt(1).toLowerCase()); +}; +const loadUsedIcons = (plugin, icons) => __awaiter(void 0, void 0, void 0, function* () { + const iconPacks = (yield listPath(plugin)).folders.map((iconPack) => iconPack.split('/').pop()); + if (plugin.doesUseNativeLucideIconPack()) { + iconPacks.push(LUCIDE_ICON_PACK_NAME); + } + for (let i = 0; i < icons.length; i++) { + const entry = icons[i]; + if (!entry) { + continue; + } + yield loadIcon(plugin, iconPacks, entry); + } +}); +const listPath = (plugin, listPath) => { + return plugin.app.vault.adapter.list(path); +}; +const getIconPackNameByPrefix = (prefix) => { + var _a; + return (_a = iconPacks.find((iconPack) => iconPack.prefix === prefix)) === null || _a === void 0 ? void 0 : _a.name; +}; +const nextIdentifier = (iconName) => { + return iconName.substring(1).search(/[(A-Z)|(0-9)]/) + 1; +}; +const loadIcon = (plugin, iconPackNames, iconName) => __awaiter(void 0, void 0, void 0, function* () { + const nextLetter = nextIdentifier(iconName); + const prefix = iconName.substring(0, nextLetter); + const name = iconName.substring(nextLetter); + const iconPack = iconPackNames.find((folder) => { + const folderPrefix = createIconPackPrefix(folder); + return prefix === folderPrefix; + }); + if (!iconPack) { + // Ignore because background check automatically adds the icons and icon pack + // directories. + if (!plugin.getSettings().iconsBackgroundCheckEnabled) { + new obsidian.Notice(`Seems like you do not have an icon pack installed. (${iconName})`, 5000); + } + return; + } + if (iconPack === LUCIDE_ICON_PACK_NAME && + plugin.doesUseNativeLucideIconPack()) { + // Native lucide icons already exist for Obsidian. + const lucideIcons = iconPacks.find((iconPack) => iconPack.name === LUCIDE_ICON_PACK_NAME); + const icon = lucideIcons.icons.find((icon) => icon.name === name); + if (!icon) { + logger.warn(`Icon ${icon} does not exist in the native Lucide icon pack.`); + return; + } + preloadedIcons.push(icon); + return; + } + const fullPath = path + '/' + iconPack + '/' + name + '.svg'; + if (!(yield plugin.app.vault.adapter.exists(fullPath))) { + logger.info(`Icon with name '${name}' was not found (full path: ${fullPath})`); + return; + } + const content = yield plugin.app.vault.adapter.read(fullPath); + const icon = generateIcon(iconPack, name, content); + preloadedIcons.push(icon); +}); +const initIconPacks = (plugin) => __awaiter(void 0, void 0, void 0, function* () { + // Remove the beginning slash because paths which start with `/` are the same as without + // a slash. + if (path.startsWith('/')) { + path = path.slice(1); + } + const loadedIconPacks = yield plugin.app.vault.adapter.list(path); + // Extract all zip files which will be downloaded icon packs. + const zipFiles = {}; + for (let i = 0; i < loadedIconPacks.files.length; i++) { + const fileName = loadedIconPacks.files[i]; + if (fileName.endsWith('.zip')) { + const arrayBuffer = yield plugin.app.vault.adapter.readBinary(fileName); + const files = yield readZipFile(arrayBuffer); + const iconPackName = fileName.split('/').pop().split('.zip')[0]; + zipFiles[iconPackName] = files; + } + } + // Check for custom-made icon packs. + for (let i = 0; i < loadedIconPacks.folders.length; i++) { + const folderName = loadedIconPacks.folders[i].split('/').pop(); + // Continue if the icon pack does have a zip file. + if (zipFiles[folderName]) { + continue; + } + const files = yield getFilesInDirectory(plugin, `${path}/${folderName}`); + const loadedIcons = []; + // Convert files into loaded svgs. + for (let j = 0; j < files.length; j++) { + const iconNameRegex = files[j].match(new RegExp(path + '/' + folderName + '/(.*)')); + const iconName = getNormalizedName(iconNameRegex[1]); + const iconContent = yield plugin.app.vault.adapter.read(files[j]); + const icon = generateIcon(folderName, iconName, iconContent); + if (icon) { + loadedIcons.push(icon); + } + } + const prefix = createIconPackPrefix(folderName); + if (!iconPacks.some((iconPack) => iconPack.name === folderName)) { + iconPacks.push({ + name: folderName, + icons: loadedIcons, + prefix, + custom: true, + }); + logger.info(`Loaded icon pack '${folderName}' (amount of icons: ${loadedIcons.length})`); + } + } + // Extract all files from the zip files. + for (const zipFile in zipFiles) { + const files = zipFiles[zipFile]; + const loadedIcons = yield getLoadedIconsFromZipFile(zipFile, files); + const prefix = createIconPackPrefix(zipFile); + if (zipFile === LUCIDE_ICON_PACK_NAME && + !plugin.doesUseCustomLucideIconPack()) { + continue; + } + if (!iconPacks.some((iconPack) => iconPack.name === zipFile)) { + iconPacks.push({ + name: zipFile, + icons: loadedIcons, + prefix, + custom: false, + }); + logger.info(`Loaded icon pack '${zipFile}' (amount of icons: ${loadedIcons.length})`); + } + } +}); +const getLoadedIconsFromZipFile = (iconPackName, files) => __awaiter(void 0, void 0, void 0, function* () { + const loadedIcons = []; + const extraPath = getExtraPath(iconPackName); + for (let j = 0; j < files.length; j++) { + // Checks if the icon pack has an extra path. Also ignores files which do not start + // with the extra path. + if (extraPath && !files[j].name.startsWith(extraPath)) { + continue; + } + const file = yield getFileFromJSZipFile(files[j]); + const iconContent = yield file.text(); + const iconName = getNormalizedName(file.name); + const icon = generateIcon(iconPackName, iconName, iconContent); + if (icon) { + loadedIcons.push(icon); + } + } + return loadedIcons; +}); +const addIconToIconPack = (iconPackName, iconName, iconContent) => { + // Normalize the icon name to remove `-` or `_` in the name. + iconName = getNormalizedName(iconName); + const icon = generateIcon(iconPackName, iconName, iconContent); + if (!icon) { + logger.warn(`Icon could not be generated (icon: ${iconName}, content: ${iconContent})`); + return undefined; + } + const iconPack = iconPacks.find((iconPack) => iconPack.name === iconPackName); + if (!iconPack) { + logger.warn(`Iconpack with name '${iconPackName}' was not found`); + return undefined; + } + iconPack.icons.push(icon); + return icon; +}; +const removeIconFromIconPackDirectory = (plugin, iconPackName, iconName) => { + const iconPack = iconPacks.find((iconPack) => iconPack.name === iconPackName); + // Checks if icon pack is custom-made. + if (!iconPack.custom) { + return plugin.app.vault.adapter.rmdir(`${path}/${iconPackName}/${iconName}.svg`, true); + } +}; +const extractIconToIconPack = (plugin, icon, iconContent) => __awaiter(void 0, void 0, void 0, function* () { + const doesIconPackDirExist = yield plugin.app.vault.adapter.exists(`${path}/${icon.iconPackName}`); + if (!doesIconPackDirExist) { + yield plugin.app.vault.adapter.mkdir(`${path}/${icon.iconPackName}`); + } + const doesIconFileExists = yield plugin.app.vault.adapter.exists(`${path}/${icon.iconPackName}/${icon.name}.svg`); + if (!doesIconFileExists) { + yield createFile(plugin, icon.iconPackName, `${icon.name}.svg`, iconContent); + } +}); +const getAllLoadedIconNames = () => { + return iconPacks.reduce((total, iconPack) => { + total.push(...iconPack.icons); + return total; + }, []); +}; +const registerIconPack = (name, arrayBuffer) => __awaiter(void 0, void 0, void 0, function* () { + const files = yield readZipFile(arrayBuffer); + const loadedIcons = yield getLoadedIconsFromZipFile(name, files); + const prefix = createIconPackPrefix(name); + iconPacks.push({ name, icons: loadedIcons, prefix, custom: false }); + logger.info(`Loaded icon pack ${name} (amount of icons: ${loadedIcons.length})`); +}); +const doesIconExists = (iconName) => { + const icons = getAllLoadedIconNames(); + return (icons.find((icon) => icon.name === iconName || icon.prefix + icon.name === iconName) !== undefined); +}; +const getIconsFromIconPack = (iconPackName) => { + return iconPacks.find((iconPack) => iconPack.name === iconPackName); +}; +const getIconFromIconPack = (iconPackName, iconPrefix, iconName) => { + const foundIcon = preloadedIcons.find((icon) => icon.prefix.toLowerCase() === iconPrefix.toLowerCase() && + icon.name.toLowerCase() === iconName.toLowerCase()); + if (foundIcon) { + return foundIcon; + } + const iconPack = iconPacks.find((iconPack) => iconPack.name === iconPackName); + if (!iconPack) { + return undefined; + } + return iconPack.icons.find((icon) => getNormalizedName(icon.name) === iconName); +}; +const getSvgFromLoadedIcon = (iconPrefix, iconName) => { + let icon = ''; + let foundIcon = preloadedIcons.find((icon) => icon.prefix.toLowerCase() === iconPrefix.toLowerCase() && + icon.name.toLowerCase() === iconName.toLowerCase()); + if (!foundIcon) { + iconPacks.forEach((iconPack) => { + const icon = iconPack.icons.find((icon) => { + return (icon.prefix.toLowerCase() === iconPrefix.toLowerCase() && + getNormalizedName(icon.name).toLowerCase() === iconName.toLowerCase()); + }); + if (icon) { + foundIcon = icon; + } + }); + } + if (foundIcon) { + icon = foundIcon.svgElement; + } + return icon; +}; + +/*! Copyright Twitter Inc. and other contributors. Licensed under MIT */ +var twemoji=function(){var twemoji={base:"https://cdn.jsdelivr.net/gh/jdecked/twemoji@15.1.0/assets/",ext:".png",size:"72x72",className:"emoji",convert:{fromCodePoint:fromCodePoint,toCodePoint:toCodePoint},onerror:function onerror(){if(this.parentNode){this.parentNode.replaceChild(createText(this.alt,false),this);}},parse:parse,replace:replace,test:test},escaper={"&":"&","<":"<",">":">","'":"'",'"':"""},re=/(?:\ud83d\udc68\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffc-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb\udffd-\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb\udffc\udffe\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb-\udffd\udfff]|\ud83e\uddd1\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83e\uddd1\ud83c[\udffb-\udffe]|\ud83d\udc68\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc68\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc68\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc68\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffc-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffd-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb\udffc\udffe\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffd\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc68\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83d\udc69\ud83c[\udffb-\udfff]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc68\ud83c[\udffb-\udffe]|\ud83d\udc69\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83d\udc69\ud83c[\udffb-\udffe]|\ud83e\uddd1\ud83c\udffb\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffc-\udfff]|\ud83e\uddd1\ud83c\udffb\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb\udffd-\udfff]|\ud83e\uddd1\ud83c\udffc\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb\udffc\udffe\udfff]|\ud83e\uddd1\ud83c\udffd\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb-\udffd\udfff]|\ud83e\uddd1\ud83c\udffe\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83e\uddd1\ud83c\udfff\u200d\u2764\ufe0f\u200d\ud83e\uddd1\ud83c[\udffb-\udffe]|\ud83e\uddd1\ud83c\udfff\u200d\ud83e\udd1d\u200d\ud83e\uddd1\ud83c[\udffb-\udfff]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d\udc68|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d\udc8b\u200d\ud83d[\udc68\udc69]|\ud83e\udef1\ud83c\udffb\u200d\ud83e\udef2\ud83c[\udffc-\udfff]|\ud83e\udef1\ud83c\udffc\u200d\ud83e\udef2\ud83c[\udffb\udffd-\udfff]|\ud83e\udef1\ud83c\udffd\u200d\ud83e\udef2\ud83c[\udffb\udffc\udffe\udfff]|\ud83e\udef1\ud83c\udffe\u200d\ud83e\udef2\ud83c[\udffb-\udffd\udfff]|\ud83e\udef1\ud83c\udfff\u200d\ud83e\udef2\ud83c[\udffb-\udffe]|\ud83d\udc68\u200d\u2764\ufe0f\u200d\ud83d\udc68|\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d[\udc68\udc69]|\ud83e\uddd1\u200d\ud83e\udd1d\u200d\ud83e\uddd1|\ud83d\udc6b\ud83c[\udffb-\udfff]|\ud83d\udc6c\ud83c[\udffb-\udfff]|\ud83d\udc6d\ud83c[\udffb-\udfff]|\ud83d\udc8f\ud83c[\udffb-\udfff]|\ud83d\udc91\ud83c[\udffb-\udfff]|\ud83e\udd1d\ud83c[\udffb-\udfff]|\ud83d[\udc6b-\udc6d\udc8f\udc91]|\ud83e\udd1d)|(?:\ud83d[\udc68\udc69]|\ud83e\uddd1)(?:\ud83c[\udffb-\udfff])?\u200d(?:\u2695\ufe0f|\u2696\ufe0f|\u2708\ufe0f|\ud83c[\udf3e\udf73\udf7c\udf84\udf93\udfa4\udfa8\udfeb\udfed]|\ud83d[\udcbb\udcbc\udd27\udd2c\ude80\ude92]|\ud83e[\uddaf-\uddb3\uddbc\uddbd])(?:\u200d\u27a1\ufe0f)?|(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75]|\u26f9)((?:\ud83c[\udffb-\udfff]|\ufe0f)\u200d[\u2640\u2642]\ufe0f(?:\u200d\u27a1\ufe0f)?)|(?:\ud83c[\udfc3\udfc4\udfca]|\ud83d[\udc6e\udc70\udc71\udc73\udc77\udc81\udc82\udc86\udc87\ude45-\ude47\ude4b\ude4d\ude4e\udea3\udeb4-\udeb6]|\ud83e[\udd26\udd35\udd37-\udd39\udd3d\udd3e\uddb8\uddb9\uddcd-\uddcf\uddd4\uddd6-\udddd])(?:\ud83c[\udffb-\udfff])?\u200d[\u2640\u2642]\ufe0f(?:\u200d\u27a1\ufe0f)?|(?:\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83e\uddd1\u200d\ud83e\uddd1\u200d\ud83e\uddd2\u200d\ud83e\uddd2|\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66|\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83e\uddd1\u200d\ud83e\uddd1\u200d\ud83e\uddd2|\ud83e\uddd1\u200d\ud83e\uddd2\u200d\ud83e\uddd2|\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f|\ud83c\udff3\ufe0f\u200d\ud83c\udf08|\ud83d\ude36\u200d\ud83c\udf2b\ufe0f|\u26d3\ufe0f\u200d\ud83d\udca5|\u2764\ufe0f\u200d\ud83d\udd25|\u2764\ufe0f\u200d\ud83e\ude79|\ud83c\udf44\u200d\ud83d\udfeb|\ud83c\udf4b\u200d\ud83d\udfe9|\ud83c\udff4\u200d\u2620\ufe0f|\ud83d\udc15\u200d\ud83e\uddba|\ud83d\udc26\u200d\ud83d\udd25|\ud83d\udc3b\u200d\u2744\ufe0f|\ud83d\udc41\u200d\ud83d\udde8|\ud83d\udc68\u200d\ud83d[\udc66\udc67]|\ud83d\udc69\u200d\ud83d[\udc66\udc67]|\ud83d\udc6f\u200d\u2640\ufe0f|\ud83d\udc6f\u200d\u2642\ufe0f|\ud83d\ude2e\u200d\ud83d\udca8|\ud83d\ude35\u200d\ud83d\udcab|\ud83d\ude42\u200d\u2194\ufe0f|\ud83d\ude42\u200d\u2195\ufe0f|\ud83e\udd3c\u200d\u2640\ufe0f|\ud83e\udd3c\u200d\u2642\ufe0f|\ud83e\uddd1\u200d\ud83e\uddd2|\ud83e\uddde\u200d\u2640\ufe0f|\ud83e\uddde\u200d\u2642\ufe0f|\ud83e\udddf\u200d\u2640\ufe0f|\ud83e\udddf\u200d\u2642\ufe0f|\ud83d\udc08\u200d\u2b1b|\ud83d\udc26\u200d\u2b1b)|[#*0-9]\ufe0f?\u20e3|(?:[©®\u2122\u265f]\ufe0f)|(?:\ud83c[\udc04\udd70\udd71\udd7e\udd7f\ude02\ude1a\ude2f\ude37\udf21\udf24-\udf2c\udf36\udf7d\udf96\udf97\udf99-\udf9b\udf9e\udf9f\udfcd\udfce\udfd4-\udfdf\udff3\udff5\udff7]|\ud83d[\udc3f\udc41\udcfd\udd49\udd4a\udd6f\udd70\udd73\udd76-\udd79\udd87\udd8a-\udd8d\udda5\udda8\uddb1\uddb2\uddbc\uddc2-\uddc4\uddd1-\uddd3\udddc-\uddde\udde1\udde3\udde8\uddef\uddf3\uddfa\udecb\udecd-\udecf\udee0-\udee5\udee9\udef0\udef3]|[\u203c\u2049\u2139\u2194-\u2199\u21a9\u21aa\u231a\u231b\u2328\u23cf\u23ed-\u23ef\u23f1\u23f2\u23f8-\u23fa\u24c2\u25aa\u25ab\u25b6\u25c0\u25fb-\u25fe\u2600-\u2604\u260e\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262a\u262e\u262f\u2638-\u263a\u2640\u2642\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267b\u267f\u2692-\u2697\u2699\u269b\u269c\u26a0\u26a1\u26a7\u26aa\u26ab\u26b0\u26b1\u26bd\u26be\u26c4\u26c5\u26c8\u26cf\u26d1\u26d3\u26d4\u26e9\u26ea\u26f0-\u26f5\u26f8\u26fa\u26fd\u2702\u2708\u2709\u270f\u2712\u2714\u2716\u271d\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u2764\u27a1\u2934\u2935\u2b05-\u2b07\u2b1b\u2b1c\u2b50\u2b55\u3030\u303d\u3297\u3299])(?:\ufe0f|(?!\ufe0e))|(?:(?:\ud83c[\udfcb\udfcc]|\ud83d[\udd74\udd75\udd90]|\ud83e\udef0|[\u261d\u26f7\u26f9\u270c\u270d])(?:\ufe0f|(?!\ufe0e))|(?:\ud83c\udfc3|\ud83d\udeb6|\ud83e\uddce)(?:\ud83c[\udffb-\udfff])?(?:\u200d\u27a1\ufe0f)?|(?:\ud83c[\udf85\udfc2\udfc4\udfc7\udfca]|\ud83d[\udc42\udc43\udc46-\udc50\udc66-\udc69\udc6e\udc70-\udc78\udc7c\udc81-\udc83\udc85-\udc87\udcaa\udd7a\udd95\udd96\ude45-\ude47\ude4b-\ude4f\udea3\udeb4\udeb5\udec0\udecc]|\ud83e[\udd0c\udd0f\udd18-\udd1c\udd1e\udd1f\udd26\udd30-\udd39\udd3d\udd3e\udd77\uddb5\uddb6\uddb8\uddb9\uddbb\uddcd\uddcf\uddd1-\udddd\udec3-\udec5\udef1-\udef8]|[\u270a\u270b]))(?:\ud83c[\udffb-\udfff])?|(?:\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc73\udb40\udc63\udb40\udc74\udb40\udc7f|\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc77\udb40\udc6c\udb40\udc73\udb40\udc7f|\ud83c\udde6\ud83c[\udde8-\uddec\uddee\uddf1\uddf2\uddf4\uddf6-\uddfa\uddfc\uddfd\uddff]|\ud83c\udde7\ud83c[\udde6\udde7\udde9-\uddef\uddf1-\uddf4\uddf6-\uddf9\uddfb\uddfc\uddfe\uddff]|\ud83c\udde8\ud83c[\udde6\udde8\udde9\uddeb-\uddee\uddf0-\uddf5\uddf7\uddfa-\uddff]|\ud83c\udde9\ud83c[\uddea\uddec\uddef\uddf0\uddf2\uddf4\uddff]|\ud83c\uddea\ud83c[\udde6\udde8\uddea\uddec\udded\uddf7-\uddfa]|\ud83c\uddeb\ud83c[\uddee-\uddf0\uddf2\uddf4\uddf7]|\ud83c\uddec\ud83c[\udde6\udde7\udde9-\uddee\uddf1-\uddf3\uddf5-\uddfa\uddfc\uddfe]|\ud83c\udded\ud83c[\uddf0\uddf2\uddf3\uddf7\uddf9\uddfa]|\ud83c\uddee\ud83c[\udde8-\uddea\uddf1-\uddf4\uddf6-\uddf9]|\ud83c\uddef\ud83c[\uddea\uddf2\uddf4\uddf5]|\ud83c\uddf0\ud83c[\uddea\uddec-\uddee\uddf2\uddf3\uddf5\uddf7\uddfc\uddfe\uddff]|\ud83c\uddf1\ud83c[\udde6-\udde8\uddee\uddf0\uddf7-\uddfb\uddfe]|\ud83c\uddf2\ud83c[\udde6\udde8-\udded\uddf0-\uddff]|\ud83c\uddf3\ud83c[\udde6\udde8\uddea-\uddec\uddee\uddf1\uddf4\uddf5\uddf7\uddfa\uddff]|\ud83c\uddf4\ud83c\uddf2|\ud83c\uddf5\ud83c[\udde6\uddea-\udded\uddf0-\uddf3\uddf7-\uddf9\uddfc\uddfe]|\ud83c\uddf6\ud83c\udde6|\ud83c\uddf7\ud83c[\uddea\uddf4\uddf8\uddfa\uddfc]|\ud83c\uddf8\ud83c[\udde6-\uddea\uddec-\uddf4\uddf7-\uddf9\uddfb\uddfd-\uddff]|\ud83c\uddf9\ud83c[\udde6\udde8\udde9\uddeb-\udded\uddef-\uddf4\uddf7\uddf9\uddfb\uddfc\uddff]|\ud83c\uddfa\ud83c[\udde6\uddec\uddf2\uddf3\uddf8\uddfe\uddff]|\ud83c\uddfb\ud83c[\udde6\udde8\uddea\uddec\uddee\uddf3\uddfa]|\ud83c\uddfc\ud83c[\uddeb\uddf8]|\ud83c\uddfd\ud83c\uddf0|\ud83c\uddfe\ud83c[\uddea\uddf9]|\ud83c\uddff\ud83c[\udde6\uddf2\uddfc]|\ud83c[\udccf\udd8e\udd91-\udd9a\udde6-\uddff\ude01\ude32-\ude36\ude38-\ude3a\ude50\ude51\udf00-\udf20\udf2d-\udf35\udf37-\udf7c\udf7e-\udf84\udf86-\udf93\udfa0-\udfc1\udfc5\udfc6\udfc8\udfc9\udfcf-\udfd3\udfe0-\udff0\udff4\udff8-\udfff]|\ud83d[\udc00-\udc3e\udc40\udc44\udc45\udc51-\udc65\udc6a\udc6f\udc79-\udc7b\udc7d-\udc80\udc84\udc88-\udc8e\udc90\udc92-\udca9\udcab-\udcfc\udcff-\udd3d\udd4b-\udd4e\udd50-\udd67\udda4\uddfb-\ude44\ude48-\ude4a\ude80-\udea2\udea4-\udeb3\udeb7-\udebf\udec1-\udec5\uded0-\uded2\uded5-\uded7\udedc-\udedf\udeeb\udeec\udef4-\udefc\udfe0-\udfeb\udff0]|\ud83e[\udd0d\udd0e\udd10-\udd17\udd20-\udd25\udd27-\udd2f\udd3a\udd3c\udd3f-\udd45\udd47-\udd76\udd78-\uddb4\uddb7\uddba\uddbc-\uddcc\uddd0\uddde-\uddff\ude70-\ude7c\ude80-\ude88\ude90-\udebd\udebf-\udec2\udece-\udedb\udee0-\udee8]|[\u23e9-\u23ec\u23f0\u23f3\u267e\u26ce\u2705\u2728\u274c\u274e\u2753-\u2755\u2795-\u2797\u27b0\u27bf\ue50a])|\ufe0f/g,UFE0Fg=/\uFE0F/g,U200D=String.fromCharCode(8205),rescaper=/[&<>'"]/g,shouldntBeParsed=/^(?:iframe|noframes|noscript|script|select|style|textarea)$/,fromCharCode=String.fromCharCode;return twemoji;function createText(text,clean){return document.createTextNode(clean?text.replace(UFE0Fg,""):text)}function escapeHTML(s){return s.replace(rescaper,replacer)}function defaultImageSrcGenerator(icon,options){return "".concat(options.base,options.size,"/",icon,options.ext)}function grabAllTextNodes(node,allText){var childNodes=node.childNodes,length=childNodes.length,subnode,nodeType;while(length--){subnode=childNodes[length];nodeType=subnode.nodeType;if(nodeType===3){allText.push(subnode);}else if(nodeType===1&&!("ownerSVGElement"in subnode)&&!shouldntBeParsed.test(subnode.nodeName.toLowerCase())){grabAllTextNodes(subnode,allText);}}return allText}function grabTheRightIcon(rawText){return toCodePoint(rawText.indexOf(U200D)<0?rawText.replace(UFE0Fg,""):rawText)}function parseNode(node,options){var allText=grabAllTextNodes(node,[]),length=allText.length,attrib,attrname,modified,fragment,subnode,text,match,i,index,img,rawText,iconId,src;while(length--){modified=false;fragment=document.createDocumentFragment();subnode=allText[length];text=subnode.nodeValue;i=0;while(match=re.exec(text)){index=match.index;if(index!==i){fragment.appendChild(createText(text.slice(i,index),true));}rawText=match[0];iconId=grabTheRightIcon(rawText);i=index+rawText.length;src=options.callback(iconId,options);if(iconId&&src){img=new Image;img.onerror=options.onerror;img.setAttribute("draggable","false");attrib=options.attributes(rawText,iconId);for(attrname in attrib){if(attrib.hasOwnProperty(attrname)&&attrname.indexOf("on")!==0&&!img.hasAttribute(attrname)){img.setAttribute(attrname,attrib[attrname]);}}img.className=options.className;img.alt=rawText;img.src=src;modified=true;fragment.appendChild(img);}if(!img)fragment.appendChild(createText(rawText,false));img=null;}if(modified){if(i");}return ret})}function replacer(m){return escaper[m]}function returnNull(){return null}function toSizeSquaredAsset(value){return typeof value==="number"?value+"x"+value:value}function fromCodePoint(codepoint){var code=typeof codepoint==="string"?parseInt(codepoint,16):codepoint;if(code<65536){return fromCharCode(code)}code-=65536;return fromCharCode(55296+(code>>10),56320+(code&1023))}function parse(what,how){if(!how||typeof how==="function"){how={callback:how};}return (typeof what==="string"?parseString:parseNode)(what,{callback:how.callback||defaultImageSrcGenerator,attributes:typeof how.attributes==="function"?how.attributes:returnNull,base:typeof how.base==="string"?how.base:twemoji.base,ext:how.ext||twemoji.ext,size:how.folder||toSizeSquaredAsset(how.size||twemoji.size),className:how.className||twemoji.className,onerror:how.onerror||twemoji.onerror})}function replace(text,callback){return String(text).replace(re,callback)}function test(text){re.lastIndex=0;var result=re.test(text);re.lastIndex=0;return result}function toCodePoint(unicodeSurrogates,sep){var r=[],c=0,p=0,i=0;while(i { + return new RegExp(/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE])))?))?|\uDC6F(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDD75(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE88\uDE90-\uDEBD\uDEBF-\uDEC2\uDECE-\uDEDB\uDEE0-\uDEE8]|\uDD3C(?:\u200D[\u2640\u2642]\uFE0F?|\uD83C[\uDFFB-\uDFFF])?|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/, 'g'); +}; +const shortNames = { + '😀': 'grinning face', + '😃': 'grinning face with big eyes', + '😄': 'grinning face with smiling eyes', + '😁': 'beaming face with smiling eyes', + '😆': 'grinning squinting face', + '😅': 'grinning face with sweat', + '🤣': 'rolling on the floor laughing', + '😂': 'face with tears of joy', + '🙂': 'slightly smiling face', + '🙃': 'upside-down face', + '🫠': '⊛ melting face', + '😉': 'winking face', + '😊': 'smiling face with smiling eyes', + '😇': 'smiling face with halo', + '🥰': 'smiling face with hearts', + '😍': 'smiling face with heart-eyes', + '🤩': 'star-struck', + '😘': 'face blowing a kiss', + '😗': 'kissing face', + '☺': 'smiling face', + '😚': 'kissing face with closed eyes', + '😙': 'kissing face with smiling eyes', + '🥲': 'smiling face with tear', + '😋': 'face savoring food', + '😛': 'face with tongue', + '😜': 'winking face with tongue', + '🤪': 'zany face', + '😝': 'squinting face with tongue', + '🤑': 'money-mouth face', + '🤗': 'smiling face with open hands', + '🤭': 'face with hand over mouth', + '🫢': '⊛ face with open eyes and hand over mouth', + '🫣': '⊛ face with peeking eye', + '🤫': 'shushing face', + '🤔': 'thinking face', + '🫡': '⊛ saluting face', + '🤐': 'zipper-mouth face', + '🤨': 'face with raised eyebrow', + '😐': 'neutral face', + '😑': 'expressionless face', + '😶': 'face without mouth', + '🫥': '⊛ dotted line face', + '😶‍🌫️': 'face in clouds', + '😏': 'smirking face', + '😒': 'unamused face', + '🙄': 'face with rolling eyes', + '😬': 'grimacing face', + '😮‍💨': 'face exhaling', + '🤥': 'lying face', + '😌': 'relieved face', + '😔': 'pensive face', + '😪': 'sleepy face', + '🤤': 'drooling face', + '😴': 'sleeping face', + '😷': 'face with medical mask', + '🤒': 'face with thermometer', + '🤕': 'face with head-bandage', + '🤢': 'nauseated face', + '🤮': 'face vomiting', + '🤧': 'sneezing face', + '🥵': 'hot face', + '🥶': 'cold face', + '🥴': 'woozy face', + '😵': 'face with crossed-out eyes', + '😵‍💫': 'face with spiral eyes', + '🤯': 'exploding head', + '🤠': 'cowboy hat face', + '🥳': 'partying face', + '🥸': 'disguised face', + '😎': 'smiling face with sunglasses', + '🤓': 'nerd face', + '🧐': 'face with monocle', + '😕': 'confused face', + '🫤': '⊛ face with diagonal mouth', + '😟': 'worried face', + '🙁': 'slightly frowning face', + '☹': 'frowning face', + '😮': 'face with open mouth', + '😯': 'hushed face', + '😲': 'astonished face', + '😳': 'flushed face', + '🥺': 'pleading face', + '🥹': '⊛ face holding back tears', + '😦': 'frowning face with open mouth', + '😧': 'anguished face', + '😨': 'fearful face', + '😰': 'anxious face with sweat', + '😥': 'sad but relieved face', + '😢': 'crying face', + '😭': 'loudly crying face', + '😱': 'face screaming in fear', + '😖': 'confounded face', + '😣': 'persevering face', + '😞': 'disappointed face', + '😓': 'downcast face with sweat', + '😩': 'weary face', + '😫': 'tired face', + '🥱': 'yawning face', + '😤': 'face with steam from nose', + '😡': 'pouting face', + '😠': 'angry face', + '🤬': 'face with symbols on mouth', + '😈': 'smiling face with horns', + '👿': 'angry face with horns', + '💀': 'skull', + '☠': 'skull and crossbones', + '💩': 'pile of poo', + '🤡': 'clown face', + '👹': 'ogre', + '👺': 'goblin', + '👻': 'ghost', + '👽': 'alien', + '👾': 'alien monster', + '🤖': 'robot', + '😺': 'grinning cat', + '😸': 'grinning cat with smiling eyes', + '😹': 'cat with tears of joy', + '😻': 'smiling cat with heart-eyes', + '😼': 'cat with wry smile', + '😽': 'kissing cat', + '🙀': 'weary cat', + '😿': 'crying cat', + '😾': 'pouting cat', + '🙈': 'see-no-evil monkey', + '🙉': 'hear-no-evil monkey', + '🙊': 'speak-no-evil monkey', + '💋': 'kiss mark', + '💌': 'love letter', + '💘': 'heart with arrow', + '💝': 'heart with ribbon', + '💖': 'sparkling heart', + '💗': 'growing heart', + '💓': 'beating heart', + '💞': 'revolving hearts', + '💕': 'two hearts', + '💟': 'heart decoration', + '❣': 'heart exclamation', + '💔': 'broken heart', + '❤️‍🔥': 'heart on fire', + '❤️‍🩹': 'mending heart', + '❤': 'red heart', + '🧡': 'orange heart', + '💛': 'yellow heart', + '💚': 'green heart', + '💙': 'blue heart', + '💜': 'purple heart', + '🤎': 'brown heart', + '🖤': 'black heart', + '🤍': 'white heart', + '💯': 'hundred points', + '💢': 'anger symbol', + '💥': 'collision', + '💫': 'dizzy', + '💦': 'sweat droplets', + '💨': 'dashing away', + '🕳': 'hole', + '💣': 'bomb', + '💬': 'speech balloon', + '👁️‍🗨️': 'eye in speech bubble', + '🗨': 'left speech bubble', + '🗯': 'right anger bubble', + '💭': 'thought balloon', + '💤': 'zzz', + '👋': 'waving hand', + '🤚': 'raised back of hand', + '🖐': 'hand with fingers splayed', + '✋': 'raised hand', + '🖖': 'vulcan salute', + '🫱': '⊛ rightwards hand', + '🫲': '⊛ leftwards hand', + '🫳': '⊛ palm down hand', + '🫴': '⊛ palm up hand', + '👌': 'OK hand', + '🤌': 'pinched fingers', + '🤏': 'pinching hand', + '✌': 'victory hand', + '🤞': 'crossed fingers', + '🫰': '⊛ hand with index finger and thumb crossed', + '🤟': 'love-you gesture', + '🤘': 'sign of the horns', + '🤙': 'call me hand', + '👈': 'backhand index pointing left', + '👉': 'backhand index pointing right', + '👆': 'backhand index pointing up', + '🖕': 'middle finger', + '👇': 'backhand index pointing down', + '☝': 'index pointing up', + '🫵': '⊛ index pointing at the viewer', + '👍': 'thumbs up', + '👎': 'thumbs down', + '✊': 'raised fist', + '👊': 'oncoming fist', + '🤛': 'left-facing fist', + '🤜': 'right-facing fist', + '👏': 'clapping hands', + '🙌': 'raising hands', + '🫶': '⊛ heart hands', + '👐': 'open hands', + '🤲': 'palms up together', + '🤝': 'handshake', + '🙏': 'folded hands', + '✍': 'writing hand', + '💅': 'nail polish', + '🤳': 'selfie', + '💪': 'flexed biceps', + '🦾': 'mechanical arm', + '🦿': 'mechanical leg', + '🦵': 'leg', + '🦶': 'foot', + '👂': 'ear', + '🦻': 'ear with hearing aid', + '👃': 'nose', + '🧠': 'brain', + '🫀': 'anatomical heart', + '🫁': 'lungs', + '🦷': 'tooth', + '🦴': 'bone', + '👀': 'eyes', + '👁': 'eye', + '👅': 'tongue', + '👄': 'mouth', + '🫦': '⊛ biting lip', + '👶': 'baby', + '🧒': 'child', + '👦': 'boy', + '👧': 'girl', + '🧑': 'person', + '👱': 'person: blond hair', + '👨': 'man', + '🧔': 'person: beard', + '🧔‍♂️': 'man: beard', + '🧔‍♀️': 'woman: beard', + '👨‍🦰': 'man: red hair', + '👨‍🦱': 'man: curly hair', + '👨‍🦳': 'man: white hair', + '👨‍🦲': 'man: bald', + '👩': 'woman', + '👩‍🦰': 'woman: red hair', + '🧑‍🦰': 'person: red hair', + '👩‍🦱': 'woman: curly hair', + '🧑‍🦱': 'person: curly hair', + '👩‍🦳': 'woman: white hair', + '🧑‍🦳': 'person: white hair', + '👩‍🦲': 'woman: bald', + '🧑‍🦲': 'person: bald', + '👱‍♀️': 'woman: blond hair', + '👱‍♂️': 'man: blond hair', + '🧓': 'older person', + '👴': 'old man', + '👵': 'old woman', + '🙍': 'person frowning', + '🙍‍♂️': 'man frowning', + '🙍‍♀️': 'woman frowning', + '🙎': 'person pouting', + '🙎‍♂️': 'man pouting', + '🙎‍♀️': 'woman pouting', + '🙅': 'person gesturing NO', + '🙅‍♂️': 'man gesturing NO', + '🙅‍♀️': 'woman gesturing NO', + '🙆': 'person gesturing OK', + '🙆‍♂️': 'man gesturing OK', + '🙆‍♀️': 'woman gesturing OK', + '💁': 'person tipping hand', + '💁‍♂️': 'man tipping hand', + '💁‍♀️': 'woman tipping hand', + '🙋': 'person raising hand', + '🙋‍♂️': 'man raising hand', + '🙋‍♀️': 'woman raising hand', + '🧏': 'deaf person', + '🧏‍♂️': 'deaf man', + '🧏‍♀️': 'deaf woman', + '🙇': 'person bowing', + '🙇‍♂️': 'man bowing', + '🙇‍♀️': 'woman bowing', + '🤦': 'person facepalming', + '🤦‍♂️': 'man facepalming', + '🤦‍♀️': 'woman facepalming', + '🤷': 'person shrugging', + '🤷‍♂️': 'man shrugging', + '🤷‍♀️': 'woman shrugging', + '🧑‍⚕️': 'health worker', + '👨‍⚕️': 'man health worker', + '👩‍⚕️': 'woman health worker', + '🧑‍🎓': 'student', + '👨‍🎓': 'man student', + '👩‍🎓': 'woman student', + '🧑‍🏫': 'teacher', + '👨‍🏫': 'man teacher', + '👩‍🏫': 'woman teacher', + '🧑‍⚖️': 'judge', + '👨‍⚖️': 'man judge', + '👩‍⚖️': 'woman judge', + '🧑‍🌾': 'farmer', + '👨‍🌾': 'man farmer', + '👩‍🌾': 'woman farmer', + '🧑‍🍳': 'cook', + '👨‍🍳': 'man cook', + '👩‍🍳': 'woman cook', + '🧑‍🔧': 'mechanic', + '👨‍🔧': 'man mechanic', + '👩‍🔧': 'woman mechanic', + '🧑‍🏭': 'factory worker', + '👨‍🏭': 'man factory worker', + '👩‍🏭': 'woman factory worker', + '🧑‍💼': 'office worker', + '👨‍💼': 'man office worker', + '👩‍💼': 'woman office worker', + '🧑‍🔬': 'scientist', + '👨‍🔬': 'man scientist', + '👩‍🔬': 'woman scientist', + '🧑‍💻': 'technologist', + '👨‍💻': 'man technologist', + '👩‍💻': 'woman technologist', + '🧑‍🎤': 'singer', + '👨‍🎤': 'man singer', + '👩‍🎤': 'woman singer', + '🧑‍🎨': 'artist', + '👨‍🎨': 'man artist', + '👩‍🎨': 'woman artist', + '🧑‍✈️': 'pilot', + '👨‍✈️': 'man pilot', + '👩‍✈️': 'woman pilot', + '🧑‍🚀': 'astronaut', + '👨‍🚀': 'man astronaut', + '👩‍🚀': 'woman astronaut', + '🧑‍🚒': 'firefighter', + '👨‍🚒': 'man firefighter', + '👩‍🚒': 'woman firefighter', + '👮': 'police officer', + '👮‍♂️': 'man police officer', + '👮‍♀️': 'woman police officer', + '🕵': 'detective', + '🕵️‍♂️': 'man detective', + '🕵️‍♀️': 'woman detective', + '💂': 'guard', + '💂‍♂️': 'man guard', + '💂‍♀️': 'woman guard', + '🥷': 'ninja', + '👷': 'construction worker', + '👷‍♂️': 'man construction worker', + '👷‍♀️': 'woman construction worker', + '🫅': '⊛ person with crown', + '🤴': 'prince', + '👸': 'princess', + '👳': 'person wearing turban', + '👳‍♂️': 'man wearing turban', + '👳‍♀️': 'woman wearing turban', + '👲': 'person with skullcap', + '🧕': 'woman with headscarf', + '🤵': 'person in tuxedo', + '🤵‍♂️': 'man in tuxedo', + '🤵‍♀️': 'woman in tuxedo', + '👰': 'person with veil', + '👰‍♂️': 'man with veil', + '👰‍♀️': 'woman with veil', + '🤰': 'pregnant woman', + '🫃': '⊛ pregnant man', + '🫄': '⊛ pregnant person', + '🤱': 'breast-feeding', + '👩‍🍼': 'woman feeding baby', + '👨‍🍼': 'man feeding baby', + '🧑‍🍼': 'person feeding baby', + '👼': 'baby angel', + '🎅': 'Santa Claus', + '🤶': 'Mrs. Claus', + '🧑‍🎄': 'mx claus', + '🦸': 'superhero', + '🦸‍♂️': 'man superhero', + '🦸‍♀️': 'woman superhero', + '🦹': 'supervillain', + '🦹‍♂️': 'man supervillain', + '🦹‍♀️': 'woman supervillain', + '🧙': 'mage', + '🧙‍♂️': 'man mage', + '🧙‍♀️': 'woman mage', + '🧚': 'fairy', + '🧚‍♂️': 'man fairy', + '🧚‍♀️': 'woman fairy', + '🧛': 'vampire', + '🧛‍♂️': 'man vampire', + '🧛‍♀️': 'woman vampire', + '🧜': 'merperson', + '🧜‍♂️': 'merman', + '🧜‍♀️': 'mermaid', + '🧝': 'elf', + '🧝‍♂️': 'man elf', + '🧝‍♀️': 'woman elf', + '🧞': 'genie', + '🧞‍♂️': 'man genie', + '🧞‍♀️': 'woman genie', + '🧟': 'zombie', + '🧟‍♂️': 'man zombie', + '🧟‍♀️': 'woman zombie', + '🧌': '⊛ troll', + '💆': 'person getting massage', + '💆‍♂️': 'man getting massage', + '💆‍♀️': 'woman getting massage', + '💇': 'person getting haircut', + '💇‍♂️': 'man getting haircut', + '💇‍♀️': 'woman getting haircut', + '🚶': 'person walking', + '🚶‍♂️': 'man walking', + '🚶‍♀️': 'woman walking', + '🧍': 'person standing', + '🧍‍♂️': 'man standing', + '🧍‍♀️': 'woman standing', + '🧎': 'person kneeling', + '🧎‍♂️': 'man kneeling', + '🧎‍♀️': 'woman kneeling', + '🧑‍🦯': 'person with white cane', + '👨‍🦯': 'man with white cane', + '👩‍🦯': 'woman with white cane', + '🧑‍🦼': 'person in motorized wheelchair', + '👨‍🦼': 'man in motorized wheelchair', + '👩‍🦼': 'woman in motorized wheelchair', + '🧑‍🦽': 'person in manual wheelchair', + '👨‍🦽': 'man in manual wheelchair', + '👩‍🦽': 'woman in manual wheelchair', + '🏃': 'person running', + '🏃‍♂️': 'man running', + '🏃‍♀️': 'woman running', + '💃': 'woman dancing', + '🕺': 'man dancing', + '🕴': 'person in suit levitating', + '👯': 'people with bunny ears', + '👯‍♂️': 'men with bunny ears', + '👯‍♀️': 'women with bunny ears', + '🧖': 'person in steamy room', + '🧖‍♂️': 'man in steamy room', + '🧖‍♀️': 'woman in steamy room', + '🧗': 'person climbing', + '🧗‍♂️': 'man climbing', + '🧗‍♀️': 'woman climbing', + '🤺': 'person fencing', + '🏇': 'horse racing', + '⛷': 'skier', + '🏂': 'snowboarder', + '🏌': 'person golfing', + '🏌️‍♂️': 'man golfing', + '🏌️‍♀️': 'woman golfing', + '🏄': 'person surfing', + '🏄‍♂️': 'man surfing', + '🏄‍♀️': 'woman surfing', + '🚣': 'person rowing boat', + '🚣‍♂️': 'man rowing boat', + '🚣‍♀️': 'woman rowing boat', + '🏊': 'person swimming', + '🏊‍♂️': 'man swimming', + '🏊‍♀️': 'woman swimming', + '⛹': 'person bouncing ball', + '⛹️‍♂️': 'man bouncing ball', + '⛹️‍♀️': 'woman bouncing ball', + '🏋': 'person lifting weights', + '🏋️‍♂️': 'man lifting weights', + '🏋️‍♀️': 'woman lifting weights', + '🚴': 'person biking', + '🚴‍♂️': 'man biking', + '🚴‍♀️': 'woman biking', + '🚵': 'person mountain biking', + '🚵‍♂️': 'man mountain biking', + '🚵‍♀️': 'woman mountain biking', + '🤸': 'person cartwheeling', + '🤸‍♂️': 'man cartwheeling', + '🤸‍♀️': 'woman cartwheeling', + '🤼': 'people wrestling', + '🤼‍♂️': 'men wrestling', + '🤼‍♀️': 'women wrestling', + '🤽': 'person playing water polo', + '🤽‍♂️': 'man playing water polo', + '🤽‍♀️': 'woman playing water polo', + '🤾': 'person playing handball', + '🤾‍♂️': 'man playing handball', + '🤾‍♀️': 'woman playing handball', + '🤹': 'person juggling', + '🤹‍♂️': 'man juggling', + '🤹‍♀️': 'woman juggling', + '🧘': 'person in lotus position', + '🧘‍♂️': 'man in lotus position', + '🧘‍♀️': 'woman in lotus position', + '🛀': 'person taking bath', + '🛌': 'person in bed', + '🧑‍🤝‍🧑': 'people holding hands', + '👭': 'women holding hands', + '👫': 'woman and man holding hands', + '👬': 'men holding hands', + '💏': 'kiss', + '👩‍❤️‍💋‍👨': 'kiss: woman, man', + '👨‍❤️‍💋‍👨': 'kiss: man, man', + '👩‍❤️‍💋‍👩': 'kiss: woman, woman', + '💑': 'couple with heart', + '👩‍❤️‍👨': 'couple with heart: woman, man', + '👨‍❤️‍👨': 'couple with heart: man, man', + '👩‍❤️‍👩': 'couple with heart: woman, woman', + '👪': 'family', + '👨‍👩‍👦': 'family: man, woman, boy', + '👨‍👩‍👧': 'family: man, woman, girl', + '👨‍👩‍👧‍👦': 'family: man, woman, girl, boy', + '👨‍👩‍👦‍👦': 'family: man, woman, boy, boy', + '👨‍👩‍👧‍👧': 'family: man, woman, girl, girl', + '👨‍👨‍👦': 'family: man, man, boy', + '👨‍👨‍👧': 'family: man, man, girl', + '👨‍👨‍👧‍👦': 'family: man, man, girl, boy', + '👨‍👨‍👦‍👦': 'family: man, man, boy, boy', + '👨‍👨‍👧‍👧': 'family: man, man, girl, girl', + '👩‍👩‍👦': 'family: woman, woman, boy', + '👩‍👩‍👧': 'family: woman, woman, girl', + '👩‍👩‍👧‍👦': 'family: woman, woman, girl, boy', + '👩‍👩‍👦‍👦': 'family: woman, woman, boy, boy', + '👩‍👩‍👧‍👧': 'family: woman, woman, girl, girl', + '👨‍👦': 'family: man, boy', + '👨‍👦‍👦': 'family: man, boy, boy', + '👨‍👧': 'family: man, girl', + '👨‍👧‍👦': 'family: man, girl, boy', + '👨‍👧‍👧': 'family: man, girl, girl', + '👩‍👦': 'family: woman, boy', + '👩‍👦‍👦': 'family: woman, boy, boy', + '👩‍👧': 'family: woman, girl', + '👩‍👧‍👦': 'family: woman, girl, boy', + '👩‍👧‍👧': 'family: woman, girl, girl', + '🗣': 'speaking head', + '👤': 'bust in silhouette', + '👥': 'busts in silhouette', + '🫂': 'people hugging', + '👣': 'footprints', + '🦰': 'red hair', + '🦱': 'curly hair', + '🦳': 'white hair', + '🦲': 'bald', + '🐵': 'monkey face', + '🐒': 'monkey', + '🦍': 'gorilla', + '🦧': 'orangutan', + '🐶': 'dog face', + '🐕': 'dog', + '🦮': 'guide dog', + '🐕‍🦺': 'service dog', + '🐩': 'poodle', + '🐺': 'wolf', + '🦊': 'fox', + '🦝': 'raccoon', + '🐱': 'cat face', + '🐈': 'cat', + '🐈‍⬛': 'black cat', + '🦁': 'lion', + '🐯': 'tiger face', + '🐅': 'tiger', + '🐆': 'leopard', + '🐴': 'horse face', + '🐎': 'horse', + '🦄': 'unicorn', + '🦓': 'zebra', + '🦌': 'deer', + '🦬': 'bison', + '🐮': 'cow face', + '🐂': 'ox', + '🐃': 'water buffalo', + '🐄': 'cow', + '🐷': 'pig face', + '🐖': 'pig', + '🐗': 'boar', + '🐽': 'pig nose', + '🐏': 'ram', + '🐑': 'ewe', + '🐐': 'goat', + '🐪': 'camel', + '🐫': 'two-hump camel', + '🦙': 'llama', + '🦒': 'giraffe', + '🐘': 'elephant', + '🦣': 'mammoth', + '🦏': 'rhinoceros', + '🦛': 'hippopotamus', + '🐭': 'mouse face', + '🐁': 'mouse', + '🐀': 'rat', + '🐹': 'hamster', + '🐰': 'rabbit face', + '🐇': 'rabbit', + '🐿': 'chipmunk', + '🦫': 'beaver', + '🦔': 'hedgehog', + '🦇': 'bat', + '🐻': 'bear', + '🐻‍❄️': 'polar bear', + '🐨': 'koala', + '🐼': 'panda', + '🦥': 'sloth', + '🦦': 'otter', + '🦨': 'skunk', + '🦘': 'kangaroo', + '🦡': 'badger', + '🐾': 'paw prints', + '🦃': 'turkey', + '🐔': 'chicken', + '🐓': 'rooster', + '🐣': 'hatching chick', + '🐤': 'baby chick', + '🐥': 'front-facing baby chick', + '🐦': 'bird', + '🐧': 'penguin', + '🕊': 'dove', + '🦅': 'eagle', + '🦆': 'duck', + '🦢': 'swan', + '🦉': 'owl', + '🦤': 'dodo', + '🪶': 'feather', + '🦩': 'flamingo', + '🦚': 'peacock', + '🦜': 'parrot', + '🐸': 'frog', + '🐊': 'crocodile', + '🐢': 'turtle', + '🦎': 'lizard', + '🐍': 'snake', + '🐲': 'dragon face', + '🐉': 'dragon', + '🦕': 'sauropod', + '🦖': 'T-Rex', + '🐳': 'spouting whale', + '🐋': 'whale', + '🐬': 'dolphin', + '🦭': 'seal', + '🐟': 'fish', + '🐠': 'tropical fish', + '🐡': 'blowfish', + '🦈': 'shark', + '🐙': 'octopus', + '🐚': 'spiral shell', + '🪸': '⊛ coral', + '🐌': 'snail', + '🦋': 'butterfly', + '🐛': 'bug', + '🐜': 'ant', + '🐝': 'honeybee', + '🪲': 'beetle', + '🐞': 'lady beetle', + '🦗': 'cricket', + '🪳': 'cockroach', + '🕷': 'spider', + '🕸': 'spider web', + '🦂': 'scorpion', + '🦟': 'mosquito', + '🪰': 'fly', + '🪱': 'worm', + '🦠': 'microbe', + '💐': 'bouquet', + '🌸': 'cherry blossom', + '💮': 'white flower', + '🪷': '⊛ lotus', + '🏵': 'rosette', + '🌹': 'rose', + '🥀': 'wilted flower', + '🌺': 'hibiscus', + '🌻': 'sunflower', + '🌼': 'blossom', + '🌷': 'tulip', + '🌱': 'seedling', + '🪴': 'potted plant', + '🌲': 'evergreen tree', + '🌳': 'deciduous tree', + '🌴': 'palm tree', + '🌵': 'cactus', + '🌾': 'sheaf of rice', + '🌿': 'herb', + '☘': 'shamrock', + '🍀': 'four leaf clover', + '🍁': 'maple leaf', + '🍂': 'fallen leaf', + '🍃': 'leaf fluttering in wind', + '🪹': '⊛ empty nest', + '🪺': '⊛ nest with eggs', + '🍇': 'grapes', + '🍈': 'melon', + '🍉': 'watermelon', + '🍊': 'tangerine', + '🍋': 'lemon', + '🍌': 'banana', + '🍍': 'pineapple', + '🥭': 'mango', + '🍎': 'red apple', + '🍏': 'green apple', + '🍐': 'pear', + '🍑': 'peach', + '🍒': 'cherries', + '🍓': 'strawberry', + '🫐': 'blueberries', + '🥝': 'kiwi fruit', + '🍅': 'tomato', + '🫒': 'olive', + '🥥': 'coconut', + '🥑': 'avocado', + '🍆': 'eggplant', + '🥔': 'potato', + '🥕': 'carrot', + '🌽': 'ear of corn', + '🌶': 'hot pepper', + '🫑': 'bell pepper', + '🥒': 'cucumber', + '🥬': 'leafy green', + '🥦': 'broccoli', + '🧄': 'garlic', + '🧅': 'onion', + '🍄': 'mushroom', + '🥜': 'peanuts', + '🫘': '⊛ beans', + '🌰': 'chestnut', + '🍞': 'bread', + '🥐': 'croissant', + '🥖': 'baguette bread', + '🫓': 'flatbread', + '🥨': 'pretzel', + '🥯': 'bagel', + '🥞': 'pancakes', + '🧇': 'waffle', + '🧀': 'cheese wedge', + '🍖': 'meat on bone', + '🍗': 'poultry leg', + '🥩': 'cut of meat', + '🥓': 'bacon', + '🍔': 'hamburger', + '🍟': 'french fries', + '🍕': 'pizza', + '🌭': 'hot dog', + '🥪': 'sandwich', + '🌮': 'taco', + '🌯': 'burrito', + '🫔': 'tamale', + '🥙': 'stuffed flatbread', + '🧆': 'falafel', + '🥚': 'egg', + '🍳': 'cooking', + '🥘': 'shallow pan of food', + '🍲': 'pot of food', + '🫕': 'fondue', + '🥣': 'bowl with spoon', + '🥗': 'green salad', + '🍿': 'popcorn', + '🧈': 'butter', + '🧂': 'salt', + '🥫': 'canned food', + '🍱': 'bento box', + '🍘': 'rice cracker', + '🍙': 'rice ball', + '🍚': 'cooked rice', + '🍛': 'curry rice', + '🍜': 'steaming bowl', + '🍝': 'spaghetti', + '🍠': 'roasted sweet potato', + '🍢': 'oden', + '🍣': 'sushi', + '🍤': 'fried shrimp', + '🍥': 'fish cake with swirl', + '🥮': 'moon cake', + '🍡': 'dango', + '🥟': 'dumpling', + '🥠': 'fortune cookie', + '🥡': 'takeout box', + '🦀': 'crab', + '🦞': 'lobster', + '🦐': 'shrimp', + '🦑': 'squid', + '🦪': 'oyster', + '🍦': 'soft ice cream', + '🍧': 'shaved ice', + '🍨': 'ice cream', + '🍩': 'doughnut', + '🍪': 'cookie', + '🎂': 'birthday cake', + '🍰': 'shortcake', + '🧁': 'cupcake', + '🥧': 'pie', + '🍫': 'chocolate bar', + '🍬': 'candy', + '🍭': 'lollipop', + '🍮': 'custard', + '🍯': 'honey pot', + '🍼': 'baby bottle', + '🥛': 'glass of milk', + '☕': 'hot beverage', + '🫖': 'teapot', + '🍵': 'teacup without handle', + '🍶': 'sake', + '🍾': 'bottle with popping cork', + '🍷': 'wine glass', + '🍸': 'cocktail glass', + '🍹': 'tropical drink', + '🍺': 'beer mug', + '🍻': 'clinking beer mugs', + '🥂': 'clinking glasses', + '🥃': 'tumbler glass', + '🫗': '⊛ pouring liquid', + '🥤': 'cup with straw', + '🧋': 'bubble tea', + '🧃': 'beverage box', + '🧉': 'mate', + '🧊': 'ice', + '🥢': 'chopsticks', + '🍽': 'fork and knife with plate', + '🍴': 'fork and knife', + '🥄': 'spoon', + '🔪': 'kitchen knife', + '🫙': '⊛ jar', + '🏺': 'amphora', + '🌍': 'globe showing Europe-Africa', + '🌎': 'globe showing Americas', + '🌏': 'globe showing Asia-Australia', + '🌐': 'globe with meridians', + '🗺': 'world map', + '🗾': 'map of Japan', + '🧭': 'compass', + '🏔': 'snow-capped mountain', + '⛰': 'mountain', + '🌋': 'volcano', + '🗻': 'mount fuji', + '🏕': 'camping', + '🏖': 'beach with umbrella', + '🏜': 'desert', + '🏝': 'desert island', + '🏞': 'national park', + '🏟': 'stadium', + '🏛': 'classical building', + '🏗': 'building construction', + '🧱': 'brick', + '🪨': 'rock', + '🪵': 'wood', + '🛖': 'hut', + '🏘': 'houses', + '🏚': 'derelict house', + '🏠': 'house', + '🏡': 'house with garden', + '🏢': 'office building', + '🏣': 'Japanese post office', + '🏤': 'post office', + '🏥': 'hospital', + '🏦': 'bank', + '🏨': 'hotel', + '🏩': 'love hotel', + '🏪': 'convenience store', + '🏫': 'school', + '🏬': 'department store', + '🏭': 'factory', + '🏯': 'Japanese castle', + '🏰': 'castle', + '💒': 'wedding', + '🗼': 'Tokyo tower', + '🗽': 'Statue of Liberty', + '⛪': 'church', + '🕌': 'mosque', + '🛕': 'hindu temple', + '🕍': 'synagogue', + '⛩': 'shinto shrine', + '🕋': 'kaaba', + '⛲': 'fountain', + '⛺': 'tent', + '🌁': 'foggy', + '🌃': 'night with stars', + '🏙': 'cityscape', + '🌄': 'sunrise over mountains', + '🌅': 'sunrise', + '🌆': 'cityscape at dusk', + '🌇': 'sunset', + '🌉': 'bridge at night', + '♨': 'hot springs', + '🎠': 'carousel horse', + '🛝': '⊛ playground slide', + '🎡': 'ferris wheel', + '🎢': 'roller coaster', + '💈': 'barber pole', + '🎪': 'circus tent', + '🚂': 'locomotive', + '🚃': 'railway car', + '🚄': 'high-speed train', + '🚅': 'bullet train', + '🚆': 'train', + '🚇': 'metro', + '🚈': 'light rail', + '🚉': 'station', + '🚊': 'tram', + '🚝': 'monorail', + '🚞': 'mountain railway', + '🚋': 'tram car', + '🚌': 'bus', + '🚍': 'oncoming bus', + '🚎': 'trolleybus', + '🚐': 'minibus', + '🚑': 'ambulance', + '🚒': 'fire engine', + '🚓': 'police car', + '🚔': 'oncoming police car', + '🚕': 'taxi', + '🚖': 'oncoming taxi', + '🚗': 'automobile', + '🚘': 'oncoming automobile', + '🚙': 'sport utility vehicle', + '🛻': 'pickup truck', + '🚚': 'delivery truck', + '🚛': 'articulated lorry', + '🚜': 'tractor', + '🏎': 'racing car', + '🏍': 'motorcycle', + '🛵': 'motor scooter', + '🦽': 'manual wheelchair', + '🦼': 'motorized wheelchair', + '🛺': 'auto rickshaw', + '🚲': 'bicycle', + '🛴': 'kick scooter', + '🛹': 'skateboard', + '🛼': 'roller skate', + '🚏': 'bus stop', + '🛣': 'motorway', + '🛤': 'railway track', + '🛢': 'oil drum', + '⛽': 'fuel pump', + '🛞': '⊛ wheel', + '🚨': 'police car light', + '🚥': 'horizontal traffic light', + '🚦': 'vertical traffic light', + '🛑': 'stop sign', + '🚧': 'construction', + '⚓': 'anchor', + '🛟': '⊛ ring buoy', + '⛵': 'sailboat', + '🛶': 'canoe', + '🚤': 'speedboat', + '🛳': 'passenger ship', + '⛴': 'ferry', + '🛥': 'motor boat', + '🚢': 'ship', + '✈': 'airplane', + '🛩': 'small airplane', + '🛫': 'airplane departure', + '🛬': 'airplane arrival', + '🪂': 'parachute', + '💺': 'seat', + '🚁': 'helicopter', + '🚟': 'suspension railway', + '🚠': 'mountain cableway', + '🚡': 'aerial tramway', + '🛰': 'satellite', + '🚀': 'rocket', + '🛸': 'flying saucer', + '🛎': 'bellhop bell', + '🧳': 'luggage', + '⌛': 'hourglass done', + '⏳': 'hourglass not done', + '⌚': 'watch', + '⏰': 'alarm clock', + '⏱': 'stopwatch', + '⏲': 'timer clock', + '🕰': 'mantelpiece clock', + '🕛': 'twelve o’clock', + '🕧': 'twelve-thirty', + '🕐': 'one o’clock', + '🕜': 'one-thirty', + '🕑': 'two o’clock', + '🕝': 'two-thirty', + '🕒': 'three o’clock', + '🕞': 'three-thirty', + '🕓': 'four o’clock', + '🕟': 'four-thirty', + '🕔': 'five o’clock', + '🕠': 'five-thirty', + '🕕': 'six o’clock', + '🕡': 'six-thirty', + '🕖': 'seven o’clock', + '🕢': 'seven-thirty', + '🕗': 'eight o’clock', + '🕣': 'eight-thirty', + '🕘': 'nine o’clock', + '🕤': 'nine-thirty', + '🕙': 'ten o’clock', + '🕥': 'ten-thirty', + '🕚': 'eleven o’clock', + '🕦': 'eleven-thirty', + '🌑': 'new moon', + '🌒': 'waxing crescent moon', + '🌓': 'first quarter moon', + '🌔': 'waxing gibbous moon', + '🌕': 'full moon', + '🌖': 'waning gibbous moon', + '🌗': 'last quarter moon', + '🌘': 'waning crescent moon', + '🌙': 'crescent moon', + '🌚': 'new moon face', + '🌛': 'first quarter moon face', + '🌜': 'last quarter moon face', + '🌡': 'thermometer', + '☀': 'sun', + '🌝': 'full moon face', + '🌞': 'sun with face', + '🪐': 'ringed planet', + '⭐': 'star', + '🌟': 'glowing star', + '🌠': 'shooting star', + '🌌': 'milky way', + '☁': 'cloud', + '⛅': 'sun behind cloud', + '⛈': 'cloud with lightning and rain', + '🌤': 'sun behind small cloud', + '🌥': 'sun behind large cloud', + '🌦': 'sun behind rain cloud', + '🌧': 'cloud with rain', + '🌨': 'cloud with snow', + '🌩': 'cloud with lightning', + '🌪': 'tornado', + '🌫': 'fog', + '🌬': 'wind face', + '🌀': 'cyclone', + '🌈': 'rainbow', + '🌂': 'closed umbrella', + '☂': 'umbrella', + '☔': 'umbrella with rain drops', + '⛱': 'umbrella on ground', + '⚡': 'high voltage', + '❄': 'snowflake', + '☃': 'snowman', + '⛄': 'snowman without snow', + '☄': 'comet', + '🔥': 'fire', + '💧': 'droplet', + '🌊': 'water wave', + '🎃': 'jack-o-lantern', + '🎄': 'Christmas tree', + '🎆': 'fireworks', + '🎇': 'sparkler', + '🧨': 'firecracker', + '✨': 'sparkles', + '🎈': 'balloon', + '🎉': 'party popper', + '🎊': 'confetti ball', + '🎋': 'tanabata tree', + '🎍': 'pine decoration', + '🎎': 'Japanese dolls', + '🎏': 'carp streamer', + '🎐': 'wind chime', + '🎑': 'moon viewing ceremony', + '🧧': 'red envelope', + '🎀': 'ribbon', + '🎁': 'wrapped gift', + '🎗': 'reminder ribbon', + '🎟': 'admission tickets', + '🎫': 'ticket', + '🎖': 'military medal', + '🏆': 'trophy', + '🏅': 'sports medal', + '🥇': '1st place medal', + '🥈': '2nd place medal', + '🥉': '3rd place medal', + '⚽': 'soccer ball', + '⚾': 'baseball', + '🥎': 'softball', + '🏀': 'basketball', + '🏐': 'volleyball', + '🏈': 'american football', + '🏉': 'rugby football', + '🎾': 'tennis', + '🥏': 'flying disc', + '🎳': 'bowling', + '🏏': 'cricket game', + '🏑': 'field hockey', + '🏒': 'ice hockey', + '🥍': 'lacrosse', + '🏓': 'ping pong', + '🏸': 'badminton', + '🥊': 'boxing glove', + '🥋': 'martial arts uniform', + '🥅': 'goal net', + '⛳': 'flag in hole', + '⛸': 'ice skate', + '🎣': 'fishing pole', + '🤿': 'diving mask', + '🎽': 'running shirt', + '🎿': 'skis', + '🛷': 'sled', + '🥌': 'curling stone', + '🎯': 'bullseye', + '🪀': 'yo-yo', + '🪁': 'kite', + '🎱': 'pool 8 ball', + '🔮': 'crystal ball', + '🪄': 'magic wand', + '🧿': 'nazar amulet', + '🪬': '⊛ hamsa', + '🎮': 'video game', + '🕹': 'joystick', + '🎰': 'slot machine', + '🎲': 'game die', + '🧩': 'puzzle piece', + '🧸': 'teddy bear', + '🪅': 'piñata', + '🪩': '⊛ mirror ball', + '🪆': 'nesting dolls', + '♠': 'spade suit', + '♥': 'heart suit', + '♦': 'diamond suit', + '♣': 'club suit', + '♟': 'chess pawn', + '🃏': 'joker', + '🀄': 'mahjong red dragon', + '🎴': 'flower playing cards', + '🎭': 'performing arts', + '🖼': 'framed picture', + '🎨': 'artist palette', + '🧵': 'thread', + '🪡': 'sewing needle', + '🧶': 'yarn', + '🪢': 'knot', + '👓': 'glasses', + '🕶': 'sunglasses', + '🥽': 'goggles', + '🥼': 'lab coat', + '🦺': 'safety vest', + '👔': 'necktie', + '👕': 't-shirt', + '👖': 'jeans', + '🧣': 'scarf', + '🧤': 'gloves', + '🧥': 'coat', + '🧦': 'socks', + '👗': 'dress', + '👘': 'kimono', + '🥻': 'sari', + '🩱': 'one-piece swimsuit', + '🩲': 'briefs', + '🩳': 'shorts', + '👙': 'bikini', + '👚': 'woman’s clothes', + '👛': 'purse', + '👜': 'handbag', + '👝': 'clutch bag', + '🛍': 'shopping bags', + '🎒': 'backpack', + '🩴': 'thong sandal', + '👞': 'man’s shoe', + '👟': 'running shoe', + '🥾': 'hiking boot', + '🥿': 'flat shoe', + '👠': 'high-heeled shoe', + '👡': 'woman’s sandal', + '🩰': 'ballet shoes', + '👢': 'woman’s boot', + '👑': 'crown', + '👒': 'woman’s hat', + '🎩': 'top hat', + '🎓': 'graduation cap', + '🧢': 'billed cap', + '🪖': 'military helmet', + '⛑': 'rescue worker’s helmet', + '📿': 'prayer beads', + '💄': 'lipstick', + '💍': 'ring', + '💎': 'gem stone', + '🔇': 'muted speaker', + '🔈': 'speaker low volume', + '🔉': 'speaker medium volume', + '🔊': 'speaker high volume', + '📢': 'loudspeaker', + '📣': 'megaphone', + '📯': 'postal horn', + '🔔': 'bell', + '🔕': 'bell with slash', + '🎼': 'musical score', + '🎵': 'musical note', + '🎶': 'musical notes', + '🎙': 'studio microphone', + '🎚': 'level slider', + '🎛': 'control knobs', + '🎤': 'microphone', + '🎧': 'headphone', + '📻': 'radio', + '🎷': 'saxophone', + '🪗': 'accordion', + '🎸': 'guitar', + '🎹': 'musical keyboard', + '🎺': 'trumpet', + '🎻': 'violin', + '🪕': 'banjo', + '🥁': 'drum', + '🪘': 'long drum', + '📱': 'mobile phone', + '📲': 'mobile phone with arrow', + '☎': 'telephone', + '📞': 'telephone receiver', + '📟': 'pager', + '📠': 'fax machine', + '🔋': 'battery', + '🪫': '⊛ low battery', + '🔌': 'electric plug', + '💻': 'laptop', + '🖥': 'desktop computer', + '🖨': 'printer', + '⌨': 'keyboard', + '🖱': 'computer mouse', + '🖲': 'trackball', + '💽': 'computer disk', + '💾': 'floppy disk', + '💿': 'optical disk', + '📀': 'dvd', + '🧮': 'abacus', + '🎥': 'movie camera', + '🎞': 'film frames', + '📽': 'film projector', + '🎬': 'clapper board', + '📺': 'television', + '📷': 'camera', + '📸': 'camera with flash', + '📹': 'video camera', + '📼': 'videocassette', + '🔍': 'magnifying glass tilted left', + '🔎': 'magnifying glass tilted right', + '🕯': 'candle', + '💡': 'light bulb', + '🔦': 'flashlight', + '🏮': 'red paper lantern', + '🪔': 'diya lamp', + '📔': 'notebook with decorative cover', + '📕': 'closed book', + '📖': 'open book', + '📗': 'green book', + '📘': 'blue book', + '📙': 'orange book', + '📚': 'books', + '📓': 'notebook', + '📒': 'ledger', + '📃': 'page with curl', + '📜': 'scroll', + '📄': 'page facing up', + '📰': 'newspaper', + '🗞': 'rolled-up newspaper', + '📑': 'bookmark tabs', + '🔖': 'bookmark', + '🏷': 'label', + '💰': 'money bag', + '🪙': 'coin', + '💴': 'yen banknote', + '💵': 'dollar banknote', + '💶': 'euro banknote', + '💷': 'pound banknote', + '💸': 'money with wings', + '💳': 'credit card', + '🧾': 'receipt', + '💹': 'chart increasing with yen', + '✉': 'envelope', + '📧': 'e-mail', + '📨': 'incoming envelope', + '📩': 'envelope with arrow', + '📤': 'outbox tray', + '📥': 'inbox tray', + '📦': 'package', + '📫': 'closed mailbox with raised flag', + '📪': 'closed mailbox with lowered flag', + '📬': 'open mailbox with raised flag', + '📭': 'open mailbox with lowered flag', + '📮': 'postbox', + '🗳': 'ballot box with ballot', + '✏': 'pencil', + '✒': 'black nib', + '🖋': 'fountain pen', + '🖊': 'pen', + '🖌': 'paintbrush', + '🖍': 'crayon', + '📝': 'memo', + '💼': 'briefcase', + '📁': 'file folder', + '📂': 'open file folder', + '🗂': 'card index dividers', + '📅': 'calendar', + '📆': 'tear-off calendar', + '🗒': 'spiral notepad', + '🗓': 'spiral calendar', + '📇': 'card index', + '📈': 'chart increasing', + '📉': 'chart decreasing', + '📊': 'bar chart', + '📋': 'clipboard', + '📌': 'pushpin', + '📍': 'round pushpin', + '📎': 'paperclip', + '🖇': 'linked paperclips', + '📏': 'straight ruler', + '📐': 'triangular ruler', + '✂': 'scissors', + '🗃': 'card file box', + '🗄': 'file cabinet', + '🗑': 'wastebasket', + '🔒': 'locked', + '🔓': 'unlocked', + '🔏': 'locked with pen', + '🔐': 'locked with key', + '🔑': 'key', + '🗝': 'old key', + '🔨': 'hammer', + '🪓': 'axe', + '⛏': 'pick', + '⚒': 'hammer and pick', + '🛠': 'hammer and wrench', + '🗡': 'dagger', + '⚔': 'crossed swords', + '🔫': 'water pistol', + '🪃': 'boomerang', + '🏹': 'bow and arrow', + '🛡': 'shield', + '🪚': 'carpentry saw', + '🔧': 'wrench', + '🪛': 'screwdriver', + '🔩': 'nut and bolt', + '⚙': 'gear', + '🗜': 'clamp', + '⚖': 'balance scale', + '🦯': 'white cane', + '🔗': 'link', + '⛓': 'chains', + '🪝': 'hook', + '🧰': 'toolbox', + '🧲': 'magnet', + '🪜': 'ladder', + '⚗': 'alembic', + '🧪': 'test tube', + '🧫': 'petri dish', + '🧬': 'dna', + '🔬': 'microscope', + '🔭': 'telescope', + '📡': 'satellite antenna', + '💉': 'syringe', + '🩸': 'drop of blood', + '💊': 'pill', + '🩹': 'adhesive bandage', + '🩼': '⊛ crutch', + '🩺': 'stethoscope', + '🩻': '⊛ x-ray', + '🚪': 'door', + '🛗': 'elevator', + '🪞': 'mirror', + '🪟': 'window', + '🛏': 'bed', + '🛋': 'couch and lamp', + '🪑': 'chair', + '🚽': 'toilet', + '🪠': 'plunger', + '🚿': 'shower', + '🛁': 'bathtub', + '🪤': 'mouse trap', + '🪒': 'razor', + '🧴': 'lotion bottle', + '🧷': 'safety pin', + '🧹': 'broom', + '🧺': 'basket', + '🧻': 'roll of paper', + '🪣': 'bucket', + '🧼': 'soap', + '🫧': '⊛ bubbles', + '🪥': 'toothbrush', + '🧽': 'sponge', + '🧯': 'fire extinguisher', + '🛒': 'shopping cart', + '🚬': 'cigarette', + '⚰': 'coffin', + '🪦': 'headstone', + '⚱': 'funeral urn', + '🗿': 'moai', + '🪧': 'placard', + '🪪': '⊛ identification card', + '🏧': 'ATM sign', + '🚮': 'litter in bin sign', + '🚰': 'potable water', + '♿': 'wheelchair symbol', + '🚹': 'men’s room', + '🚺': 'women’s room', + '🚻': 'restroom', + '🚼': 'baby symbol', + '🚾': 'water closet', + '🛂': 'passport control', + '🛃': 'customs', + '🛄': 'baggage claim', + '🛅': 'left luggage', + '⚠': 'warning', + '🚸': 'children crossing', + '⛔': 'no entry', + '🚫': 'prohibited', + '🚳': 'no bicycles', + '🚭': 'no smoking', + '🚯': 'no littering', + '🚱': 'non-potable water', + '🚷': 'no pedestrians', + '📵': 'no mobile phones', + '🔞': 'no one under eighteen', + '☢': 'radioactive', + '☣': 'biohazard', + '⬆': 'up arrow', + '↗': 'up-right arrow', + '➡': 'right arrow', + '↘': 'down-right arrow', + '⬇': 'down arrow', + '↙': 'down-left arrow', + '⬅': 'left arrow', + '↖': 'up-left arrow', + '↕': 'up-down arrow', + '↔': 'left-right arrow', + '↩': 'right arrow curving left', + '↪': 'left arrow curving right', + '⤴': 'right arrow curving up', + '⤵': 'right arrow curving down', + '🔃': 'clockwise vertical arrows', + '🔄': 'counterclockwise arrows button', + '🔙': 'BACK arrow', + '🔚': 'END arrow', + '🔛': 'ON! arrow', + '🔜': 'SOON arrow', + '🔝': 'TOP arrow', + '🛐': 'place of worship', + '⚛': 'atom symbol', + '🕉': 'om', + '✡': 'star of David', + '☸': 'wheel of dharma', + '☯': 'yin yang', + '✝': 'latin cross', + '☦': 'orthodox cross', + '☪': 'star and crescent', + '☮': 'peace symbol', + '🕎': 'menorah', + '🔯': 'dotted six-pointed star', + '♈': 'Aries', + '♉': 'Taurus', + '♊': 'Gemini', + '♋': 'Cancer', + '♌': 'Leo', + '♍': 'Virgo', + '♎': 'Libra', + '♏': 'Scorpio', + '♐': 'Sagittarius', + '♑': 'Capricorn', + '♒': 'Aquarius', + '♓': 'Pisces', + '⛎': 'Ophiuchus', + '🔀': 'shuffle tracks button', + '🔁': 'repeat button', + '🔂': 'repeat single button', + '▶': 'play button', + '⏩': 'fast-forward button', + '⏭': 'next track button', + '⏯': 'play or pause button', + '◀': 'reverse button', + '⏪': 'fast reverse button', + '⏮': 'last track button', + '🔼': 'upwards button', + '⏫': 'fast up button', + '🔽': 'downwards button', + '⏬': 'fast down button', + '⏸': 'pause button', + '⏹': 'stop button', + '⏺': 'record button', + '⏏': 'eject button', + '🎦': 'cinema', + '🔅': 'dim button', + '🔆': 'bright button', + '📶': 'antenna bars', + '📳': 'vibration mode', + '📴': 'mobile phone off', + '♀': 'female sign', + '♂': 'male sign', + '⚧': 'transgender symbol', + '✖': 'multiply', + '➕': 'plus', + '➖': 'minus', + '➗': 'divide', + '🟰': '⊛ heavy equals sign', + '♾': 'infinity', + '‼': 'double exclamation mark', + '⁉': 'exclamation question mark', + '❓': 'red question mark', + '❔': 'white question mark', + '❕': 'white exclamation mark', + '❗': 'red exclamation mark', + '〰': 'wavy dash', + '💱': 'currency exchange', + '💲': 'heavy dollar sign', + '⚕': 'medical symbol', + '♻': 'recycling symbol', + '⚜': 'fleur-de-lis', + '🔱': 'trident emblem', + '📛': 'name badge', + '🔰': 'Japanese symbol for beginner', + '⭕': 'hollow red circle', + '✅': 'check mark button', + '☑': 'check box with check', + '✔': 'check mark', + '❌': 'cross mark', + '❎': 'cross mark button', + '➰': 'curly loop', + '➿': 'double curly loop', + '〽': 'part alternation mark', + '✳': 'eight-spoked asterisk', + '✴': 'eight-pointed star', + '❇': 'sparkle', + '©': 'copyright', + '®': 'registered', + '™': 'trade mark', + '#️⃣': 'keycap: #', + '*️⃣': 'keycap: *', + '0️⃣': 'keycap: 0', + '1️⃣': 'keycap: 1', + '2️⃣': 'keycap: 2', + '3️⃣': 'keycap: 3', + '4️⃣': 'keycap: 4', + '5️⃣': 'keycap: 5', + '6️⃣': 'keycap: 6', + '7️⃣': 'keycap: 7', + '8️⃣': 'keycap: 8', + '9️⃣': 'keycap: 9', + '🔟': 'keycap: 10', + '🔠': 'input latin uppercase', + '🔡': 'input latin lowercase', + '🔢': 'input numbers', + '🔣': 'input symbols', + '🔤': 'input latin letters', + '🅰': 'A button (blood type)', + '🆎': 'AB button (blood type)', + '🅱': 'B button (blood type)', + '🆑': 'CL button', + '🆒': 'COOL button', + '🆓': 'FREE button', + ℹ: 'information', + '🆔': 'ID button', + 'Ⓜ': 'circled M', + '🆕': 'NEW button', + '🆖': 'NG button', + '🅾': 'O button (blood type)', + '🆗': 'OK button', + '🅿': 'P button', + '🆘': 'SOS button', + '🆙': 'UP! button', + '🆚': 'VS button', + '🈁': 'Japanese “here” button', + '🈂': 'Japanese “service charge” button', + '🈷': 'Japanese “monthly amount” button', + '🈶': 'Japanese “not free of charge” button', + '🈯': 'Japanese “reserved” button', + '🉐': 'Japanese “bargain” button', + '🈹': 'Japanese “discount” button', + '🈚': 'Japanese “free of charge” button', + '🈲': 'Japanese “prohibited” button', + '🉑': 'Japanese “acceptable” button', + '🈸': 'Japanese “application” button', + '🈴': 'Japanese “passing grade” button', + '🈳': 'Japanese “vacancy” button', + '㊗': 'Japanese “congratulations” button', + '㊙': 'Japanese “secret” button', + '🈺': 'Japanese “open for business” button', + '🈵': 'Japanese “no vacancy” button', + '🔴': 'red circle', + '🟠': 'orange circle', + '🟡': 'yellow circle', + '🟢': 'green circle', + '🔵': 'blue circle', + '🟣': 'purple circle', + '🟤': 'brown circle', + '⚫': 'black circle', + '⚪': 'white circle', + '🟥': 'red square', + '🟧': 'orange square', + '🟨': 'yellow square', + '🟩': 'green square', + '🟦': 'blue square', + '🟪': 'purple square', + '🟫': 'brown square', + '⬛': 'black large square', + '⬜': 'white large square', + '◼': 'black medium square', + '◻': 'white medium square', + '◾': 'black medium-small square', + '◽': 'white medium-small square', + '▪': 'black small square', + '▫': 'white small square', + '🔶': 'large orange diamond', + '🔷': 'large blue diamond', + '🔸': 'small orange diamond', + '🔹': 'small blue diamond', + '🔺': 'red triangle pointed up', + '🔻': 'red triangle pointed down', + '💠': 'diamond with a dot', + '🔘': 'radio button', + '🔳': 'white square button', + '🔲': 'black square button', + '🏁': 'chequered flag', + '🚩': 'triangular flag', + '🎌': 'crossed flags', + '🏴': 'black flag', + '🏳': 'white flag', + '🏳️‍🌈': 'rainbow flag', + '🏳️‍⚧️': 'transgender flag', + '🏴‍☠️': 'pirate flag', + '🇦🇨': 'flag: Ascension Island', + '🇦🇩': 'flag: Andorra', + '🇦🇪': 'flag: United Arab Emirates', + '🇦🇫': 'flag: Afghanistan', + '🇦🇬': 'flag: Antigua & Barbuda', + '🇦🇮': 'flag: Anguilla', + '🇦🇱': 'flag: Albania', + '🇦🇲': 'flag: Armenia', + '🇦🇴': 'flag: Angola', + '🇦🇶': 'flag: Antarctica', + '🇦🇷': 'flag: Argentina', + '🇦🇸': 'flag: American Samoa', + '🇦🇹': 'flag: Austria', + '🇦🇺': 'flag: Australia', + '🇦🇼': 'flag: Aruba', + '🇦🇽': 'flag: Åland Islands', + '🇦🇿': 'flag: Azerbaijan', + '🇧🇦': 'flag: Bosnia & Herzegovina', + '🇧🇧': 'flag: Barbados', + '🇧🇩': 'flag: Bangladesh', + '🇧🇪': 'flag: Belgium', + '🇧🇫': 'flag: Burkina Faso', + '🇧🇬': 'flag: Bulgaria', + '🇧🇭': 'flag: Bahrain', + '🇧🇮': 'flag: Burundi', + '🇧🇯': 'flag: Benin', + '🇧🇱': 'flag: St. Barthélemy', + '🇧🇲': 'flag: Bermuda', + '🇧🇳': 'flag: Brunei', + '🇧🇴': 'flag: Bolivia', + '🇧🇶': 'flag: Caribbean Netherlands', + '🇧🇷': 'flag: Brazil', + '🇧🇸': 'flag: Bahamas', + '🇧🇹': 'flag: Bhutan', + '🇧🇻': 'flag: Bouvet Island', + '🇧🇼': 'flag: Botswana', + '🇧🇾': 'flag: Belarus', + '🇧🇿': 'flag: Belize', + '🇨🇦': 'flag: Canada', + '🇨🇨': 'flag: Cocos (Keeling) Islands', + '🇨🇩': 'flag: Congo - Kinshasa', + '🇨🇫': 'flag: Central African Republic', + '🇨🇬': 'flag: Congo - Brazzaville', + '🇨🇭': 'flag: Switzerland', + '🇨🇮': 'flag: Côte d’Ivoire', + '🇨🇰': 'flag: Cook Islands', + '🇨🇱': 'flag: Chile', + '🇨🇲': 'flag: Cameroon', + '🇨🇳': 'flag: China', + '🇨🇴': 'flag: Colombia', + '🇨🇵': 'flag: Clipperton Island', + '🇨🇷': 'flag: Costa Rica', + '🇨🇺': 'flag: Cuba', + '🇨🇻': 'flag: Cape Verde', + '🇨🇼': 'flag: Curaçao', + '🇨🇽': 'flag: Christmas Island', + '🇨🇾': 'flag: Cyprus', + '🇨🇿': 'flag: Czechia', + '🇩🇪': 'flag: Germany', + '🇩🇬': 'flag: Diego Garcia', + '🇩🇯': 'flag: Djibouti', + '🇩🇰': 'flag: Denmark', + '🇩🇲': 'flag: Dominica', + '🇩🇴': 'flag: Dominican Republic', + '🇩🇿': 'flag: Algeria', + '🇪🇦': 'flag: Ceuta & Melilla', + '🇪🇨': 'flag: Ecuador', + '🇪🇪': 'flag: Estonia', + '🇪🇬': 'flag: Egypt', + '🇪🇭': 'flag: Western Sahara', + '🇪🇷': 'flag: Eritrea', + '🇪🇸': 'flag: Spain', + '🇪🇹': 'flag: Ethiopia', + '🇪🇺': 'flag: European Union', + '🇫🇮': 'flag: Finland', + '🇫🇯': 'flag: Fiji', + '🇫🇰': 'flag: Falkland Islands', + '🇫🇲': 'flag: Micronesia', + '🇫🇴': 'flag: Faroe Islands', + '🇫🇷': 'flag: France', + '🇬🇦': 'flag: Gabon', + '🇬🇧': 'flag: United Kingdom', + '🇬🇩': 'flag: Grenada', + '🇬🇪': 'flag: Georgia', + '🇬🇫': 'flag: French Guiana', + '🇬🇬': 'flag: Guernsey', + '🇬🇭': 'flag: Ghana', + '🇬🇮': 'flag: Gibraltar', + '🇬🇱': 'flag: Greenland', + '🇬🇲': 'flag: Gambia', + '🇬🇳': 'flag: Guinea', + '🇬🇵': 'flag: Guadeloupe', + '🇬🇶': 'flag: Equatorial Guinea', + '🇬🇷': 'flag: Greece', + '🇬🇸': 'flag: South Georgia & South Sandwich Islands', + '🇬🇹': 'flag: Guatemala', + '🇬🇺': 'flag: Guam', + '🇬🇼': 'flag: Guinea-Bissau', + '🇬🇾': 'flag: Guyana', + '🇭🇰': 'flag: Hong Kong SAR China', + '🇭🇲': 'flag: Heard & McDonald Islands', + '🇭🇳': 'flag: Honduras', + '🇭🇷': 'flag: Croatia', + '🇭🇹': 'flag: Haiti', + '🇭🇺': 'flag: Hungary', + '🇮🇨': 'flag: Canary Islands', + '🇮🇩': 'flag: Indonesia', + '🇮🇪': 'flag: Ireland', + '🇮🇱': 'flag: Israel', + '🇮🇲': 'flag: Isle of Man', + '🇮🇳': 'flag: India', + '🇮🇴': 'flag: British Indian Ocean Territory', + '🇮🇶': 'flag: Iraq', + '🇮🇷': 'flag: Iran', + '🇮🇸': 'flag: Iceland', + '🇮🇹': 'flag: Italy', + '🇯🇪': 'flag: Jersey', + '🇯🇲': 'flag: Jamaica', + '🇯🇴': 'flag: Jordan', + '🇯🇵': 'flag: Japan', + '🇰🇪': 'flag: Kenya', + '🇰🇬': 'flag: Kyrgyzstan', + '🇰🇭': 'flag: Cambodia', + '🇰🇮': 'flag: Kiribati', + '🇰🇲': 'flag: Comoros', + '🇰🇳': 'flag: St. Kitts & Nevis', + '🇰🇵': 'flag: North Korea', + '🇰🇷': 'flag: South Korea', + '🇰🇼': 'flag: Kuwait', + '🇰🇾': 'flag: Cayman Islands', + '🇰🇿': 'flag: Kazakhstan', + '🇱🇦': 'flag: Laos', + '🇱🇧': 'flag: Lebanon', + '🇱🇨': 'flag: St. Lucia', + '🇱🇮': 'flag: Liechtenstein', + '🇱🇰': 'flag: Sri Lanka', + '🇱🇷': 'flag: Liberia', + '🇱🇸': 'flag: Lesotho', + '🇱🇹': 'flag: Lithuania', + '🇱🇺': 'flag: Luxembourg', + '🇱🇻': 'flag: Latvia', + '🇱🇾': 'flag: Libya', + '🇲🇦': 'flag: Morocco', + '🇲🇨': 'flag: Monaco', + '🇲🇩': 'flag: Moldova', + '🇲🇪': 'flag: Montenegro', + '🇲🇫': 'flag: St. Martin', + '🇲🇬': 'flag: Madagascar', + '🇲🇭': 'flag: Marshall Islands', + '🇲🇰': 'flag: North Macedonia', + '🇲🇱': 'flag: Mali', + '🇲🇲': 'flag: Myanmar (Burma)', + '🇲🇳': 'flag: Mongolia', + '🇲🇴': 'flag: Macao SAR China', + '🇲🇵': 'flag: Northern Mariana Islands', + '🇲🇶': 'flag: Martinique', + '🇲🇷': 'flag: Mauritania', + '🇲🇸': 'flag: Montserrat', + '🇲🇹': 'flag: Malta', + '🇲🇺': 'flag: Mauritius', + '🇲🇻': 'flag: Maldives', + '🇲🇼': 'flag: Malawi', + '🇲🇽': 'flag: Mexico', + '🇲🇾': 'flag: Malaysia', + '🇲🇿': 'flag: Mozambique', + '🇳🇦': 'flag: Namibia', + '🇳🇨': 'flag: New Caledonia', + '🇳🇪': 'flag: Niger', + '🇳🇫': 'flag: Norfolk Island', + '🇳🇬': 'flag: Nigeria', + '🇳🇮': 'flag: Nicaragua', + '🇳🇱': 'flag: Netherlands', + '🇳🇴': 'flag: Norway', + '🇳🇵': 'flag: Nepal', + '🇳🇷': 'flag: Nauru', + '🇳🇺': 'flag: Niue', + '🇳🇿': 'flag: New Zealand', + '🇴🇲': 'flag: Oman', + '🇵🇦': 'flag: Panama', + '🇵🇪': 'flag: Peru', + '🇵🇫': 'flag: French Polynesia', + '🇵🇬': 'flag: Papua New Guinea', + '🇵🇭': 'flag: Philippines', + '🇵🇰': 'flag: Pakistan', + '🇵🇱': 'flag: Poland', + '🇵🇲': 'flag: St. Pierre & Miquelon', + '🇵🇳': 'flag: Pitcairn Islands', + '🇵🇷': 'flag: Puerto Rico', + '🇵🇸': 'flag: Palestinian Territories', + '🇵🇹': 'flag: Portugal', + '🇵🇼': 'flag: Palau', + '🇵🇾': 'flag: Paraguay', + '🇶🇦': 'flag: Qatar', + '🇷🇪': 'flag: Réunion', + '🇷🇴': 'flag: Romania', + '🇷🇸': 'flag: Serbia', + '🇷🇺': 'flag: Russia', + '🇷🇼': 'flag: Rwanda', + '🇸🇦': 'flag: Saudi Arabia', + '🇸🇧': 'flag: Solomon Islands', + '🇸🇨': 'flag: Seychelles', + '🇸🇩': 'flag: Sudan', + '🇸🇪': 'flag: Sweden', + '🇸🇬': 'flag: Singapore', + '🇸🇭': 'flag: St. Helena', + '🇸🇮': 'flag: Slovenia', + '🇸🇯': 'flag: Svalbard & Jan Mayen', + '🇸🇰': 'flag: Slovakia', + '🇸🇱': 'flag: Sierra Leone', + '🇸🇲': 'flag: San Marino', + '🇸🇳': 'flag: Senegal', + '🇸🇴': 'flag: Somalia', + '🇸🇷': 'flag: Suriname', + '🇸🇸': 'flag: South Sudan', + '🇸🇹': 'flag: São Tomé & Príncipe', + '🇸🇻': 'flag: El Salvador', + '🇸🇽': 'flag: Sint Maarten', + '🇸🇾': 'flag: Syria', + '🇸🇿': 'flag: Eswatini', + '🇹🇦': 'flag: Tristan da Cunha', + '🇹🇨': 'flag: Turks & Caicos Islands', + '🇹🇩': 'flag: Chad', + '🇹🇫': 'flag: French Southern Territories', + '🇹🇬': 'flag: Togo', + '🇹🇭': 'flag: Thailand', + '🇹🇯': 'flag: Tajikistan', + '🇹🇰': 'flag: Tokelau', + '🇹🇱': 'flag: Timor-Leste', + '🇹🇲': 'flag: Turkmenistan', + '🇹🇳': 'flag: Tunisia', + '🇹🇴': 'flag: Tonga', + '🇹🇷': 'flag: Turkey', + '🇹🇹': 'flag: Trinidad & Tobago', + '🇹🇻': 'flag: Tuvalu', + '🇹🇼': 'flag: Taiwan', + '🇹🇿': 'flag: Tanzania', + '🇺🇦': 'flag: Ukraine', + '🇺🇬': 'flag: Uganda', + '🇺🇲': 'flag: U.S. Outlying Islands', + '🇺🇳': 'flag: United Nations', + '🇺🇸': 'flag: United States', + '🇺🇾': 'flag: Uruguay', + '🇺🇿': 'flag: Uzbekistan', + '🇻🇦': 'flag: Vatican City', + '🇻🇨': 'flag: St. Vincent & Grenadines', + '🇻🇪': 'flag: Venezuela', + '🇻🇬': 'flag: British Virgin Islands', + '🇻🇮': 'flag: U.S. Virgin Islands', + '🇻🇳': 'flag: Vietnam', + '🇻🇺': 'flag: Vanuatu', + '🇼🇫': 'flag: Wallis & Futuna', + '🇼🇸': 'flag: Samoa', + '🇽🇰': 'flag: Kosovo', + '🇾🇪': 'flag: Yemen', + '🇾🇹': 'flag: Mayotte', + '🇿🇦': 'flag: South Africa', + '🇿🇲': 'flag: Zambia', + '🇿🇼': 'flag: Zimbabwe', + '🏴󠁧󠁢󠁥󠁮󠁧󠁿': 'flag: England', + '🏴󠁧󠁢󠁳󠁣󠁴󠁿': 'flag: Scotland', + '🏴󠁧󠁢󠁷󠁬󠁳󠁿': 'flag: Wales', +}; +const isEmoji = (str) => { + const regex = getRegex(); + const emojiMatches = str.match(regex); + const emojiString = emojiMatches ? emojiMatches.join('') : ''; + return !/\d/.test(str) && emojiString === str; +}; +const parseEmoji = (style, str, size = 16) => { + switch (style) { + case 'twemoji': + return twemoji.parse(str, { + folder: 'svg', + ext: '.svg', + attributes: () => ({ + width: `${size}px`, + height: `${size}px`, + }), + }); + case 'native': + return str; + default: + return null; + } +}; +/** + * Gets the shortcode for a given emoji by the name of the emoji. This function replaces + * spaces with underscores and removes colons. + * @param key String to replace with shortcode. + * @returns String with shortcode, or `undefined` if no shortcode exists. + */ +const getShortcode = (key) => { + var _a; + // Removable of colons is necessary for the flag shortcodes. + return (_a = shortNames[key]) === null || _a === void 0 ? void 0 : _a.replace(/\s/g, '_').replace(/:/g, '').toLowerCase(); +}; +var emoji = { + shortNames, + isEmoji, + getShortcode, + parseEmoji, + getRegex, +}; + +// Default obsidian file icon. +const DEFAULT_FILE_ICON = ''; +// Default obsidian folder icon. +const DEFAULT_FOLDER_ICON = ''; +/** + * Tries to read the file synchronously. + * @param file File that will be read. + * @returns A promise that will resolve to a string which is the content of the file. + */ +const readFileSync = (file) => __awaiter(void 0, void 0, void 0, function* () { + const content = yield new Promise((resolve) => { + const reader = new FileReader(); + reader.readAsText(file, 'UTF-8'); + reader.onload = (readerEvent) => resolve(readerEvent.target.result); + }); + return content; +}); +/** + * Gets all the currently opened files by getting the markdown leaves and then checking + * for the `file` property in the view. This also returns the leaf of the file. + * @param plugin Instance of the IconizePlugin. + * @returns An array of {@link FileWithLeaf} objects. + */ +const getAllOpenedFiles = (plugin) => { + return plugin.app.workspace + .getLeavesOfType('markdown') + .reduce((prev, curr) => { + const file = curr.view.file; + if (file) { + prev.push(Object.assign(Object.assign({}, file), { leaf: curr, pinned: false })); + } + return prev; + }, []); +}; +/** + * Gets the file item title element by either accessing `titleEl` or `selfEl`. + * @param fileItem FileItem which will be used to retrieve the title element from. + * @returns HTMLElement which is the title element. + */ +const getFileItemTitleEl = (fileItem) => { + var _a; + return (_a = fileItem.titleEl) !== null && _a !== void 0 ? _a : fileItem.selfEl; +}; +/** + * Gets the file item inner title element by either accessing `titleInnerEl` or `innerEl`. + * @param fileItem FileItem which will be used to retrieve the inner title element from. + * @returns HTMLElement which is the inner title element. + */ +const getFileItemInnerTitleEl = (fileItem) => { + var _a; + return (_a = fileItem.titleInnerEl) !== null && _a !== void 0 ? _a : fileItem.innerEl; +}; +/** + * A utility function which will add the icon to the icon pack and then extract the icon + * to the icon pack. + * @param plugin IconizePlugin that will be used for extracting the icon. + * @param iconNameWithPrefix String that will be used to add the icon to the icon pack. + */ +const saveIconToIconPack = (plugin, iconNameWithPrefix) => { + const iconNextIdentifier = nextIdentifier(iconNameWithPrefix); + const iconName = iconNameWithPrefix.substring(iconNextIdentifier); + const iconPrefix = iconNameWithPrefix.substring(0, iconNextIdentifier); + const possibleIcon = getSvgFromLoadedIcon(iconPrefix, iconName); + if (!possibleIcon) { + throw new Error(`Icon ${iconNameWithPrefix} could not be found.`); + } + const iconPackName = getIconPackNameByPrefix(iconPrefix); + if (iconPackName === LUCIDE_ICON_PACK_NAME && + !plugin.doesUseCustomLucideIconPack()) { + return; + } + const icon = getIconFromIconPack(iconPackName, iconPrefix, iconName); + extractIconToIconPack(plugin, icon, possibleIcon); +}; +/** + * A utility function which will remove the icon from the icon pack by removing the icon + * file from the icon pack directory. + * @param plugin IconizePlugin that will be used for removing the icon. + * @param iconNameWithPrefix String that will be used to remove the icon from the icon pack. + */ +const removeIconFromIconPack = (plugin, iconNameWithPrefix) => { + const identifier = nextIdentifier(iconNameWithPrefix); + const prefix = iconNameWithPrefix.substring(0, identifier); + const iconName = iconNameWithPrefix.substring(identifier); + const iconPackName = getIconPackNameByPrefix(prefix); + const duplicatedIcon = plugin.getDataPathByValue(iconNameWithPrefix); + if (!duplicatedIcon) { + removeIconFromIconPackDirectory(plugin, iconPackName, iconName); + } +}; +/** + * A utility function which will convert a string to a hexadecimal color. + * @param str String that will be converted to a hexadecimal color. + * @returns A string which is the hexadecimal color. + */ +const stringToHex = (str) => { + const validHex = str.replace(/[^0-9a-fA-F]/g, ''); + const hex = validHex.padStart(6, '0').substring(0, 6); + return `#${hex}`; +}; +/** + * A utility function which will check if a string is a hexadecimal color. + * @param str String that will be checked if it is a hexadecimal color. + * @param includeHash Boolean which will include the hash in the check. + * @returns A boolean which is true if the string is a hexadecimal color. + */ +const isHexadecimal = (str, includeHash = false) => { + const regex = new RegExp(`^${includeHash ? '#' : ''}[0-9A-Fa-f]{1,6}$`); + return regex.test(str); +}; + +// This library file does not include any other dependency and is a standalone file that +// only include utility functions for setting styles for nodes or icons. The only +// dependency is the `svg` library. +/** + * Sets the margin for a specific node. + * @param el Node where the margin will be set. + * @param margin Margin that will be applied to the node. + * @returns The modified node with the applied margin. + */ +const setMargin = (el, margin) => { + el.style.margin = `${margin.top}px ${margin.right}px ${margin.bottom}px ${margin.left}px`; + return el; +}; +/** + * Applies all stylings to the specified svg icon string and applies styling to the node + * (container). The styling to the specified element is only modified when it is an emoji + * or extra margin is defined in the settings. + * @param plugin Instance of the IconizePlugin. + * @param iconString SVG that will be used to apply the svg styles to. + * @param el Node for manipulating the style. + * @returns Icon svg string with the manipulate style attributes. + */ +const applyAll = (plugin, iconString, container) => { + iconString = svg.setFontSize(iconString, plugin.getSettings().fontSize); + container.style.color = plugin.getSettings().iconColor; + iconString = svg.colorize(iconString, plugin.getSettings().iconColor); + // Sets the margin of an element. + const margin = plugin.getSettings().extraMargin; + const normalizedMargin = { + top: margin.top !== undefined ? margin.top : 4, + right: margin.right !== undefined ? margin.right : 4, + left: margin.left !== undefined ? margin.left : 4, + bottom: margin.bottom !== undefined ? margin.bottom : 4, + }; + if (plugin.getSettings().extraMargin) { + setMargin(container, normalizedMargin); + } + if (emoji.isEmoji(iconString)) { + container.style.fontSize = `${plugin.getSettings().fontSize}px`; + container.style.lineHeight = `${plugin.getSettings().fontSize}px`; + } + return iconString; +}; +/** + * Refreshes all the styles of all the applied icons where a `.iconize-icon` + * class is defined. This function only modifies the styling of the node. + * @param plugin Instance of the IconizePlugin. + * @param applyStyles Function that is getting called when the icon node is found and + * typically applies all the styles to the icon. + */ +const refreshIconNodes = (plugin, applyStyles = applyAll) => { + const fileExplorers = plugin.app.workspace.getLeavesOfType('file-explorer'); + for (const fileExplorer of fileExplorers) { + Object.keys(plugin.getData()).forEach((path) => { + const fileItem = fileExplorer.view.fileItems[path]; + if (fileItem) { + const titleEl = getFileItemTitleEl(fileItem); + const iconNode = titleEl.querySelector('.iconize-icon'); + if (iconNode) { + const pathValue = plugin.getData()[path]; + const hasIndividualColor = typeof pathValue === 'object' && pathValue.iconColor; + iconNode.innerHTML = applyStyles(plugin, iconNode.innerHTML, iconNode); + if (hasIndividualColor) { + iconNode.style.color = pathValue.iconColor; + const colorizedInnerHtml = svg.colorize(iconNode.innerHTML, pathValue.iconColor); + iconNode.innerHTML = colorizedInnerHtml; + } + } + } + }); + } +}; +var style = { + applyAll, + setMargin, + refreshIconNodes, +}; + +/** + * Removes the `iconize-icon` icon node from the provided HTMLElement. + * @param el HTMLElement from which the icon node will be removed. + */ +const removeIconInNode = (el) => { + const iconNode = el.querySelector('.iconize-icon'); + if (!iconNode) { + return; + } + iconNode.remove(); +}; +/** + * Removes the 'iconize-icon' icon node from the HTMLElement corresponding + * to the specified file path. + * @param path File path for which the icon node will be removed. + */ +const removeIconInPath = (path, options) => { + var _a; + const node = (_a = options === null || options === void 0 ? void 0 : options.container) !== null && _a !== void 0 ? _a : document.querySelector(`[data-path="${path}"]`); + if (!node) { + logger.warn(`Element with data path not found (path: ${path})`); + return; + } + removeIconInNode(node); +}; +/** + * Sets an icon or emoji for an HTMLElement based on the specified icon name and color. + * The function manipulates the specified node inline. + * @param plugin Instance of the IconizePlugin. + * @param iconName Name of the icon or emoji to add. + * @param node HTMLElement to which the icon or emoji will be added. + * @param options Options for adjusting settings while the icon is being set. + */ +const setIconForNode = (plugin, iconName, node, options) => { + var _a, _b; + options !== null && options !== void 0 ? options : (options = {}); + (_a = options.shouldApplyAllStyles) !== null && _a !== void 0 ? _a : (options.shouldApplyAllStyles = true); + // Gets the possible icon based on the icon name. + const iconNextIdentifier = nextIdentifier(iconName); + const possibleIcon = getSvgFromLoadedIcon(iconName.substring(0, iconNextIdentifier), iconName.substring(iconNextIdentifier)); + if (possibleIcon) { + // The icon is possibly not an emoji. + let iconContent = (options === null || options === void 0 ? void 0 : options.shouldApplyAllStyles) + ? style.applyAll(plugin, possibleIcon, node) + : possibleIcon; + if (options === null || options === void 0 ? void 0 : options.color) { + node.style.color = options.color; + iconContent = svg.colorize(iconContent, options.color); + } + node.innerHTML = iconContent; + } + else { + const parsedEmoji = (_b = emoji.parseEmoji(plugin.getSettings().emojiStyle, iconName)) !== null && _b !== void 0 ? _b : iconName; + node.innerHTML = (options === null || options === void 0 ? void 0 : options.shouldApplyAllStyles) + ? style.applyAll(plugin, parsedEmoji, node) + : parsedEmoji; + } + node.setAttribute('title', iconName); +}; +/** + * Creates an icon node for the specified path and inserts it to the DOM. + * @param plugin Instance of the IconizePlugin. + * @param path Path for which the icon node will be created. + * @param iconName Name of the icon or emoji to add. + * @param color Optional color of the icon to add. + */ +const createIconNode = (plugin, path, iconName, options) => { + var _a; + // Get the container from the provided options or try to find the node that has the + // path from the document itself. + const node = (_a = options === null || options === void 0 ? void 0 : options.container) !== null && _a !== void 0 ? _a : document.querySelector(`[data-path="${path}"]`); + if (!node) { + logger.warn(`Element with data path not found (path: ${path})`); + return; + } + // Get the folder or file title node. + let titleNode = node.querySelector('.nav-folder-title-content'); + if (!titleNode) { + titleNode = node.querySelector('.nav-file-title-content'); + if (!titleNode) { + logger.warn(`Element with title node not found (path: ${path})`); + return; + } + } + let iconNode = node.querySelector('.iconize-icon'); + // If the icon is already set in the path, we do not need to create a new div element. + if (iconNode) { + setIconForNode(plugin, iconName, iconNode, { color: options === null || options === void 0 ? void 0 : options.color }); + } + else { + // Creates a new icon node and inserts it to the DOM. + iconNode = document.createElement('div'); + iconNode.setAttribute(config.ICON_ATTRIBUTE_NAME, iconName); + iconNode.classList.add('iconize-icon'); + setIconForNode(plugin, iconName, iconNode, { color: options === null || options === void 0 ? void 0 : options.color }); + node.insertBefore(iconNode, titleNode); + } +}; +/** + * Checks if the element has an icon node by checking if the element has a child with the + * class `iconize-icon`. + * @param element HTMLElement which will be checked if it has an icon. + * @returns Boolean whether the element has an icon node or not. + */ +const doesElementHasIconNode = (element) => { + return element.querySelector('.iconize-icon') !== null; +}; +/** + * Gets the icon name of the element if it has an icon node. + * @param element HTMLElement parent which includes a node with the icon. + * @returns String with the icon name if the element has an icon, `undefined` otherwise. + */ +const getIconFromElement = (element) => { + const iconNode = element.querySelector('.iconize-icon'); + const existingIcon = iconNode === null || iconNode === void 0 ? void 0 : iconNode.getAttribute(config.ICON_ATTRIBUTE_NAME); + return existingIcon; +}; +const getIconNodeFromPath = (path) => { + var _a; + return (_a = document + .querySelector(`[data-path="${path}"]`)) === null || _a === void 0 ? void 0 : _a.querySelector('[data-icon]'); +}; +var dom = { + setIconForNode, + createIconNode, + doesElementHasIconNode, + getIconFromElement, + getIconNodeFromPath, + removeIconInNode, + removeIconInPath, +}; + +class IconsPickerModal extends obsidian.FuzzySuggestModal { + constructor(app, plugin, path) { + super(app); + this.renderIndex = 0; + this.plugin = plugin; + this.path = path; + this.limit = 150; + const pluginRecentltyUsedItems = [ + ...plugin.getSettings().recentlyUsedIcons, + ]; + this.recentlyUsedItems = new Set(pluginRecentltyUsedItems.reverse().filter((iconName) => { + return doesIconExists(iconName) || emoji.isEmoji(iconName); + })); + this.resultContainerEl.classList.add('iconize-modal'); + } + onOpen() { + super.onOpen(); + } + onClose() { + const { contentEl } = this; + contentEl.empty(); + } + getItemText(item) { + return `${item.name} (${item.prefix})`; + } + getItems() { + const iconKeys = []; + if (this.inputEl.value.length === 0) { + this.renderIndex = 0; + this.recentlyUsedItems.forEach((iconName) => { + if (emoji.isEmoji(iconName)) { + iconKeys.push({ + name: emoji.shortNames[iconName], + prefix: 'Emoji', + displayName: iconName, + iconPackName: null, + }); + return; + } + const nextLetter = nextIdentifier(iconName); + const iconPrefix = iconName.substring(0, nextLetter); + const iconPackName = getIconPackNameByPrefix(iconPrefix); + iconKeys.push({ + name: iconName.substring(nextLetter), + prefix: iconPrefix, + displayName: iconName, + iconPackName: iconPackName, + }); + }); + } + for (const icon of getAllLoadedIconNames()) { + iconKeys.push({ + name: icon.name, + prefix: icon.prefix, + displayName: icon.prefix + icon.name, + iconPackName: icon.iconPackName, + }); + } + Object.entries(emoji.shortNames).forEach(([unicode, shortName]) => { + iconKeys.push({ + name: shortName, + prefix: 'Emoji', + displayName: unicode, + iconPackName: null, + }); + iconKeys.push({ + name: unicode, + prefix: 'Emoji', + displayName: unicode, + iconPackName: null, + }); + }); + return iconKeys; + } + onChooseItem(item) { + var _a; + const iconNameWithPrefix = typeof item === 'object' ? item.displayName : item; + dom.createIconNode(this.plugin, this.path, iconNameWithPrefix); + (_a = this.onSelect) === null || _a === void 0 ? void 0 : _a.call(this, iconNameWithPrefix); + this.plugin.addFolderIcon(this.path, item); + // Extracts the icon file to the icon pack. + if (typeof item === 'object' && !emoji.isEmoji(iconNameWithPrefix)) { + saveIconToIconPack(this.plugin, iconNameWithPrefix); + } + this.plugin.notifyPlugins(); + } + renderSuggestion(item, el) { + super.renderSuggestion(item, el); + // if (getAllIconPacks().length === 0) { + // this.resultContainerEl.style.display = 'block'; + // this.resultContainerEl.innerHTML = '
You need to create an icon pack.
'; + // return; + // } + // Render subheadlines for modal. + if (this.recentlyUsedItems.size !== 0 && this.inputEl.value.length === 0) { + if (this.renderIndex === 0) { + const subheadline = this.resultContainerEl.createDiv(); + subheadline.classList.add('iconize-subheadline'); + subheadline.innerText = 'Recently used Icons:'; + this.resultContainerEl.prepend(subheadline); + } + else if (this.renderIndex === this.recentlyUsedItems.size - 1) { + const subheadline = this.resultContainerEl.createDiv(); + subheadline.classList.add('iconize-subheadline'); + subheadline.innerText = 'All Icons:'; + this.resultContainerEl.append(subheadline); + } + } + if (item.item.name !== 'default') { + if (item.item.prefix === 'Emoji') { + const displayName = emoji.parseEmoji(this.plugin.getSettings().emojiStyle, item.item.displayName); + if (!displayName) { + return; + } + el.innerHTML = `
${el.innerHTML}
${displayName}
`; + } + else { + el.innerHTML = `
${el.innerHTML}
${getSvgFromLoadedIcon(item.item.prefix, item.item.name)}
`; + } + } + this.renderIndex++; + } +} + +var IconInTitlePosition; +(function (IconInTitlePosition) { + IconInTitlePosition["Above"] = "above"; + IconInTitlePosition["Inline"] = "inline"; +})(IconInTitlePosition || (IconInTitlePosition = {})); +const DEFAULT_SETTINGS = { + migrated: 2, + iconPacksPath: '.obsidian/icons', + fontSize: 16, + emojiStyle: 'native', + iconColor: null, + recentlyUsedIcons: [], + recentlyUsedIconsSize: 5, + rules: [], + extraMargin: { + top: 0, + right: 4, + bottom: 0, + left: 0, + }, + iconInTabsEnabled: false, + iconInTitleEnabled: false, + iconInTitlePosition: IconInTitlePosition.Above, + iconInFrontmatterEnabled: false, + iconInFrontmatterFieldName: 'icon', + iconColorInFrontmatterFieldName: 'iconColor', + iconsBackgroundCheckEnabled: false, + iconsInNotesEnabled: true, + iconsInLinksEnabled: true, + iconIdentifier: ':', + lucideIconPackType: 'native', + debugMode: false, + useInternalPlugins: false, +}; + +function migrate$5(plugin) { + return __awaiter(this, void 0, void 0, function* () { + // Migration for new syncing mechanism. + if (plugin.getSettings().migrated === 1) { + new obsidian.Notice('Please delete your old icon packs and redownload your icon packs to use the new syncing mechanism.', 20000); + plugin.getSettings().migrated++; + } + }); +} + +function migrate$4(plugin) { + return __awaiter(this, void 0, void 0, function* () { + // Migration for new order functionality of custom rules. + if (plugin.getSettings().migrated === 2) { + // Sorting alphabetically was the default behavior before. + plugin + .getSettings() + .rules.sort((a, b) => a.rule.localeCompare(b.rule)) + .forEach((rule, i) => { + rule.order = i; + }); + plugin.getSettings().migrated++; + } + }); +} + +class IconCache { + constructor() { + this.cache = new Map(); + this.set = (path, result) => { + this.cache.set(path, result); + }; + this.invalidate = (path) => { + this.cache.delete(path); + }; + this.clear = () => { + this.cache.clear(); + }; + this.get = (path) => { + var _a; + return (_a = this.cache.get(path)) !== null && _a !== void 0 ? _a : null; + }; + this.doesRecordExist = (path) => { + return this.get(path) !== null; + }; + if (IconCache.instance) { + throw new Error('Error: Instantiation failed: Use `IconCache.getInstance()` instead of new.'); + } + IconCache.instance = this; + } +} +IconCache.instance = new IconCache(); +IconCache.getInstance = () => { + return IconCache.instance; +}; + +/** + * Checks if the file type is equal to the `for` property of the custom rule. + * @param rule CustomRule that will be checked. + * @param fileType CustomRuleFileType that will be checked. Can be either `file` or `folder`. + * @returns Boolean whether the custom rule `for` matches the file type or not. + */ +const doesMatchFileType = (rule, fileType) => { + return (rule.for === 'everything' || + (rule.for === 'files' && fileType === 'file') || + (rule.for === 'folders' && fileType === 'folder')); +}; +/** + * Determines whether a given file or folder matches a specified custom rule. + * @param plugin Plugin instance. + * @param rule CustomRule to check against the file or folder. + * @param filePath String to check against the custom rule. + * @returns Promise that resolves to `true` if the file matches the rule, `false` otherwise. + */ +const isApplicable = (plugin, rule, filePath) => __awaiter(void 0, void 0, void 0, function* () { + const metadata = yield plugin.app.vault.adapter.stat(filePath); + if (!metadata) { + return false; + } + const fileType = metadata.type; + const doesMatch = doesMatchFileType(rule, fileType); + if (!doesMatch) { + return false; + } + return doesMatchPath(rule, filePath); +}); +/** + * Removes the icon from the custom rule from all the files and folders, if applicable. + * @param plugin IconizePlugin instance. + * @param rule CustomRule where the icons will be removed based on this rule. + */ +const removeFromAllFiles = (plugin, rule) => __awaiter(void 0, void 0, void 0, function* () { + const nodesWithIcon = document.querySelectorAll(`[${config.ICON_ATTRIBUTE_NAME}="${rule.icon}"]`); + for (let i = 0; i < nodesWithIcon.length; i++) { + const node = nodesWithIcon[i]; + // Parent element is the node which contains the data path. + const parent = node.parentElement; + if (!parent) { + continue; + } + const dataPath = parent.getAttribute('data-path'); + if (!dataPath) { + continue; + } + const fileType = (yield plugin.app.vault.adapter.stat(dataPath)).type; + if (doesMatchPath(rule, dataPath) && doesMatchFileType(rule, fileType)) { + dom.removeIconInNode(parent); + IconCache.getInstance().invalidate(dataPath); + } + } +}); +/** + * Gets all the custom rules sorted by their order property in ascending order. + * @param plugin IconizePlugin instance. + * @returns CustomRule array sorted by their order property in ascending order. + */ +const getSortedRules = (plugin) => { + return plugin.getSettings().rules.sort((a, b) => a.order - b.order); +}; +/** + * Tries to add all specific custom rule icons to all registered files and directories. + * It does that by calling the {@link add} function. Custom rules should have the lowest + * priority and will get ignored if an icon already exists in the file or directory. + * @param plugin IconizePlugin instance. + * @param rule CustomRule that will be applied, if applicable, to all files and folders. + */ +const addToAllFiles = (plugin, rule) => __awaiter(void 0, void 0, void 0, function* () { + const fileItems = yield getFileItems(plugin, rule); + for (const fileItem of fileItems) { + yield add$2(plugin, rule, fileItem.file, getFileItemTitleEl(fileItem)); + } +}); +/** + * Tries to add the icon of the custom rule to a file or folder. This function also checks + * if the file type matches the `for` property of the custom rule. + * @param plugin IconizePlugin instance. + * @param rule CustomRule that will be used to check if the rule is applicable to the file + * or directory. + * @param file TAbstractFile that will be used to possibly create the icon for. + * @param container HTMLElement where the icon will be added if the custom rules matches. + * @returns A promise that resolves to `true` if the icon was added, `false` otherwise. + */ +const add$2 = (plugin, rule, file, container) => __awaiter(void 0, void 0, void 0, function* () { + if (container && dom.doesElementHasIconNode(container)) { + return false; + } + // Checks if the file or directory already has an icon. + const hasIcon = plugin.getIconNameFromPath(file.path); + if (hasIcon) { + return false; + } + const doesMatch = yield isApplicable(plugin, rule, file.path); + if (doesMatch) { + IconCache.getInstance().set(file.path, { + iconNameWithPrefix: rule.icon, + inCustomRule: true, + }); + dom.createIconNode(plugin, file.path, rule.icon, { + color: rule.color, + container, + }); + return true; + } + return false; +}); +/** + * Determines whether a given rule exists in a given path. + * @param rule Rule to check for. + * @param path Path to check in. + * @returns True if the rule exists in the path, false otherwise. + */ +const doesMatchPath = (rule, path) => { + const toMatch = rule.useFilePath ? path : path.split('/').pop(); + try { + // Rule is in some sort of regex. + const regex = new RegExp(rule.rule); + if (toMatch.match(regex)) { + return true; + } + } + catch (_a) { + // Rule is not in some sort of regex, check for basic string match. + return toMatch.includes(rule.rule); + } + return false; +}; +/** + * Gets all the file items that can be applied to the specific custom rule. + * @param plugin Instance of IconizePlugin. + * @param rule Custom rule that will be checked for. + * @returns A promise that resolves to an array of file items that match the custom rule. + */ +const getFileItems = (plugin, rule) => __awaiter(void 0, void 0, void 0, function* () { + const result = []; + for (const fileExplorer of plugin.getRegisteredFileExplorers()) { + const files = Object.values(fileExplorer.fileItems || {}); + for (const fileItem of files) { + if (yield isApplicable(plugin, rule, fileItem.file.path)) { + result.push(fileItem); + } + } + } + return result; +}); +var customRule = { + getFileItems, + doesMatchPath, + doesMatchFileType, + getSortedRules, + removeFromAllFiles, + add: add$2, + addToAllFiles, + isApplicable, +}; + +function migrate$3(plugin) { + return __awaiter(this, void 0, void 0, function* () { + // Migration for inheritance to custom rule. + if (plugin.getSettings().migrated === 3) { + let hasRemovedInheritance = false; + for (const [key, value] of Object.entries(plugin.getData())) { + if (key === 'settings' || typeof value !== 'object') { + continue; + } + const folderData = value; + const inheritanceIcon = folderData.inheritanceIcon; + if (!inheritanceIcon) { + continue; + } + const folderIconName = folderData.iconName; + // Clean up old data. + if (folderData.iconColor && folderIconName) { + delete folderData.inheritanceIcon; + } + else if (folderIconName) { + delete plugin.getData()[key]; + plugin.getData()[key] = folderIconName; + } + else if (!folderIconName) { + delete plugin.getData()[key]; + } + const folderPath = key + '\\/[\\w\\d\\s]+'; + const newRule = { + icon: inheritanceIcon, + rule: `${folderPath}\\.(?:\\w+\\.)*\\w+`, + for: 'files', + order: 0, + useFilePath: true, + }; + // Reorder existing custom rules so that the new inheritance custom rule + // is at the top. + plugin.getSettings().rules.map((rule) => { + rule.order++; + }); + plugin.getSettings().rules.unshift(newRule); + // Apply the custom rule. + yield customRule.addToAllFiles(plugin, newRule); + hasRemovedInheritance = true; + } + if (hasRemovedInheritance) { + new obsidian.Notice(`[${config.PLUGIN_NAME}] Inheritance has been removed and replaced with custom rules.`); + } + plugin.getSettings().migrated++; + } + }); +} + +function migrate$2(plugin) { + return __awaiter(this, void 0, void 0, function* () { + if (plugin.getSettings().migrated === 4) { + if (plugin.getSettings().emojiStyle === 'none') { + plugin.getSettings().emojiStyle = 'native'; + } + plugin.getSettings().migrated++; + } + }); +} + +function migrate$1(plugin) { + return __awaiter(this, void 0, void 0, function* () { + if (plugin.getSettings().migrated === 5) { + yield deleteIconPack(plugin, LUCIDE_ICON_PACK_NAME); + plugin.getSettings().migrated++; + } + }); +} + +const migrate = (plugin) => __awaiter(void 0, void 0, void 0, function* () { + // eslint-disable-next-line + // @ts-ignore - Required because an older version of the plugin saved the `migrated` + // property as a boolean instead of a number. + if (plugin.getSettings().migrated === true) { + plugin.getSettings().migrated = 1; + } + yield migrate$5(plugin); + yield migrate$4(plugin); + yield migrate$3(plugin); + yield migrate$2(plugin); + yield migrate$1(plugin); + yield plugin.saveIconFolderData(); +}); + +class IconFolderSetting { + constructor(plugin, containerEl) { + this.plugin = plugin; + this.containerEl = containerEl; + } +} + +/** + * Gets the tab leaves of a specific file path by looping through all opened files and + * checking if the file path matches. + * @param plugin IconizePlugin instance. + * @param path String of the file path to get the tab leaf of. + * @returns TabHeaderLeaf array that includes all tab leaves of the file path. + */ +const getTabLeavesOfFilePath = (plugin, path) => { + const openedFiles = getAllOpenedFiles(plugin); + const openedFile = openedFiles.filter((openedFile) => openedFile.path === path); + const leaves = openedFile.map((openedFile) => openedFile.leaf); + return leaves; +}; +/** + * Adds an icon to the tab and its container. This function respects the + * custom rules and individually icon set. + * @param plugin IconizePlugin instance. + * @param filePath String file path to add the icon to. + * @param iconContainer HTMLElement where the icon will be added to. + * @param options AddOptions for the add function which can optionally be used. + */ +const add$1 = (plugin, filePath, iconContainer, options) => __awaiter(void 0, void 0, void 0, function* () { + var _a; + const iconColor = (_a = options === null || options === void 0 ? void 0 : options.iconColor) !== null && _a !== void 0 ? _a : plugin.getSettings().iconColor; + const data = Object.entries(plugin.getData()); + // Removes the `display: none` from the obsidian styling. + iconContainer.style.display = 'flex'; + // Only add the icon name manually when it is defined in the options. + if (options === null || options === void 0 ? void 0 : options.iconName) { + dom.setIconForNode(plugin, options.iconName, iconContainer, { + color: iconColor, + }); + // TODO: Refactor to include option to `insertIconToNode` function. + iconContainer.style.margin = null; + return; + } + // Add icons to tabs if a custom rule is applicable. + for (const rule of customRule.getSortedRules(plugin)) { + const isApplicable = yield customRule.isApplicable(plugin, rule, filePath); + if (isApplicable) { + dom.setIconForNode(plugin, rule.icon, iconContainer, { + color: rule.color, + }); + // TODO: Refactor to include option to `insertIconToNode` function. + iconContainer.style.margin = null; + break; + } + } + // Add icons to tabs if there is an icon set. + const iconData = data.find(([dataPath]) => dataPath === filePath); + if (!iconData) { + return; + } + const value = iconData[1]; + if (typeof value !== 'string' && typeof value !== 'object') { + return; + } + let iconName; + if (typeof value === 'object') { + const v = value; + if (v.iconName === null) { + return; + } + iconName = v.iconName; + } + else { + iconName = value; + } + dom.setIconForNode(plugin, iconName, iconContainer, { + color: iconColor, + shouldApplyAllStyles: true, + }); + // TODO: Refactor to include option to `insertIconToNode` function. + iconContainer.style.margin = null; +}); +/** + * Updates the icon in the tab and container by setting calling the `setIconForNode` + * function and removing the margin from the icon container. + * @param plugin IconizePlugin instance. + * @param iconName String of the icon name to update to. + * @param iconContainer HTMLElement where the icon is located and will be updated. + */ +const update = (plugin, iconName, iconContainer) => { + dom.setIconForNode(plugin, iconName, iconContainer); + // TODO: Refactor to include option to `insertIconToNode` function. + iconContainer.style.margin = null; +}; +/** + * Removes the icon from the tab and container by setting the `display` style property + * to `none`. Optionally, the icon can be replaced with the default obsidian icon. + * @param iconContainer HTMLElement where the icon is located and will be removed from. + * @param options RemoveOptions for the remove function which can optionally be used. + */ +const remove$1 = (iconContainer, options) => { + if (!(options === null || options === void 0 ? void 0 : options.replaceWithDefaultIcon)) { + // Removes the display of the icon container to remove the icons from the tabs. + iconContainer.style.display = 'none'; + } + else { + iconContainer.innerHTML = DEFAULT_FILE_ICON; + } +}; +var iconTabs = { + add: add$1, + update, + remove: remove$1, + getTabLeavesOfFilePath, +}; + +const checkMissingIcons = (plugin, data) => __awaiter(void 0, void 0, void 0, function* () { + const missingIcons = new Set(); + const allIcons = new Map(); + const getMissingIcon = (iconNameWithPrefix) => __awaiter(void 0, void 0, void 0, function* () { + const iconNextIdentifier = nextIdentifier(iconNameWithPrefix); + const iconName = iconNameWithPrefix.substring(iconNextIdentifier); + const iconPrefix = iconNameWithPrefix.substring(0, iconNextIdentifier); + const iconPackName = getIconPackNameByPrefix(iconPrefix); + if (iconPackName === LUCIDE_ICON_PACK_NAME && + !plugin.doesUseCustomLucideIconPack()) { + return; + } + const icon = getIconFromIconPack(iconPackName, iconPrefix, iconName); + if (!icon) { + logger.error(`Icon file with name ${iconNameWithPrefix} could not be found`); + return null; + } + const doesIconFileExists = yield plugin.app.vault.adapter.exists(`${getPath()}/${iconPackName}/${iconName}.svg`); + if (!doesIconFileExists) { + const possibleIcon = getSvgFromLoadedIcon(iconPrefix, iconName); + if (!possibleIcon) { + logger.error(`Icon SVG with name ${iconNameWithPrefix} could not be found`); + return null; + } + yield extractIconToIconPack(plugin, icon, possibleIcon); + return icon; + } + return null; + }); + for (const rule of plugin.getSettings().rules) { + if (!emoji.isEmoji(rule.icon)) { + allIcons.set(rule.icon, true); + const icon = yield getMissingIcon(rule.icon); + if (icon) { + missingIcons.add(icon); + } + } + } + for (const [_, value] of data) { + // Check for missing icon names. + let iconNameWithPrefix = value; + if (typeof value === 'object') { + iconNameWithPrefix = value.iconName; + } + if (iconNameWithPrefix && !emoji.isEmoji(iconNameWithPrefix)) { + allIcons.set(iconNameWithPrefix, true); + const icon = yield getMissingIcon(iconNameWithPrefix); + if (icon) { + missingIcons.add(icon); + } + } + } + // Show notice that background check is running. + if (missingIcons.size !== 0) { + new obsidian.Notice(`[${config.PLUGIN_NAME}] Background Check: found missing icons. Adding missing icons...`, 10000); + } + // Iterates over all the missing icons with its path and adds the icon to the node. + for (const icon of missingIcons) { + const normalizedName = getNormalizedName(icon.prefix + icon.name); + const nodesWithIcon = document.querySelectorAll(`[${config.ICON_ATTRIBUTE_NAME}="${normalizedName}"]`); + nodesWithIcon.forEach((node) => { + dom.setIconForNode(plugin, normalizedName, node); + }); + } + // Show notice that background check was finished. + if (missingIcons.size !== 0) { + new obsidian.Notice(`[${config.PLUGIN_NAME}] Background Check: added missing icons`, 10000); + } + // Remove all icon files that can not be found in the data. + for (const iconPack of getAllIconPacks()) { + // Checks if the icon pack exists. + const doesIconPackExist = yield plugin.app.vault.adapter.exists(`${getPath()}/${iconPack.name}`); + if (!doesIconPackExist) { + continue; + } + const iconFiles = yield plugin.app.vault.adapter.list(`${getPath()}/${iconPack.name}`); + for (const iconFilePath of iconFiles.files) { + const iconNameWithExtension = iconFilePath.split('/').pop(); + // Removes the file extension. + const iconName = iconNameWithExtension === null || iconNameWithExtension === void 0 ? void 0 : iconNameWithExtension.substring(0, iconNameWithExtension.length - 4); + const iconNameWithPrefix = iconPack.prefix + iconName; + const doesIconExist = allIcons.get(iconNameWithPrefix); + if (!doesIconExist) { + const path = `${getPath()}/${iconPack.name}/${iconName}.svg`; + const doesPathExist = yield plugin.app.vault.adapter.exists(path); + if (doesPathExist) { + logger.info(`Removing icon with path '${path}' because it is not used anymore`); + // Removes the icon file. + yield plugin.app.vault.adapter.remove(`${getPath()}/${iconPack.name}/${iconName}.svg`); + } + } + } + } +}); +/** + * This function adds all the possible icons to the corresponding nodes. It + * adds the icons, that are defined in the data as a basic string to the nodes + * and the custom rule icons. + * @param plugin Instance of IconizePlugin. + * @param data Data that will be used to add all the icons to the nodes. + * @param registeredFileExplorers A WeakSet of file explorers that are being used as a + * cache for already handled file explorers. + * @param callback Callback is being called whenever the icons are added to one file + * explorer. + */ +const addAll = (plugin, data, registeredFileExplorers, callback) => { + const fileExplorers = plugin.app.workspace.getLeavesOfType('file-explorer'); + for (const fileExplorer of fileExplorers) { + if (registeredFileExplorers.has(fileExplorer.view)) { + continue; + } + registeredFileExplorers.add(fileExplorer.view); + const setIcons = () => { + var _a, _b; + // Adds icons to already open file tabs. + if (plugin.getSettings().iconInTabsEnabled) { + for (const leaf of plugin.app.workspace.getLeavesOfType('markdown')) { + const filePath = (_b = (_a = leaf.view.file) === null || _a === void 0 ? void 0 : _a.path) !== null && _b !== void 0 ? _b : leaf.view.getState().file; + if (typeof filePath === 'string') { + const tabHeaderLeaf = leaf; + const iconColor = plugin.getIconColor(filePath); + iconTabs.add(plugin, filePath, tabHeaderLeaf.tabHeaderInnerIconEl, { + iconColor, + }); + } + } + } + for (const [dataPath, value] of data) { + const fileItem = fileExplorer.view.fileItems[dataPath]; + if (fileItem) { + const titleEl = getFileItemTitleEl(fileItem); + const titleInnerEl = getFileItemInnerTitleEl(fileItem); + // Need to check this because refreshing the plugin will duplicate all the icons. + if (titleEl.children.length === 2 || titleEl.children.length === 1) { + const iconName = typeof value === 'string' ? value : value.iconName; + const iconColor = typeof value === 'string' ? undefined : value.iconColor; + if (iconName) { + // Removes a possible existing icon. + const existingIcon = titleEl.querySelector('.iconize-icon'); + if (existingIcon) { + existingIcon.remove(); + } + // Creates the new node with the icon inside. + const iconNode = titleEl.createDiv(); + iconNode.setAttribute(config.ICON_ATTRIBUTE_NAME, iconName); + iconNode.classList.add('iconize-icon'); + IconCache.getInstance().set(dataPath, { + iconNameWithPrefix: iconName, + }); + dom.setIconForNode(plugin, iconName, iconNode, { + color: iconColor, + }); + titleEl.insertBefore(iconNode, titleInnerEl); + } + } + } + } + // Callback function to register other events to this file explorer. + callback === null || callback === void 0 ? void 0 : callback(); + }; + if (obsidian.requireApiVersion('1.7.2')) { + // TODO: Remove loading deferred view to improve performance. + fileExplorer.loadIfDeferred().then(setIcons); + } + else { + setIcons(); + } + } + // Handles the custom rules. + for (const rule of customRule.getSortedRules(plugin)) { + customRule.addToAllFiles(plugin, rule); + } +}; +/** + * Gets the icon of a given path. This function returns the first occurrence of an icon. + * @param plugin Instance of the IconizePlugin. + * @param path Path to get the icon of. + * @returns The icon of the path if it exists, undefined otherwise. + */ +const getByPath = (plugin, path) => { + if (path === 'settings' || path === 'migrated') { + return undefined; + } + const value = plugin.getData()[path]; + if (typeof value === 'string') { + // If the value is a plain icon name, return it. + return value; + } + else if (typeof value === 'object') { + const v = value; + if (v.iconName !== null) { + return v.iconName; + } + } + // Tries to get the custom rule for the path and returns its icon if it exists. + const rule = customRule.getSortedRules(plugin).find((rule) => { + return customRule.doesMatchPath(rule, path); + }); + if (rule) { + return rule.icon; + } + return undefined; +}; +/** + * Gets all the icons with their paths as an object. + * @param plugin Instance of the IconizePlugin. + * @returns An object that consists of the path and the icon name for the data + * or custom rule. + */ +const getAllWithPath = (plugin) => { + const result = []; + Object.keys(plugin.getData()).forEach((path) => { + if (path === 'settings' || path === 'migrated') { + return; + } + const icon = getByPath(plugin, path); + if (icon && !emoji.isEmoji(icon)) { + result.push({ path, icon }); + } + }); + // Add all icons for the custom rules with the rule as the path. + for (const rule of plugin.getSettings().rules) { + if (!emoji.isEmoji(rule.icon)) { + result.push({ path: rule.rule, icon: rule.icon }); + } + } + return result; +}; +/** + * Returns the {@link Icon} for the given icon name. It is important, that the icon name + * contains the icon pack prefix. + * @param iconNameWithPrefix String that contains the icon pack prefix combined with the + * icon name. + * @returns Icon if it exists, `null` otherwise. + */ +const getIconByName = (iconNameWithPrefix) => { + const iconNextIdentifier = nextIdentifier(iconNameWithPrefix); + const iconName = iconNameWithPrefix.substring(iconNextIdentifier); + const iconPrefix = iconNameWithPrefix.substring(0, iconNextIdentifier); + const iconPackName = getIconPackNameByPrefix(iconPrefix); + const icon = getIconFromIconPack(iconPackName, iconPrefix, iconName); + if (!icon) { + return null; + } + return icon; +}; +/** + * Returns the {@link Icon} for the given path. + * @param plugin IconizePlugin instance. + * @param path String which is the path to get the icon of. + * @returns Icon or Emoji as string if it exists, `null` otherwise. + */ +const getIconByPath = (plugin, path) => { + const iconNameWithPrefix = getByPath(plugin, path); + if (!iconNameWithPrefix) { + return null; + } + if (emoji.isEmoji(iconNameWithPrefix)) { + return iconNameWithPrefix; + } + return getIconByName(iconNameWithPrefix); +}; +var icon = { + addAll, + getByPath, + getAllWithPath, + getIconByPath, + getIconByName, + checkMissingIcons, +}; + +class CustomIconPackSetting extends IconFolderSetting { + constructor(plugin, containerEl, refreshDisplay) { + super(plugin, containerEl); + this.refreshDisplay = refreshDisplay; + this.dragOverElement = document.createElement('div'); + this.dragOverElement.addClass('iconize-dragover-el'); + this.dragOverElement.style.display = 'hidden'; + this.dragOverElement.innerHTML = '

Drop to add icon.

'; + } + normalizeIconPackName(value) { + return value.toLowerCase().replace(/\s/g, '-'); + } + preventDefaults(event) { + event.preventDefault(); + event.stopPropagation(); + } + highlight(el) { + clearTimeout(this.closeTimer); + if (!this.dragTargetElement) { + el.appendChild(this.dragOverElement); + el.classList.add('iconize-dragover'); + this.dragTargetElement = el; + } + } + unhighlight(target, el) { + if (this.dragTargetElement && this.dragTargetElement !== target) { + this.dragTargetElement.removeChild(this.dragOverElement); + this.dragTargetElement.classList.remove('iconize-dragover'); + this.dragTargetElement = undefined; + } + clearTimeout(this.closeTimer); + this.closeTimer = setTimeout(() => { + if (this.dragTargetElement) { + el.removeChild(this.dragOverElement); + el.classList.remove('iconize-dragover'); + this.dragTargetElement = undefined; + } + }, 100); + } + display() { + new obsidian.Setting(this.containerEl) + .setName('Add custom icon pack') + .setDesc('Add a custom icon pack.') + .addText((text) => { + text.setPlaceholder('Your icon pack name'); + this.textComponent = text; + }) + .addButton((btn) => { + btn.setButtonText('Add icon pack'); + btn.onClick(() => __awaiter(this, void 0, void 0, function* () { + const name = this.textComponent.getValue(); + if (name.length === 0) { + return; + } + const normalizedName = this.normalizeIconPackName(this.textComponent.getValue()); + if (yield doesIconPackExist(this.plugin, normalizedName)) { + new obsidian.Notice('Icon pack already exists.'); + return; + } + yield createCustomIconPackDirectory(this.plugin, normalizedName); + this.textComponent.setValue(''); + this.refreshDisplay(); + new obsidian.Notice('Icon pack successfully created.'); + })); + }); + // Sorts lucide icon pack always to the top. + const iconPacks = [...getAllIconPacks()].sort((a, b) => { + if (a.name === LUCIDE_ICON_PACK_NAME) + return -1; + if (b.name === LUCIDE_ICON_PACK_NAME) + return 1; + return a.name.localeCompare(b.name); + }); + iconPacks.forEach((iconPack) => { + const isLucideIconPack = iconPack.name === LUCIDE_ICON_PACK_NAME; + const additionalLucideDescription = '(Native Pack has fewer icons but 100% Obsidian Sync support)'; + const iconPackSetting = new obsidian.Setting(this.containerEl) + .setName(`${iconPack.name} (${iconPack.prefix})`) + .setDesc(`Total icons: ${iconPack.icons.length}${isLucideIconPack ? ` ${additionalLucideDescription}` : ''}`); + // iconPackSetting.addButton((btn) => { + // btn.setIcon('broken-link'); + // btn.setTooltip('Try to fix icon pack'); + // btn.onClick(async () => { + // new Notice('Try to fix icon pack...'); + // getIconPack(iconPack.name).icons = []; + // const icons = await getFilesInDirectory(this.plugin, `${getPath()}/${iconPack.name}`); + // for (let i = 0; i < icons.length; i++) { + // const filePath = icons[i]; + // const fileName = filePath.split('/').pop(); + // const file = await this.plugin.app.vault.adapter.read(filePath); + // const iconContent = file + // .replace(/stroke="#fff"/g, 'stroke="currentColor"') + // .replace(/fill="#fff"/g, 'fill="currentColor"'); + // await this.plugin.app.vault.adapter.write(filePath, iconContent); + // await normalizeFileName(this.plugin, filePath); + // addIconToIconPack(iconPack.name, fileName, iconContent); + // } + // new Notice('...tried to fix icon pack'); + // // Refreshes the DOM. + // Object.entries(this.plugin.getData()).forEach(async ([k, v]) => { + // const doesPathExist = await this.plugin.app.vault.adapter.exists(k, true); + // if (doesPathExist && typeof v === 'string') { + // // dom.removeIconInPath(k); + // dom.createIconNode(this.plugin, k, v); + // } + // }); + // }); + // }); + if (isLucideIconPack) { + iconPackSetting.addDropdown((dropdown) => { + dropdown.addOptions({ + native: 'Native', + custom: 'Custom', + none: 'None', + }); + dropdown.setValue(this.plugin.getSettings().lucideIconPackType); + dropdown.onChange((value) => __awaiter(this, void 0, void 0, function* () { + dropdown.setDisabled(true); + new obsidian.Notice('Changing icon packs...'); + this.plugin.getSettings().lucideIconPackType = value; + yield this.plugin.saveIconFolderData(); + if (value === 'native' || value === 'none') { + yield removeCustomLucideIconPack(this.plugin); + addLucideIconsPack(this.plugin); + } + else { + yield addCustomLucideIconPack(this.plugin); + yield icon.checkMissingIcons(this.plugin, Object.entries(this.plugin.getData())); + } + dropdown.setDisabled(false); + new obsidian.Notice('Done. This change requires a restart of Obsidian'); + })); + }); + return; + } + iconPackSetting.addButton((btn) => { + btn.setIcon('plus'); + btn.setTooltip('Add an icon'); + btn.onClick(() => __awaiter(this, void 0, void 0, function* () { + const fileSelector = document.createElement('input'); + fileSelector.setAttribute('type', 'file'); + fileSelector.setAttribute('multiple', 'multiple'); + fileSelector.setAttribute('accept', '.svg'); + fileSelector.click(); + fileSelector.onchange = (e) => __awaiter(this, void 0, void 0, function* () { + const target = e.target; + for (let i = 0; i < target.files.length; i++) { + const file = target.files[i]; + const content = yield readFileSync(file); + yield createFile(this.plugin, iconPack.name, file.name, content); + addIconToIconPack(iconPack.name, file.name, content); + iconPackSetting.setDesc(`Total icons: ${iconPack.icons.length} (added: ${file.name})`); + } + new obsidian.Notice('Icons successfully added.'); + }); + })); + }); + iconPackSetting.addButton((btn) => { + btn.setIcon('trash'); + btn.setTooltip('Remove the icon pack'); + btn.onClick(() => __awaiter(this, void 0, void 0, function* () { + yield deleteIconPack(this.plugin, iconPack.name); + this.refreshDisplay(); + new obsidian.Notice('Icon pack successfully deleted.'); + })); + }); + ['dragenter', 'dragover', 'dragleave', 'drop'].forEach((event) => { + iconPackSetting.settingEl.addEventListener(event, this.preventDefaults, false); + }); + ['dragenter', 'dragover'].forEach((event) => { + iconPackSetting.settingEl.addEventListener(event, () => this.highlight(iconPackSetting.settingEl), false); + }); + ['dragleave', 'drop'].forEach((event) => { + iconPackSetting.settingEl.addEventListener(event, (event) => this.unhighlight(event.currentTarget, iconPackSetting.settingEl), false); + }); + iconPackSetting.settingEl.addEventListener('drop', (event) => __awaiter(this, void 0, void 0, function* () { + const files = event.dataTransfer.files; + let successful = false; + for (let i = 0; i < files.length; i++) { + const file = files[i]; + if (file.type !== 'image/svg+xml') { + new obsidian.Notice(`File ${file.name} is not a SVG file.`); + continue; + } + successful = true; + const content = yield readFileSync(file); + yield createFile(this.plugin, iconPack.name, file.name, content); + addIconToIconPack(iconPack.name, file.name, content); + iconPackSetting.setDesc(`Total icons: ${iconPack.icons.length} (added: ${file.name})`); + } + if (successful) { + new obsidian.Notice('Icons successfully added.'); + } + }), false); + }); + } +} + +class CustomIconRuleSetting extends IconFolderSetting { + constructor(plugin, containerEl, app, refreshDisplay) { + super(plugin, containerEl); + this.app = app; + this.refreshDisplay = refreshDisplay; + } + /** + * Updates all the open files based on the custom rule that was specified. + * @param rule Rule that will be used to update all the icons for all opened files. + * @param remove Whether to remove the icons that are applicable to the rule or not. + */ + updateIconTabs(rule_1, remove_1) { + return __awaiter(this, arguments, void 0, function* (rule, remove, cachedPaths = []) { + if (this.plugin.getSettings().iconInTabsEnabled) { + for (const openedFile of getAllOpenedFiles(this.plugin)) { + if (cachedPaths.includes(openedFile.path)) { + continue; + } + const applicable = yield customRule.isApplicable(this.plugin, rule, openedFile.path); + if (!applicable) { + continue; + } + const leaf = openedFile.leaf; + if (remove) { + iconTabs.remove(leaf.tabHeaderInnerIconEl, { + replaceWithDefaultIcon: true, + }); + } + else { + iconTabs.add(this.plugin, openedFile.path, leaf.tabHeaderInnerIconEl, { + iconName: rule.icon, + iconColor: rule.color, + }); + } + } + } + }); + } + createDescriptionEl(container, text) { + const description = container.createEl('p', { + text, + cls: 'setting-item-description', + }); + description.style.marginBottom = 'var(--size-2-2)'; + } + display() { + new obsidian.Setting(this.containerEl) + .setName('Add icon rule') + .setDesc('Will add the icon based on the defined rule (as a plain string or in regex format).') + .addText((text) => { + text.onChange((value) => { + this.chooseIconBtn.setDisabled(value.length === 0); + this.chooseIconBtn.buttonEl.style.cursor = + value.length === 0 ? 'not-allowed' : 'default'; + this.chooseIconBtn.buttonEl.style.opacity = + value.length === 0 ? '50%' : '100%'; + }); + text.setPlaceholder('regex or simple string'); + this.textComponent = text; + }) + .addButton((btn) => { + btn.setDisabled(true); + btn.setButtonText('Choose icon'); + btn.onClick(() => __awaiter(this, void 0, void 0, function* () { + if (this.textComponent.getValue().length === 0) { + return; + } + const modal = new IconsPickerModal(this.app, this.plugin, ''); + modal.onChooseItem = (item) => __awaiter(this, void 0, void 0, function* () { + const icon = getNormalizedName(typeof item === 'object' ? item.displayName : item); + const rule = { + rule: this.textComponent.getValue(), + icon, + for: 'everything', + order: this.plugin.getSettings().rules.length, + }; + this.plugin.getSettings().rules = [ + ...this.plugin.getSettings().rules, + rule, + ]; + yield this.plugin.saveIconFolderData(); + this.refreshDisplay(); + new obsidian.Notice('Icon rule added.'); + this.textComponent.setValue(''); + saveIconToIconPack(this.plugin, rule.icon); + yield customRule.addToAllFiles(this.plugin, rule); + this.updateIconTabs(rule, false); + }); + modal.open(); + })); + this.chooseIconBtn = btn; + }); + this.plugin.getSettings().rules.forEach((rule) => { + // Keeping track of the old rule so that we can get a reference to it for old values. + const oldRule = Object.assign({}, rule); + const settingRuleEl = new obsidian.Setting(this.containerEl) + .setName(rule.rule) + .setDesc(`Icon: ${rule.icon}`); + const currentOrder = rule.order; + /** + * Re-orders the custom rule based on the value that is passed in. + * @param valueForReorder Number that will be used to determine whether to swap the + * custom rule with the next rule or the previous rule. + */ + const orderCustomRules = (valueForReorder) => __awaiter(this, void 0, void 0, function* () { + const otherRule = this.plugin.getSettings().rules[currentOrder + valueForReorder]; + // Swap the current rule with the next rule. + otherRule.order = otherRule.order - valueForReorder; + rule.order = currentOrder + valueForReorder; + // Refreshes the DOM. + yield customRule.removeFromAllFiles(this.plugin, oldRule); + yield this.plugin.saveIconFolderData(); + const addedPaths = []; + for (const fileExplorer of this.plugin.getRegisteredFileExplorers()) { + const files = Object.values(fileExplorer.fileItems || {}); + for (const rule of customRule.getSortedRules(this.plugin)) { + // Removes the icon tabs from all opened files. + this.updateIconTabs(rule, true, addedPaths); + // Adds the icon tabs to all opened files. + this.updateIconTabs(rule, false, addedPaths); + for (const fileItem of files) { + if (addedPaths.includes(fileItem.file.path)) { + continue; + } + const added = yield customRule.add(this.plugin, rule, fileItem.file, getFileItemTitleEl(fileItem)); + if (added) { + addedPaths.push(fileItem.file.path); + } + } + } + } + this.refreshDisplay(); + }); + // Add the move down custom rule button to re-order the custom rule. + settingRuleEl.addExtraButton((btn) => { + const isFirstOrder = currentOrder === 0; + btn.setDisabled(isFirstOrder); + btn.extraSettingsEl.style.cursor = isFirstOrder + ? 'not-allowed' + : 'default'; + btn.extraSettingsEl.style.opacity = isFirstOrder ? '50%' : '100%'; + btn.setIcon('arrow-up'); + btn.setTooltip('Prioritize the custom rule'); + btn.onClick(() => __awaiter(this, void 0, void 0, function* () { + yield orderCustomRules(-1); + })); + }); + // Add the move up custom rule button to re-order the custom rule. + settingRuleEl.addExtraButton((btn) => { + const isLastOrder = currentOrder === this.plugin.getSettings().rules.length - 1; + btn.setDisabled(isLastOrder); + btn.extraSettingsEl.style.cursor = isLastOrder + ? 'not-allowed' + : 'default'; + btn.extraSettingsEl.style.opacity = isLastOrder ? '50%' : '100%'; + btn.setIcon('arrow-down'); + btn.setTooltip('Deprioritize the custom rule'); + btn.onClick(() => __awaiter(this, void 0, void 0, function* () { + yield orderCustomRules(1); + })); + }); + // Add the edit custom rule button. + settingRuleEl.addButton((btn) => { + btn.setIcon('pencil'); + btn.setTooltip('Edit the custom rule'); + btn.onClick(() => { + var _a, _b; + // Create modal and its children elements. + const modal = new obsidian.Modal(this.plugin.app); + modal.contentEl.style.display = 'block'; + modal.modalEl.classList.add('iconize-custom-modal'); + modal.titleEl.setText('Edit custom rule'); + // Create the input for the rule. + this.createDescriptionEl(modal.contentEl, 'Regex or simple string'); + const input = new obsidian.TextComponent(modal.contentEl); + input.setValue(rule.rule); + input.onChange((value) => __awaiter(this, void 0, void 0, function* () { + rule.rule = value; + })); + const useFilePathContainer = modal.contentEl.createDiv(); + useFilePathContainer.style.display = 'flex'; + useFilePathContainer.style.alignItems = 'center'; + useFilePathContainer.style.justifyContent = 'space-between'; + useFilePathContainer.style.marginTop = 'var(--size-4-5)'; + const useFilePathDescription = useFilePathContainer.createEl('p', { + text: 'Include folders and files that are part of the path.', + cls: 'setting-item-description', + }); + useFilePathDescription.style.margin = '0'; + useFilePathDescription.style.marginBottom = 'var(--size-2-2)'; + new obsidian.ToggleComponent(useFilePathContainer) + .setValue(rule.useFilePath === true) + .onChange((value) => { + rule.useFilePath = value; + }); + // Create the toggle for changing the rule type. + const ruleTypeContainer = modal.contentEl.createDiv(); + ruleTypeContainer.style.display = 'flex'; + ruleTypeContainer.style.alignItems = 'center'; + ruleTypeContainer.style.justifyContent = 'space-between'; + ruleTypeContainer.style.marginTop = 'var(--size-4-5)'; + const ruleTypeDescription = ruleTypeContainer.createEl('p', { + text: 'Where the custom rule gets applied to.', + cls: 'setting-item-description', + }); + ruleTypeDescription.style.margin = '0'; + ruleTypeDescription.style.marginBottom = 'var(--size-2-2)'; + const ruleTypeButton = new obsidian.ButtonComponent(ruleTypeContainer); + const setButtonContent = (isFor) => { + if (isFor === 'folders') { + ruleTypeButton.setIcon('folder'); + } + else if (isFor === 'files') { + ruleTypeButton.setIcon('document'); + } + else { + ruleTypeButton.setIcon('documents'); + } + ruleTypeButton.setTooltip(`Icon applicable to: ${isFor}`); + }; + setButtonContent((_a = rule.for) !== null && _a !== void 0 ? _a : 'everything'); + ruleTypeButton.onClick(() => __awaiter(this, void 0, void 0, function* () { + var _a; + const isFor = (_a = rule.for) !== null && _a !== void 0 ? _a : 'everything'; + this.updateIconTabs(rule, true); + yield customRule.removeFromAllFiles(this.plugin, Object.assign(Object.assign({}, rule), { for: isFor })); + if (isFor === 'folders') { + rule.for = 'everything'; + } + else if (isFor === 'files') { + rule.for = 'folders'; + } + else { + rule.for = 'files'; + } + setButtonContent(rule.for); + })); + // Create the change icon button with icon preview. + this.createDescriptionEl(modal.contentEl, 'Custom rule icon'); + const iconContainer = modal.contentEl.createDiv(); + iconContainer.style.display = 'flex'; + iconContainer.style.alignItems = 'center'; + iconContainer.style.justifyContent = 'space-between'; + const iconEl = iconContainer.createDiv(); + const iconPreviewEl = iconEl.createDiv(); + dom.setIconForNode(this.plugin, rule.icon, iconPreviewEl); + iconEl.style.display = 'flex'; + iconEl.style.alignItems = 'center'; + iconEl.style.justifyContent = 'space-between'; + iconEl.style.margin = null; + iconPreviewEl.innerHTML = svg.setFontSize(iconPreviewEl.innerHTML, 20); + const iconNameEl = iconEl.createEl('div', { + cls: 'setting-item-description', + }); + iconNameEl.style.paddingTop = '0'; + iconNameEl.style.marginLeft = 'var(--size-2-2)'; + iconNameEl.innerText = rule.icon; + const changeIconBtn = new obsidian.ButtonComponent(iconContainer); + changeIconBtn.setButtonText('Change icon'); + changeIconBtn.onClick(() => __awaiter(this, void 0, void 0, function* () { + const modal = new IconsPickerModal(this.app, this.plugin, rule.icon); + modal.onChooseItem = (item) => __awaiter(this, void 0, void 0, function* () { + const icon = typeof item === 'object' ? item.displayName : item; + rule.icon = icon; + dom.setIconForNode(this.plugin, rule.icon, iconPreviewEl); + iconPreviewEl.innerHTML = svg.setFontSize(iconPreviewEl.innerHTML, 20); + iconNameEl.innerText = getNormalizedName(rule.icon); + }); + modal.open(); + })); + // Create the color picker for the rule. + this.createDescriptionEl(modal.contentEl, 'Color of the icon'); + const colorContainer = modal.contentEl.createDiv(); + colorContainer.style.display = 'flex'; + colorContainer.style.alignItems = 'center'; + colorContainer.style.justifyContent = 'space-between'; + const colorPicker = new obsidian.ColorComponent(colorContainer) + .setValue((_b = rule.color) !== null && _b !== void 0 ? _b : '#000000') + .onChange((value) => { + rule.color = value; + }); + const defaultColorButton = new obsidian.ButtonComponent(colorContainer); + defaultColorButton.setTooltip('Set color to the default one'); + defaultColorButton.setButtonText('Default'); + defaultColorButton.onClick(() => { + colorPicker.setValue('#000000'); + rule.color = undefined; + }); + // Create the save button. + const button = new obsidian.ButtonComponent(modal.contentEl); + button.buttonEl.style.marginTop = 'var(--size-4-4)'; + button.buttonEl.style.float = 'right'; + button.setButtonText('Save Changes'); + button.onClick(() => __awaiter(this, void 0, void 0, function* () { + if (!emoji.isEmoji(oldRule.icon)) { + // Tries to remove the previously used icon from the icon pack. + removeIconFromIconPack(this.plugin, oldRule.icon); + } + if (!emoji.isEmoji(rule.icon)) { + // Tries to add the newly used icon to the icon pack. + saveIconToIconPack(this.plugin, rule.icon); + rule.icon = getNormalizedName(rule.icon); + } + this.refreshDisplay(); + new obsidian.Notice('Custom rule updated.'); + // Refresh the DOM. + yield customRule.removeFromAllFiles(this.plugin, oldRule); + this.updateIconTabs(rule, true); + this.plugin.getSettings().rules.forEach((rule) => __awaiter(this, void 0, void 0, function* () { + yield customRule.addToAllFiles(this.plugin, rule); + this.updateIconTabs(rule, false); + })); + yield this.plugin.saveIconFolderData(); + modal.close(); + })); + modal.open(); + }); + }); + // Add the delete custom rule button. + settingRuleEl.addButton((btn) => { + btn.setIcon('trash'); + btn.setTooltip('Remove the custom rule'); + btn.onClick(() => __awaiter(this, void 0, void 0, function* () { + const newRules = this.plugin + .getSettings() + .rules.filter((r) => rule.rule !== r.rule || + rule.color !== r.color || + rule.icon !== r.icon || + rule.for !== r.for); + this.plugin.getSettings().rules = newRules; + yield this.plugin.saveIconFolderData(); + this.refreshDisplay(); + new obsidian.Notice('Custom rule deleted.'); + yield customRule.removeFromAllFiles(this.plugin, rule); + removeIconFromIconPack(this.plugin, rule.icon); + this.updateIconTabs(rule, true); + const previousRules = this.plugin + .getSettings() + .rules.filter((r) => rule.for === r.for); + previousRules.forEach((previousRule) => __awaiter(this, void 0, void 0, function* () { + yield customRule.addToAllFiles(this.plugin, previousRule); + this.updateIconTabs(previousRule, false); + })); + })); + }); + }); + } +} + +const getTitleIcon = (leaf) => { + return leaf.querySelector(`.${config.TITLE_ICON_CLASS}`); +}; +const add = (plugin, inlineTitleEl, svgElement, options) => { + var _a; + if (!inlineTitleEl.parentElement) { + return; + } + if (options === null || options === void 0 ? void 0 : options.fontSize) { + svgElement = svg.setFontSize(svgElement, options.fontSize); + } + let titleIcon = getTitleIcon(inlineTitleEl.parentElement); + if (!titleIcon) { + titleIcon = document.createElement('div'); + } + const isInline = plugin.getSettings().iconInTitlePosition === IconInTitlePosition.Inline; + if (isInline) { + titleIcon.style.display = 'inline-block'; + titleIcon.style.removeProperty('margin-inline'); + titleIcon.style.removeProperty('width'); + } + else { + titleIcon.style.display = 'block'; + titleIcon.style.width = 'var(--line-width)'; + titleIcon.style.marginInline = '0'; + } + titleIcon.classList.add(config.TITLE_ICON_CLASS); + // Checks if the passed element is an emoji. + if (emoji.isEmoji(svgElement) && options.fontSize) { + svgElement = + (_a = emoji.parseEmoji(plugin.getSettings().emojiStyle, svgElement, options.fontSize)) !== null && _a !== void 0 ? _a : svgElement; + titleIcon.style.fontSize = `${options.fontSize}px`; + } + titleIcon.innerHTML = svgElement; + let wrapperElement = inlineTitleEl.parentElement; + // Checks the parent and selects the correct wrapper element. + // This should only happen in the beginning. + if (wrapperElement && + !wrapperElement.classList.contains(config.INLINE_TITLE_WRAPPER_CLASS)) { + wrapperElement = wrapperElement.querySelector(`.${config.INLINE_TITLE_WRAPPER_CLASS}`); + } + // Whenever there is no correct wrapper element, we create one. + if (!wrapperElement) { + wrapperElement = inlineTitleEl.parentElement.createDiv(); + wrapperElement.classList.add(config.INLINE_TITLE_WRAPPER_CLASS); + } + // Avoiding adding the same nodes together when changing the title. + if (wrapperElement !== inlineTitleEl.parentElement) { + inlineTitleEl.parentElement.prepend(wrapperElement); + } + if (isInline) { + wrapperElement.style.display = 'flex'; + wrapperElement.style.alignItems = 'flex-start'; + const inlineTitlePaddingTop = getComputedStyle(inlineTitleEl, null).getPropertyValue('padding-top'); + titleIcon.style.paddingTop = inlineTitlePaddingTop; + if (emoji.isEmoji(svgElement)) { + titleIcon.style.transform = 'translateY(-9%)'; + } + else { + titleIcon.style.transform = 'translateY(9%)'; + } + } + else { + wrapperElement.style.display = 'block'; + titleIcon.style.transform = 'translateY(9%)'; + } + wrapperElement.append(titleIcon); + wrapperElement.append(inlineTitleEl); +}; +const updateStyle = (inlineTitleEl, options) => { + if (!inlineTitleEl.parentElement) { + return; + } + const titleIcon = getTitleIcon(inlineTitleEl.parentElement); + if (!titleIcon) { + return; + } + if (options.fontSize) { + if (!emoji.isEmoji(titleIcon.innerHTML)) { + titleIcon.innerHTML = svg.setFontSize(titleIcon.innerHTML, options.fontSize); + } + else { + titleIcon.style.fontSize = `${options.fontSize}px`; + } + } +}; +/** + * Hides the title icon from the provided HTMLElement. + * @param contentEl HTMLElement to hide the title icon from. + */ +const hide = (inlineTitleEl) => { + if (!inlineTitleEl.parentElement) { + return; + } + const titleIconContainer = getTitleIcon(inlineTitleEl.parentElement); + if (!titleIconContainer) { + return; + } + titleIconContainer.style.display = 'none'; +}; +const remove = (inlineTitleEl) => { + if (!inlineTitleEl.parentElement) { + return; + } + const titleIconContainer = getTitleIcon(inlineTitleEl.parentElement); + if (!titleIconContainer) { + return; + } + titleIconContainer.remove(); +}; +var titleIcon = { + add, + updateStyle, + hide, + remove, +}; + +// Cache for font size +let cachedFontSize = null; +let fontSizeCacheTime = 0; +const calculateFontTextSize = () => { + var _a; + // get cached font size if available + const now = Date.now(); + if (cachedFontSize !== null && now - fontSizeCacheTime < 2000) { + return cachedFontSize; + } + let fontSize = parseFloat((_a = getComputedStyle(document.body).getPropertyValue('--font-text-size')) !== null && _a !== void 0 ? _a : '0'); + if (!fontSize) { + fontSize = parseFloat(getComputedStyle(document.documentElement).fontSize); + } + // set font size cache + cachedFontSize = fontSize; + fontSizeCacheTime = now; + return fontSize; +}; +const calculateInlineTitleSize = () => { + const fontSize = calculateFontTextSize(); + const inlineTitleSizeValue = getComputedStyle(document.body).getPropertyValue('--inline-title-size'); + const unit = inlineTitleSizeValue.replace(/[\d.]/g, ''); + let inlineTitleSize = parseFloat(inlineTitleSizeValue); + if (unit === 'px') { + inlineTitleSize /= 16; + } + return fontSize * inlineTitleSize; +}; +const isHeader = (value) => { + return /^h[1-6]$/.test(value); +}; +const getHTMLHeaderByToken = (header) => { + for (let i = 1; i <= 6; i++) { + if (header === `header-${i}`) { + return `h${i}`; + } + } + return null; +}; +const calculateHeaderSize = (header) => { + var _a; + const fontSize = calculateFontTextSize(); + const htmlHeader = (_a = getHTMLHeaderByToken(header)) !== null && _a !== void 0 ? _a : header; + const headerComputedStyle = getComputedStyle(document.body).getPropertyValue(`--${htmlHeader}-size`); + let headerSize = parseFloat(headerComputedStyle); + if (isPx(headerComputedStyle)) { + headerSize = pxToRem(headerSize, fontSize); + } + // If there is some `calc` operation going on, it has to be evaluated. + if (headerComputedStyle.includes('calc')) { + const temp = document.createElement('div'); + temp.style.setProperty('font-size', `var(--${htmlHeader}-size)`); + document.body.appendChild(temp); + const computedStyle = window.getComputedStyle(temp); + const computedValue = computedStyle.getPropertyValue('font-size'); + headerSize = parseFloat(computedValue); + if (isPx(computedValue)) { + headerSize = pxToRem(headerSize, fontSize); + } + document.body.removeChild(temp); + } + return fontSize * headerSize; +}; +const pxToRem = (px, baseSize = 16) => { + return px / baseSize; +}; +const isPx = (value) => { + return /^-?\d+(\.\d+)?px$/.test(value); +}; + +class EmojiStyleSetting extends IconFolderSetting { + display() { + const emojiStyle = new obsidian.Setting(this.containerEl) + .setName('Emoji style') + .setDesc('Change the style of your emojis.'); + emojiStyle.addDropdown((dropdown) => { + dropdown.addOption('native', 'Native'); + dropdown.addOption('twemoji', 'Twemoji'); + dropdown.setValue(this.plugin.getSettings().emojiStyle); + dropdown.onChange((value) => __awaiter(this, void 0, void 0, function* () { + this.plugin.getSettings().emojiStyle = value; + this.updateDOM(); + yield this.plugin.saveIconFolderData(); + })); + }); + } + updateDOM() { + for (const fileExplorer of this.plugin.getRegisteredFileExplorers()) { + const fileItems = Object.entries(fileExplorer.fileItems || {}); + for (const [path, _] of fileItems) { + let iconName = this.plugin.getData()[path]; + if (!iconName) { + continue; + } + const data = this.plugin.getData()[path]; + if (typeof data === 'object') { + const data = this.plugin.getData()[path]; + if (data.iconName) { + iconName = data.iconName; + } + } + if (emoji.isEmoji(iconName)) { + dom.createIconNode(this.plugin, path, iconName); + if (this.plugin.getSettings().iconInTabsEnabled) { + const tabLeaves = iconTabs.getTabLeavesOfFilePath(this.plugin, path); + for (const tabLeaf of tabLeaves) { + iconTabs.update(this.plugin, iconName, tabLeaf.tabHeaderInnerIconEl); + } + } + if (this.plugin.getSettings().iconInTitleEnabled) { + for (const openedFile of getAllOpenedFiles(this.plugin)) { + const activeView = openedFile.leaf.view; + if (activeView instanceof obsidian.MarkdownView && + openedFile.path === path) { + titleIcon.add(this.plugin, activeView.inlineTitleEl, iconName, { + fontSize: calculateInlineTitleSize(), + }); + } + } + } + } + } + } + for (const rule of customRule.getSortedRules(this.plugin)) { + customRule.addToAllFiles(this.plugin, rule); + } + } +} + +/** + * Helper function that refreshes the style of all the icons that are defined + * or in a custom rule involved. + * @param plugin Instance of the IconizePlugin. + */ +const refreshStyleOfIcons = (plugin) => __awaiter(void 0, void 0, void 0, function* () { + // Refreshes the icon style for all normally added icons. + style.refreshIconNodes(plugin); + // Refreshes the icon style for all custom icon rules, when the color of the rule is + // not defined. + for (const rule of customRule.getSortedRules(plugin)) { + const fileItems = yield customRule.getFileItems(plugin, rule); + for (const fileItem of fileItems) { + const titleEl = getFileItemTitleEl(fileItem); + const iconNode = titleEl.querySelector('.iconize-icon'); + let iconContent = iconNode.innerHTML; + iconContent = style.applyAll(plugin, iconContent, iconNode); + if (rule.color) { + iconContent = svg.colorize(iconContent, rule.color); + iconNode.style.color = rule.color; + } + iconNode.innerHTML = iconContent; + } + } +}); +var helper = { + refreshStyleOfIcons, +}; + +class ExtraMarginSetting extends IconFolderSetting { + display() { + var _a, _b; + const extraMarginSetting = new obsidian.Setting(this.containerEl) + .setName('Extra margin (in pixels)') + .setDesc('Change the margin of the icons.') + .setClass('iconize-setting'); + const extraMarginDropdown = new obsidian.DropdownComponent(extraMarginSetting.controlEl).addOptions({ + top: 'Top', + right: 'Right', + bottom: 'Bottom', + left: 'Left', + }); + const extraMarginSlider = new obsidian.SliderComponent(extraMarginSetting.controlEl) + .setLimits(-24, 24, 1) + .setDynamicTooltip() + .setValue((_b = (_a = this.plugin.getSettings().extraMargin) === null || _a === void 0 ? void 0 : _a.top) !== null && _b !== void 0 ? _b : 2) + .onChange((val) => __awaiter(this, void 0, void 0, function* () { + const dropdownValue = extraMarginDropdown.getValue(); + if (this.plugin.getSettings().extraMargin) { + this.plugin.getSettings().extraMargin[dropdownValue] = val; + } + else { + this.plugin.getSettings().extraMargin = { + [dropdownValue]: val, + }; + } + yield this.plugin.saveIconFolderData(); + helper.refreshStyleOfIcons(this.plugin); + })); + extraMarginDropdown.onChange((val) => { + var _a; + if (this.plugin.getSettings().extraMargin) { + extraMarginSlider.setValue((_a = this.plugin.getSettings().extraMargin[val]) !== null && _a !== void 0 ? _a : 2); + } + else { + extraMarginSlider.setValue(2); + } + }); + extraMarginSetting.components.push(extraMarginDropdown, extraMarginSlider); + } +} + +class ResetButtonComponent extends obsidian.ButtonComponent { + constructor(contentEl) { + super(contentEl); + this.contentEl = contentEl; + this.setTooltip('Restore default'); + this.setIcon('rotate-ccw'); + this.render(); + } + render() { + this.buttonEl.classList.add('clickable-icon'); + this.buttonEl.classList.add('extra-setting-button'); + } +} + +const DEFAULT_VALUE = DEFAULT_SETTINGS.iconColor; +class IconColorSetting extends IconFolderSetting { + display() { + var _a; + const setting = new obsidian.Setting(this.containerEl) + .setName('Icon color') + .setDesc('Change the color of the displayed icons.'); + new ResetButtonComponent(setting.controlEl).onClick(() => __awaiter(this, void 0, void 0, function* () { + colorPicker.setValue(DEFAULT_VALUE); + this.plugin.getSettings().iconColor = null; + // Custom saving to not save the color black in the data. + yield this.plugin.saveIconFolderData(); + helper.refreshStyleOfIcons(this.plugin); + })); + const colorPicker = new obsidian.ColorComponent(setting.controlEl) + .setValue((_a = this.plugin.getSettings().iconColor) !== null && _a !== void 0 ? _a : DEFAULT_VALUE) + .onChange((value) => __awaiter(this, void 0, void 0, function* () { + this.plugin.getSettings().iconColor = value; + yield this.plugin.saveIconFolderData(); + helper.refreshStyleOfIcons(this.plugin); + })); + } +} + +const values = { + min: 10, + max: 64, + default: DEFAULT_SETTINGS.fontSize, + step: 1, +}; +class IconFontSizeSetting extends IconFolderSetting { + display() { + const setting = new obsidian.Setting(this.containerEl) + .setName('Icon font size (in pixels)') + .setDesc('Change the font size of the displayed icons.'); + new ResetButtonComponent(setting.controlEl).onClick(() => { + this.slider.setValue(values.default); + }); + setting.addSlider((slider) => { + var _a; + this.slider = slider; + slider + .setLimits(values.min, values.max, values.step) + .setDynamicTooltip() + .setValue((_a = this.plugin.getSettings().fontSize) !== null && _a !== void 0 ? _a : DEFAULT_SETTINGS.fontSize) + .onChange((val) => __awaiter(this, void 0, void 0, function* () { + this.plugin.getSettings().fontSize = val; + yield this.plugin.saveIconFolderData(); + helper.refreshStyleOfIcons(this.plugin); + })); + }); + } +} + +class IconPacksPathSetting extends IconFolderSetting { + display() { + const iconPacksPathSetting = new obsidian.Setting(this.containerEl) + .setName('Icon packs folder path') + .setDesc('Change the default icon packs folder path.'); + iconPacksPathSetting.addText((text) => { + this.iconPacksSettingTextComp = text; + text.setValue(this.plugin.getSettings().iconPacksPath); + }); + iconPacksPathSetting.addButton((btn) => { + btn.setButtonText('Save'); + btn.onClick(() => __awaiter(this, void 0, void 0, function* () { + const newPath = this.iconPacksSettingTextComp.getValue(); + const oldPath = this.plugin.getSettings().iconPacksPath; + if (oldPath === this.iconPacksSettingTextComp.getValue()) { + return; + } + new obsidian.Notice('Saving in progress...'); + setPath(newPath); + yield createDefaultDirectory(this.plugin); + yield moveIconPackDirectories(this.plugin, oldPath, newPath); + this.plugin.getSettings().iconPacksPath = newPath; + yield this.plugin.saveIconFolderData(); + new obsidian.Notice('...saved successfully'); + })); + }); + } +} + +class IconPacksBackgroundChecker extends IconFolderSetting { + display() { + new obsidian.Setting(this.containerEl) + .setName('Icons background check') + .setDesc('Check in the background on every load of Obsidian, if icons are missing and it will try to add them to the specific icon pack.') + .addToggle((toggle) => { + toggle + .setValue(this.plugin.getSettings().iconsBackgroundCheckEnabled) + .onChange((enabled) => __awaiter(this, void 0, void 0, function* () { + this.plugin.getSettings().iconsBackgroundCheckEnabled = enabled; + yield this.plugin.saveIconFolderData(); + if (enabled) { + new obsidian.Notice('You need to reload Obsidian for this to take effect.', 10000); + } + })); + }); + } +} + +class IconPackBrowserModal extends obsidian.FuzzySuggestModal { + constructor(app, plugin) { + super(app); + this.plugin = plugin; + this.resultContainerEl.classList.add('iconize-browse-modal'); + this.inputEl.placeholder = 'Select to download icon pack'; + } + // eslint-disable-next-line + onAddedIconPack() { } + onOpen() { + super.onOpen(); + } + onClose() { + this.contentEl.empty(); + } + getItemText(item) { + const prefix = createIconPackPrefix(item.name); + return `${item.displayName} (${prefix})`; + } + getItems() { + const predefinedIconPacks = Object.values(iconPacks$1); + const allIconPacks = getAllIconPacks(); + return predefinedIconPacks.filter((iconPack) => allIconPacks.find((ip) => iconPack.name === ip.name) === undefined); + } + onChooseItem(item, _event) { + return __awaiter(this, void 0, void 0, function* () { + new obsidian.Notice(`Adding ${item.displayName}...`); + const arrayBuffer = yield downloadZipFile(item.downloadLink); + yield createZipFile(this.plugin, `${item.name}.zip`, arrayBuffer); + yield registerIconPack(item.name, arrayBuffer); + new obsidian.Notice(`...${item.displayName} added`); + this.onAddedIconPack(); + }); + } + renderSuggestion(item, el) { + super.renderSuggestion(item, el); + el.innerHTML = `
${el.innerHTML}
`; + } +} + +class PredefinedIconPacksSetting extends IconFolderSetting { + constructor(plugin, containerEl, app, refreshDisplay) { + super(plugin, containerEl); + this.app = app; + this.refreshDisplay = refreshDisplay; + } + display() { + new obsidian.Setting(this.containerEl) + .setName('Add predefined icon pack') + .setDesc('Add a predefined icon pack that is officially supported.') + .addButton((btn) => { + btn.setButtonText('Browse icon packs'); + btn.onClick(() => { + const modal = new IconPackBrowserModal(this.app, this.plugin); + modal.onAddedIconPack = () => { + this.refreshDisplay(); + }; + modal.open(); + }); + }); + } +} + +class RecentlyUsedIconsSetting extends IconFolderSetting { + display() { + new obsidian.Setting(this.containerEl) + .setName('Recently used icons limit') + .setDesc('Change the limit for the recently used icons displayed in the icon selection modal.') + .addSlider((slider) => { + var _a; + slider + .setLimits(1, 25, 1) + .setDynamicTooltip() + .setValue((_a = this.plugin.getSettings().recentlyUsedIconsSize) !== null && _a !== void 0 ? _a : DEFAULT_SETTINGS.recentlyUsedIconsSize) + .onChange((val) => __awaiter(this, void 0, void 0, function* () { + this.plugin.getSettings().recentlyUsedIconsSize = val; + yield this.plugin.checkRecentlyUsedIcons(); + yield this.plugin.saveIconFolderData(); + })); + }); + } +} + +class ToggleIconInTabs extends IconFolderSetting { + display() { + new obsidian.Setting(this.containerEl) + .setName('Toggle icon in tabs') + .setDesc('Toggles the visibility of an icon for a file in the tab bar.') + .addToggle((toggle) => { + toggle + .setValue(this.plugin.getSettings().iconInTabsEnabled) + .onChange((enabled) => __awaiter(this, void 0, void 0, function* () { + this.plugin.getSettings().iconInTabsEnabled = enabled; + yield this.plugin.saveIconFolderData(); + // Updates the already opened files. + this.plugin.app.workspace + .getLeavesOfType('markdown') + .forEach((leaf) => { + const file = leaf.view.file; + if (file) { + const tabHeaderLeaf = leaf; + if (enabled) { + // Adds the icons to already opened files. + iconTabs.add(this.plugin, file.path, tabHeaderLeaf.tabHeaderInnerIconEl); + } + else { + // Removes the icons from already opened files. + iconTabs.remove(tabHeaderLeaf.tabHeaderInnerIconEl); + } + } + }); + })); + }); + } +} + +class ToggleIconInTitle extends IconFolderSetting { + updateLeaves(options) { + this.plugin.app.workspace.getLeavesOfType('markdown').forEach((leaf) => { + const view = leaf.view; + if (view instanceof obsidian.MarkdownView) { + const foundIcon = icon.getIconByPath(this.plugin, view.file.path); + if (foundIcon && options.enabled) { + if (options.removeBeforeReAdd) { + // Remove the icon before re-adding it. This is needed to update the DOM because + // the icon node will be inserted in the beginning inline title node. + titleIcon.remove(view.contentEl); + } + const content = typeof foundIcon === 'string' ? foundIcon : foundIcon.svgElement; + titleIcon.add(this.plugin, view.inlineTitleEl, content, { + fontSize: calculateInlineTitleSize(), + }); + } + else { + titleIcon.remove(view.contentEl); + } + } + }); + } + display() { + new obsidian.Setting(this.containerEl) + .setName('Toggle icon in title') + .setDesc('Toggles the visibility of an icon above the title of a file.') + .addDropdown((dropdown) => { + this.dropdown = dropdown; + dropdown.setDisabled(!this.plugin.getSettings().iconInTitleEnabled); + dropdown.addOptions({ + above: 'Above title', + inline: 'Next to title', + }); + dropdown.setValue(this.plugin.getSettings().iconInTitlePosition); + dropdown.onChange((value) => __awaiter(this, void 0, void 0, function* () { + this.plugin.getSettings().iconInTitlePosition = + value; + yield this.plugin.saveIconFolderData(); + this.updateLeaves({ enabled: true, removeBeforeReAdd: true }); + })); + }) + .addToggle((toggle) => { + toggle + .setValue(this.plugin.getSettings().iconInTitleEnabled) + .onChange((enabled) => __awaiter(this, void 0, void 0, function* () { + if (this.dropdown) { + this.dropdown.setDisabled(!enabled); + } + this.plugin.getSettings().iconInTitleEnabled = enabled; + yield this.plugin.saveIconFolderData(); + this.updateLeaves({ enabled }); + })); + }); + } +} + +class FrontmatterOptions extends IconFolderSetting { + display() { + new obsidian.Setting(this.containerEl) + .setName('Use icon in frontmatter') + .setDesc('Toggles whether to set the icon based on the frontmatter property `icon`.') + .addToggle((toggle) => { + toggle + .setValue(this.plugin.getSettings().iconInFrontmatterEnabled) + .onChange((enabled) => __awaiter(this, void 0, void 0, function* () { + this.plugin.getSettings().iconInFrontmatterEnabled = enabled; + yield this.plugin.saveIconFolderData(); + })); + }); + new obsidian.Setting(this.containerEl) + .setName('Frontmatter icon field name') + .setDesc('Sets the name of the frontmatter field which contains the icon.') + .addText((text) => { + this.iconFieldNameTextComp = text; + text.setValue(this.plugin.getSettings().iconInFrontmatterFieldName); + }) + .addButton((button) => { + button.setButtonText('Save'); + button.onClick(() => __awaiter(this, void 0, void 0, function* () { + const newValue = this.iconFieldNameTextComp.getValue(); + const oldValue = this.plugin.getSettings().iconInFrontmatterFieldName; + if (newValue === oldValue) { + return; + } + this.plugin.getSettings().iconInFrontmatterFieldName = newValue; + yield this.plugin.saveIconFolderData(); + new obsidian.Notice('...saved successfully'); + })); + }); + new obsidian.Setting(this.containerEl) + .setName('Frontmatter icon color field name') + .setDesc('Sets the name of the frontmatter field which contains the icon color.') + .addText((text) => { + this.iconColorFieldNameTextComp = text; + text.setValue(this.plugin.getSettings().iconColorInFrontmatterFieldName); + }) + .addButton((button) => { + button.setButtonText('Save'); + button.onClick(() => __awaiter(this, void 0, void 0, function* () { + const newValue = this.iconColorFieldNameTextComp.getValue(); + const oldValue = this.plugin.getSettings().iconColorInFrontmatterFieldName; + if (newValue === oldValue) { + return; + } + this.plugin.getSettings().iconColorInFrontmatterFieldName = newValue; + yield this.plugin.saveIconFolderData(); + new obsidian.Notice('...saved successfully'); + })); + }); + new obsidian.Setting(this.containerEl) + .setName('Refresh icons from frontmatter') + .setDesc('Sets the icon and color for each note in the vault based on the frontmatter properties. WARNING: This will change any manually set icons to the one defined in the frontmatter. IF A NOTE HAS NO FRONTMATTER, THE CURRENT ICON WILL BE REMOVED. Please restart Obsidian after this completes to see the changes.') + .addButton((btn) => { + btn.setButtonText('Refresh').onClick(() => __awaiter(this, void 0, void 0, function* () { + var _a, _b; + if (!this.plugin.getSettings().iconInFrontmatterEnabled) { + new obsidian.Notice(`[${config.PLUGIN_NAME}] Please enable "Use icon in frontmatter".`); + return; + } + new obsidian.Notice(`[${config.PLUGIN_NAME}] Refreshing icons from frontmatter, please wait...`); + const files = this.plugin.app.vault.getMarkdownFiles(); + for (const file of files) { + const fileCache = this.plugin.app.metadataCache.getFileCache(file); + const frontmatterIconKey = this.plugin.getSettings().iconInFrontmatterFieldName; + const frontmatterIconColorKey = this.plugin.getSettings().iconColorInFrontmatterFieldName; + const iconName = (_a = fileCache.frontmatter) === null || _a === void 0 ? void 0 : _a[frontmatterIconKey]; + let iconColor = (_b = fileCache.frontmatter) === null || _b === void 0 ? void 0 : _b[frontmatterIconColorKey]; + if (!iconName) { + yield this.plugin.removeFolderIcon(file.path); + continue; + } + if (typeof iconName !== 'string') { + const message = `${file.path}\nFrontmatter property type \`${frontmatterIconKey}\` has to be of type \`text\`.`; + logger.warn(message); + new obsidian.Notice(`[${config.PLUGIN_NAME}]\n${message}`); + continue; + } + this.plugin.addFolderIcon(file.path, iconName); + if (!iconColor) { + yield this.plugin.removeIconColor(file.path); + continue; + } + if (typeof iconColor !== 'string') { + const message = `${file.path}\nFrontmatter property type \`${frontmatterIconColorKey}\` has to be of type \`text\`.`; + logger.warn(message); + new obsidian.Notice(`[${config.PLUGIN_NAME}]\n${message}`); + continue; + } + iconColor = isHexadecimal(iconColor) + ? stringToHex(iconColor) + : iconColor; + this.plugin.addIconColor(file.path, iconColor); + } + new obsidian.Notice(`[${config.PLUGIN_NAME}] Refreshed icons from frontmatter. Please restart Obsidian to see the changes.`); + })); + }); + } +} + +class ToggleIconsInEditor extends IconFolderSetting { + display() { + new obsidian.Setting(this.containerEl) + .setName('Toggle icons while editing notes') + .setDesc('Toggles whether you are able to add and see icons in your notes and editor (e.g., ability to have :LiSofa: as an icon in your notes).') + .addToggle((toggle) => { + toggle + .setValue(this.plugin.getSettings().iconsInNotesEnabled) + .onChange((enabled) => __awaiter(this, void 0, void 0, function* () { + this.plugin.getSettings().iconsInNotesEnabled = enabled; + yield this.plugin.saveIconFolderData(); + new obsidian.Notice(`[${config.PLUGIN_NAME}] Obsidian has to be restarted for this change to take effect.`); + })); + }); + } +} + +class ToggleIconsInLinks extends IconFolderSetting { + display() { + new obsidian.Setting(this.containerEl) + .setName('Toggle icons in links') + .setDesc('Toggles whether you are able to see icons in the links to other notes') + .addToggle((toggle) => { + toggle + .setValue(this.plugin.getSettings().iconsInLinksEnabled) + .onChange((enabled) => __awaiter(this, void 0, void 0, function* () { + this.plugin.getSettings().iconsInLinksEnabled = enabled; + yield this.plugin.saveIconFolderData(); + new obsidian.Notice(`[${config.PLUGIN_NAME}] Obsidian has to be restarted for this change to take effect.`); + })); + }); + } +} + +class IconIdentifierSetting extends IconFolderSetting { + display() { + const setting = new obsidian.Setting(this.containerEl) + .setName('Icon identifier') + .setDesc('Change the icon identifier used in notes.') + .setClass('iconize-setting'); + setting.addText((text) => { + this.textComp = text; + text.setValue(this.plugin.getSettings().iconIdentifier); + }); + setting.addButton((btn) => { + btn.setButtonText('Save'); + btn.onClick(() => __awaiter(this, void 0, void 0, function* () { + const newIdentifier = this.textComp.getValue(); + const oldIdentifier = this.plugin.getSettings().iconIdentifier; + if (newIdentifier === oldIdentifier) { + return; + } + this.plugin.getSettings().iconIdentifier = newIdentifier; + yield this.plugin.saveIconFolderData(); + new obsidian.Notice('...saved successfully'); + })); + }); + } +} + +class DebugMode extends IconFolderSetting { + display() { + new obsidian.Setting(this.containerEl) + .setName('Toggle Debug Mode') + .setDesc('Toggle debug mode to see more detailed logs in the console. Do not touch this unless you know what you are doing.') + .addToggle((toggle) => { + toggle + .setValue(this.plugin.getSettings().debugMode) + .onChange((enabled) => __awaiter(this, void 0, void 0, function* () { + this.plugin.getSettings().debugMode = enabled; + yield this.plugin.saveIconFolderData(); + })); + }); + } +} + +class UseInternalPlugins extends IconFolderSetting { + display() { + new obsidian.Setting(this.containerEl) + .setName('EXPERIMENTAL: Use internal plugins') + .setDesc('Toggles whether to try to add icons to the bookmark and outline internal plugins.') + .addToggle((toggle) => { + toggle + .setValue(this.plugin.getSettings().useInternalPlugins) + .onChange((enabled) => __awaiter(this, void 0, void 0, function* () { + this.plugin.getSettings().useInternalPlugins = enabled; + yield this.plugin.saveIconFolderData(); + new obsidian.Notice(`[${config.PLUGIN_NAME}] Obsidian has to be restarted for this change to take effect.`); + })); + }); + } +} + +class IconFolderSettings extends obsidian.PluginSettingTab { + constructor(app, plugin) { + super(app, plugin); + this.plugin = plugin; + } + display() { + const { plugin, containerEl, app } = this; + containerEl.empty(); + containerEl.createEl('h1', { text: 'General' }); + new RecentlyUsedIconsSetting(plugin, containerEl).display(); + new IconPacksPathSetting(plugin, containerEl).display(); + new IconPacksBackgroundChecker(plugin, containerEl).display(); + new EmojiStyleSetting(plugin, containerEl).display(); + new IconIdentifierSetting(plugin, containerEl).display(); + new UseInternalPlugins(plugin, containerEl).display(); + new DebugMode(plugin, containerEl).display(); + containerEl.createEl('h3', { text: 'Visibility of icons' }); + new ToggleIconInTabs(plugin, containerEl).display(); + new ToggleIconInTitle(plugin, containerEl).display(); + new FrontmatterOptions(plugin, containerEl).display(); + new ToggleIconsInEditor(plugin, containerEl).display(); + new ToggleIconsInLinks(plugin, containerEl).display(); + containerEl.createEl('h1', { + text: 'Icon customization for files/folders', + }); + new IconFontSizeSetting(plugin, containerEl).display(); + new IconColorSetting(plugin, containerEl).display(); + new ExtraMarginSetting(plugin, containerEl).display(); + containerEl.createEl('h1', { text: 'Custom icon rules' }); + new CustomIconRuleSetting(plugin, containerEl, app, () => this.display()).display(); + containerEl.createEl('h1', { text: 'Icon packs' }); + new PredefinedIconPacksSetting(plugin, containerEl, app, () => this.display()).display(); + new CustomIconPackSetting(plugin, containerEl, () => this.display()).display(); + } +} + +function around(obj, factories) { + const removers = Object.keys(factories).map(key => around1(obj, key, factories[key])); + return removers.length === 1 ? removers[0] : function () { removers.forEach(r => r()); }; +} +function around1(obj, method, createWrapper) { + const original = obj[method], hadOwn = obj.hasOwnProperty(method); + let current = createWrapper(original); + // Let our wrapper inherit static props from the wrapping method, + // and the wrapping method, props from the original method + if (original) + Object.setPrototypeOf(current, original); + Object.setPrototypeOf(wrapper, current); + obj[method] = wrapper; + // Return a callback to allow safe removal + return remove; + function wrapper(...args) { + // If we have been deactivated and are no longer wrapped, remove ourselves + if (current === original && obj[method] === wrapper) + remove(); + return current.apply(this, args); + } + function remove() { + // If no other patches, just do a direct removal + if (obj[method] === wrapper) { + if (hadOwn) + obj[method] = original; + else + delete obj[method]; + } + if (current === original) + return; + // Else pass future calls through, and remove wrapper from the prototype chain + current = original; + Object.setPrototypeOf(wrapper, original || Function); + } +} + +class InternalPluginInjector { + constructor(plugin) { + this.plugin = plugin; + } + get fileExplorers() { + return this.plugin.app.workspace.getLeavesOfType('file-explorer'); + } + onMount() { } +} + +/** + * @deprecated After obsidian 1.2.6 in favor of the bookmarks plugin. + */ +class StarredInternalPlugin extends InternalPluginInjector { + constructor(plugin) { + super(plugin); + } + get starred() { + return this.plugin.app.internalPlugins.getPluginById('starred'); + } + get enabled() { + return this.plugin.app.internalPlugins.getPluginById('starred').enabled; + } + get leaf() { + const leaf = this.plugin.app.workspace.getLeavesOfType('starred'); + if (!leaf) { + return undefined; + } + if (leaf.length === 1) { + return leaf[0].view; + } + return undefined; + } + setIcon(filePath, node) { + const iconName = icon.getByPath(this.plugin, filePath); + const iconNode = node.querySelector('.nav-file-icon'); + if (!iconNode || !iconName) { + return; + } + dom.setIconForNode(this.plugin, iconName, iconNode); + } + computeNodesWithPath(callback) { + const { itemLookup, containerEl } = this.leaf; + const navFileEls = containerEl.querySelectorAll('.nav-file'); + navFileEls.forEach((navFileEl) => { + const lookupFile = itemLookup.get(navFileEl); + if (!lookupFile) { + return; + } + callback(navFileEl, lookupFile.path); + }); + } + onMount() { + const nodesWithPath = {}; + this.computeNodesWithPath((node, filePath) => { + nodesWithPath[filePath] = node; + }); + Object.entries(nodesWithPath).forEach(([filePath, node]) => this.setIcon(filePath, node)); + } + register() { + if (!this.plugin.app.internalPlugins.getPluginById('file-explorer').enabled) { + console.info(`[${config.PLUGIN_NAME}/Starred] Skipping starred internal plugin registration because file-explorer is not enabled.`); + return; + } + if (!this.enabled) { + console.info(`[${config.PLUGIN_NAME}/Starred] Skipping starred internal plugin registration because it's not enabled.`); + return; + } + // eslint-disable-next-line + const self = this; + this.plugin.register(around(this.starred.instance, { + addItem: function (next) { + return function (file) { + next.call(this, file); + self.onMount(); + }; + }, + removeItem: function (next) { + return function (file) { + next.call(this, file); + self.onMount(); + }; + }, + })); + } +} + +class BookmarkInternalPlugin extends InternalPluginInjector { + constructor(plugin) { + super(plugin); + } + get bookmark() { + return this.plugin.app.internalPlugins.getPluginById('bookmarks'); + } + get enabled() { + return this.plugin.app.internalPlugins.getPluginById('bookmarks').enabled; + } + get leaf() { + const leaf = this.plugin.app.workspace.getLeavesOfType('bookmarks'); + if (!leaf) { + return undefined; + } + if (leaf.length === 1) { + return leaf[0]; + } + return undefined; + } + setIconOrRemove(filePath, node) { + var _a; + const iconName = icon.getByPath(this.plugin, filePath); + let iconNode = node.querySelector('.tree-item-icon'); + if (!iconName) { + if (iconNode) { + // Reset the icon to the default obsidian icon. + const items = this.bookmark.instance.items; + const item = items.find((item) => item.path === filePath); + if ((item === null || item === void 0 ? void 0 : item.type) === 'file') { + iconNode.innerHTML = DEFAULT_FILE_ICON; + } + else if ((item === null || item === void 0 ? void 0 : item.type) === 'folder') { + iconNode.innerHTML = DEFAULT_FOLDER_ICON; + } + } + return; + } + // If the icon node is not defined, then we need to recreate it. + if (!iconNode) { + // Get the tree-item-self element where the original icon is set. + const treeItemSelf = node.querySelector('.tree-item-self'); + if (!treeItemSelf) { + return; + } + iconNode = node.createDiv({ cls: 'tree-item-icon' }); + // Prepends the icon to the tree-item-self element as a first child. + treeItemSelf.prepend(iconNode); + } + const defaultMargin = iconNode.style.margin; + const iconColor = (_a = this.plugin.getIconColor(filePath)) !== null && _a !== void 0 ? _a : this.plugin.getSettings().iconColor; + dom.setIconForNode(this.plugin, iconName, iconNode, { color: iconColor }); + // Reset the margin to the default value to prevent overlapping with the text. + iconNode.style.margin = defaultMargin; + } + computeNodesWithPath(callback) { + if (!this.leaf || !this.leaf.view) { + return; + } + /** + * Retrieves the lookup item from the bookmark plugin and calls the callback with the + * element and the path of the item. + * @param item BookmarkItem object which can be a folder or a file. + * @param itemDoms WeakMap of the bookmark plugin which contains the lookup item. + */ + const retrieveLookupItem = (item, itemDoms) => { + const lookupItem = itemDoms.get(item); + if (!lookupItem) { + return; + } + if (item.items) { + // If the item is a folder, then we need to retrieve all the items inside it. + for (const subItem of item.items) { + retrieveLookupItem(subItem, itemDoms); + } + } + // If the item is a `file` or a `folder` (not of type `group`), then we can call the callback. + if (item.type === 'file' || item.type === 'folder') { + callback(lookupItem.el, item.path); + } + }; + const { itemDoms } = this.leaf.view; + // Retrieves all the items of the bookmark plugin which areo objects. + const items = this.bookmark.instance.items; + items.forEach((item) => { + retrieveLookupItem(item, itemDoms); + }); + } + onMount() { + var _a; + const setBookmarkIcon = () => { + const nodesWithPath = {}; + this.computeNodesWithPath((node, filePath) => { + nodesWithPath[filePath] = node; + }); + Object.entries(nodesWithPath).forEach(([filePath, node]) => this.setIconOrRemove(filePath, node)); + }; + if (obsidian.requireApiVersion('1.7.2')) { + // TODO: Might improve the performance here. + (_a = this.leaf) === null || _a === void 0 ? void 0 : _a.loadIfDeferred().then(setBookmarkIcon); + } + else { + setBookmarkIcon(); + } + } + register() { + if (!this.plugin.app.internalPlugins.getPluginById('file-explorer').enabled) { + console.info(`[${config.PLUGIN_NAME}/Bookmarks] Skipping bookmark internal plugin registration because file-explorer is not enabled.`); + return; + } + if (!this.enabled) { + console.info(`[${config.PLUGIN_NAME}/Bookmarks] Skipping bookmark internal plugin registration because it's not enabled.`); + return; + } + // eslint-disable-next-line + const self = this; + this.plugin.register(around(this.bookmark.instance, { + addItem: function (next) { + return function (...args) { + next.call(this, ...args); + // TODO: Remove in the future, I could not think of a better way to do this. + setTimeout(() => { + self.onMount(); + }, 1000); + }; + }, + removeItem: function (next) { + return function (...args) { + next.call(this, ...args); + self.onMount(); + }; + }, + })); + } +} + +// TODO: Optimize the code to reduce the number of iterations and improve the +// performance. +const createIconShortcodeRegex = (plugin) => { + return new RegExp(`(${plugin.getSettings().iconIdentifier})((\\w{1,64}:\\d{17,18})|(\\w{1,64}))(${plugin.getSettings().iconIdentifier})`, 'g'); +}; +const createTreeWalker = (plugin, root) => { + return document.createTreeWalker(root, NodeFilter.SHOW_ALL, { + acceptNode: function (node) { + if (node.nodeName === 'CODE') { + return NodeFilter.FILTER_REJECT; + } + else if (node.nodeName === '#text') { + if (node.nodeValue && + (emoji.getRegex().test(node.nodeValue) || + createIconShortcodeRegex(plugin).test(node.nodeValue))) { + return NodeFilter.FILTER_ACCEPT; + } + else { + return NodeFilter.FILTER_REJECT; + } + } + return NodeFilter.FILTER_SKIP; + }, + }); +}; +const checkForTextNodes = (treeWalker, match, cb) => { + let currentNode = treeWalker.currentNode; + while (currentNode) { + if (currentNode.nodeType === Node.TEXT_NODE) { + const text = currentNode; + const textNodes = [...Array.from(text.parentElement.childNodes)].filter((n) => n instanceof Text); + for (const text of textNodes) { + for (const code of [...text.wholeText.matchAll(match)] + .sort((a, b) => b.index - a.index) + .map((arr) => ({ text: arr[0], index: arr.index }))) { + if (!text.textContent) { + continue; + } + cb(text, code); + } + } + } + currentNode = treeWalker.nextNode(); + } +}; +const processIconInTextMarkdown = (plugin, element) => { + // Ignore if codeblock + const codeElement = element.querySelector('pre > code'); + const callOut = element.querySelector('.callout'); + if (codeElement && !callOut) { + return; + } + const iconTreeWalker = createTreeWalker(plugin, element); + const iconShortcodeRegex = createIconShortcodeRegex(plugin); + const iconIdentifierLength = plugin.getSettings().iconIdentifier.length; + checkForTextNodes(iconTreeWalker, iconShortcodeRegex, (text, code) => { + var _a, _b; + const shortcode = code.text; + const iconName = shortcode.slice(iconIdentifierLength, shortcode.length - iconIdentifierLength); + const iconObject = icon.getIconByName(iconName); + if (iconObject) { + const toReplace = text.splitText(code.index); + const rootSpan = createSpan({ + cls: 'cm-iconize-icon', + attr: { + 'aria-label': iconName, + 'data-icon': iconName, + 'aria-hidden': 'true', + }, + }); + rootSpan.style.display = 'inline-flex'; + rootSpan.style.transform = 'translateY(13%)'; + const parentElement = toReplace.parentElement; + const tagName = (_b = (_a = parentElement === null || parentElement === void 0 ? void 0 : parentElement.tagName) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== null && _b !== void 0 ? _b : ''; + let fontSize = calculateFontTextSize(); + if (isHeader(tagName)) { + fontSize = calculateHeaderSize(tagName); + const svgElement = svg.setFontSize(iconObject.svgElement, fontSize); + rootSpan.innerHTML = svgElement; + } + else { + const svgElement = svg.setFontSize(iconObject.svgElement, fontSize); + rootSpan.innerHTML = svgElement; + } + parentElement === null || parentElement === void 0 ? void 0 : parentElement.insertBefore(rootSpan, toReplace); + toReplace.textContent = toReplace.wholeText.substring(code.text.length); + // Set the font size to its parent font size if defined. + // We do this after that to not freeze the insertion while iterating over the tree. + // We are also updating the size after the animation because the styling won't be set + // in the first place. + requestAnimationFrame(() => { + const parentFontSize = parseFloat(getComputedStyle(parentElement).fontSize); + if (!isNaN(parentFontSize)) { + rootSpan.innerHTML = svg.setFontSize(rootSpan.innerHTML, parentFontSize); + } + }); + } + }); + const emojiTreeWalker = createTreeWalker(plugin, element); + checkForTextNodes(emojiTreeWalker, emoji.getRegex(), (text, code) => { + var _a, _b, _c, _d; + if (!emoji.isEmoji(code.text)) { + return; + } + if (plugin.getSettings().emojiStyle === 'twemoji') { + const toReplace = text.splitText(code.index); + const tagName = (_c = (_b = (_a = toReplace.parentElement) === null || _a === void 0 ? void 0 : _a.tagName) === null || _b === void 0 ? void 0 : _b.toLowerCase()) !== null && _c !== void 0 ? _c : ''; + let fontSize = calculateFontTextSize(); + if (isHeader(tagName)) { + fontSize = calculateHeaderSize(tagName); + } + const emojiValue = emoji.parseEmoji(plugin.getSettings().emojiStyle, code.text, fontSize); + if (!emojiValue) { + return; + } + const emojiNode = createSpan(); + emojiNode.innerHTML = emojiValue; + (_d = toReplace.parentElement) === null || _d === void 0 ? void 0 : _d.insertBefore(emojiNode, toReplace); + toReplace.textContent = toReplace.wholeText.substring(code.text.length); + } + }); +}; + +const processIconInLinkMarkdown = (plugin, element, ctx) => { + const linkElements = element.querySelectorAll('a'); + if (!linkElements || linkElements.length === 0) { + return; + } + linkElements.forEach((linkElement) => { + var _a, _b, _c, _d, _e; + // Skip if the link element e.g., is a tag. + if (!linkElement.hasAttribute('data-href')) { + return; + } + const linkHref = linkElement.getAttribute('href'); + if (!linkHref) { + logger.warn('Link element does not have an `href` attribute'); + return; + } + const file = plugin.app.metadataCache.getFirstLinkpathDest(linkHref, ctx.sourcePath); + if (!file) { + logger.warn('Link element does not have a linkpath to a file'); + return; + } + const path = file.path; + const iconValue = icon.getIconByPath(plugin, path); + if (!iconValue) { + return; + } + let fontSize = calculateFontTextSize(); + const tagName = (_c = (_b = (_a = linkElement.parentElement) === null || _a === void 0 ? void 0 : _a.tagName) === null || _b === void 0 ? void 0 : _b.toLowerCase()) !== null && _c !== void 0 ? _c : ''; + if (isHeader(tagName)) { + fontSize = calculateHeaderSize(tagName); + } + const iconName = typeof iconValue === 'string' + ? iconValue + : iconValue.prefix + iconValue.name; + const rootSpan = createSpan({ + cls: 'iconize-icon-in-link', + attr: { + title: iconName, + 'aria-label': iconName, + 'data-icon': iconName, + 'aria-hidden': 'true', + }, + }); + rootSpan.style.color = + (_d = plugin.getIconColor(path)) !== null && _d !== void 0 ? _d : plugin.getSettings().iconColor; + if (emoji.isEmoji(iconName)) { + const parsedEmoji = (_e = emoji.parseEmoji(plugin.getSettings().emojiStyle, iconName, fontSize)) !== null && _e !== void 0 ? _e : iconName; + rootSpan.style.transform = 'translateY(0)'; + rootSpan.innerHTML = parsedEmoji; + } + else { + let svgEl = icon.getIconByName(iconName).svgElement; + svgEl = svg.setFontSize(svgEl, fontSize); + if (svgEl) { + rootSpan.style.transform = 'translateY(20%)'; + rootSpan.innerHTML = svgEl; + } + } + linkElement.prepend(rootSpan); + }); +}; + +const TREE_ITEM_CLASS = 'tree-item-self'; +const TREE_ITEM_INNER = 'tree-item-inner'; +class OutlineInternalPlugin extends InternalPluginInjector { + constructor(plugin) { + super(plugin); + } + onMount() { + // TODO: Might improve the performance here. + } + register() { + if (!this.enabled) { + logger.info('Skipping internal plugin registration because it is not enabled.', LoggerPrefix.Outline); + return; + } + const updateTreeItems = () => { + var _a, _b, _c; + if (!((_b = (_a = this.leaf) === null || _a === void 0 ? void 0 : _a.view) === null || _b === void 0 ? void 0 : _b.tree)) { + return; + } + const treeItems = Array.from(this.leaf.view.tree.containerEl.querySelectorAll(`.${TREE_ITEM_CLASS}`)); + for (const treeItem of treeItems) { + const treeItemInner = treeItem.querySelector(`.${TREE_ITEM_INNER}`); + let text = treeItemInner === null || treeItemInner === void 0 ? void 0 : treeItemInner.getText(); + if (!text) { + continue; + } + const iconShortcodeRegex = createIconShortcodeRegex(this.plugin); + const iconIdentifierLength = this.plugin.getSettings().iconIdentifier.length; + let trimmedLength = 0; + for (const code of [...text.matchAll(iconShortcodeRegex)] + .sort((a, b) => a.index - b.index) + .map((arr) => ({ text: arr[0], index: arr.index }))) { + const shortcode = code.text; + const iconName = shortcode.slice(iconIdentifierLength, shortcode.length - iconIdentifierLength); + const iconObject = icon.getIconByName(iconName); + if (iconObject) { + const startIndex = code.index - trimmedLength; + const endIndex = code.index + code.text.length - trimmedLength; + const str = text.substring(0, startIndex) + text.substring(endIndex); + const iconSpan = createSpan({ + cls: 'cm-iconize-icon', + attr: { + 'aria-label': iconName, + 'data-icon': iconName, + 'aria-hidden': 'true', + }, + }); + const fontSize = parseFloat((_c = getComputedStyle(document.body).getPropertyValue('--nav-item-size')) !== null && _c !== void 0 ? _c : '16'); + const svgElement = svg.setFontSize(iconObject.svgElement, fontSize); + iconSpan.style.display = 'inline-flex'; + iconSpan.style.transform = 'translateY(13%)'; + iconSpan.innerHTML = svgElement; + treeItemInner.innerHTML = treeItemInner.innerHTML.replace(shortcode, iconSpan.outerHTML); + text = str; + trimmedLength += code.text.length; + } + } + } + }; + const setOutlineIcons = () => { + this.plugin.getEventEmitter().once('allIconsLoaded', () => { + updateTreeItems(); + const callback = (mutations) => { + mutations.forEach((mutation) => { + if (mutation.type !== 'childList') { + return; + } + const addedNodes = mutation.addedNodes; + if (addedNodes.length === 0) { + return; + } + updateTreeItems(); + }); + if (!this.enabled) { + observer.disconnect(); + } + }; + const observer = new MutationObserver(callback); + observer.observe(this.leaf.view.tree.containerEl, { + childList: true, + subtree: true, + }); + }); + }; + if (obsidian.requireApiVersion('1.7.2')) { + // TODO: Might improve the performance here. + this.leaf.loadIfDeferred().then(setOutlineIcons); + } + else { + setOutlineIcons(); + } + } + get leaf() { + const leaf = this.plugin.app.workspace.getLeavesOfType('outline'); + if (!leaf) { + logger.log('`leaf` in outline is undefined', LoggerPrefix.Outline); + return undefined; + } + if (leaf.length === 0) { + logger.log('`leaf` length in outline is 0', LoggerPrefix.Outline); + return undefined; + } + return leaf[0]; + } + get outline() { + return this.plugin.app.internalPlugins.getPluginById('outline'); + } + get enabled() { + return this.plugin.app.internalPlugins.getPluginById('outline').enabled; + } +} + +class SuggestionIcon extends obsidian.EditorSuggest { + constructor(app, plugin) { + super(app); + this.plugin = plugin; + } + onTrigger(cursor, editor) { + // Isolate shortcode starting position closest to the cursor. + const shortcodeStart = editor + .getLine(cursor.line) + .substring(0, cursor.ch) + .lastIndexOf(this.plugin.getSettings().iconIdentifier); + // `onTrigger` needs to return `null` as soon as possible to save processing performance. + if (shortcodeStart === -1) { + return null; + } + // Regex for checking if the shortcode is not done yet. + const regex = new RegExp(`^(${this.plugin.getSettings().iconIdentifier})\\w+$`, 'g'); + const regexOngoingShortcode = editor + .getLine(cursor.line) + .substring(shortcodeStart, cursor.ch) + .match(regex); + if (regexOngoingShortcode === null) { + return null; + } + const startingIndex = editor + .getLine(cursor.line) + .indexOf(regexOngoingShortcode[0]); + return { + start: { + line: cursor.line, + ch: startingIndex, + }, + end: { + line: cursor.line, + ch: startingIndex + regexOngoingShortcode[0].length, + }, + query: regexOngoingShortcode[0], + }; + } + getSuggestions(context) { + const queryLowerCase = context.query + .substring(this.plugin.getSettings().iconIdentifier.length) + .toLowerCase(); + // Store all icons corresponding to the current query. + const iconsNameArray = getAllLoadedIconNames() + .filter((iconObject) => { + const name = iconObject.prefix.toLowerCase() + iconObject.name.toLowerCase(); + return name.toLowerCase().includes(queryLowerCase); + }) + .map((iconObject) => iconObject.prefix + iconObject.name); + // Store all emojis correspoding to the current query - parsing whitespaces and + // colons for shortcodes compatibility. + const emojisNameArray = Object.keys(emoji.shortNames).filter((e) => { var _a; return (_a = emoji.getShortcode(e)) === null || _a === void 0 ? void 0 : _a.includes(queryLowerCase); }); + return [...iconsNameArray, ...emojisNameArray]; + } + renderSuggestion(value, el) { + const iconObject = icon.getIconByName(value); + el.style.display = 'flex'; + el.style.alignItems = 'center'; + el.style.gap = '0.25rem'; + if (iconObject) { + // Suggest an icon. + el.innerHTML = `${iconObject.svgElement} ${value}`; + } + else { + // Suggest an emoji - display its shortcode version. + const shortcode = emoji.getShortcode(value); + if (shortcode) { + el.innerHTML = `${value} ${shortcode}`; + } + } + } + selectSuggestion(value) { + const isEmoji = emoji.isEmoji(value.replace(/_/g, ' ')); + if (!isEmoji) { + saveIconToIconPack(this.plugin, value); + } + // Replace query with iconNameWithPrefix or emoji unicode directly. + const updatedValue = isEmoji + ? value + : `${this.plugin.getSettings().iconIdentifier}${value}${this.plugin.getSettings().iconIdentifier}`; + this.context.editor.replaceRange(updatedValue, this.context.start, this.context.end); + } +} + +class IconInTextWidget extends view.WidgetType { + constructor(plugin, id) { + super(); + this.plugin = plugin; + this.id = id; + this.start = -1; + this.end = -1; + } + setPosition(start, end) { + this.start = start; + this.end = end; + } + eq(other) { + return other instanceof IconInTextWidget && other.id === this.id; + } + getSize(view) { + let fontSize = calculateFontTextSize(); + const line = view.state.doc.lineAt(this.end); + const headerMatch = line.text.match(/^#{1,6}\s/); + if (headerMatch && headerMatch[0].trim()) { + const mapping = { + '#': 'h1', + '##': 'h2', + '###': 'h3', + '####': 'h4', + '#####': 'h5', + '######': 'h6', + }; + const header = mapping[headerMatch[0].trim()]; + fontSize = calculateHeaderSize(header); + } + return fontSize; + } + toDOM(view) { + const wrap = createSpan({ + cls: 'cm-iconize-icon', + attr: { + 'aria-label': this.id, + 'data-icon': this.id, + 'aria-hidden': 'true', + }, + }); + const foundIcon = icon.getIconByName(this.id); + const fontSize = this.getSize(view); + if (foundIcon) { + const svgElement = svg.setFontSize(foundIcon.svgElement, fontSize); + wrap.style.display = 'inline-flex'; + wrap.style.transform = 'translateY(13%)'; + wrap.innerHTML = svgElement; + } + else if (emoji.isEmoji(this.id)) { + wrap.innerHTML = emoji.parseEmoji(this.plugin.getSettings().emojiStyle, this.id, fontSize); + } + else { + wrap.append(`${this.plugin.getSettings().iconIdentifier}${this.id}${this.plugin.getSettings().iconIdentifier}`); + } + return wrap; + } + ignoreEvent() { + return false; + } +} + +class IconInLinkWidget extends view.WidgetType { + constructor(plugin, iconData, path, headerType) { + super(); + this.plugin = plugin; + this.iconData = iconData; + this.path = path; + this.headerType = headerType; + } + toDOM() { + var _a; + const iconNode = document.createElement('span'); + const iconName = typeof this.iconData === 'string' + ? this.iconData + : this.iconData.prefix + this.iconData.name; + iconNode.style.color = + (_a = this.plugin.getIconColor(this.path)) !== null && _a !== void 0 ? _a : this.plugin.getSettings().iconColor; + iconNode.setAttribute('title', iconName); + iconNode.classList.add('iconize-icon-in-link'); + if (typeof this.iconData === 'string') { + iconNode.style.transform = 'translateY(0)'; + } + let innerHTML = typeof this.iconData === 'string' + ? this.iconData + : this.iconData.svgElement; + let fontSize = calculateFontTextSize(); + if (this.headerType) { + fontSize = calculateHeaderSize(this.headerType); + } + if (emoji.isEmoji(innerHTML)) { + innerHTML = emoji.parseEmoji(this.plugin.getSettings().emojiStyle, innerHTML, fontSize); + } + else { + innerHTML = svg.setFontSize(innerHTML, fontSize); + } + iconNode.innerHTML = innerHTML; + return iconNode; + } + ignoreEvent() { + return true; + } +} + +const buildLinkDecorations = (view$1, plugin) => { + const builder = new state.RangeSetBuilder(); + const mdView = view$1.state.field(obsidian.editorInfoField); + for (const { from, to } of view$1.visibleRanges) { + language.syntaxTree(view$1.state).iterate({ + from, + to, + enter: (node) => { + const tokenProps = node.type.prop(language.tokenClassNodeProp); + if (tokenProps) { + const props = new Set(tokenProps.split(' ')); + const isLink = props.has('hmd-internal-link'); + const headerType = [ + 'header-1', + 'header-2', + 'header-3', + 'header-4', + 'header-5', + 'header-6', + ].find((header) => props.has(header)); + if (isLink) { + let linkText = view$1.state.doc.sliceString(node.from, node.to); + linkText = linkText.split('#')[0]; + const file = plugin.app.metadataCache.getFirstLinkpathDest(linkText, mdView.file.basename); + if (file) { + const possibleIcon = icon.getIconByPath(plugin, file.path); + if (possibleIcon) { + const iconDecoration = view.Decoration.widget({ + widget: new IconInLinkWidget(plugin, possibleIcon, file.path, headerType), + }); + builder.add(node.from, node.from, iconDecoration); + } + } + } + } + }, + }); + } + return builder.finish(); +}; + +const buildTextDecorations = (view$1, plugin) => { + const ranges = []; + const iconInfo = view$1.state.field(plugin.positionField); + for (const { from, to } of view$1.visibleRanges) { + iconInfo.between(from - 1, to + 1, (from, to, { iconId }) => { + ranges.push([iconId, from, to]); + }); + } + return view.Decoration.set(ranges.map(([code, from, to]) => { + const widget = new IconInTextWidget(plugin, code); + widget.setPosition(from, to); + if (view$1.state.field(obsidian.editorLivePreviewField)) { + return view.Decoration.replace({ + widget, + side: -1, + }).range(from, to); + } + return view.Decoration.widget({ + widget, + side: -1, + }).range(to); + }), true); +}; + +const buildIconInTextPlugin = (plugin) => { + return view.ViewPlugin.fromClass(class IconPlugin { + constructor(view) { + this.plugin = plugin; + this.decorations = buildTextDecorations(view, plugin); + } + update(update) { + this.decorations = buildTextDecorations(update.view, this.plugin); + } + }, { + decorations: (v) => v.decorations, + provide: (plugin) => view.EditorView.atomicRanges.of((view$1) => { + const value = view$1.plugin(plugin); + return value ? value.decorations : view.Decoration.none; + }), + }); +}; + +const buildIconInLinksPlugin = (plugin) => { + return view.ViewPlugin.fromClass(class { + constructor(view) { + this.plugin = plugin; + this.decorations = buildLinkDecorations(view, plugin); + } + destroy() { } + update(update) { + if (update.docChanged || update.viewportChanged) { + this.decorations = buildLinkDecorations(update.view, this.plugin); + } + } + }, { + decorations: (v) => v.decorations, + }); +}; + +// TODO: Optimize the code to reduce the number of iterations and improve the +// performance. +function checkForSourceMode(plugin) { + let isSourceMode = false; + // Iterate over all leaves to check if any is in source mode + plugin.app.workspace.iterateAllLeaves((leaf) => { + var _a; + if (!isSourceMode && leaf.view.getViewType() === 'markdown') { + if ((_a = leaf.getViewState().state) === null || _a === void 0 ? void 0 : _a.source) { + isSourceMode = true; + } + } + }); + return isSourceMode; +} +class IconPosition extends state.RangeValue { + constructor(text) { + super(); + this.text = text; + } + get iconId() { + return this.text; + } + eq(other) { + return other instanceof IconPosition && other.text === this.text; + } +} +/** + * Builds a position field for the editor state. This field will track the + * positions of the icons in the document. + **/ +const buildPositionField = (plugin) => { + /** + * Checks the ranges of the icons in the document. If the range is not + * excluded, the range is added to the range set. If the range is excluded, + * the range is removed from the range set. + * @param state EditorState to get the ranges from. + * @param excludeFrom Number to exclude from the ranges. + * @param excludeTo Number to exclude to the ranges. + * @param updateRange Function callback to update the range. + */ + const checkRanges = (state, excludeFrom, excludeTo, updateRange) => { + const isSourceMode = checkForSourceMode(plugin); + const text = state.doc.sliceString(0, state.doc.length); + const identifier = plugin.getSettings().iconIdentifier; + const regex = new RegExp(`(${identifier})((\\w{1,64}:\\d{17,18})|(\\w{1,64}))(${identifier})`, 'g'); + for (const { 0: rawCode, index: offset } of text.matchAll(regex)) { + const iconName = rawCode.substring(identifier.length, rawCode.length - identifier.length); + if (!icon.getIconByName(iconName)) { + continue; + } + const from = offset; + const to = offset + rawCode.length; + if (!isNodeInRangeAccepted(state, from, to)) { + continue; + } + if (offset < excludeFrom || offset > excludeTo) { + updateRange(from, to, new IconPosition(iconName), isSourceMode); + continue; + } + updateRange(from, to, new IconPosition(iconName), true); + } + for (const { 0: emojiName, index: offset } of text.matchAll(emoji.getRegex())) { + if (!emoji.isEmoji(emojiName)) { + continue; + } + const from = offset; + const to = offset + emojiName.length; + if (!isNodeInRangeAccepted(state, from, to)) { + continue; + } + if (offset < excludeFrom || offset > excludeTo) { + updateRange(from, to, new IconPosition(emojiName), isSourceMode); + continue; + } + updateRange(from, to, new IconPosition(emojiName), true); + } + }; + const isNodeInRangeAccepted = (state, from, to) => { + let isRangeAccepted = true; + language.syntaxTree(state).iterate({ + from, + to, + enter: ({ type }) => { + var _a; + if (type.name === 'Document') { + return; + } + const allowedNodeTypes = [ + 'header', + 'strong', + 'em', + 'quote', + 'link', + 'list-1', + 'list-2', + 'list-3', + 'highlight', + 'footref', + 'comment', + 'link-alias', + ]; + const excludedNodeTypes = [ + 'formatting', + 'hmd-codeblock', + 'inline-code', + 'hr', + ]; + const nodeProps = (_a = type.prop(language.tokenClassNodeProp)) !== null && _a !== void 0 ? _a : ''; + const s = new Set(nodeProps.split(' ')); + if (excludedNodeTypes.some((t) => s.has(t)) && + allowedNodeTypes.every((t) => !s.has(t))) { + isRangeAccepted = false; + } + }, + }); + return isRangeAccepted; + }; + return state.StateField.define({ + create: (state$1) => { + const rangeSet = new state.RangeSetBuilder(); + const changedLines = []; + checkRanges(state$1, -1, -1, (from, to, iconPosition) => { + changedLines.push({ from, to, iconPosition }); + }); + changedLines.sort((a, b) => a.from - b.from); + for (const { from, to, iconPosition } of changedLines) { + rangeSet.add(from, to, iconPosition); + } + return rangeSet.finish(); + }, + update: (rangeSet, transaction) => { + const newRanges = []; + if (!transaction.docChanged) { + if (transaction.selection) { + const from = transaction.selection.ranges[0].from; + const to = transaction.selection.ranges[0].to; + const lineEnd = transaction.state.doc.lineAt(to).length; + const lineStart = transaction.state.doc.lineAt(from).from; + // Checks the ranges of the icons in the document except for the + // excluded line start and end. + checkRanges(transaction.state, lineStart, lineStart + lineEnd, (from, to, value, removed) => { + rangeSet = rangeSet.update({ + filterFrom: from, + filterTo: to, + filter: () => false, + }); + if (!removed) { + newRanges.push(value.range(from, to)); + } + }); + } + else { + checkRanges(transaction.state, -1, -1, (from, to, value, removed) => { + rangeSet = rangeSet.update({ + filterFrom: from, + filterTo: to, + filter: () => false, + }); + if (!removed) { + newRanges.push(value.range(from, to)); + } + }); + } + newRanges.sort((a, b) => a.from - b.from); + rangeSet = rangeSet.update({ add: newRanges }); + return rangeSet; + } + rangeSet = rangeSet.map(transaction.changes); + const changedLines = []; + transaction.changes.iterChangedRanges((_f, _t, from, to) => { + changedLines.push([ + transaction.state.doc.lineAt(from).number, + transaction.state.doc.lineAt(to).number, + ]); + }); + for (const [start, end] of changedLines) { + const from = transaction.state.doc.line(start).from; + const to = transaction.state.doc.line(end).to; + rangeSet = rangeSet.update({ + filterFrom: from, + filterTo: to, + filter: () => false, + }); + const lineEnd = transaction.state.doc.line(end).length; + const lineStart = transaction.state.doc.line(end).from; + // Checks the ranges of the icons in the document except for the excluded + // line start and end. + checkRanges(transaction.state, lineStart, lineStart + lineEnd, (from, to, value, removed) => { + if (!removed) { + newRanges.push(value.range(from, to)); + } + }); + } + newRanges.sort((a, b) => a.from - b.from); + rangeSet = rangeSet.update({ add: newRanges }); + return rangeSet; + }, + }); +}; + +class ChangeColorModal extends obsidian.Modal { + constructor(app, plugin, path) { + var _a; + super(app); + this.plugin = plugin; + this.path = path; + this.usedColor = this.plugin.getIconColor(this.path); + this.contentEl.style.display = 'block'; + this.modalEl.classList.add('iconize-custom-modal'); + this.titleEl.setText('Change color'); + const description = this.contentEl.createEl('p', { + text: 'Select a color for this icon', + cls: 'setting-item-description', + }); + description.style.marginBottom = 'var(--size-2-2)'; + const colorContainer = this.contentEl.createDiv(); + colorContainer.style.display = 'flex'; + colorContainer.style.alignItems = 'center'; + colorContainer.style.justifyContent = 'space-between'; + const colorPicker = new obsidian.ColorComponent(colorContainer) + .setValue((_a = this.usedColor) !== null && _a !== void 0 ? _a : '#000000') + .onChange((value) => { + this.usedColor = value; + }); + const defaultColorButton = new obsidian.ButtonComponent(colorContainer); + defaultColorButton.setTooltip('Set color to the default one'); + defaultColorButton.setButtonText('Reset'); + defaultColorButton.onClick(() => { + colorPicker.setValue('#000000'); + this.usedColor = undefined; + }); + // Save button. + const button = new obsidian.ButtonComponent(this.contentEl); + button.buttonEl.style.marginTop = 'var(--size-4-4)'; + button.buttonEl.style.float = 'right'; + button.setButtonText('Save Changes'); + button.onClick(() => __awaiter(this, void 0, void 0, function* () { + var _a; + new obsidian.Notice('Color of icon changed.'); + if (this.usedColor) { + this.plugin.addIconColor(this.path, this.usedColor); + } + else { + this.plugin.removeIconColor(this.path); + } + // Refresh the DOM. + const iconNode = dom.getIconNodeFromPath(this.path); + iconNode.style.color = (_a = this.usedColor) !== null && _a !== void 0 ? _a : null; + const colorizedInnerHtml = svg.colorize(iconNode.innerHTML, this.usedColor); + iconNode.innerHTML = colorizedInnerHtml; + this.close(); + })); + } + onOpen() { + super.onOpen(); + } + onClose() { + const { contentEl } = this; + contentEl.empty(); + } +} + +class EventEmitter { + constructor() { + this.listeners = {}; + } + on(type, listener, priority = 0) { + var _a, _b; + var _c; + (_a = (_c = this.listeners)[type]) !== null && _a !== void 0 ? _a : (_c[type] = []); + (_b = this.listeners[type]) === null || _b === void 0 ? void 0 : _b.push({ listener, once: false, priority }); + this.sortListeners(type); + } + once(type, listener, priority = 0) { + var _a, _b; + var _c; + (_a = (_c = this.listeners)[type]) !== null && _a !== void 0 ? _a : (_c[type] = []); + (_b = this.listeners[type]) === null || _b === void 0 ? void 0 : _b.push({ listener, once: true, priority }); + this.sortListeners(type); + } + off(type, listener) { + var _a; + if (!this.listeners[type]) { + return; + } + this.listeners[type] = (_a = this.listeners[type]) === null || _a === void 0 ? void 0 : _a.filter((entry) => entry.listener !== listener); + } + emit(type, payload) { + const listeners = this.listeners[type]; + if (!listeners) { + return; + } + const event = { payload }; + listeners.slice().forEach((entry) => { + entry.listener(event); + if (entry.once) { + this.off(type, entry.listener); + } + }); + } + sortListeners(type) { + var _a; + if (this.listeners[type]) { + (_a = this.listeners[type]) === null || _a === void 0 ? void 0 : _a.sort((a, b) => b.priority - a.priority); + } + } +} + +function getApi(plugin) { + return { + getEventEmitter: () => plugin.getEventEmitter(), + getIconByName: (iconNameWithPrefix) => icon.getIconByName(iconNameWithPrefix), + setIconForNode: (iconName, node, color) => dom.setIconForNode(plugin, iconName, node, { color }), + saveIconToIconPack: (iconNameWithPrefix) => saveIconToIconPack(plugin, iconNameWithPrefix), + removeIconFromIconPack: (iconNameWithPrefix) => removeIconFromIconPack(plugin, iconNameWithPrefix), + getIconsFromIconPack: getIconsFromIconPack, + getAllIconPacks: getAllIconPacks, + doesElementHasIconNode: dom.doesElementHasIconNode, + getIconFromElement: dom.getIconFromElement, + removeIconInNode: dom.removeIconInNode, + removeIconInPath: dom.removeIconInPath, + util: { + dom, + svg, + }, + version: { + get current() { + return plugin.manifest.version; + }, + }, + }; +} + +class IconizePlugin extends obsidian.Plugin { + constructor() { + super(...arguments); + this.registeredFileExplorers = new Set(); + this.modifiedInternalPlugins = []; + this.positionField = buildPositionField(this); + this.frontmatterCache = new Set(); + this.eventEmitter = new EventEmitter(); + this.api = getApi(this); + } + onload() { + return __awaiter(this, void 0, void 0, function* () { + console.log(`loading ${config.PLUGIN_NAME}`); + yield this.loadIconFolderData(); + logger.toggleLogging(this.getSettings().debugMode); + setPath(this.getSettings().iconPacksPath); + if (this.getSettings().useInternalPlugins) { + // Registers all modified internal plugins. + // Only adds star plugin for obsidian under v0.12.6. + if (!obsidian.requireApiVersion('0.12.6')) { + this.modifiedInternalPlugins.push(new StarredInternalPlugin(this)); + } + else if (obsidian.requireApiVersion('1.2.0')) { + this.modifiedInternalPlugins.push(new BookmarkInternalPlugin(this)); + } + this.modifiedInternalPlugins.push(new OutlineInternalPlugin(this)); + } + yield createDefaultDirectory(this); + yield this.checkRecentlyUsedIcons(); + yield migrate(this); + const usedIconNames = icon.getAllWithPath(this).map((value) => value.icon); + if (!this.doesUseCustomLucideIconPack()) { + addLucideIconsPack(this); + } + yield loadUsedIcons(this, usedIconNames); + this.app.workspace.onLayoutReady(() => this.handleChangeLayout()); + this.addCommand({ + id: 'iconize:set-icon-for-file', + name: 'Set icon for file', + hotkeys: [ + { + modifiers: ['Mod', 'Shift'], + key: 'j', + }, + ], + editorCallback: (editor) => __awaiter(this, void 0, void 0, function* () { + var _a; + const file = (_a = editor.editorComponent) === null || _a === void 0 ? void 0 : _a.file; + if (!file) { + logger.warn(`'editor.editorComponent?.file' is undefined for file: ${file}`); + return; + } + const modal = new IconsPickerModal(this.app, this, file.path); + modal.open(); + modal.onSelect = (iconName) => { + IconCache.getInstance().set(file.path, { + iconNameWithPrefix: iconName, + }); + // Update icon in tab when setting is enabled. + if (this.getSettings().iconInTabsEnabled) { + const tabLeaves = iconTabs.getTabLeavesOfFilePath(this, file.path); + for (const tabLeaf of tabLeaves) { + iconTabs.update(this, iconName, tabLeaf.tabHeaderInnerIconEl); + } + } + // Update icon in title when setting is enabled. + if (this.getSettings().iconInTitleEnabled) { + this.addIconInTitle(iconName); + } + }; + }), + }); + this.registerEvent( + // Registering file menu event for listening to file pinning and unpinning. + this.app.workspace.on('file-menu', (menu, file) => { + // I've researched other ways of doing this. However, there is no other way to listen to file pinning and unpinning. + menu.onHide(() => { + const path = file.path; + if (this.getSettings().iconInTabsEnabled) { + for (const openedFile of getAllOpenedFiles(this)) { + if (openedFile.path === path) { + const possibleIcon = IconCache.getInstance().get(path); + if (!possibleIcon) { + return; + } + const tabLeaves = iconTabs.getTabLeavesOfFilePath(this, file.path); + for (const tabLeaf of tabLeaves) { + // Add timeout to ensure that the default icon is already set. + setTimeout(() => { + iconTabs.add(this, file.path, tabLeaf.tabHeaderInnerIconEl); + }, 5); + } + } + } + } + }); + })); + this.registerEvent(this.app.workspace.on('layout-change', () => this.handleChangeLayout())); + this.registerEvent(this.app.workspace.on('file-menu', (menu, file) => { + const addIconMenuItem = (item) => { + item.setTitle('Change icon'); + item.setIcon('hashtag'); + item.onClick(() => { + const modal = new IconsPickerModal(this.app, this, file.path); + modal.open(); + modal.onSelect = (iconName) => { + IconCache.getInstance().set(file.path, { + iconNameWithPrefix: iconName, + }); + // Update icon in tab when setting is enabled. + if (this.getSettings().iconInTabsEnabled) { + const tabLeaves = iconTabs.getTabLeavesOfFilePath(this, file.path); + for (const tabLeaf of tabLeaves) { + iconTabs.update(this, iconName, tabLeaf.tabHeaderInnerIconEl); + } + } + // Update icon in title when setting is enabled. + if (this.getSettings().iconInTitleEnabled) { + this.addIconInTitle(iconName); + } + }; + }); + }; + const removeIconMenuItem = (item) => { + item.setTitle('Remove icon'); + item.setIcon('trash'); + item.onClick(() => __awaiter(this, void 0, void 0, function* () { + yield this.removeSingleIcon(file); + })); + }; + const changeColorOfIcon = (item) => { + item.setTitle('Change color of icon'); + item.setIcon('palette'); + item.onClick(() => { + const modal = new ChangeColorModal(this.app, this, file.path); + modal.open(); + }); + }; + menu.addItem(addIconMenuItem); + const filePathData = this.getData()[file.path]; + const hasNestedIcon = typeof filePathData === 'object' && + filePathData.iconName !== null; + // Only add remove icon menu item when the file path exists in the data. + // We do not want to show this menu item for e.g. custom rules. + if (filePathData && + (typeof filePathData === 'string' || hasNestedIcon)) { + const icon = typeof filePathData === 'string' + ? filePathData + : filePathData.iconName; + if (!emoji.isEmoji(icon)) { + menu.addItem(changeColorOfIcon); + } + menu.addItem(removeIconMenuItem); + } + })); + // deleting event + this.registerEvent(this.app.vault.on('delete', (file) => { + const path = file.path; + this.removeFolderIcon(path); + })); + // renaming event + this.registerEvent(this.app.vault.on('rename', (file, oldPath) => { + // Check if the file was moved and had an icon before. + const dataPoint = this.data[oldPath]; + if (dataPoint && oldPath !== 'settings') { + const iconNameWithPrefix = typeof dataPoint === 'object' + ? dataPoint.iconName + : dataPoint; + dom.createIconNode(this, file.path, iconNameWithPrefix); + } + this.renameFolder(file.path, oldPath); + })); + if (this.getSettings().iconsInNotesEnabled) { + this.registerMarkdownPostProcessor((el) => processIconInTextMarkdown(this, el)); + this.registerEditorSuggest(new SuggestionIcon(this.app, this)); + this.registerEditorExtension([ + this.positionField, + buildIconInTextPlugin(this), + ]); + } + if (this.getSettings().iconsInLinksEnabled) { + this.registerMarkdownPostProcessor((el, ctx) => processIconInLinkMarkdown(this, el, ctx)); + this.registerEditorExtension([ + this.positionField, + buildIconInLinksPlugin(this), + ]); + } + this.addSettingTab(new IconFolderSettings(this.app, this)); + }); + } + notifyPlugins() { + this.modifiedInternalPlugins.forEach((internalPlugin) => { + if (internalPlugin.enabled) { + internalPlugin.onMount(); + } + }); + } + removeSingleIcon(file) { + return __awaiter(this, void 0, void 0, function* () { + this.removeFolderIcon(file.path); + dom.removeIconInPath(file.path); + IconCache.getInstance().invalidate(file.path); + this.notifyPlugins(); + let didUpdate = false; + // Refreshes the icon tab and title icon for custom rules. + for (const rule of customRule.getSortedRules(this)) { + const applicable = yield customRule.isApplicable(this, rule, file.path); + if (applicable) { + customRule.add(this, rule, file); + this.addIconInTitle(rule.icon); + const tabLeaves = iconTabs.getTabLeavesOfFilePath(this, file.path); + for (const tabLeaf of tabLeaves) { + iconTabs.add(this, file.path, tabLeaf.tabHeaderInnerIconEl, { + iconName: rule.icon, + }); + } + didUpdate = true; + break; + } + } + // Only remove icon above titles and icon in tabs if no custom rule was found. + if (!didUpdate) { + // Refreshes icons above title and icons in tabs. + for (const openedFile of getAllOpenedFiles(this)) { + if (this.getSettings().iconInTitleEnabled) { + titleIcon.remove(openedFile.leaf.view.inlineTitleEl); + } + if (this.getSettings().iconInTabsEnabled) { + const leaf = openedFile.leaf; + iconTabs.remove(leaf.tabHeaderInnerIconEl, { + replaceWithDefaultIcon: true, + }); + } + } + } + }); + } + handleChangeLayout() { + // Transform data that are objects to single strings. + const data = Object.entries(this.data); + this.modifiedInternalPlugins.forEach((internalPlugin) => { + if (internalPlugin.enabled) { + internalPlugin.onMount(); + internalPlugin.register(); + } + }); + icon.addAll(this, data, this.registeredFileExplorers, () => { + // After initialization of the icon packs, checks the vault for missing icons and + // adds them. + initIconPacks(this).then(() => __awaiter(this, void 0, void 0, function* () { + if (this.getSettings().iconsBackgroundCheckEnabled) { + const data = Object.entries(this.data); + yield icon.checkMissingIcons(this, data); + resetPreloadedIcons(); + } + this.eventEmitter.emit('allIconsLoaded'); + })); + if (this.getSettings().iconInFrontmatterEnabled) { + const activeFile = this.app.workspace.getActiveFile(); + if (activeFile) { + this.frontmatterCache.add(activeFile.path); + } + } + // Adds the title icon to the active leaf view. + if (this.getSettings().iconInTitleEnabled) { + for (const openedFile of getAllOpenedFiles(this)) { + const iconName = icon.getByPath(this, openedFile.path); + const activeView = openedFile.leaf.view; + if (activeView instanceof obsidian.MarkdownView && iconName) { + let possibleIcon = iconName; + if (!emoji.isEmoji(iconName)) { + const iconNextIdentifier = nextIdentifier(iconName); + possibleIcon = getSvgFromLoadedIcon(iconName.substring(0, iconNextIdentifier), iconName.substring(iconNextIdentifier)); + } + if (possibleIcon) { + titleIcon.add(this, activeView.inlineTitleEl, possibleIcon, { + fontSize: calculateInlineTitleSize(), + }); + } + } + } + } + // Register rename event for adding icons with custom rules to the DOM + // when file was moved to another directory. + this.registerEvent(this.app.vault.on('rename', (file, oldPath) => __awaiter(this, void 0, void 0, function* () { + const sortedRules = customRule.getSortedRules(this); + // Removes possible icons from the renamed file. + sortedRules.forEach((rule) => { + if (customRule.doesMatchPath(rule, oldPath)) { + dom.removeIconInPath(file.path); + } + }); + // Adds possible icons to the renamed file. + sortedRules.forEach((rule) => { + if (customRule.doesMatchPath(rule, oldPath)) { + return; + } + customRule.add(this, rule, file, undefined); + }); + // Updates icon tabs for the renamed file. + for (const rule of customRule.getSortedRules(this)) { + const applicable = yield customRule.isApplicable(this, rule, file.path); + if (!applicable) { + continue; + } + const openedFiles = getAllOpenedFiles(this); + const openedFile = openedFiles.find((openedFile) => openedFile.path === file.path); + if (openedFile) { + const leaf = openedFile.leaf; + iconTabs.update(this, rule.icon, leaf.tabHeaderInnerIconEl); + } + break; + } + }))); + // Register `layout-change` event for adding icons to tabs when moving a pane or + // enabling reading mode. + this.registerEvent(this.app.workspace.on('layout-change', () => { + var _a, _b; + if (this.getSettings().iconInTitleEnabled) { + const activeView = this.app.workspace.getActiveViewOfType(obsidian.MarkdownView); + if (activeView) { + const file = activeView.file; + const view = activeView.leaf.view.currentMode + .view; + const iconNameWithPrefix = icon.getByPath(this, file.path); + if (!iconNameWithPrefix) { + titleIcon.hide(view.inlineTitleEl); + return; + } + let foundIcon = iconNameWithPrefix; + if (!emoji.isEmoji(foundIcon)) { + foundIcon = (_a = icon.getIconByName(iconNameWithPrefix)) === null || _a === void 0 ? void 0 : _a.svgElement; + // Check for preloaded icons if no icon was found when the start up was faster + // than the loading of the icons. + if (!foundIcon && getPreloadedIcons().length > 0) { + foundIcon = (_b = getPreloadedIcons().find((icon) => icon.prefix + icon.name === iconNameWithPrefix)) === null || _b === void 0 ? void 0 : _b.svgElement; + } + } + if (foundIcon) { + // Removes the node because the editor markdown content is being rerendered + // when the content mode changes back to editing. + titleIcon.remove(view.inlineTitleEl); + titleIcon.add(this, view.inlineTitleEl, foundIcon, { + fontSize: calculateInlineTitleSize(), + }); + } + } + } + if (!this.getSettings().iconInTabsEnabled) { + return; + } + for (const openedFile of getAllOpenedFiles(this)) { + const leaf = openedFile.leaf; + const iconColor = this.getIconColor(leaf.view.file.path); + iconTabs.add(this, openedFile.path, leaf.tabHeaderInnerIconEl, { + iconColor, + }); + } + })); + // Register `file-open` event for adding icon to title. + this.registerEvent(this.app.workspace.on('file-open', (file) => { + var _a, _b; + if (!this.getSettings().iconInTitleEnabled) { + return; + } + for (const openedFile of getAllOpenedFiles(this)) { + if (!file || !openedFile || openedFile.path !== file.path) { + continue; + } + const leaf = openedFile.leaf.view; + const iconNameWithPrefix = icon.getByPath(this, file.path); + if (!iconNameWithPrefix) { + titleIcon.hide(leaf.inlineTitleEl); + return; + } + let foundIcon = iconNameWithPrefix; + if (!emoji.isEmoji(foundIcon)) { + foundIcon = (_a = icon.getIconByName(iconNameWithPrefix)) === null || _a === void 0 ? void 0 : _a.svgElement; + // Check for preloaded icons if no icon was found when the start up was faster + // than the loading of the icons. + if (!foundIcon && getPreloadedIcons().length > 0) { + foundIcon = (_b = getPreloadedIcons().find((icon) => icon.prefix + icon.name === iconNameWithPrefix)) === null || _b === void 0 ? void 0 : _b.svgElement; + } + } + if (foundIcon) { + titleIcon.add(this, leaf.inlineTitleEl, foundIcon, { + fontSize: calculateInlineTitleSize(), + }); + } + else { + titleIcon.hide(leaf.inlineTitleEl); + } + } + })); + // Register event for frontmatter icon registration. + this.registerEvent(this.app.metadataCache.on('resolve', (file) => __awaiter(this, void 0, void 0, function* () { + if (!this.getSettings().iconInFrontmatterEnabled) { + return; + } + const fileCache = this.app.metadataCache.getFileCache(file); + const iconFrontmatterName = this.getSettings().iconInFrontmatterFieldName; + const iconColorFrontmatterName = this.getSettings().iconColorInFrontmatterFieldName; + if (fileCache === null || fileCache === void 0 ? void 0 : fileCache.frontmatter) { + const { [iconFrontmatterName]: newIconName, [iconColorFrontmatterName]: newIconColor, } = fileCache.frontmatter; + // If `icon` property is empty, we will remove it from the data and remove the icon. + if (!newIconName) { + if (this.frontmatterCache.has(file.path)) { + yield this.removeSingleIcon(file); + this.frontmatterCache.delete(file.path); + } + return; + } + if (typeof newIconName !== 'string') { + new obsidian.Notice(`[${config.PLUGIN_NAME}] Frontmatter property type \`icon\` has to be of type \`text\`.`); + return; + } + if (newIconColor && typeof newIconColor !== 'string') { + new obsidian.Notice(`[${config.PLUGIN_NAME}] Frontmatter property type \`iconColor\` has to be of type \`text\`.`); + return; + } + let iconColor = newIconColor; + if (isHexadecimal(iconColor)) { + iconColor = stringToHex(iconColor); + } + const cachedIcon = IconCache.getInstance().get(file.path); + if (newIconName === (cachedIcon === null || cachedIcon === void 0 ? void 0 : cachedIcon.iconNameWithPrefix) && + iconColor === (cachedIcon === null || cachedIcon === void 0 ? void 0 : cachedIcon.iconColor)) { + return; + } + this.frontmatterCache.add(file.path); + try { + if (!emoji.isEmoji(newIconName)) { + saveIconToIconPack(this, newIconName); + } + } + catch (e) { + logger.warn(`Something went wrong while saving icon to icon pack (error: ${e})`); + new obsidian.Notice(e.message); + return; + } + dom.createIconNode(this, file.path, newIconName, { + color: iconColor, + }); + this.addFolderIcon(file.path, newIconName); + this.addIconColor(file.path, iconColor); + IconCache.getInstance().set(file.path, { + iconNameWithPrefix: newIconName, + iconColor, + }); + // Update icon in tab when setting is enabled. + if (this.getSettings().iconInTabsEnabled) { + const tabLeaves = iconTabs.getTabLeavesOfFilePath(this, file.path); + for (const tabLeaf of tabLeaves) { + iconTabs.update(this, newIconName, tabLeaf.tabHeaderInnerIconEl); + } + } + // Update icon in title when setting is enabled. + if (this.getSettings().iconInTitleEnabled) { + this.addIconInTitle(newIconName); + } + } + }))); + // Register active leaf change event for adding icon of file to tab. + this.registerEvent(this.app.workspace.on('active-leaf-change', (leaf) => { + if (!this.getSettings().iconInTabsEnabled) { + return; + } + // TODO: Maybe change in the future to a more optimal solution. + // Fixes a problem when the file was clicked twice in the same tab. + // See https://github.com/FlorianWoelki/obsidian-iconize/issues/208. + if (leaf.view.getViewType() === 'file-explorer') { + for (const openedFile of getAllOpenedFiles(this)) { + const leaf = openedFile.leaf; + const iconColor = this.getIconColor(leaf.view.file.path); + iconTabs.add(this, openedFile.path, leaf.tabHeaderInnerIconEl, { + iconColor, + }); + } + return; + } + if (leaf.view.getViewType() !== 'markdown') { + return; + } + const tabHeaderLeaf = leaf; + if (tabHeaderLeaf.view.file) { + const iconColor = this.getIconColor(tabHeaderLeaf.view.file.path); + iconTabs.add(this, tabHeaderLeaf.view.file.path, tabHeaderLeaf.tabHeaderInnerIconEl, { + iconColor, + }); + } + })); + this.registerEvent(this.app.workspace.on('css-change', () => { + for (const openedFile of getAllOpenedFiles(this)) { + const activeView = openedFile.leaf.view; + if (activeView instanceof obsidian.MarkdownView) { + titleIcon.updateStyle(activeView.inlineTitleEl, { + fontSize: calculateInlineTitleSize(), + }); + } + } + })); + }); + } + addIconInTitle(iconName) { + var _a; + for (const openedFile of getAllOpenedFiles(this)) { + const activeView = openedFile.leaf.view; + if (activeView instanceof obsidian.MarkdownView) { + let possibleIcon = iconName; + if (!emoji.isEmoji(iconName)) { + possibleIcon = (_a = icon.getIconByName(iconName)) === null || _a === void 0 ? void 0 : _a.svgElement; + } + if (possibleIcon) { + titleIcon.add(this, activeView.inlineTitleEl, possibleIcon, { + fontSize: calculateInlineTitleSize(), + }); + } + } + } + } + onunload() { + console.log('unloading obsidian-icon-folder'); + } + renameFolder(newPath, oldPath) { + if (!this.data[oldPath] || newPath === oldPath) { + return; + } + Object.defineProperty(this.data, newPath, Object.getOwnPropertyDescriptor(this.data, oldPath)); + delete this.data[oldPath]; + this.saveIconFolderData(); + } + addIconColor(path, iconColor) { + const pathData = this.getData()[path]; + if (typeof pathData === 'string') { + this.getData()[path] = { + iconName: pathData, + iconColor, + }; + } + else { + pathData.iconColor = iconColor; + } + this.saveIconFolderData(); + } + getIconColor(path) { + const pathData = this.getData()[path]; + if (!pathData) { + return undefined; + } + if (typeof pathData === 'string') { + return undefined; + } + return pathData.iconColor; + } + removeIconColor(path) { + const pathData = this.getData()[path]; + if (typeof pathData === 'string') { + return; + } + const currentValue = pathData; + this.getData()[path] = currentValue.iconName; + this.saveIconFolderData(); + } + removeFolderIcon(path) { + if (!this.data[path]) { + return; + } + // Saves the icon name with prefix to remove it from the icon pack directory later. + const iconData = this.data[path]; + delete this.data[path]; + // Removes the icon from the icon pack directory if it is not used as an icon somewhere + // else. + if (iconData) { + let iconNameWithPrefix = iconData; + if (typeof iconData === 'object') { + iconNameWithPrefix = iconData.iconName; + } + else { + iconNameWithPrefix = iconData; + } + if (!emoji.isEmoji(iconNameWithPrefix)) { + removeIconFromIconPack(this, iconNameWithPrefix); + } + } + //this.addIconsToSearch(); + this.saveIconFolderData(); + } + addFolderIcon(path, icon) { + const iconName = getNormalizedName(typeof icon === 'object' ? icon.displayName : icon); + this.data[path] = iconName; + // Update recently used icons. + if (!this.getSettings().recentlyUsedIcons.includes(iconName)) { + if (this.getSettings().recentlyUsedIcons.length >= + this.getSettings().recentlyUsedIconsSize) { + this.getSettings().recentlyUsedIcons = + this.getSettings().recentlyUsedIcons.slice(0, this.getSettings().recentlyUsedIconsSize - 1); + } + this.getSettings().recentlyUsedIcons.unshift(iconName); + this.checkRecentlyUsedIcons(); + } + //this.addIconsToSearch(); + this.saveIconFolderData(); + } + getSettings() { + return this.data.settings; + } + loadIconFolderData() { + return __awaiter(this, void 0, void 0, function* () { + const data = yield this.loadData(); + if (data) { + Object.entries(DEFAULT_SETTINGS).forEach(([k, v]) => { + if (data.settings[k] === undefined) { + data.settings[k] = v; + } + }); + } + this.data = Object.assign({ settings: Object.assign({}, DEFAULT_SETTINGS) }, {}, data); + }); + } + saveIconFolderData() { + return __awaiter(this, void 0, void 0, function* () { + yield this.saveData(this.data); + }); + } + checkRecentlyUsedIcons() { + return __awaiter(this, void 0, void 0, function* () { + if (this.getSettings().recentlyUsedIcons.length > + this.getSettings().recentlyUsedIconsSize) { + this.getSettings().recentlyUsedIcons = + this.getSettings().recentlyUsedIcons.slice(0, this.getSettings().recentlyUsedIconsSize); + yield this.saveIconFolderData(); + } + }); + } + getEventEmitter() { + return this.eventEmitter; + } + getData() { + return this.data; + } + getIconNameFromPath(path) { + if (typeof this.getData()[path] === 'object') { + return this.getData()[path].iconName; + } + return this.getData()[path]; + } + getRegisteredFileExplorers() { + return this.registeredFileExplorers; + } + doesUseCustomLucideIconPack() { + return this.getSettings().lucideIconPackType === 'custom'; + } + doesUseNativeLucideIconPack() { + return this.getSettings().lucideIconPackType === 'native'; + } + /** + * Returns a possible data path by the given value. This function checks for + * direct icon and custom rules. + * @param value String that will be used to find the data path. + * @returns String that is the data path or `undefined` if no data path was found. + */ + getDataPathByValue(value) { + return Object.entries(this.data).find(([k, v]) => { + if (typeof v === 'string') { + if (value === v) { + return k; + } + } + else if (typeof v === 'object') { + // Check for custom rules. + if (k === 'settings') { + // `rules` are defined in the settings object. + const rules = v.rules; + return rules.find((rule) => rule.icon === value); + } + v = v; + if (value === v.iconName) { + return k; + } + } + }); + } +} + +module.exports = IconizePlugin; + + +/* nosourcemap */ \ No newline at end of file diff --git a/.obsidian/plugins/obsidian-icon-folder/manifest.json b/.obsidian/plugins/obsidian-icon-folder/manifest.json new file mode 100644 index 0000000..6e916c3 --- /dev/null +++ b/.obsidian/plugins/obsidian-icon-folder/manifest.json @@ -0,0 +1,10 @@ +{ + "id": "obsidian-icon-folder", + "name": "Iconize", + "version": "2.14.7", + "minAppVersion": "0.9.12", + "description": "Add icons to anything you desire in Obsidian, including files, folders, and text.", + "author": "Florian Woelki", + "authorUrl": "https://florianwoelki.com/", + "isDesktopOnly": false +} diff --git a/.obsidian/plugins/obsidian-icon-folder/styles.css b/.obsidian/plugins/obsidian-icon-folder/styles.css new file mode 100644 index 0000000..a74fdd4 --- /dev/null +++ b/.obsidian/plugins/obsidian-icon-folder/styles.css @@ -0,0 +1,120 @@ +.iconize-inline-title-wrapper { + width: var(--line-width); + max-width: var(--max-width); + margin-inline: var(--content-margin); +} + +.iconize-title-icon { + max-width: var(--max-width); + margin-right: var(--size-4-2); +} + +.iconize-icon-in-link { + transform: translateY(20%); + margin-right: var(--size-2-2); + display: inline-flex; +} + +.iconize-icon { + border: 1px solid transparent; + margin: 0px 4px 0px 0px; + display: flex; + align-self: center; + margin: auto 0; +} + +.nav-folder-title, +.nav-file-title { + align-items: center; +} + +.iconize-setting input[type='color'] { + margin: 0 6px; +} + +.iconize-modal.prompt-results { + margin: 0; + overflow-y: auto; + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)); +} + +.prompt .iconize-subheadline { + margin-top: 12px; + font-size: 12px; + color: gray; + grid-column-start: 1; + grid-column-end: 6; +} + +@media (max-width: 640px) { + .iconize-modal.prompt-results { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } + .prompt .iconize-subheadline { + grid-column-end: 4; + } +} + +.iconize-modal.prompt-results .suggestion-item { + cursor: pointer; + white-space: pre-wrap; + display: flex; + justify-content: flex-end; + align-items: center; + flex-direction: column-reverse; + text-align: center; + font-size: 13px; + color: var(--text-muted); + padding: 16px 8px; + line-break: auto; + word-break: break-word; + line-height: 1.3; +} + +.iconize-modal.prompt-results .suggestion-item.suggestion-item__center { + justify-content: center; +} + +.iconize-icon-preview { + font-size: 22px; +} + +.iconize-icon-preview img { + width: 16px; + height: 16px; +} + +.iconize-icon-preview svg { + width: 24px; + height: 24px; + color: currentColor; + margin-bottom: 4px; +} + +.iconize-dragover { + position: relative; +} + +.iconize-dragover-el { + position: absolute; + width: 100%; + height: 100%; + color: var(--text-normal); + background-color: var(--background-secondary-alt); + display: flex; + align-items: center; + justify-content: center; +} + +/* Custom rule modal. */ +.iconize-custom-modal .modal-content { + display: flex; + align-items: center; + justify-content: center; +} + +.iconize-custom-modal .modal-content input { + width: 100%; + margin-right: 0.5rem; +} diff --git a/.obsidian/plugins/tasknotes/data.json b/.obsidian/plugins/tasknotes/data.json new file mode 100644 index 0000000..1ca95e7 --- /dev/null +++ b/.obsidian/plugins/tasknotes/data.json @@ -0,0 +1,492 @@ +{ + "tasksFolder": "TaskNotes/Tasks", + "moveArchivedTasks": false, + "archiveFolder": "TaskNotes/Archive", + "taskTag": "task", + "taskIdentificationMethod": "tag", + "hideIdentifyingTagsInCards": false, + "hideIdentifyingTagsMode": "all", + "taskPropertyName": "", + "taskPropertyValue": "", + "excludedFolders": "", + "defaultTaskPriority": "normal", + "defaultTaskStatus": "open", + "taskOrgFiltersCollapsed": false, + "taskFilenameFormat": "zettel", + "storeTitleInFilename": true, + "customFilenameTemplate": "{{title}}", + "occurrenceFilenameTemplate": "", + "occurrenceFilenameTemplateProperty": "occurrenceFilenameTemplate", + "taskCreationDefaults": { + "defaultContexts": "", + "defaultTags": "", + "defaultProjects": "", + "useParentNoteForTaskCreation": false, + "useParentNoteAsProject": false, + "useParentHeaderAsProject": false, + "inheritParentTaskProperties": false, + "defaultTimeEstimate": 0, + "defaultRecurrence": "none", + "defaultDueDate": "none", + "defaultDueTime": "none", + "defaultScheduledDate": "today", + "defaultScheduledTime": "none", + "bodyTemplate": "", + "useBodyTemplate": false, + "occurrenceBodyTemplate": "", + "useOccurrenceBodyTemplate": false, + "defaultReminders": [] + }, + "openTaskAfterCreation": "none", + "calendarViewSettings": { + "defaultView": "dayGridMonth", + "customDayCount": 3, + "slotDuration": "00:30:00", + "slotMinTime": "00:00:00", + "slotMaxTime": "24:00:00", + "scrollTime": "08:00:00", + "firstDay": 1, + "timeFormat": "24", + "showWeekends": true, + "locale": "", + "defaultShowScheduled": true, + "defaultShowDue": true, + "defaultShowDueWhenScheduled": true, + "defaultShowScheduledToDueSpan": false, + "defaultShowTimeEntries": false, + "defaultShowRecurring": true, + "defaultShowICSEvents": true, + "enableTimeblocking": false, + "defaultShowTimeblocks": true, + "defaultTimeblockColor": "#6366f1", + "timeblockAttachmentSearchOrder": "name-asc", + "nowIndicator": true, + "selectMirror": true, + "weekNumbers": false, + "showTodayHighlight": true, + "eventMinHeight": 15, + "slotEventOverlap": true, + "eventMaxStack": null, + "dayMaxEvents": true, + "dayMaxEventRows": false + }, + "pomodoroWorkDuration": 25, + "pomodoroShortBreakDuration": 5, + "pomodoroLongBreakDuration": 15, + "pomodoroLongBreakInterval": 4, + "pomodoroAutoStartBreaks": true, + "pomodoroAutoStartWork": false, + "pomodoroNotifications": true, + "pomodoroSoundEnabled": true, + "pomodoroSoundVolume": 50, + "pomodoroStorageLocation": "plugin", + "pomodoroMobileSidebar": "tab", + "showPomodoroInStatusBar": true, + "enableTaskLinkOverlay": true, + "disableOverlayOnAlias": false, + "enableInstantTaskConvert": true, + "useDefaultsOnInstantConvert": true, + "preserveCheckboxOnConvert": false, + "taskModalTabMovesFocus": true, + "enableNaturalLanguageInput": true, + "nlpDefaultToScheduled": true, + "nlpLanguage": "en", + "uiLanguage": "system", + "statusSuggestionTrigger": "*", + "nlpTriggers": { + "triggers": [ + { + "propertyId": "tags", + "trigger": "#", + "enabled": true + }, + { + "propertyId": "contexts", + "trigger": "@", + "enabled": true + }, + { + "propertyId": "projects", + "trigger": "+", + "enabled": true + }, + { + "propertyId": "status", + "trigger": "*", + "enabled": true + }, + { + "propertyId": "priority", + "trigger": "!", + "enabled": false + } + ] + }, + "singleClickAction": "edit", + "doubleClickAction": "openNote", + "projectAutosuggest": { + "enableFuzzy": false, + "rows": [ + "{title|n(Title)}", + "{aliases|n(Aliases)}", + "{file.path|n(Path)}" + ], + "showAdvanced": false, + "requiredTags": [], + "includeFolders": [], + "propertyKey": "", + "propertyValue": "" + }, + "inlineTaskConvertFolder": "{{currentNotePath}}", + "disableNoteIndexing": false, + "suggestionDebounceMs": 0, + "fieldMapping": { + "title": "title", + "status": "status", + "priority": "priority", + "due": "due", + "scheduled": "scheduled", + "contexts": "contexts", + "projects": "projects", + "attachments": "attachments", + "timeEstimate": "timeEstimate", + "completedDate": "completedDate", + "dateCreated": "dateCreated", + "dateModified": "dateModified", + "recurrence": "recurrence", + "recurrenceAnchor": "recurrence_anchor", + "recurrenceParent": "recurrence_parent", + "occurrenceDate": "occurrence_date", + "occurrenceMaterialization": "occurrence_materialization", + "occurrenceNextTrigger": "occurrence_next_trigger", + "occurrenceTemplate": "occurrence_template", + "occurrencePastHorizon": "occurrence_past_horizon", + "occurrenceFutureHorizon": "occurrence_future_horizon", + "archiveTag": "archived", + "timeEntries": "timeEntries", + "completeInstances": "complete_instances", + "skippedInstances": "skipped_instances", + "blockedBy": "blockedBy", + "pomodoros": "pomodoros", + "icsEventId": "icsEventId", + "icsEventTag": "ics_event", + "googleCalendarEventId": "googleCalendarEventId", + "googleCalendarExceptionEventId": "googleCalendarExceptionEventId", + "googleCalendarExceptionOriginalScheduled": "googleCalendarExceptionOriginalScheduled", + "googleCalendarMovedOriginalDates": "googleCalendarMovedOriginalDates", + "reminders": "reminders", + "sortOrder": "tasknotes_manual_order" + }, + "customStatuses": [ + { + "id": "none", + "value": "none", + "label": "None", + "color": "#cccccc", + "isCompleted": false, + "excludeFromCycle": false, + "order": 0, + "autoArchive": false, + "autoArchiveDelay": 5 + }, + { + "id": "open", + "value": "open", + "label": "Open", + "color": "#808080", + "isCompleted": false, + "excludeFromCycle": false, + "order": 1, + "autoArchive": false, + "autoArchiveDelay": 5 + }, + { + "id": "in-progress", + "value": "in-progress", + "label": "In progress", + "color": "#0066cc", + "isCompleted": false, + "excludeFromCycle": false, + "order": 2, + "autoArchive": false, + "autoArchiveDelay": 5 + }, + { + "id": "done", + "value": "done", + "label": "Done", + "color": "#00aa00", + "isCompleted": true, + "excludeFromCycle": false, + "order": 3, + "autoArchive": false, + "autoArchiveDelay": 5 + } + ], + "customPriorities": [ + { + "id": "none", + "value": "none", + "label": "None", + "color": "#cccccc", + "weight": 0 + }, + { + "id": "low", + "value": "low", + "label": "Low", + "color": "#00aa00", + "weight": 1 + }, + { + "id": "normal", + "value": "normal", + "label": "Normal", + "color": "#ffaa00", + "weight": 2 + }, + { + "id": "high", + "value": "high", + "label": "High", + "color": "#ff0000", + "weight": 3 + } + ], + "recurrenceMigrated": false, + "showReleaseNotesOnUpdate": true, + "checkForUpdatesOnStartup": true, + "starterNoteCreated": true, + "showTrackedTasksInStatusBar": false, + "autoStopTimeTrackingOnComplete": true, + "autoStopTimeTrackingNotification": false, + "showRelationships": true, + "relationshipsPosition": "bottom", + "showTaskCardInNote": true, + "showCompletedTaskStrikethrough": true, + "completionMenuAsSubmenu": true, + "showExpandableSubtasks": true, + "expandSubtasksByDefault": false, + "subtaskChevronPosition": "right", + "viewsButtonAlignment": "right", + "hideCompletedFromOverdue": true, + "icsIntegration": { + "defaultNoteTemplate": "", + "defaultNoteFolder": "", + "icsNoteFilenameFormat": "title", + "customICSNoteFilenameTemplate": "{title}", + "enableAutoExport": false, + "autoExportPath": "tasknotes-calendar.ics", + "autoExportInterval": 60, + "useDurationForExport": false, + "excludeArchivedFromExport": false, + "excludeCompletedFromExport": false, + "requireDueDateForExport": false, + "requireScheduledDateForExport": false, + "useICSEndAsDue": false, + "recurringEventRelatedNotesMode": "series" + }, + "savedViews": [], + "enableNotifications": true, + "notificationType": "system", + "notificationSoundEnabled": false, + "notificationSoundVolume": 50, + "enableAPI": false, + "apiPort": 8080, + "apiAuthToken": "", + "enableMCP": false, + "webhooks": [], + "userFields": [], + "modalFieldsConfig": { + "version": 1, + "fields": [ + { + "id": "title", + "fieldType": "core", + "group": "basic", + "displayName": "Title", + "visibleInCreation": true, + "visibleInEdit": true, + "order": 0, + "enabled": true, + "required": true + }, + { + "id": "details", + "fieldType": "core", + "group": "basic", + "displayName": "Details", + "visibleInCreation": true, + "visibleInEdit": true, + "order": 1, + "enabled": true + }, + { + "id": "contexts", + "fieldType": "core", + "group": "metadata", + "displayName": "Contexts", + "visibleInCreation": true, + "visibleInEdit": true, + "order": 0, + "enabled": true + }, + { + "id": "tags", + "fieldType": "core", + "group": "metadata", + "displayName": "Tags", + "visibleInCreation": true, + "visibleInEdit": true, + "order": 1, + "enabled": true + }, + { + "id": "time-estimate", + "fieldType": "core", + "group": "metadata", + "displayName": "Time Estimate", + "visibleInCreation": true, + "visibleInEdit": true, + "order": 2, + "enabled": true + }, + { + "id": "projects", + "fieldType": "organization", + "group": "organization", + "displayName": "Projects", + "visibleInCreation": true, + "visibleInEdit": true, + "order": 0, + "enabled": true + }, + { + "id": "subtasks", + "fieldType": "organization", + "group": "organization", + "displayName": "Subtasks", + "visibleInCreation": true, + "visibleInEdit": true, + "order": 1, + "enabled": true + }, + { + "id": "blocked-by", + "fieldType": "dependency", + "group": "dependencies", + "displayName": "Blocked By", + "visibleInCreation": true, + "visibleInEdit": true, + "order": 0, + "enabled": true + }, + { + "id": "blocking", + "fieldType": "dependency", + "group": "dependencies", + "displayName": "Blocking", + "visibleInCreation": true, + "visibleInEdit": true, + "order": 1, + "enabled": true + } + ], + "groups": [ + { + "id": "basic", + "displayName": "Basic Information", + "order": 0, + "collapsible": false, + "defaultCollapsed": false + }, + { + "id": "metadata", + "displayName": "Metadata", + "order": 1, + "collapsible": true, + "defaultCollapsed": false + }, + { + "id": "organization", + "displayName": "Organization", + "order": 2, + "collapsible": true, + "defaultCollapsed": false + }, + { + "id": "dependencies", + "displayName": "Dependencies", + "order": 3, + "collapsible": true, + "defaultCollapsed": false + }, + { + "id": "custom", + "displayName": "Custom Fields", + "order": 4, + "collapsible": true, + "defaultCollapsed": false + } + ] + }, + "enableModalSplitLayout": true, + "defaultVisibleProperties": [ + "status", + "priority", + "due", + "scheduled", + "projects", + "contexts", + "tags", + "blocked", + "blocking" + ], + "inlineVisibleProperties": [ + "status", + "priority", + "due", + "scheduled", + "recurrence" + ], + "enableBases": true, + "enableMdbaseSpec": false, + "autoCreateDefaultBasesFiles": true, + "commandFileMapping": { + "open-calendar-view": "TaskNotes/Views/mini-calendar-default.base", + "open-kanban-view": "TaskNotes/Views/kanban-default.base", + "open-tasks-view": "TaskNotes/Views/tasks-default.base", + "open-advanced-calendar-view": "TaskNotes/Views/calendar-default.base", + "open-agenda-view": "TaskNotes/Views/agenda-default.base", + "pomodoro-stats-base": "TaskNotes/Views/pomodoro-stats.base", + "relationships": "TaskNotes/Views/relationships.base" + }, + "maintainDueDateOffsetInRecurring": false, + "resetCheckboxesOnRecurrence": false, + "useFrontmatterMarkdownLinks": false, + "enableGoogleCalendar": false, + "enableMicrosoftCalendar": false, + "disableCalendarOnMobile": false, + "enabledGoogleCalendars": [], + "googleCalendarSyncTokens": {}, + "enabledMicrosoftCalendars": [], + "microsoftCalendarSyncTokens": {}, + "googleCalendarExport": { + "enabled": false, + "targetCalendarId": "", + "syncOnTaskCreate": true, + "syncOnTaskUpdate": true, + "syncOnTaskComplete": true, + "syncOnTaskDelete": true, + "eventTitleTemplate": "{{title}}", + "includeDescription": true, + "eventColorId": null, + "syncTrigger": "scheduled", + "createAsAllDay": true, + "defaultEventDuration": 60, + "includeObsidianLink": true, + "defaultReminderMinutes": null + }, + "enableDebugLogging": false, + "lastSeenVersion": "4.13.5" +} \ No newline at end of file diff --git a/.obsidian/plugins/tasknotes/main.js b/.obsidian/plugins/tasknotes/main.js new file mode 100644 index 0000000..7d2c40a --- /dev/null +++ b/.obsidian/plugins/tasknotes/main.js @@ -0,0 +1,3683 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ESBUILD +if you want to view the source, please visit the github repository of this plugin +*/ + +var vFe=Object.create;var Fg=Object.defineProperty;var oK=Object.getOwnPropertyDescriptor;var kFe=Object.getOwnPropertyNames;var TFe=Object.getPrototypeOf,bFe=Object.prototype.hasOwnProperty;var lK=n=>{throw TypeError(n)};var wFe=(n,e,t)=>e in n?Fg(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var y=(n,e)=>()=>(n&&(e=n(n=0)),e);var te=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Xe=(n,e)=>{for(var t in e)Fg(n,t,{get:e[t],enumerable:!0})},cK=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of kFe(e))!bFe.call(n,a)&&a!==t&&Fg(n,a,{get:()=>e[a],enumerable:!(r=oK(e,a))||r.enumerable});return n};var tt=(n,e,t)=>(t=n!=null?vFe(TFe(n)):{},cK(e||!n||!n.__esModule?Fg(t,"default",{value:n,enumerable:!0}):t,n)),BP=n=>cK(Fg({},"__esModule",{value:!0}),n),Qe=(n,e,t,r)=>{for(var a=r>1?void 0:r?oK(e,t):e,i=n.length-1,s;i>=0;i--)(s=n[i])&&(a=(r?s(e,t,a):s(a))||a);return r&&a&&Fg(e,t,a),a};var z=(n,e,t)=>wFe(n,typeof e!="symbol"?e+"":e,t),dK=(n,e,t)=>e.has(n)||lK("Cannot "+t);var un=(n,e,t)=>(dK(n,e,"read from private field"),t?t.call(n):e.get(n)),Al=(n,e,t)=>e.has(n)?lK("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),Us=(n,e,t,r)=>(dK(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t);var SFe,Aut,jP,uK,g1,y1,CFe,pK,Mut,xFe,EFe,Iut,v1,Lg=y(()=>{SFe=Math.pow(10,8)*24*60*60*1e3,Aut=-SFe,jP=6048e5,uK=864e5,g1=6e4,y1=36e5,CFe=3600,pK=CFe*24,Mut=pK*7,xFe=pK*365.2425,EFe=xFe/12,Iut=EFe*3,v1=Symbol.for("constructDateFrom")});function Tn(n,e){return typeof n=="function"?n(e):n&&typeof n=="object"&&v1 in n?n[v1](e):n instanceof Date?new n.constructor(e):new Date(e)}var Ho=y(()=>{Lg()});function ct(n,e){return Tn(e||n,n)}var pn=y(()=>{Ho()});function Jm(n,e,t){let r=ct(n,t==null?void 0:t.in);return isNaN(e)?Tn((t==null?void 0:t.in)||n,NaN):(e&&r.setDate(r.getDate()+e),r)}var $P=y(()=>{Ho();pn()});function UP(n,e,t){let r=ct(n,t==null?void 0:t.in);if(isNaN(e))return Tn((t==null?void 0:t.in)||n,NaN);if(!e)return r;let a=r.getDate(),i=Tn((t==null?void 0:t.in)||n,r.getTime());i.setMonth(r.getMonth()+e+1,0);let s=i.getDate();return a>=s?i:(r.setFullYear(i.getFullYear(),i.getMonth(),a),r)}var k1=y(()=>{Ho();pn()});var mK=y(()=>{});var fK=y(()=>{});var hK=y(()=>{});var gK=y(()=>{});var yK=y(()=>{});var vK=y(()=>{});var kK=y(()=>{});function Ml(){return DFe}var DFe,Og=y(()=>{DFe={}});function ni(n,e){var o,l,c,d,u,p,m,f;let t=Ml(),r=(f=(m=(d=(c=e==null?void 0:e.weekStartsOn)!=null?c:(l=(o=e==null?void 0:e.locale)==null?void 0:o.options)==null?void 0:l.weekStartsOn)!=null?d:t.weekStartsOn)!=null?m:(p=(u=t.locale)==null?void 0:u.options)==null?void 0:p.weekStartsOn)!=null?f:0,a=ct(n,e==null?void 0:e.in),i=a.getDay(),s=(i{Og();pn()});function Xm(n,e){return ni(n,{...e,weekStartsOn:1})}var ib=y(()=>{zg()});function HP(n,e){let t=ct(n,e==null?void 0:e.in),r=t.getFullYear(),a=Tn(t,0);a.setFullYear(r+1,0,4),a.setHours(0,0,0,0);let i=Xm(a),s=Tn(t,0);s.setFullYear(r,0,4),s.setHours(0,0,0,0);let o=Xm(s);return t.getTime()>=i.getTime()?r+1:t.getTime()>=o.getTime()?r:r-1}var VP=y(()=>{Ho();ib();pn()});function T1(n){let e=ct(n),t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),+n-+t}var TK=y(()=>{pn()});function WP(n,...e){let t=Tn.bind(null,n||e.find(r=>typeof r=="object"));return e.map(t)}var b1=y(()=>{Ho()});function Vo(n,e){let t=ct(n,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}var qP=y(()=>{pn()});function bK(n,e,t){let[r,a]=WP(t==null?void 0:t.in,n,e),i=Vo(r),s=Vo(a),o=+i-T1(i),l=+s-T1(s);return Math.round((o-l)/uK)}var w1=y(()=>{TK();b1();Lg();qP()});function wK(n,e){let t=HP(n,e),r=Tn((e==null?void 0:e.in)||n,0);return r.setFullYear(t,0,4),r.setHours(0,0,0,0),Xm(r)}var S1=y(()=>{Ho();VP();ib()});var SK=y(()=>{});var CK=y(()=>{});var xK=y(()=>{});var EK=y(()=>{});var DK=y(()=>{});function PK(n,e,t){return Jm(n,e*7,t)}var AK=y(()=>{$P()});function MK(n,e,t){return UP(n,e*12,t)}var IK=y(()=>{k1()});var NK=y(()=>{});var RK=y(()=>{});var _K=y(()=>{});var FK=y(()=>{});var LK=y(()=>{});var OK=y(()=>{});var zK=y(()=>{});var BK=y(()=>{});var jK=y(()=>{});var $K=y(()=>{});function C1(n,e,t){let[r,a]=WP(t==null?void 0:t.in,n,e);return+Vo(r)==+Vo(a)}var UK=y(()=>{b1();qP()});function HK(n){return n instanceof Date||typeof n=="object"&&Object.prototype.toString.call(n)==="[object Date]"}var x1=y(()=>{});function ta(n){return!(!HK(n)&&typeof n!="number"||isNaN(+ct(n)))}var E1=y(()=>{x1();pn()});var VK=y(()=>{});var WK=y(()=>{});var qK=y(()=>{});var GK=y(()=>{});var YK=y(()=>{});var KK=y(()=>{});var ZK=y(()=>{});var QK=y(()=>{});var JK=y(()=>{});var XK=y(()=>{});var e7=y(()=>{});var t7=y(()=>{});var r7=y(()=>{});var n7=y(()=>{});function sb(n,e){let t=ct(n,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}var a7=y(()=>{pn()});function GP(n,e){let t=ct(n,e==null?void 0:e.in),r=t.getMonth();return t.setFullYear(t.getFullYear(),r+1,0),t.setHours(23,59,59,999),t}var i7=y(()=>{pn()});var s7=y(()=>{});var o7=y(()=>{});var l7=y(()=>{});var c7=y(()=>{});var d7=y(()=>{});var u7=y(()=>{});var p7=y(()=>{});var m7=y(()=>{});var f7=y(()=>{});var h7=y(()=>{});var g7=y(()=>{});var y7=y(()=>{});var v7=y(()=>{});var k7=y(()=>{});function YP(n,e){let t=ct(n,e==null?void 0:e.in);return t.setDate(1),t.setHours(0,0,0,0),t}var T7=y(()=>{pn()});var b7=y(()=>{});function w7(n,e){let t=ct(n,e==null?void 0:e.in),r=t.getFullYear();return t.setFullYear(r+1,0,0),t.setHours(23,59,59,999),t}var S7=y(()=>{pn()});function KP(n,e){let t=ct(n,e==null?void 0:e.in);return t.setFullYear(t.getFullYear(),0,1),t.setHours(0,0,0,0),t}var D1=y(()=>{pn()});var C7=y(()=>{});var x7=y(()=>{});var E7=y(()=>{});var D7=y(()=>{});function Bg(n,e){var o,l,c,d,u,p,m,f;let t=Ml(),r=(f=(m=(d=(c=e==null?void 0:e.weekStartsOn)!=null?c:(l=(o=e==null?void 0:e.locale)==null?void 0:o.options)==null?void 0:l.weekStartsOn)!=null?d:t.weekStartsOn)!=null?m:(p=(u=t.locale)==null?void 0:u.options)==null?void 0:p.weekStartsOn)!=null?f:0,a=ct(n,e==null?void 0:e.in),i=a.getDay(),s=(i{Og();pn()});var A7=y(()=>{});var M7=y(()=>{});var I7=y(()=>{});var N7=y(()=>{});var R7=y(()=>{});var _7=y(()=>{});var F7=y(()=>{});var L7=y(()=>{});var PFe,O7,z7=y(()=>{PFe={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},O7=(n,e,t)=>{let r,a=PFe[n];return typeof a=="string"?r=a:e===1?r=a.one:r=a.other.replace("{{count}}",e.toString()),t!=null&&t.addSuffix?t.comparison&&t.comparison>0?"in "+r:r+" ago":r}});function ZP(n){return(e={})=>{let t=e.width?String(e.width):n.defaultWidth;return n.formats[t]||n.formats[n.defaultWidth]}}var B7=y(()=>{});var AFe,MFe,IFe,j7,$7=y(()=>{B7();AFe={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},MFe={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},IFe={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},j7={date:ZP({formats:AFe,defaultWidth:"full"}),time:ZP({formats:MFe,defaultWidth:"full"}),dateTime:ZP({formats:IFe,defaultWidth:"full"})}});var NFe,U7,H7=y(()=>{NFe={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},U7=(n,e,t,r)=>NFe[n]});function jg(n){return(e,t)=>{let r=t!=null&&t.context?String(t.context):"standalone",a;if(r==="formatting"&&n.formattingValues){let s=n.defaultFormattingWidth||n.defaultWidth,o=t!=null&&t.width?String(t.width):s;a=n.formattingValues[o]||n.formattingValues[s]}else{let s=n.defaultWidth,o=t!=null&&t.width?String(t.width):n.defaultWidth;a=n.values[o]||n.values[s]}let i=n.argumentCallback?n.argumentCallback(e):e;return a[i]}}var V7=y(()=>{});var RFe,_Fe,FFe,LFe,OFe,zFe,BFe,W7,q7=y(()=>{V7();RFe={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},_Fe={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},FFe={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},LFe={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},OFe={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},zFe={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},BFe=(n,e)=>{let t=Number(n),r=t%100;if(r>20||r<10)switch(r%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},W7={ordinalNumber:BFe,era:jg({values:RFe,defaultWidth:"wide"}),quarter:jg({values:_Fe,defaultWidth:"wide",argumentCallback:n=>n-1}),month:jg({values:FFe,defaultWidth:"wide"}),day:jg({values:LFe,defaultWidth:"wide"}),dayPeriod:jg({values:OFe,defaultWidth:"wide",formattingValues:zFe,defaultFormattingWidth:"wide"})}});function $g(n){return(e,t={})=>{let r=t.width,a=r&&n.matchPatterns[r]||n.matchPatterns[n.defaultMatchWidth],i=e.match(a);if(!i)return null;let s=i[0],o=r&&n.parsePatterns[r]||n.parsePatterns[n.defaultParseWidth],l=Array.isArray(o)?$Fe(o,u=>u.test(s)):jFe(o,u=>u.test(s)),c;c=n.valueCallback?n.valueCallback(l):l,c=t.valueCallback?t.valueCallback(c):c;let d=e.slice(s.length);return{value:c,rest:d}}}function jFe(n,e){for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&e(n[t]))return t}function $Fe(n,e){for(let t=0;t{});function Y7(n){return(e,t={})=>{let r=e.match(n.matchPattern);if(!r)return null;let a=r[0],i=e.match(n.parsePattern);if(!i)return null;let s=n.valueCallback?n.valueCallback(i[0]):i[0];s=t.valueCallback?t.valueCallback(s):s;let o=e.slice(a.length);return{value:s,rest:o}}}var K7=y(()=>{});var UFe,HFe,VFe,WFe,qFe,GFe,YFe,KFe,ZFe,QFe,JFe,XFe,Z7,Q7=y(()=>{G7();K7();UFe=/^(\d+)(th|st|nd|rd)?/i,HFe=/\d+/i,VFe={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},WFe={any:[/^b/i,/^(a|c)/i]},qFe={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},GFe={any:[/1/i,/2/i,/3/i,/4/i]},YFe={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},KFe={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},ZFe={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},QFe={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},JFe={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},XFe={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},Z7={ordinalNumber:Y7({matchPattern:UFe,parsePattern:HFe,valueCallback:n=>parseInt(n,10)}),era:$g({matchPatterns:VFe,defaultMatchWidth:"wide",parsePatterns:WFe,defaultParseWidth:"any"}),quarter:$g({matchPatterns:qFe,defaultMatchWidth:"wide",parsePatterns:GFe,defaultParseWidth:"any",valueCallback:n=>n+1}),month:$g({matchPatterns:YFe,defaultMatchWidth:"wide",parsePatterns:KFe,defaultParseWidth:"any"}),day:$g({matchPatterns:ZFe,defaultMatchWidth:"wide",parsePatterns:QFe,defaultParseWidth:"any"}),dayPeriod:$g({matchPatterns:JFe,defaultMatchWidth:"any",parsePatterns:XFe,defaultParseWidth:"any"})}});var P1,J7=y(()=>{z7();$7();H7();q7();Q7();P1={code:"en-US",formatDistance:O7,formatLong:j7,formatRelative:U7,localize:W7,match:Z7,options:{weekStartsOn:0,firstWeekContainsDate:1}}});var X7=y(()=>{J7()});function eZ(n,e){let t=ct(n,e==null?void 0:e.in);return bK(t,KP(t))+1}var A1=y(()=>{w1();D1();pn()});function tZ(n,e){let t=ct(n,e==null?void 0:e.in),r=+Xm(t)-+wK(t);return Math.round(r/jP)+1}var M1=y(()=>{Lg();ib();S1();pn()});function QP(n,e){var d,u,p,m,f,h,g,v;let t=ct(n,e==null?void 0:e.in),r=t.getFullYear(),a=Ml(),i=(v=(g=(m=(p=e==null?void 0:e.firstWeekContainsDate)!=null?p:(u=(d=e==null?void 0:e.locale)==null?void 0:d.options)==null?void 0:u.firstWeekContainsDate)!=null?m:a.firstWeekContainsDate)!=null?g:(h=(f=a.locale)==null?void 0:f.options)==null?void 0:h.firstWeekContainsDate)!=null?v:1,s=Tn((e==null?void 0:e.in)||n,0);s.setFullYear(r+1,0,i),s.setHours(0,0,0,0);let o=ni(s,e),l=Tn((e==null?void 0:e.in)||n,0);l.setFullYear(r,0,i),l.setHours(0,0,0,0);let c=ni(l,e);return+t>=+o?r+1:+t>=+c?r:r-1}var JP=y(()=>{Og();Ho();zg();pn()});function rZ(n,e){var o,l,c,d,u,p,m,f;let t=Ml(),r=(f=(m=(d=(c=e==null?void 0:e.firstWeekContainsDate)!=null?c:(l=(o=e==null?void 0:e.locale)==null?void 0:o.options)==null?void 0:l.firstWeekContainsDate)!=null?d:t.firstWeekContainsDate)!=null?m:(p=(u=t.locale)==null?void 0:u.options)==null?void 0:p.firstWeekContainsDate)!=null?f:1,a=QP(n,e),i=Tn((e==null?void 0:e.in)||n,0);return i.setFullYear(a,0,r),i.setHours(0,0,0,0),ni(i,e)}var I1=y(()=>{Og();Ho();JP();zg()});function nZ(n,e){let t=ct(n,e==null?void 0:e.in),r=+ni(t,e)-+rZ(t,e);return Math.round(r/jP)+1}var N1=y(()=>{Lg();zg();I1();pn()});function ar(n,e){let t=n<0?"-":"",r=Math.abs(n).toString().padStart(e,"0");return t+r}var R1=y(()=>{});var sd,aZ=y(()=>{R1();sd={y(n,e){let t=n.getFullYear(),r=t>0?t:1-t;return ar(e==="yy"?r%100:r,e.length)},M(n,e){let t=n.getMonth();return e==="M"?String(t+1):ar(t+1,2)},d(n,e){return ar(n.getDate(),e.length)},a(n,e){let t=n.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];case"aaaa":default:return t==="am"?"a.m.":"p.m."}},h(n,e){return ar(n.getHours()%12||12,e.length)},H(n,e){return ar(n.getHours(),e.length)},m(n,e){return ar(n.getMinutes(),e.length)},s(n,e){return ar(n.getSeconds(),e.length)},S(n,e){let t=e.length,r=n.getMilliseconds(),a=Math.trunc(r*Math.pow(10,t-3));return ar(a,e.length)}}});function iZ(n,e=""){let t=n>0?"-":"+",r=Math.abs(n),a=Math.trunc(r/60),i=r%60;return i===0?t+String(a):t+String(a)+e+ar(i,2)}function sZ(n,e){return n%60===0?(n>0?"-":"+")+ar(Math.abs(n)/60,2):ef(n,e)}function ef(n,e=""){let t=n>0?"-":"+",r=Math.abs(n),a=ar(Math.trunc(r/60),2),i=ar(r%60,2);return t+a+e+i}var Ug,_1,oZ=y(()=>{A1();M1();VP();N1();JP();R1();aZ();Ug={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},_1={G:function(n,e,t){let r=n.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return t.era(r,{width:"abbreviated"});case"GGGGG":return t.era(r,{width:"narrow"});case"GGGG":default:return t.era(r,{width:"wide"})}},y:function(n,e,t){if(e==="yo"){let r=n.getFullYear(),a=r>0?r:1-r;return t.ordinalNumber(a,{unit:"year"})}return sd.y(n,e)},Y:function(n,e,t,r){let a=QP(n,r),i=a>0?a:1-a;if(e==="YY"){let s=i%100;return ar(s,2)}return e==="Yo"?t.ordinalNumber(i,{unit:"year"}):ar(i,e.length)},R:function(n,e){let t=HP(n);return ar(t,e.length)},u:function(n,e){let t=n.getFullYear();return ar(t,e.length)},Q:function(n,e,t){let r=Math.ceil((n.getMonth()+1)/3);switch(e){case"Q":return String(r);case"QQ":return ar(r,2);case"Qo":return t.ordinalNumber(r,{unit:"quarter"});case"QQQ":return t.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return t.quarter(r,{width:"wide",context:"formatting"})}},q:function(n,e,t){let r=Math.ceil((n.getMonth()+1)/3);switch(e){case"q":return String(r);case"qq":return ar(r,2);case"qo":return t.ordinalNumber(r,{unit:"quarter"});case"qqq":return t.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return t.quarter(r,{width:"wide",context:"standalone"})}},M:function(n,e,t){let r=n.getMonth();switch(e){case"M":case"MM":return sd.M(n,e);case"Mo":return t.ordinalNumber(r+1,{unit:"month"});case"MMM":return t.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return t.month(r,{width:"wide",context:"formatting"})}},L:function(n,e,t){let r=n.getMonth();switch(e){case"L":return String(r+1);case"LL":return ar(r+1,2);case"Lo":return t.ordinalNumber(r+1,{unit:"month"});case"LLL":return t.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return t.month(r,{width:"wide",context:"standalone"})}},w:function(n,e,t,r){let a=nZ(n,r);return e==="wo"?t.ordinalNumber(a,{unit:"week"}):ar(a,e.length)},I:function(n,e,t){let r=tZ(n);return e==="Io"?t.ordinalNumber(r,{unit:"week"}):ar(r,e.length)},d:function(n,e,t){return e==="do"?t.ordinalNumber(n.getDate(),{unit:"date"}):sd.d(n,e)},D:function(n,e,t){let r=eZ(n);return e==="Do"?t.ordinalNumber(r,{unit:"dayOfYear"}):ar(r,e.length)},E:function(n,e,t){let r=n.getDay();switch(e){case"E":case"EE":case"EEE":return t.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(r,{width:"short",context:"formatting"});case"EEEE":default:return t.day(r,{width:"wide",context:"formatting"})}},e:function(n,e,t,r){let a=n.getDay(),i=(a-r.weekStartsOn+8)%7||7;switch(e){case"e":return String(i);case"ee":return ar(i,2);case"eo":return t.ordinalNumber(i,{unit:"day"});case"eee":return t.day(a,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(a,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(a,{width:"short",context:"formatting"});case"eeee":default:return t.day(a,{width:"wide",context:"formatting"})}},c:function(n,e,t,r){let a=n.getDay(),i=(a-r.weekStartsOn+8)%7||7;switch(e){case"c":return String(i);case"cc":return ar(i,e.length);case"co":return t.ordinalNumber(i,{unit:"day"});case"ccc":return t.day(a,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(a,{width:"narrow",context:"standalone"});case"cccccc":return t.day(a,{width:"short",context:"standalone"});case"cccc":default:return t.day(a,{width:"wide",context:"standalone"})}},i:function(n,e,t){let r=n.getDay(),a=r===0?7:r;switch(e){case"i":return String(a);case"ii":return ar(a,e.length);case"io":return t.ordinalNumber(a,{unit:"day"});case"iii":return t.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(r,{width:"short",context:"formatting"});case"iiii":default:return t.day(r,{width:"wide",context:"formatting"})}},a:function(n,e,t){let a=n.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return t.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(a,{width:"narrow",context:"formatting"});case"aaaa":default:return t.dayPeriod(a,{width:"wide",context:"formatting"})}},b:function(n,e,t){let r=n.getHours(),a;switch(r===12?a=Ug.noon:r===0?a=Ug.midnight:a=r/12>=1?"pm":"am",e){case"b":case"bb":return t.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(a,{width:"narrow",context:"formatting"});case"bbbb":default:return t.dayPeriod(a,{width:"wide",context:"formatting"})}},B:function(n,e,t){let r=n.getHours(),a;switch(r>=17?a=Ug.evening:r>=12?a=Ug.afternoon:r>=4?a=Ug.morning:a=Ug.night,e){case"B":case"BB":case"BBB":return t.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(a,{width:"narrow",context:"formatting"});case"BBBB":default:return t.dayPeriod(a,{width:"wide",context:"formatting"})}},h:function(n,e,t){if(e==="ho"){let r=n.getHours()%12;return r===0&&(r=12),t.ordinalNumber(r,{unit:"hour"})}return sd.h(n,e)},H:function(n,e,t){return e==="Ho"?t.ordinalNumber(n.getHours(),{unit:"hour"}):sd.H(n,e)},K:function(n,e,t){let r=n.getHours()%12;return e==="Ko"?t.ordinalNumber(r,{unit:"hour"}):ar(r,e.length)},k:function(n,e,t){let r=n.getHours();return r===0&&(r=24),e==="ko"?t.ordinalNumber(r,{unit:"hour"}):ar(r,e.length)},m:function(n,e,t){return e==="mo"?t.ordinalNumber(n.getMinutes(),{unit:"minute"}):sd.m(n,e)},s:function(n,e,t){return e==="so"?t.ordinalNumber(n.getSeconds(),{unit:"second"}):sd.s(n,e)},S:function(n,e){return sd.S(n,e)},X:function(n,e,t){let r=n.getTimezoneOffset();if(r===0)return"Z";switch(e){case"X":return sZ(r);case"XXXX":case"XX":return ef(r);case"XXXXX":case"XXX":default:return ef(r,":")}},x:function(n,e,t){let r=n.getTimezoneOffset();switch(e){case"x":return sZ(r);case"xxxx":case"xx":return ef(r);case"xxxxx":case"xxx":default:return ef(r,":")}},O:function(n,e,t){let r=n.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+iZ(r,":");case"OOOO":default:return"GMT"+ef(r,":")}},z:function(n,e,t){let r=n.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+iZ(r,":");case"zzzz":default:return"GMT"+ef(r,":")}},t:function(n,e,t){let r=Math.trunc(+n/1e3);return ar(r,e.length)},T:function(n,e,t){return ar(+n,e.length)}}});var lZ,cZ,eLe,dZ,uZ=y(()=>{lZ=(n,e)=>{switch(n){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});case"PPPP":default:return e.date({width:"full"})}},cZ=(n,e)=>{switch(n){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});case"pppp":default:return e.time({width:"full"})}},eLe=(n,e)=>{let t=n.match(/(P+)(p+)?/)||[],r=t[1],a=t[2];if(!a)return lZ(n,e);let i;switch(r){case"P":i=e.dateTime({width:"short"});break;case"PP":i=e.dateTime({width:"medium"});break;case"PPP":i=e.dateTime({width:"long"});break;case"PPPP":default:i=e.dateTime({width:"full"});break}return i.replace("{{date}}",lZ(r,e)).replace("{{time}}",cZ(a,e))},dZ={p:cZ,P:eLe}});function pZ(n){return tLe.test(n)}function mZ(n){return rLe.test(n)}function fZ(n,e,t){let r=aLe(n,e,t);if(console.warn(r),nLe.includes(n))throw new RangeError(r)}function aLe(n,e,t){let r=n[0]==="Y"?"years":"days of the month";return`Use \`${n.toLowerCase()}\` instead of \`${n}\` (in \`${e}\`) for formatting ${r} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}var tLe,rLe,nLe,hZ=y(()=>{tLe=/^D+$/,rLe=/^Y+$/,nLe=["D","DD","YY","YYYY"]});function D(n,e,t){var d,u,p,m,f,h,g,v,k,T,b,w,S,C,x,E,_,F;let r=Ml(),a=(u=(d=t==null?void 0:t.locale)!=null?d:r.locale)!=null?u:P1,i=(T=(k=(h=(f=t==null?void 0:t.firstWeekContainsDate)!=null?f:(m=(p=t==null?void 0:t.locale)==null?void 0:p.options)==null?void 0:m.firstWeekContainsDate)!=null?h:r.firstWeekContainsDate)!=null?k:(v=(g=r.locale)==null?void 0:g.options)==null?void 0:v.firstWeekContainsDate)!=null?T:1,s=(F=(_=(C=(S=t==null?void 0:t.weekStartsOn)!=null?S:(w=(b=t==null?void 0:t.locale)==null?void 0:b.options)==null?void 0:w.weekStartsOn)!=null?C:r.weekStartsOn)!=null?_:(E=(x=r.locale)==null?void 0:x.options)==null?void 0:E.weekStartsOn)!=null?F:0,o=ct(n,t==null?void 0:t.in);if(!ta(o))throw new RangeError("Invalid time value");let l=e.match(sLe).map(I=>{let A=I[0];if(A==="p"||A==="P"){let R=dZ[A];return R(I,a.formatLong)}return I}).join("").match(iLe).map(I=>{if(I==="''")return{isToken:!1,value:"'"};let A=I[0];if(A==="'")return{isToken:!1,value:dLe(I)};if(_1[A])return{isToken:!0,value:I};if(A.match(cLe))throw new RangeError("Format string contains an unescaped latin alphabet character `"+A+"`");return{isToken:!1,value:I}});a.localize.preprocessor&&(l=a.localize.preprocessor(o,l));let c={firstWeekContainsDate:i,weekStartsOn:s,locale:a};return l.map(I=>{if(!I.isToken)return I.value;let A=I.value;(!(t!=null&&t.useAdditionalWeekYearTokens)&&mZ(A)||!(t!=null&&t.useAdditionalDayOfYearTokens)&&pZ(A))&&fZ(A,e,String(n));let R=_1[A[0]];return R(o,A,a.localize,c)}).join("")}function dLe(n){let e=n.match(oLe);return e?e[1].replace(lLe,"'"):n}var iLe,sLe,oLe,lLe,cLe,gZ=y(()=>{X7();Og();oZ();uZ();hZ();E1();pn();iLe=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,sLe=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,oLe=/^'([^]*?)'?$/,lLe=/''/g,cLe=/[a-zA-Z]/});var yZ=y(()=>{});var vZ=y(()=>{});var kZ=y(()=>{});var TZ=y(()=>{});var bZ=y(()=>{});var wZ=y(()=>{});var SZ=y(()=>{});var CZ=y(()=>{});var xZ=y(()=>{});var EZ=y(()=>{});var DZ=y(()=>{});var PZ=y(()=>{});var AZ=y(()=>{});var MZ=y(()=>{});var IZ=y(()=>{});var NZ=y(()=>{});var RZ=y(()=>{});var _Z=y(()=>{});var FZ=y(()=>{});var LZ=y(()=>{});var OZ=y(()=>{});var zZ=y(()=>{});var BZ=y(()=>{});var jZ=y(()=>{});var $Z=y(()=>{});var UZ=y(()=>{});var HZ=y(()=>{});var VZ=y(()=>{});var WZ=y(()=>{});var qZ=y(()=>{});var GZ=y(()=>{});var YZ=y(()=>{});var KZ=y(()=>{});var ZZ=y(()=>{});var QZ=y(()=>{});var JZ=y(()=>{});var XZ=y(()=>{});var eQ=y(()=>{});var tQ=y(()=>{});var rQ=y(()=>{});var nQ=y(()=>{});function F1(n,e){return+ct(n)<+ct(e)}var aQ=y(()=>{pn()});var iQ=y(()=>{});var sQ=y(()=>{});var oQ=y(()=>{});var lQ=y(()=>{});var cQ=y(()=>{});var dQ=y(()=>{});var uQ=y(()=>{});var pQ=y(()=>{});var mQ=y(()=>{});var fQ=y(()=>{});var hQ=y(()=>{});var gQ=y(()=>{});var yQ=y(()=>{});var vQ=y(()=>{});var kQ=y(()=>{});var TQ=y(()=>{});var bQ=y(()=>{});var wQ=y(()=>{});var SQ=y(()=>{});var CQ=y(()=>{});var xQ=y(()=>{});var EQ=y(()=>{});var DQ=y(()=>{});var PQ=y(()=>{});var AQ=y(()=>{});var MQ=y(()=>{});var IQ=y(()=>{});var NQ=y(()=>{});var RQ=y(()=>{});var _Q=y(()=>{});var FQ=y(()=>{});var LQ=y(()=>{});var OQ=y(()=>{});var zQ=y(()=>{});var BQ=y(()=>{});var jQ=y(()=>{});var $Q=y(()=>{});var UQ=y(()=>{});var HQ=y(()=>{});var VQ=y(()=>{});function Hg(n,e,t){return Jm(n,-e,t)}var WQ=y(()=>{$P()});var qQ=y(()=>{});var GQ=y(()=>{});var YQ=y(()=>{});var KQ=y(()=>{});var ZQ=y(()=>{});var QQ=y(()=>{});var JQ=y(()=>{});var XQ=y(()=>{});var eJ=y(()=>{});var tJ=y(()=>{});var rJ=y(()=>{});var nJ=y(()=>{});var aJ=y(()=>{});var iJ=y(()=>{});var sJ=y(()=>{});var oJ=y(()=>{});var lJ=y(()=>{});var cJ=y(()=>{});var dJ=y(()=>{});var uJ=y(()=>{});var pJ=y(()=>{});var mJ=y(()=>{});var fJ=y(()=>{});var hJ=y(()=>{});var gJ=y(()=>{});function Na(n,e){var c;let t=()=>Tn(e==null?void 0:e.in,NaN),r=(c=e==null?void 0:e.additionalDigits)!=null?c:2,a=fLe(n),i;if(a.date){let d=hLe(a.date,r);i=gLe(d.restDateString,d.year)}if(!i||isNaN(+i))return t();let s=+i,o=0,l;if(a.time&&(o=yLe(a.time),isNaN(o)))return t();if(a.timezone){if(l=vLe(a.timezone),isNaN(l))return t()}else{let d=new Date(s+o),u=ct(0,e==null?void 0:e.in);return u.setFullYear(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate()),u.setHours(d.getUTCHours(),d.getUTCMinutes(),d.getUTCSeconds(),d.getUTCMilliseconds()),u}return ct(s+o+l,e==null?void 0:e.in)}function fLe(n){let e={},t=n.split(XP.dateTimeDelimiter),r;if(t.length>2)return e;if(/:/.test(t[0])?r=t[0]:(e.date=t[0],r=t[1],XP.timeZoneDelimiter.test(e.date)&&(e.date=n.split(XP.timeZoneDelimiter)[0],r=n.substr(e.date.length,n.length))),r){let a=XP.timezone.exec(r);a?(e.time=r.replace(a[1],""),e.timezone=a[1]):e.time=r}return e}function hLe(n,e){let t=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+e)+"})|(\\d{2}|[+-]\\d{"+(2+e)+"})$)"),r=n.match(t);if(!r)return{year:NaN,restDateString:""};let a=r[1]?parseInt(r[1]):null,i=r[2]?parseInt(r[2]):null;return{year:i===null?a:i*100,restDateString:n.slice((r[1]||r[2]).length)}}function gLe(n,e){if(e===null)return new Date(NaN);let t=n.match(uLe);if(!t)return new Date(NaN);let r=!!t[4],a=ob(t[1]),i=ob(t[2])-1,s=ob(t[3]),o=ob(t[4]),l=ob(t[5])-1;if(r)return SLe(e,o,l)?kLe(e,o,l):new Date(NaN);{let c=new Date(0);return!bLe(e,i,s)||!wLe(e,a)?new Date(NaN):(c.setUTCFullYear(e,i,Math.max(a,s)),c)}}function ob(n){return n?parseInt(n):1}function yLe(n){let e=n.match(pLe);if(!e)return NaN;let t=L1(e[1]),r=L1(e[2]),a=L1(e[3]);return CLe(t,r,a)?t*y1+r*g1+a*1e3:NaN}function L1(n){return n&&parseFloat(n.replace(",","."))||0}function vLe(n){if(n==="Z")return 0;let e=n.match(mLe);if(!e)return 0;let t=e[1]==="+"?-1:1,r=parseInt(e[2]),a=e[3]&&parseInt(e[3])||0;return xLe(r,a)?t*(r*y1+a*g1):NaN}function kLe(n,e,t){let r=new Date(0);r.setUTCFullYear(n,0,4);let a=r.getUTCDay()||7,i=(e-1)*7+t+1-a;return r.setUTCDate(r.getUTCDate()+i),r}function yJ(n){return n%400===0||n%4===0&&n%100!==0}function bLe(n,e,t){return e>=0&&e<=11&&t>=1&&t<=(TLe[e]||(yJ(n)?29:28))}function wLe(n,e){return e>=1&&e<=(yJ(n)?366:365)}function SLe(n,e,t){return e>=1&&e<=53&&t>=0&&t<=6}function CLe(n,e,t){return n===24?e===0&&t===0:t>=0&&t<60&&e>=0&&e<60&&n>=0&&n<25}function xLe(n,e){return e>=0&&e<=59}var XP,uLe,pLe,mLe,TLe,vJ=y(()=>{Lg();Ho();pn();XP={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},uLe=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,pLe=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,mLe=/^([+-])(\d{2})(?::?(\d{2}))?$/;TLe=[31,null,31,30,31,30,31,31,30,31,30,31]});var kJ=y(()=>{});var TJ=y(()=>{});var bJ=y(()=>{});var wJ=y(()=>{});var SJ=y(()=>{});var CJ=y(()=>{});var xJ=y(()=>{});var EJ=y(()=>{});var DJ=y(()=>{});var PJ=y(()=>{});var AJ=y(()=>{});var MJ=y(()=>{});var IJ=y(()=>{});var NJ=y(()=>{});var RJ=y(()=>{});var _J=y(()=>{});var FJ=y(()=>{});var LJ=y(()=>{});var OJ=y(()=>{});var zJ=y(()=>{});var BJ=y(()=>{});var jJ=y(()=>{});var $J=y(()=>{});var UJ=y(()=>{});var HJ=y(()=>{});var VJ=y(()=>{});var WJ=y(()=>{});var qJ=y(()=>{});var GJ=y(()=>{});var YJ=y(()=>{});var KJ=y(()=>{});var ZJ=y(()=>{});var QJ=y(()=>{});var JJ=y(()=>{});var XJ=y(()=>{});var eX=y(()=>{});var tX=y(()=>{});var rX=y(()=>{});var nX=y(()=>{});var aX=y(()=>{});var iX=y(()=>{});var sX=y(()=>{});var oX=y(()=>{});var lX=y(()=>{});var cX=y(()=>{});var dX=y(()=>{});var Cr=y(()=>{mK();yK();$P();kK();CK();vK();xK();k1();EK();DK();AK();IK();NK();FK();LK();OK();zK();BK();Ho();jK();$K();VK();w1();WK();qK();GK();KK();ZK();QK();JK();XK();t7();r7();n7();o7();l7();c7();d7();u7();p7();m7();f7();h7();y7();v7();k7();b7();C7();x7();a7();E7();D7();A7();M7();I7();i7();N7();R7();_7();F7();P7();S7();L7();gZ();yZ();vZ();kZ();TZ();bZ();wZ();SZ();CZ();xZ();EZ();DZ();PZ();AZ();MZ();A1();IZ();RZ();_Z();FZ();LZ();OZ();M1();VP();zZ();BZ();jZ();$Z();UZ();YK();HZ();VZ();WZ();N1();qZ();JP();YZ();KZ();ZZ();QZ();JZ();XZ();eQ();tQ();rQ();nQ();aQ();x1();iQ();sQ();oQ();lQ();cQ();s7();NZ();gQ();yQ();vQ();UK();TQ();wQ();SQ();xQ();EQ();DQ();AQ();bQ();MQ();fK();hK();IQ();NQ();RQ();_Q();FQ();LQ();OQ();zQ();BQ();jQ();$Q();UQ();E1();HQ();gK();VQ();qQ();GQ();KQ();ZQ();GZ();QQ();YQ();JQ();XQ();RK();eJ();tJ();rJ();nJ();_K();aJ();iJ();sJ();oJ();lJ();cJ();dJ();uJ();pJ();mJ();fJ();hJ();gJ();hQ();vJ();kJ();TJ();bJ();wJ();SJ();CJ();xJ();EJ();DJ();PJ();AJ();MJ();IJ();NJ();RJ();_J();LJ();OJ();mQ();zJ();BJ();jJ();fQ();pQ();SK();$J();UJ();FJ();HJ();VJ();uQ();WJ();qJ();qP();GJ();kQ();ib();S1();CQ();T7();g7();PQ();YJ();KJ();zg();I1();D1();ZJ();JJ();XJ();WQ();eX();e7();tX();rX();QJ();nX();aX();iX();sX();pn();dQ();oX();lX();cX();dX()});var od=te(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});var tn=require("obsidian"),O1="YYYY-MM-DD",z1="gggg-[W]ww",uX="YYYY-MM",pX="YYYY-[Q]Q",mX="YYYY";function lb(n){var t,r;let e=window.app.plugins.getPlugin("periodic-notes");return e&&((r=(t=e.settings)==null?void 0:t[n])==null?void 0:r.enabled)}function cb(){var n,e,t,r;try{let{internalPlugins:a,plugins:i}=window.app;if(lb("daily")){let{format:c,folder:d,template:u}=((e=(n=i.getPlugin("periodic-notes"))==null?void 0:n.settings)==null?void 0:e.daily)||{};return{format:c||O1,folder:(d==null?void 0:d.trim())||"",template:(u==null?void 0:u.trim())||""}}let{folder:s,format:o,template:l}=((r=(t=a.getPluginById("daily-notes"))==null?void 0:t.instance)==null?void 0:r.options)||{};return{format:o||O1,folder:(s==null?void 0:s.trim())||"",template:(l==null?void 0:l.trim())||""}}catch(a){console.info("No custom daily note settings found!",a)}}function db(){var n,e,t,r,a,i,s;try{let o=window.app.plugins,l=(n=o.getPlugin("calendar"))==null?void 0:n.options,c=(t=(e=o.getPlugin("periodic-notes"))==null?void 0:e.settings)==null?void 0:t.weekly;if(lb("weekly"))return{format:c.format||z1,folder:((r=c.folder)==null?void 0:r.trim())||"",template:((a=c.template)==null?void 0:a.trim())||""};let d=l||{};return{format:d.weeklyNoteFormat||z1,folder:((i=d.weeklyNoteFolder)==null?void 0:i.trim())||"",template:((s=d.weeklyNoteTemplate)==null?void 0:s.trim())||""}}catch(o){console.info("No custom weekly note settings found!",o)}}function ub(){var e,t,r,a;let n=window.app.plugins;try{let i=lb("monthly")&&((t=(e=n.getPlugin("periodic-notes"))==null?void 0:e.settings)==null?void 0:t.monthly)||{};return{format:i.format||uX,folder:((r=i.folder)==null?void 0:r.trim())||"",template:((a=i.template)==null?void 0:a.trim())||""}}catch(i){console.info("No custom monthly note settings found!",i)}}function pb(){var e,t,r,a;let n=window.app.plugins;try{let i=lb("quarterly")&&((t=(e=n.getPlugin("periodic-notes"))==null?void 0:e.settings)==null?void 0:t.quarterly)||{};return{format:i.format||pX,folder:((r=i.folder)==null?void 0:r.trim())||"",template:((a=i.template)==null?void 0:a.trim())||""}}catch(i){console.info("No custom quarterly note settings found!",i)}}function mb(){var e,t,r,a;let n=window.app.plugins;try{let i=lb("yearly")&&((t=(e=n.getPlugin("periodic-notes"))==null?void 0:e.settings)==null?void 0:t.yearly)||{};return{format:i.format||mX,folder:((r=i.folder)==null?void 0:r.trim())||"",template:((a=i.template)==null?void 0:a.trim())||""}}catch(i){console.info("No custom yearly note settings found!",i)}}function fX(...n){let e=[];for(let r=0,a=n.length;r{let k=r(),T=n.clone().set({hour:k.get("hour"),minute:k.get("minute"),second:k.get("second")});return f&&T.add(parseInt(h,10),g),v?T.format(v.substring(1).trim()):T.format(i)}).replace(/{{\s*yesterday\s*}}/gi,n.clone().subtract(1,"day").format(i)).replace(/{{\s*tomorrow\s*}}/gi,n.clone().add(1,"d").format(i)));return e.foldManager.save(u,l),u}catch(u){console.error(`Failed to create file: '${d}'`,u),new tn.Notice("Unable to create new file.")}}function MLe(n,e){var t;return(t=e[Wo(n,"day")])!=null?t:null}function ILe(){let{vault:n}=window.app,{folder:e}=cb(),t=n.getAbstractFileByPath(tn.normalizePath(e));if(!t)throw new B1("Failed to find daily notes folder");let r={};return tn.Vault.recurseChildren(t,a=>{if(a instanceof tn.TFile){let i=Wg(a,"day");if(i){let s=Wo(i,"day");r[s]=a}}}),r}var j1=class extends Error{};function NLe(){let{moment:n}=window,e=n.localeData()._week.dow,t=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];for(;e;)t.push(t.shift()),e--;return t}function RLe(n){return NLe().indexOf(n.toLowerCase())}async function vX(n){let{vault:e}=window.app,{template:t,format:r,folder:a}=db(),[i,s]=await Vg(t),o=n.format(r),l=await fb(a,o);try{let c=await e.create(l,i.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(d,u,p,m,f,h)=>{let g=window.moment(),v=n.clone().set({hour:g.get("hour"),minute:g.get("minute"),second:g.get("second")});return p&&v.add(parseInt(m,10),f),h?v.format(h.substring(1).trim()):v.format(r)}).replace(/{{\s*title\s*}}/gi,o).replace(/{{\s*time\s*}}/gi,window.moment().format("HH:mm")).replace(/{{\s*(sunday|monday|tuesday|wednesday|thursday|friday|saturday)\s*:(.*?)}}/gi,(d,u,p)=>{let m=RLe(u);return n.weekday(m).format(p.trim())}));return window.app.foldManager.save(c,s),c}catch(c){console.error(`Failed to create file: '${l}'`,c),new tn.Notice("Unable to create new file.")}}function _Le(n,e){var t;return(t=e[Wo(n,"week")])!=null?t:null}function FLe(){let n={};if(!TX())return n;let{vault:e}=window.app,{folder:t}=db(),r=e.getAbstractFileByPath(tn.normalizePath(t));if(!r)throw new j1("Failed to find weekly notes folder");return tn.Vault.recurseChildren(r,a=>{if(a instanceof tn.TFile){let i=Wg(a,"week");if(i){let s=Wo(i,"week");n[s]=a}}}),n}var $1=class extends Error{};async function kX(n){let{vault:e}=window.app,{template:t,format:r,folder:a}=ub(),[i,s]=await Vg(t),o=n.format(r),l=await fb(a,o);try{let c=await e.create(l,i.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(d,u,p,m,f,h)=>{let g=window.moment(),v=n.clone().set({hour:g.get("hour"),minute:g.get("minute"),second:g.get("second")});return p&&v.add(parseInt(m,10),f),h?v.format(h.substring(1).trim()):v.format(r)}).replace(/{{\s*date\s*}}/gi,o).replace(/{{\s*time\s*}}/gi,window.moment().format("HH:mm")).replace(/{{\s*title\s*}}/gi,o));return window.app.foldManager.save(c,s),c}catch(c){console.error(`Failed to create file: '${l}'`,c),new tn.Notice("Unable to create new file.")}}function LLe(n,e){var t;return(t=e[Wo(n,"month")])!=null?t:null}function OLe(){let n={};if(!bX())return n;let{vault:e}=window.app,{folder:t}=ub(),r=e.getAbstractFileByPath(tn.normalizePath(t));if(!r)throw new $1("Failed to find monthly notes folder");return tn.Vault.recurseChildren(r,a=>{if(a instanceof tn.TFile){let i=Wg(a,"month");if(i){let s=Wo(i,"month");n[s]=a}}}),n}var U1=class extends Error{};async function zLe(n){let{vault:e}=window.app,{template:t,format:r,folder:a}=pb(),[i,s]=await Vg(t),o=n.format(r),l=await fb(a,o);try{let c=await e.create(l,i.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(d,u,p,m,f,h)=>{let g=window.moment(),v=n.clone().set({hour:g.get("hour"),minute:g.get("minute"),second:g.get("second")});return p&&v.add(parseInt(m,10),f),h?v.format(h.substring(1).trim()):v.format(r)}).replace(/{{\s*date\s*}}/gi,o).replace(/{{\s*time\s*}}/gi,window.moment().format("HH:mm")).replace(/{{\s*title\s*}}/gi,o));return window.app.foldManager.save(c,s),c}catch(c){console.error(`Failed to create file: '${l}'`,c),new tn.Notice("Unable to create new file.")}}function BLe(n,e){var t;return(t=e[Wo(n,"quarter")])!=null?t:null}function jLe(){let n={};if(!wX())return n;let{vault:e}=window.app,{folder:t}=pb(),r=e.getAbstractFileByPath(tn.normalizePath(t));if(!r)throw new U1("Failed to find quarterly notes folder");return tn.Vault.recurseChildren(r,a=>{if(a instanceof tn.TFile){let i=Wg(a,"quarter");if(i){let s=Wo(i,"quarter");n[s]=a}}}),n}var H1=class extends Error{};async function $Le(n){let{vault:e}=window.app,{template:t,format:r,folder:a}=mb(),[i,s]=await Vg(t),o=n.format(r),l=await fb(a,o);try{let c=await e.create(l,i.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(d,u,p,m,f,h)=>{let g=window.moment(),v=n.clone().set({hour:g.get("hour"),minute:g.get("minute"),second:g.get("second")});return p&&v.add(parseInt(m,10),f),h?v.format(h.substring(1).trim()):v.format(r)}).replace(/{{\s*date\s*}}/gi,o).replace(/{{\s*time\s*}}/gi,window.moment().format("HH:mm")).replace(/{{\s*title\s*}}/gi,o));return window.app.foldManager.save(c,s),c}catch(c){console.error(`Failed to create file: '${l}'`,c),new tn.Notice("Unable to create new file.")}}function ULe(n,e){var t;return(t=e[Wo(n,"year")])!=null?t:null}function HLe(){let n={};if(!SX())return n;let{vault:e}=window.app,{folder:t}=mb(),r=e.getAbstractFileByPath(tn.normalizePath(t));if(!r)throw new H1("Failed to find yearly notes folder");return tn.Vault.recurseChildren(r,a=>{if(a instanceof tn.TFile){let i=Wg(a,"year");if(i){let s=Wo(i,"year");n[s]=a}}}),n}function VLe(){var r,a;let{app:n}=window,e=n.internalPlugins.plugins["daily-notes"];if(e&&e.enabled)return!0;let t=n.plugins.getPlugin("periodic-notes");return t&&((a=(r=t.settings)==null?void 0:r.daily)==null?void 0:a.enabled)}function TX(){var t,r;let{app:n}=window;if(n.plugins.getPlugin("calendar"))return!0;let e=n.plugins.getPlugin("periodic-notes");return e&&((r=(t=e.settings)==null?void 0:t.weekly)==null?void 0:r.enabled)}function bX(){var t,r;let{app:n}=window,e=n.plugins.getPlugin("periodic-notes");return e&&((r=(t=e.settings)==null?void 0:t.monthly)==null?void 0:r.enabled)}function wX(){var t,r;let{app:n}=window,e=n.plugins.getPlugin("periodic-notes");return e&&((r=(t=e.settings)==null?void 0:t.quarterly)==null?void 0:r.enabled)}function SX(){var t,r;let{app:n}=window,e=n.plugins.getPlugin("periodic-notes");return e&&((r=(t=e.settings)==null?void 0:t.yearly)==null?void 0:r.enabled)}function WLe(n){let e={day:cb,week:db,month:ub,quarter:pb,year:mb}[n];return e()}function qLe(n,e){return{day:yX,month:kX,week:vX}[n](e)}wt.DEFAULT_DAILY_NOTE_FORMAT=O1;wt.DEFAULT_MONTHLY_NOTE_FORMAT=uX;wt.DEFAULT_QUARTERLY_NOTE_FORMAT=pX;wt.DEFAULT_WEEKLY_NOTE_FORMAT=z1;wt.DEFAULT_YEARLY_NOTE_FORMAT=mX;wt.appHasDailyNotesPluginLoaded=VLe;wt.appHasMonthlyNotesPluginLoaded=bX;wt.appHasQuarterlyNotesPluginLoaded=wX;wt.appHasWeeklyNotesPluginLoaded=TX;wt.appHasYearlyNotesPluginLoaded=SX;wt.createDailyNote=yX;wt.createMonthlyNote=kX;wt.createPeriodicNote=qLe;wt.createQuarterlyNote=zLe;wt.createWeeklyNote=vX;wt.createYearlyNote=$Le;wt.getAllDailyNotes=ILe;wt.getAllMonthlyNotes=OLe;wt.getAllQuarterlyNotes=jLe;wt.getAllWeeklyNotes=FLe;wt.getAllYearlyNotes=HLe;wt.getDailyNote=MLe;wt.getDailyNoteSettings=cb;wt.getDateFromFile=Wg;wt.getDateFromPath=ALe;wt.getDateUID=Wo;wt.getMonthlyNote=LLe;wt.getMonthlyNoteSettings=ub;wt.getPeriodicNoteSettings=WLe;wt.getQuarterlyNote=BLe;wt.getQuarterlyNoteSettings=pb;wt.getTemplateInfo=Vg;wt.getWeeklyNote=_Le;wt.getWeeklyNoteSettings=db;wt.getYearlyNote=ULe;wt.getYearlyNoteSettings=mb});function CX(n){return n.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"")}function Il(n){let e=Array.isArray(n)?n:typeof n=="string"?n.split(","):[];return Array.from(new Set(e.map(t=>CX(t.trim())).filter(t=>t.length>0)))}function qg(n,e){let t=CX(n);return e.some(r=>t===r||t.startsWith(`${r}/`))}var hb=y(()=>{});function GLe(n){let e=n.toLowerCase();return e==="true"||e==="false"?e==="true":n}function gb(n){let e=n.trim();return(e.startsWith("#")?e.slice(1).trim():e).replace(/\s+/g,"-")}function V1(n){return n.trim().toLowerCase()==="tags"}function YLe(n){return typeof n=="string"&&n.trim().length===0}function xX(n,e){return n===e}function qo(n){let e=[],t=new Set,r=a=>{let i=gb(String(a));!i||t.has(i)||(t.add(i),e.push(i))};return Array.isArray(n)?(n.forEach(r),e):typeof n=="string"&&n.trim().length>0?(r(n),e):[]}function Gg(n,e,t){if(!e||!t)return;if(V1(e)){let i=qo(n.tags),s=gb(t);i.some(l=>gb(l)===s)||i.push(s),n.tags=i;return}let r=GLe(t),a=n[e];if(Array.isArray(a)){a.some(i=>xX(i,r))||a.push(r),n[e]=a;return}if(a==null||YLe(a)){n[e]=r;return}if(xX(a,r)){n[e]=a;return}n[e]=[a,r]}var Yg=y(()=>{});function Tb(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function q1(n){return`note["${Tb(n)}"]`}function DX(n){return`file(if(${n}.isType("object"), ${n}.uid, ${n}))`}function EX(n){return`${DX(n)}.asLink()`}function vb(n){return`file(${n}.replace(/^\\[[^\\]]+\\]\\((.*)\\)$/, "$1").replace(/%20/g, " ")).asLink()`}function KLe(n){if(n.taskIdentificationMethod==="tag")return`file.hasTag("${n.taskTag||"task"}")`;{let e=n.taskPropertyName,t=n.taskPropertyValue;if(!e)return`file.hasTag("${n.taskTag||"task"}")`;if(t){if(V1(e))return`file.hasTag("${Tb(t)}")`;let r=q1(e),a=t.toLowerCase();return a==="true"||a==="false"?`list(${r}).contains(${a})`:`list(${r}).contains("${Tb(t)}")`}else{let r=q1(e);return`${r} && ${r} != "" && ${r} != null`}}}function PX(n){return Il(n.excludedFolders).map(e=>`file.inFolder("${Tb(e)}") != true`)}function ZLe(n){return[KLe(n),...PX(n)]}function yb(n){return`filters: + and: +${(Array.isArray(n)?n:[n]).map(r=>` - ${r}`).join(` +`)}`}function Ei(n){return n.replace(/^(note\.|file\.|task\.|formula\.)/,"")}function kb(n){return`date(${n}).format("YYYY-MM-DD")`}function AX(){return'today().format("YYYY-MM-DD")'}function MX(){return'(today() + "7 days").format("YYYY-MM-DD")'}function Ut(n,e){var a;let t=e.fieldMapper;if(n.startsWith("user:")){let i=n.substring(5),s=(a=e.settings.userFields)==null?void 0:a.find(o=>o.id===i);return s?s.key:n}switch(n){case"tags":return"file.tags";case"dateCreated":return"file.ctime";case"dateModified":return"file.mtime";case"title":return"file.name";case"blocked":case"blocking":return t.toUserField("blockedBy");case"complete_instances":return t.toUserField("completeInstances");case"totalTrackedTime":return t.toUserField("timeEntries");case"checklistProgress":return"file.tasks"}let r=t.getMapping();return n in r?t.toUserField(n):n}function QLe(n){let r=(n.settings.defaultVisibleProperties||["status","priority","due","scheduled","projects","contexts","tags"]).map(o=>Ut(o,n)).filter(o=>!!o),a=["file.name",Ut("recurrence",n),Ut("complete_instances",n),Ut("checklistProgress",n)].filter(o=>!!o),i=[],s=new Set;for(let o of r)o&&!s.has(o)&&(i.push(o),s.add(o));for(let o of a)o&&!s.has(o)&&(i.push(o),s.add(o));return i}function W1(n){return n.map(e=>` - ${e}`).join(` +`)}function JLe(n,e,t){if(!e)return n;let r=n.filter(i=>i!==e),a=r.indexOf(t);return a===-1?r.push(e):r.splice(a+1,0,e),r}function XLe(n){let e=n.settings,t=Ei(Ut("priority",n)),r=[...e.customPriorities].sort((i,s)=>i.weight-s.weight);if(r.length===0)return"999";let a="999";for(let i=r.length-1;i>=0;i--){let s=r[i];a=`if(${t}=="${s.value}",${i},${a})`}return a}function eOe(n){let e=Ei(Ut("priority",n)),t=n.settings.customPriorities;if(t.length===0)return'"No priority"';let r='"No priority"';for(let a=t.length-1;a>=0;a--){let i=t[a];r=`if(${e}=="${i.value}","${i.label}",${r})`}return r}function tOe(n){let e=Ei(Ut("due",n)),t=Ei(Ut("status",n)),r=Ei(Ut("timeEstimate",n)),a=Ei(Ut("timeEntries",n)),i=Ei(Ut("projects",n)),s=Ei(Ut("contexts",n)),l=n.settings.customStatuses.filter(x=>x.isCompleted).map(x=>x.value).map(x=>`${t} != "${x}"`).join(" && "),c=Ei(Ut("scheduled",n)),d=Ei(Ut("recurrence",n)),u=`${e}.isEmpty()`,p=`${c}.isEmpty()`,m=`(${u} == false)`,f=`(${p} == false)`,h="if(formula.daysUntilNext, formula.daysUntilNext, 0)",g=AX(),v=MX(),k='(today() + "1 day").format("YYYY-MM-DD")',T='(today() - "1 day").format("YYYY-MM-DD")',b=kb(e),w=kb(c),S=kb("value.startTime");return{priorityWeight:XLe(n),daysUntilDue:`if(${m}, ((number(date(${e})) - number(today())) / 86400000).floor(), null)`,dueIn:`if(${u}, "", if(formula.daysUntilDue == 0, "Today", if(formula.daysUntilDue == 1, "1 day", if(formula.daysUntilDue > 1, formula.daysUntilDue + " days", if(formula.daysUntilDue == -1, "1 day overdue", formula.daysUntilDue * -1 + " days overdue")))))`,daysUntilScheduled:`if(${f}, ((number(date(${c})) - number(today())) / 86400000).floor(), null)`,daysSinceCreated:"((number(now()) - number(file.ctime)) / 86400000).floor()",daysSinceModified:"((number(now()) - number(file.mtime)) / 86400000).floor()",isOverdue:`${m} && date(${e}) < today() && ${l}`,isDueToday:`${m} && ${b} == ${g}`,isDueThisWeek:`${m} && ${b} >= ${g} && ${b} <= ${v}`,isScheduledToday:`${f} && ${w} == ${g}`,isRecurring:`${d} && !${d}.isEmpty()`,hasTimeEstimate:`${r} && ${r} > 0`,timeRemaining:`if(${r} && ${r} > 0, ${r} - if(${a}, list(${a}).filter(value.endTime).map((number(date(value.endTime)) - number(date(value.startTime))) / 60000).reduce(acc + value, 0), 0), null)`,efficiencyRatio:`if(${r} && ${r} > 0 && ${a}, (list(${a}).filter(value.endTime).map((number(date(value.endTime)) - number(date(value.startTime))) / 60000).reduce(acc + value, 0) / ${r} * 100).round(), null)`,timeTrackedThisWeek:`if(${a}, list(${a}).filter(value.endTime && date(value.startTime) >= today() - "7d").map((number(date(value.endTime)) - number(date(value.startTime))) / 60000).reduce(acc + value, 0).round(), 0)`,timeTrackedToday:`if(${a}, list(${a}).filter(value.endTime && ${S} == ${g}).map((number(date(value.endTime)) - number(date(value.startTime))) / 60000).reduce(acc + value, 0).round(), 0)`,dueMonth:`if(${m}, date(${e}).format("YYYY-MM"), "No due date")`,dueWeek:`if(${m}, date(${e}).format("YYYY-[W]WW"), "No due date")`,scheduledMonth:`if(${f}, date(${c}).format("YYYY-MM"), "Not scheduled")`,scheduledWeek:`if(${f}, date(${c}).format("YYYY-[W]WW"), "Not scheduled")`,dueDateCategory:`if(${u}, "No due date", if(date(${e}) < today(), "Overdue", if(${b} == ${g}, "Today", if(${b} == ${k}, "Tomorrow", if(${b} <= ${v}, "This week", "Later")))))`,timeEstimateCategory:`if(!${r} || ${r} == 0 || ${r} == null, "No estimate", if(${r} < 30, "Quick (<30m)", if(${r} <= 120, "Medium (30m-2h)", "Long (>2h)")))`,ageCategory:'if(((number(now()) - number(file.ctime)) / 86400000) < 1, "Today", if(((number(now()) - number(file.ctime)) / 86400000) < 7, "This week", if(((number(now()) - number(file.ctime)) / 86400000) < 30, "This month", "Older")))',createdMonth:'file.ctime.format("YYYY-MM")',modifiedMonth:'file.mtime.format("YYYY-MM")',priorityCategory:eOe(n),projectCount:`if(!${i} || list(${i}).length == 0, "No projects", if(list(${i}).length == 1, "Single project", "Multiple projects"))`,contextCount:`if(!${s} || list(${s}).length == 0, "No contexts", if(list(${s}).length == 1, "Single context", "Multiple contexts"))`,trackingStatus:`if(!${r} || ${r} == 0 || ${r} == null, "No estimate", if(!${a} || list(${a}).length == 0, "Not started", if(formula.efficiencyRatio < 100, "Under estimate", "Over estimate")))`,nextDate:`if(${m} && ${f}, if(date(${e}) < date(${c}), ${e}, ${c}), if(${m}, ${e}, ${c}))`,daysUntilNext:`if(${m} && ${f}, min(formula.daysUntilDue, formula.daysUntilScheduled), if(${m}, formula.daysUntilDue, formula.daysUntilScheduled))`,hasDate:`${m} || ${f}`,isToday:`(${m} && ${b} == ${g}) || (${f} && ${w} == ${g})`,isThisWeek:`(${m} && ${b} >= ${g} && ${b} <= ${v}) || (${f} && ${w} >= ${g} && ${w} <= ${v})`,nextDateCategory:`if(${u} && ${p}, "No date", if((${m} && date(${e}) < today()) || (${f} && date(${c}) < today()), "Overdue/Past", if((${m} && ${b} == ${g}) || (${f} && ${w} == ${g}), "Today", if((${m} && ${b} == ${k}) || (${f} && ${w} == ${k}), "Tomorrow", if((${m} && ${b} <= ${v}) || (${f} && ${w} <= ${v}), "This week", "Later")))))`,nextDateMonth:`if(${m} && ${f}, if(date(${e}) < date(${c}), date(${e}).format("YYYY-MM"), date(${c}).format("YYYY-MM")), if(${m}, date(${e}).format("YYYY-MM"), if(${f}, date(${c}).format("YYYY-MM"), "No date")))`,nextDateWeek:`if(${m} && ${f}, if(date(${e}) < date(${c}), date(${e}).format("YYYY-[W]WW"), date(${c}).format("YYYY-[W]WW")), if(${m}, date(${e}).format("YYYY-[W]WW"), if(${f}, date(${c}).format("YYYY-[W]WW"), "No date")))`,urgencyScore:`if(${u} && ${p}, formula.priorityWeight, formula.priorityWeight + max(0, 10 - ${h}) + (1 - ((number(date(formula.nextDate)) - number(date(date(formula.nextDate).format("YYYY-MM-DD")))) / 86400000)))`,timeTrackedFormatted:`if(${a}, if(list(${a}).filter(value.endTime).map((number(date(value.endTime)) - number(date(value.startTime))) / 60000).reduce(acc + value, 0) >= 60, (list(${a}).filter(value.endTime).map((number(date(value.endTime)) - number(date(value.startTime))) / 60000).reduce(acc + value, 0) / 60).floor() + "h " + (list(${a}).filter(value.endTime).map((number(date(value.endTime)) - number(date(value.startTime))) / 60000).reduce(acc + value, 0) % 60).round() + "m", list(${a}).filter(value.endTime).map((number(date(value.endTime)) - number(date(value.startTime))) / 60000).reduce(acc + value, 0).round() + "m"), "0m")`,dueDateDisplay:`if(${u}, "", if(${b} == ${g}, "Today", if(${b} == ${k}, "Tomorrow", if(${b} == ${T}, "Yesterday", if(date(${e}) < today(), formula.daysUntilDue * -1 + "d ago", if(${b} <= ${v}, date(${e}).format("ddd"), date(${e}).format("MMM D")))))))`}}function rOe(n){let e=tOe(n);return`formulas: +${Object.entries(e).map(([r,a])=>` ${r}: '${a}'`).join(` +`)}`}function nOe(n,e,t){if(n.includes(t)||!e||!n.includes(e))return n;let r=[],a=!1;for(let i of n)r.push(i),!a&&e&&i===e&&(r.push(t),a=!0);return r}function aOe(n){let e=Ut("pomodoros",n),t=q1(e),r=`list(${t}).filter(value.type == "work")`,a=`list(${t}).filter(value.type == "work" && value.completed == true)`,i=`${a}.map(if(value.plannedDuration && value.plannedDuration > 0, value.plannedDuration, if(value.startTime && value.endTime, ((number(date(value.endTime)) - number(date(value.startTime))) / 60000).round(), 0)))`;return`# Pomodoro statistics +# Generated with your TaskNotes settings +# Requires Pomodoro data storage to be set to Daily notes. + +filters: + and: + - file.hasProperty("${Tb(e)}") + - list(${t}).filter(value.startTime).isEmpty() == false + +formulas: + pomodoroDate: 'if(${t}, list(${t}).filter(value.startTime).map(date(value.startTime).format("YYYY-MM-DD")).unique().join(", "), file.basename)' + pomodoroMonth: 'if(${t}, list(${t}).filter(value.startTime).map(date(value.startTime).format("YYYY-MM")).unique().join(", "), "")' + completedPomos: 'if(${t}, ${a}.length, 0)' + attemptedPomos: 'if(${t}, ${r}.length, 0)' + interruptedPomos: 'if(${t}, list(${t}).filter(value.type == "work" && value.completed == false).length, 0)' + focusMinutes: 'if(${t}, ${i}.reduce(acc + value, 0).round(), 0)' + focusTime: 'if(formula.focusMinutes >= 60, (formula.focusMinutes / 60).floor() + "h " + (formula.focusMinutes % 60).round() + "m", formula.focusMinutes + "m")' + completionRate: 'if(formula.attemptedPomos > 0, (formula.completedPomos / formula.attemptedPomos * 100).round() + "%", "0%")' + shortBreaks: 'if(${t}, list(${t}).filter(value.type == "short-break").length, 0)' + longBreaks: 'if(${t}, list(${t}).filter(value.type == "long-break").length, 0)' + +properties: + formula.pomodoroDate: + displayName: Date + formula.pomodoroMonth: + displayName: Month + formula.completedPomos: + displayName: Completed + formula.attemptedPomos: + displayName: Attempted + formula.interruptedPomos: + displayName: Interrupted + formula.focusMinutes: + displayName: Focus minutes + formula.focusTime: + displayName: Focus time + formula.completionRate: + displayName: Completion + formula.shortBreaks: + displayName: Short breaks + formula.longBreaks: + displayName: Long breaks + +views: + - type: table + name: "Daily" + order: + - formula.pomodoroDate + - formula.completedPomos + - formula.focusTime + - formula.attemptedPomos + - formula.completionRate + - formula.interruptedPomos + - formula.shortBreaks + - formula.longBreaks + - file.name + sort: + - column: formula.pomodoroDate + direction: DESC + - type: table + name: "Monthly" + groupBy: + property: formula.pomodoroMonth + direction: DESC + order: + - formula.pomodoroDate + - formula.completedPomos + - formula.focusMinutes + - formula.focusTime + - formula.attemptedPomos + - formula.completionRate + - formula.interruptedPomos + - formula.shortBreaks + - formula.longBreaks + - file.name + summaries: + formula.completedPomos: Sum + formula.focusMinutes: Sum + formula.attemptedPomos: Sum + formula.interruptedPomos: Sum + formula.shortBreaks: Sum + formula.longBreaks: Sum + sort: + - column: formula.pomodoroDate + direction: DESC +`}function IX(n,e){let t=e.settings,r=ZLe(t),a=PX(t),i=QLe(e),s=W1(i),o=rOe(e);switch(n){case"open-calendar-view":{let l=Ut("due",e),c=Ut("scheduled",e);return`# Mini Calendar +# Generated with your TaskNotes settings + +${yb(r)} + +${o} + +views: + - type: tasknotesMiniCalendar + name: "Due" + order: +${s} + sort: + - property: ${l} + direction: ASC + dateProperty: ${l} + - type: tasknotesMiniCalendar + name: "Scheduled" + order: [] + dateProperty: ${c} + - type: tasknotesMiniCalendar + name: "Created" + dateProperty: file.ctime + - type: tasknotesMiniCalendar + name: "Modified" + dateProperty: file.mtime +`}case"open-kanban-view":{let l=Ut("status",e),c=Ut("sortOrder",e);return`# Kanban Board + +${yb(r)} + +${o} + +views: + - type: tasknotesKanban + name: "Kanban Board" + order: +${s} + sort: + - column: ${c} + direction: DESC + groupBy: + property: ${l} + direction: ASC + config: + columnWidth: 280 + hideEmptyColumns: false +`}case"open-tasks-view":{let l=Ut("status",e),c=Ut("due",e),d=Ut("scheduled",e),u=Ut("recurrence",e),p=Ut("completeInstances",e),m=Ut("blockedBy",e),f=Ut("sortOrder",e),h=`${c}.isEmpty() == false`,g=`${d}.isEmpty() == false`,v=AX(),k=MX(),T=kb(c),b=kb(d),w=t.customStatuses.filter(E=>E.isCompleted).map(E=>E.value),S=w.map(E=>`${l} != "${E}"`).join(` + - `),C=`${p}.map(date(value).format("YYYY-MM-DD")).contains(${v}) != true`,x=w.map(E=>`${DX("value")}.properties.${Ei(l)} != "${E}"`).join(" && ");return`# All Tasks + +${yb(r)} + +${o} + +views: + - type: tasknotesTaskList + name: "Manual Order" + order: +${s} + sort: + - column: ${f} + direction: DESC + groupBy: + property: ${l} + direction: ASC + - type: tasknotesTaskList + name: "All Tasks" + order: +${s} + sort: + - column: due + direction: ASC + - type: tasknotesTaskList + name: "Not Blocked" + filters: + and: + # Incomplete tasks + - or: + # Non-recurring task that's not in any completed status + - and: + - ${u}.isEmpty() + - ${S} + # Recurring task where today is not in complete_instances + - and: + - ${u}.isEmpty() == false + - ${C} + # Not blocked by any incomplete tasks + - or: + # No blocking dependencies at all + - ${m}.isEmpty() + # All blocking tasks are completed (filter returns only incomplete, then check if empty) + - 'list(${m}).filter(${x}).isEmpty()' + order: +${s} + sort: + - column: formula.urgencyScore + direction: DESC + - type: tasknotesTaskList + name: "Today" + filters: + and: + # Incomplete tasks (handles both recurring and non-recurring) + - or: + # Non-recurring task that's not in any completed status + - and: + - ${u}.isEmpty() + - ${S} + # Recurring task where today is not in complete_instances + - and: + - ${u}.isEmpty() == false + - ${C} + # Due or scheduled today + - or: + - and: + - ${h} + - ${T} == ${v} + - and: + - ${g} + - ${b} == ${v} + order: +${s} + sort: + - column: formula.urgencyScore + direction: DESC + - type: tasknotesTaskList + name: "Overdue" + filters: + and: + # Incomplete tasks + - or: + # Non-recurring task that's not in any completed status + - and: + - ${u}.isEmpty() + - ${S} + # Recurring task where today is not in complete_instances + - and: + - ${u}.isEmpty() == false + - ${C} + # Due or scheduled in the past + - or: + - and: + - ${h} + - date(${c}) < today() + - and: + - ${g} + - date(${d}) < today() + order: +${s} + sort: + - column: formula.urgencyScore + direction: DESC + - type: tasknotesTaskList + name: "This Week" + filters: + and: + # Incomplete tasks + - or: + # Non-recurring task that's not in any completed status + - and: + - ${u}.isEmpty() + - ${S} + # Recurring task where today is not in complete_instances + - and: + - ${u}.isEmpty() == false + - ${C} + # Due or scheduled this week + - or: + - and: + - ${h} + - ${T} >= ${v} + - ${T} <= ${k} + - and: + - ${g} + - ${b} >= ${v} + - ${b} <= ${k} + order: +${s} + sort: + - column: formula.urgencyScore + direction: DESC + - type: tasknotesTaskList + name: "Unscheduled" + filters: + and: + # Incomplete tasks + - or: + # Non-recurring task that's not in any completed status + - and: + - ${u}.isEmpty() + - ${S} + # Recurring task where today is not in complete_instances + - and: + - ${u}.isEmpty() == false + - ${C} + # No due date and no scheduled date + - date(${c}).isEmpty() + - date(${d}).isEmpty() + order: +${s} + sort: + - column: ${l} + direction: ASC +`}case"open-advanced-calendar-view":return`# Calendar + +${yb(r)} + +${o} + +views: + - type: tasknotesCalendar + name: "Calendar" + order: +${s} + options: + showScheduled: true + showDue: true + showRecurring: true + showTimeEntries: true + showTimeblocks: true + showPropertyBasedEvents: true + createDailyNotesFromDateLinks: true + calendarView: "timeGridWeek" + customDayCount: 3 + firstDay: ${e.settings.calendarViewSettings.firstDay} +`;case"open-agenda-view":{let l=Ut("due",e),c=nOe(i,l,"formula.dueIn"),d=W1(c),u=c.includes("formula.dueIn")?` +properties: + formula.dueIn: + displayName: Due in +`:"";return`# Agenda + +${yb(r)} + +${o} +${u} + +views: + - type: tasknotesCalendar + name: "Agenda" + order: +${d} + options: + showPropertyBasedEvents: false + showOverdueOnToday: true + createDailyNotesFromDateLinks: true + calendarView: "listWeek" + startDateProperty: file.ctime + listDayCount: 7 + titleProperty: file.basename +`}case"pomodoro-stats-base":return aOe(e);case"relationships":{let l=Ei(Ut("projects",e)),c=Ei(Ut("blockedBy",e)),d=Ei(Ut("recurrenceParent",e)),u=Ut("occurrenceDate",e),p=Ut("scheduled",e),m=Ut("status",e),f=Ut("sortOrder",e),h=W1(JLe(i,u,p)),g=r.map(T=>` - ${T}`).join(` +`),v=a.map(T=>` - ${T}`).join(` +`),k=v?`${v} +`:"";return`# Relationships +# This view shows all relationships for the current file +# Dynamically shows/hides tabs based on available data + +${o} + +views: + - type: tasknotesKanban + name: "Subtasks" + filters: + and: +${g} + - file.hasLink(this.file) && list(note.${l}).map(${vb("value")}).contains(this.file.asLink()) + order: +${s} + sort: + - column: ${f} + direction: DESC + groupBy: + property: ${m} + direction: ASC + - type: tasknotesTaskList + name: "Occurrences" + filters: + and: +${g} + - file.hasLink(this.file) && note.${d} && ${vb(`note.${d}`)} == this.file.asLink() + order: +${h} + sort: + - column: ${u} + direction: ASC + - type: tasknotesTaskList + name: "Projects" + filters: + and: +${k} - list(this.${l}).map(${vb("value")}).contains(file.asLink()) + order: +${s} + - type: tasknotesTaskList + name: "Blocked By" + filters: + and: +${g} + - list(this.note.${c}).map(${EX("value")}).contains(file.asLink()) + order: +${s} + sort: + - column: ${f} + direction: DESC + - type: tasknotesKanban + name: "Blocking" + filters: + and: +${g} + - list(note.${c}).map(${EX("value")}).contains(this.file.asLink()) + order: +${s} + sort: + - column: ${f} + direction: DESC + groupBy: + property: ${m} + direction: ASC +`}default:return""}}var G1=y(()=>{hb();Yg()});var NX,RX,ld,Kg,Zg,Ra,rt,Di,cd,dd,ud,ai,Ou,_X,FX,Pr=y(()=>{NX="tasknotes-mini-calendar-view",RX="tasknotes-agenda-view",ld="tasknotes-pomodoro-view",Kg="tasknotes-pomodoro-stats-view",Zg="tasknotes-stats-view",Ra="data-changed",rt="task-updated",Di="task-deleted",cd="pomodoro-start",dd="pomodoro-complete",ud="pomodoro-interrupt",ai="pomodoro-tick",Ou="date-changed",_X=[{id:"title",label:"Title",category:"text",supportedOperators:["is","is-not","contains","does-not-contain","is-empty","is-not-empty"],valueInputType:"text"},{id:"path",label:"Path",category:"select",supportedOperators:["contains","does-not-contain","is-empty","is-not-empty"],valueInputType:"select"},{id:"status",label:"Status",category:"select",supportedOperators:["is","is-not","is-empty","is-not-empty"],valueInputType:"select"},{id:"priority",label:"Priority",category:"select",supportedOperators:["is","is-not","is-empty","is-not-empty"],valueInputType:"select"},{id:"tags",label:"Tags",category:"select",supportedOperators:["contains","does-not-contain","is-empty","is-not-empty"],valueInputType:"select"},{id:"contexts",label:"Contexts",category:"select",supportedOperators:["contains","does-not-contain","is-empty","is-not-empty"],valueInputType:"select"},{id:"projects",label:"Projects",category:"select",supportedOperators:["contains","does-not-contain","is-empty","is-not-empty"],valueInputType:"select"},{id:"blockedBy",label:"Blocked By",category:"select",supportedOperators:["contains","does-not-contain","is-empty","is-not-empty"],valueInputType:"text"},{id:"blocking",label:"Blocking",category:"select",supportedOperators:["contains","does-not-contain","is-empty","is-not-empty"],valueInputType:"text"},{id:"due",label:"Due Date",category:"date",supportedOperators:["is","is-not","is-before","is-after","is-on-or-before","is-on-or-after","is-empty","is-not-empty"],valueInputType:"date"},{id:"scheduled",label:"Scheduled Date",category:"date",supportedOperators:["is","is-not","is-before","is-after","is-on-or-before","is-on-or-after","is-empty","is-not-empty"],valueInputType:"date"},{id:"completedDate",label:"Completed Date",category:"date",supportedOperators:["is","is-not","is-before","is-after","is-on-or-before","is-on-or-after","is-empty","is-not-empty"],valueInputType:"date"},{id:"dateCreated",label:"Created Date",category:"date",supportedOperators:["is","is-not","is-before","is-after","is-on-or-before","is-on-or-after","is-empty","is-not-empty"],valueInputType:"date"},{id:"dateModified",label:"Modified Date",category:"date",supportedOperators:["is","is-not","is-before","is-after","is-on-or-before","is-on-or-after","is-empty","is-not-empty"],valueInputType:"date"},{id:"archived",label:"Archived",category:"boolean",supportedOperators:["is-checked","is-not-checked"],valueInputType:"none"},{id:"hasSubtasks",label:"Has Subtasks",category:"boolean",supportedOperators:["is-checked","is-not-checked"],valueInputType:"none"},{id:"timeEstimate",label:"Time Estimate",category:"numeric",supportedOperators:["is","is-not","is-greater-than","is-less-than","is-greater-than-or-equal","is-less-than-or-equal"],valueInputType:"number"},{id:"recurrence",label:"Recurrence",category:"special",supportedOperators:["is-empty","is-not-empty"],valueInputType:"none"},{id:"status.isCompleted",label:"Completed",category:"boolean",supportedOperators:["is-checked","is-not-checked"],valueInputType:"none"},{id:"dependencies.isBlocked",label:"Blocked",category:"boolean",supportedOperators:["is-checked","is-not-checked"],valueInputType:"none"},{id:"dependencies.isBlocking",label:"Blocking Others",category:"boolean",supportedOperators:["is-checked","is-not-checked"],valueInputType:"none"}],FX=[{id:"is",label:"is",requiresValue:!0},{id:"is-not",label:"is not",requiresValue:!0},{id:"contains",label:"contains",requiresValue:!0},{id:"does-not-contain",label:"does not contain",requiresValue:!0},{id:"is-before",label:"is before",requiresValue:!0},{id:"is-after",label:"is after",requiresValue:!0},{id:"is-on-or-before",label:"is on or before",requiresValue:!0},{id:"is-on-or-after",label:"is on or after",requiresValue:!0},{id:"is-empty",label:"is empty",requiresValue:!1},{id:"is-not-empty",label:"is not empty",requiresValue:!1},{id:"is-checked",label:"is checked",requiresValue:!1},{id:"is-not-checked",label:"is not checked",requiresValue:!1},{id:"is-greater-than",label:"is greater than",requiresValue:!0},{id:"is-less-than",label:"is less than",requiresValue:!0},{id:"is-greater-than-or-equal",label:"is equal or greater than",requiresValue:!0},{id:"is-less-than-or-equal",label:"is equal or less than",requiresValue:!0}]});var $X={};Xe($X,{DEFAULT_CORE_FIELDS:()=>OX,DEFAULT_FIELD_GROUPS:()=>LX,createDefaultFieldConfig:()=>zX,getFieldsByGroup:()=>iOe,getFieldsForModal:()=>BX,initializeFieldConfig:()=>Nl,migrateUserFieldsToFieldConfig:()=>jX});function zX(){return{version:1,fields:[...OX],groups:[...LX]}}function BX(n,e){return n.fields.filter(t=>t.enabled).filter(t=>e?t.visibleInCreation:t.visibleInEdit).sort((t,r)=>{var o,l;let a=n.groups.find(c=>c.id===t.group),i=n.groups.find(c=>c.id===r.group),s=((o=a==null?void 0:a.order)!=null?o:0)-((l=i==null?void 0:i.order)!=null?l:0);return s!==0?s:t.order-r.order})}function iOe(n,e){let t=BX(n,e),r=new Map;for(let a of t){let i=r.get(a.group)||[];i.push(a),r.set(a.group,i)}return r}function jX(n){return!n||n.length===0?[]:n.map((e,t)=>({id:e.id||`user-${t}`,fieldType:"user",group:"custom",displayName:e.displayName||`Field ${t+1}`,visibleInCreation:!0,visibleInEdit:!0,order:t,enabled:!0}))}function Nl(n,e){if(n)return n;let t=zX();if(e&&e.length>0){let r=jX(e);t.fields.push(...r)}return t}var LX,OX,bb=y(()=>{LX=[{id:"basic",displayName:"Basic Information",order:0,collapsible:!1,defaultCollapsed:!1},{id:"metadata",displayName:"Metadata",order:1,collapsible:!0,defaultCollapsed:!1},{id:"organization",displayName:"Organization",order:2,collapsible:!0,defaultCollapsed:!1},{id:"dependencies",displayName:"Dependencies",order:3,collapsible:!0,defaultCollapsed:!1},{id:"custom",displayName:"Custom Fields",order:4,collapsible:!0,defaultCollapsed:!1}],OX=[{id:"title",fieldType:"core",group:"basic",displayName:"Title",visibleInCreation:!0,visibleInEdit:!0,order:0,enabled:!0,required:!0},{id:"details",fieldType:"core",group:"basic",displayName:"Details",visibleInCreation:!0,visibleInEdit:!0,order:1,enabled:!0},{id:"contexts",fieldType:"core",group:"metadata",displayName:"Contexts",visibleInCreation:!0,visibleInEdit:!0,order:0,enabled:!0},{id:"tags",fieldType:"core",group:"metadata",displayName:"Tags",visibleInCreation:!0,visibleInEdit:!0,order:1,enabled:!0},{id:"time-estimate",fieldType:"core",group:"metadata",displayName:"Time Estimate",visibleInCreation:!0,visibleInEdit:!0,order:2,enabled:!0},{id:"projects",fieldType:"organization",group:"organization",displayName:"Projects",visibleInCreation:!0,visibleInEdit:!0,order:0,enabled:!0},{id:"subtasks",fieldType:"organization",group:"organization",displayName:"Subtasks",visibleInCreation:!0,visibleInEdit:!0,order:1,enabled:!0},{id:"blocked-by",fieldType:"dependency",group:"dependencies",displayName:"Blocked By",visibleInCreation:!0,visibleInEdit:!0,order:0,enabled:!0},{id:"blocking",fieldType:"dependency",group:"dependencies",displayName:"Blocking",visibleInCreation:!0,visibleInEdit:!0,order:1,enabled:!0}]});function UX(n,e,t){if(!(e!=null&&e.fields))return!0;let r=e.fields.find(i=>i.id===n);if(!r)return!0;let a=t?r.visibleInCreation:r.visibleInEdit;return!!r.enabled&&!!a}function HX(n,e){let{getFieldsByGroup:t}=(bb(),BP($X)),r=t(n,e);return[...n.groups||[]].sort((i,s)=>i.order-s.order).map(i=>({id:i.id,fields:r.get(i.id)||[]})).filter(i=>i.fields.length>0)}var Y1=y(()=>{});function K1(n){let{container:e,fieldConfig:t,fieldRenderers:r,renderUserField:a}=n,i=r[t.id];return i?(i(e,t),!0):t.fieldType==="user"?(a(e,t),!0):!1}function VX(n){let e=HX(n.config,n.isCreationMode),t={groupsRendered:0,fieldsRendered:0,ignoredFieldIds:[]};for(let r of e){let a=r.id==="basic"?r.fields.filter(s=>!sOe.has(s.id)):r.fields;if(a.length===0)continue;let i=n.container.createDiv({cls:"task-modal__field-group"});t.groupsRendered+=1;for(let s of a)K1({container:i,fieldConfig:s,fieldRenderers:n.fieldRenderers,renderUserField:n.renderUserField})?t.fieldsRendered+=1:t.ignoredFieldIds.push(s.id)}return t}var sOe,WX=y(()=>{Y1();sOe=new Set(["title","details"])});function Z1(n){let e=typeof n=="function"?n():n,t=e==null?void 0:e.trim();return t||null}function oOe(n,e,t={}){let r=["TaskNotes"],a=Z1(n);return a&&r.push(a),t.category&&r.push(t.category),t.operation&&r.push(t.operation),`${r.map(i=>`[${i}]`).join("")} ${e}`}function e0(n,e,t,r,a){let i=[oOe(t,r,a)];a!=null&&a.details&&i.push(a.details),(a==null?void 0:a.error)!==void 0&&i.push(a.error),n[e](...i)}function M(n={}){var r,a;let e=(r=n.sink)!=null?r:console,t=(a=n.isDebugEnabled)!=null?a:(()=>!1);return{debug(i,s){t()&&e0(e,"debug",n.tag,i,s)},info(i,s){e0(e,"info",n.tag,i,s)},warn(i,s){e0(e,"warn",n.tag,i,s)},error(i,s){e0(e,"error",n.tag,i,s)},child(i){let s=n.tag;return M({...n,tag:()=>{let o=Z1(s),l=Z1(i);return[o,l].filter(Boolean).join("/")}})}}}var q=y(()=>{});function qX(n,e){let t=Object.keys(e).map(r=>lOe(n,r,e[r]));return t.length===1?t[0]:function(){t.forEach(r=>r())}}function lOe(n,e,t){let r=n[e],a=n.hasOwnProperty(e),i=a?r:function(){return Object.getPrototypeOf(n)[e].apply(this,arguments)},s=t(i);return r&&Object.setPrototypeOf(s,r),Object.setPrototypeOf(o,s),n[e]=o,l;function o(...c){return s===i&&n[e]===o&&l(),s.apply(this,c)}function l(){n[e]===o&&(a?n[e]=i:delete n[e]),s!==i&&(s=i,Object.setPrototypeOf(o,r||Function))}}var GX=y(()=>{});function YX(n){var i;let e=n.workspace.getActiveFile(),t=e instanceof Q1.TFile&&e.extension==="md"?e:n.vault.getMarkdownFiles()[0];if(!t){let s=Q1.TFile;t=new s(n.vault,"__tasknotes_editor_probe__.md")}let r=activeWindow.createDiv(),a=n.embedRegistry.embedByExtension.md({app:n,containerEl:r},t,"");try{a.editable=!0,a.showEditor();let s=a.editMode;if(!s)throw new Error("Markdown editor edit mode was not initialized");return Object.getPrototypeOf(Object.getPrototypeOf(s)).constructor}finally{try{(i=a.editMode)==null||i.destroy()}finally{a.unload(),r.remove()}}}var Q1,KX=y(()=>{Q1=require("obsidian")});var ez={};Xe(ez,{EmbeddableMarkdownEditor:()=>X1,getMarkdownEditorTooltipParent:()=>JX});function cOe(){return typeof app=="undefined"?class{constructor(e,t,r){this.containerEl=activeWindow.createDiv();this.editor={cm:new pd.EditorView};this.editorEl=activeWindow.createDiv();this.owner={editMode:null,editor:null};this._loaded=!1;this.app=e,this.containerEl=t}set(e){let t=this.editor.cm;t.dispatch({changes:{from:0,to:t.state.doc.length,insert:e}})}onUpdate(e,t){}buildLocalExtensions(){return[]}destroy(){}unload(){}}:YX(app)}function JX(n){var e,t;return(t=(e=n.ownerDocument)==null?void 0:e.body)!=null?t:activeDocument.body}var QX,Rl,pd,ZX,J1,X1,tz=y(()=>{QX=require("obsidian"),Rl=require("@codemirror/state"),pd=require("@codemirror/view");GX();KX();ZX={cursorLocation:void 0,value:"",cls:"",placeholder:"",onEnter:()=>!1,onEscape:()=>{},onTab:()=>!1,onSubmit:()=>{},onBlur:()=>{},onPaste:()=>{},onChange:()=>{},extensions:[],enterVimInsertMode:!1,file:void 0};J1=class{constructor(e){this.view=e}getDoc(){return this}getValue(){return this.view.state.doc.toString()}setValue(e){this.view.dispatch({changes:{from:0,to:this.view.state.doc.length,insert:e}})}getLine(e){return this.view.state.doc.line(e+1).text}lineCount(){return this.view.state.doc.lines}lastLine(){return this.lineCount()-1}getSelection(){let e=this.view.state.selection.main;return this.view.state.doc.sliceString(e.from,e.to)}somethingSelected(){return!this.view.state.selection.main.empty}setHeading(e){let t=Math.max(0,Math.min(6,Number(e)||0)),r=t>0?`${"#".repeat(t)} `:"";this.updateSelectedLines(a=>{let i=a.replace(/^ {0,3}#{1,6}\s+/,"");return`${r}${i}`})}toggleBulletList(){let t=this.getSelectedLines().some(r=>/^\s*[-*+]\s+/.test(r.text));this.updateSelectedLines(r=>{var s;if(t)return r.replace(/^(\s*)[-*+]\s+/,"$1");let[,a="",i=""]=(s=r.match(/^(\s*)(.*)$/))!=null?s:[];return`${a}- ${i}`})}toggleNumberedList(){let t=this.getSelectedLines().some(r=>/^\s*\d+[.)]\s+/.test(r.text));this.updateSelectedLines((r,a)=>{var o;if(t)return r.replace(/^(\s*)\d+[.)]\s+/,"$1");let[,i="",s=""]=(o=r.match(/^(\s*)(.*)$/))!=null?o:[];return`${i}${a+1}. ${s}`})}toggleNumberList(){this.toggleNumberedList()}toggleCheckListStatus(){this.updateSelectedLines(e=>{var a;if(/^(\s*[-*+]\s+\[[ xX]\]\s*)/.test(e))return e.replace(/^(\s*[-*+]\s+\[)([ xX])(\]\s*)/,(i,s,o,l)=>`${s}${o.toLowerCase()==="x"?" ":"x"}${l}`);if(/^\s*[-*+]\s+/.test(e))return e.replace(/^(\s*[-*+]\s+)/,"$1[ ] ");let[,t="",r=""]=(a=e.match(/^(\s*)(.*)$/))!=null?a:[];return`${t}- [ ] ${r}`})}toggleCheckList(){this.toggleCheckListStatus()}getRange(e,t){return this.view.state.doc.sliceString(this.posToOffset(e),this.posToOffset(t))}replaceSelection(e){let t=this.view.state.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:e},range:Rl.EditorSelection.cursor(r.from+e.length)}));this.view.dispatch(t)}replaceRange(e,t,r){this.view.dispatch({changes:{from:this.posToOffset(t),to:this.posToOffset(r!=null?r:t),insert:e}})}getCursor(e="head"){let t=this.view.state.selection.main;switch(e){case"from":return this.offsetToPos(t.from);case"to":return this.offsetToPos(t.to);case"anchor":return this.offsetToPos(t.anchor);case"head":default:return this.offsetToPos(t.head)}}listSelections(){return this.view.state.selection.ranges.map(e=>({anchor:this.offsetToPos(e.anchor),head:this.offsetToPos(e.head)}))}setCursor(e,t){if(typeof e=="number"){this.setSelection({line:e,ch:t!=null?t:0});return}this.setSelection(e)}setSelection(e,t){this.view.dispatch({selection:Rl.EditorSelection.range(this.posToOffset(e),this.posToOffset(t!=null?t:e))})}setSelections(e,t=0){e.length!==0&&this.view.dispatch({selection:Rl.EditorSelection.create(e.map(r=>{var a;return Rl.EditorSelection.range(this.posToOffset(r.anchor),this.posToOffset((a=r.head)!=null?a:r.anchor))}),t)})}focus(){this.view.focus()}blur(){this.view.contentDOM.blur()}hasFocus(){return this.view.hasFocus}transaction(e){var a,i;if(e.replaceSelection!==void 0){this.replaceSelection(e.replaceSelection);return}let t=(a=e.changes)==null?void 0:a.map(s=>{var o;return{from:this.posToOffset(s.from),to:this.posToOffset((o=s.to)!=null?o:s.from),insert:s.text}}),r=(i=e.selections)!=null?i:e.selection?[e.selection]:void 0;this.view.dispatch({...t?{changes:t}:{},...r&&r.length>0?{selection:Rl.EditorSelection.create(r.map(s=>{var o;return Rl.EditorSelection.range(this.posToOffset(s.from),this.posToOffset((o=s.to)!=null?o:s.from))}))}:{}})}posToOffset(e){let t=Math.max(1,Math.min(e.line+1,this.view.state.doc.lines)),r=this.view.state.doc.line(t);return Math.max(r.from,Math.min(r.from+e.ch,r.to))}offsetToPos(e){let t=Math.max(0,Math.min(e,this.view.state.doc.length)),r=this.view.state.doc.lineAt(t);return{line:r.number-1,ch:t-r.from}}getSelectedLines(){let e=this.view.state.doc,t=new Set;for(let r of this.view.state.selection.ranges){let a=Math.min(r.from,r.to),i=Math.max(r.from,r.to),s=e.lineAt(a).number,o=e.lineAt(i).number;o>s&&i===e.line(o).from&&(o-=1);for(let l=s;l<=o;l+=1)t.add(l)}return Array.from(t).sort((r,a)=>r-a).map(r=>{let a=e.line(r);return{number:r,text:a.text}})}updateSelectedLines(e){let t=this.view.state.doc,r=this.getSelectedLines().map((a,i)=>{let s=t.line(a.number);return{from:s.from,to:s.to,insert:e(a.text,i)}});r.length!==0&&this.view.dispatch({changes:r})}},X1=class extends cOe(){constructor(t,r,a={}){super(t,r,{app:t,onMarkdownScroll:()=>{},getMode:()=>"source"});this.hasEnteredVimInsertMode=!1;this.options={...ZX,...a},this.initial_value=this.options.value,this.scope=new QX.Scope(this.app.scope),this.scope.register(["Mod"],"Enter",(i,s)=>!0),this.scope.register(["Mod","Shift"],"Enter",(i,s)=>!0),this.owner.editMode=this,this.owner.editor=this.editor,this.activeEditorOwner={editMode:this,editor:new J1(this.editor.cm),file:this.getActiveEditorFile(),getMode:()=>"source"},this.set(a.value||""),this.uninstaller=qX(this.app.workspace,{setActiveLeaf:i=>function(...s){var o;(o=this.activeCM)!=null&&o.hasFocus||i.call(this,...s)}}),this.options.onBlur!==ZX.onBlur&&this.editor.cm.contentDOM.addEventListener("blur",()=>{this.app.keymap.popScope(this.scope),this._loaded&&this.options.onBlur(this)}),this.editor.cm.contentDOM.addEventListener("focusin",()=>{this.app.keymap.pushScope(this.scope),this.activeEditorOwner.file=this.getActiveEditorFile(),this.app.workspace.activeEditor=this.activeEditorOwner,this.options.enterVimInsertMode&&!this.hasEnteredVimInsertMode&&(this.hasEnteredVimInsertMode=!0,this.enterVimInsertMode())}),a.cls&&this.editorEl.classList.add(a.cls),a.cursorLocation&&this.editor.cm.dispatch({selection:Rl.EditorSelection.range(a.cursorLocation.anchor,a.cursorLocation.head)})}getActiveEditorFile(){var t;return this.options.file!==void 0?(t=this.options.file)!=null?t:null:this.app.workspace.getActiveFile()}get value(){return this.editor.cm.state.doc.toString()}setValue(t){this.set(t)}enterVimInsertMode(){window.setTimeout(()=>{var t,r;try{if(!this.app.vault.getConfig("vimMode"))return;let i=(t=window.CodeMirrorAdapter)==null?void 0:t.Vim;if(!i)return;let s=(r=this.editor.cm.cm)!=null?r:this.activeCM;if(!s)return;i.handleKey(s,"i","api")}catch(a){}},50)}onUpdate(t,r){super.onUpdate(t,r),r&&this.options.onChange(this.value,t)}buildLocalExtensions(){let t=super.buildLocalExtensions();return t.push((0,pd.tooltips)({parent:JX(this.containerEl)})),this.options.placeholder&&t.push((0,pd.placeholder)(this.options.placeholder)),t.push(pd.EditorView.domEventHandlers({paste:r=>{this.options.onPaste(r,this)}})),t.push(Rl.Prec.highest(pd.keymap.of([{key:"Enter",run:r=>this.options.onEnter(this,!1,!1),shift:r=>this.options.onEnter(this,!1,!0)},{key:"Shift-Mod-Enter",run:r=>(this.options.onSubmit(this,!0),!0)},{key:"Mod-Enter",run:r=>(this.options.onSubmit(this,!1),!0)},{key:"Escape",run:r=>(this.options.onEscape(this),!0)},{key:"Tab",run:r=>this.options.onTab(this,!1)},{key:"Shift-Tab",run:r=>this.options.onTab(this,!0)}]))),this.options.extensions&&this.options.extensions.length>0&&t.push(...this.options.extensions),t}destroy(){this._loaded&&this.unload(),this.app.keymap.popScope(this.scope);let t=this.app.workspace;t.activeEditor===this.activeEditorOwner&&(t.activeEditor=null),this.uninstaller&&(this.uninstaller(),this.uninstaller=void 0),this.containerEl.empty(),super.destroy()}onunload(){this.destroy()}}});function uOe(){return(tz(),BP(ez)).EmbeddableMarkdownEditor}function t0(n,e,t){try{let r=uOe();return new r(n,e,{...t,onSubmit:(a,i)=>t.onSubmit(i),onTab:(a,i)=>t.onTab(i)})}catch(r){dOe.error("Failed to create markdown editor:",{category:"persistence",operation:"create-markdown-editor",error:r});let a=e.createEl("textarea",{cls:t.cls+"-fallback",placeholder:t.placeholder});return a.value=t.value,a.addEventListener("input",i=>{t.onChange(i.target.value)}),a.addEventListener("keydown",i=>{i.key==="Enter"&&(i.ctrlKey||i.metaKey)?(i.preventDefault(),t.onSubmit(i.shiftKey)):i.key==="Escape"?(i.preventDefault(),t.onEscape()):i.key==="Tab"&&t.onTab(i.shiftKey)&&i.preventDefault()}),null}}var dOe,rz=y(()=>{q();dOe=M({tag:"Modals/TaskModalEditorAdapter"})});function XX(n){var r;let e=n.parent.createDiv("detail-label");e.textContent=n.label;let t=n.parent.createDiv("tn-task-modal__markdown-editor tn-task-modal__markdown-editor--details");return n.attachMobileKeyboardScrollGuard(t),t0(n.app,t,{value:n.value,placeholder:n.placeholder,cls:"details-editor",onChange:n.onChange,onSubmit:n.onSubmit,onEscape:n.onEscape,onTab:a=>n.tabMovesFocus?a?n.focusPreviousField():n.focusNextField():!1,file:(r=n.file)!=null?r:null})}function eee(n,e){n==null||n.setValue(e)}function tee(n){n==null||n.destroy()}var nz=y(()=>{rz()});function pOe(n){if(n==null)return;let t=(Array.isArray(n)?n:[n]).filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return t.length>0?t:void 0}function oee(n){let e=yOe(n),t=e.match(iz);if(t){let[,a,i,s]=t,o=Number(a),l=Number(i),c=Number(s);if(!lee(o,l,c))throw new Error(`Invalid date "${n}".`);return new Date(Date.UTC(o,l-1,c,0,0,0,0))}if(!vOe(e))throw new Error(`Invalid date "${n}".`);let r=new Date(e);if(!cee(r))throw new Error(`Invalid date "${n}".`);return r}function fOe(n){if(!cee(n))return"";let e=n.getUTCFullYear(),t=String(n.getUTCMonth()+1).padStart(2,"0"),r=String(n.getUTCDate()).padStart(2,"0");return`${e}-${t}-${r}`}function hOe(n){if(!/^\d{4}-\d{2}-\d{2}$/.test(n))throw new Error(`Invalid date "${n}". Expected YYYY-MM-DD.`);return oee(n),n}function gOe(n){if(!n)return"";let e=n.trim();if(iz.test(e))return e;let t=e.indexOf("T");if(t>-1)return e.slice(0,t);let r=e.indexOf(" ");return r>-1&&iz.test(e.slice(0,r))?e.slice(0,r):fOe(oee(e))}function ree(n){let e=[],t=new Set;for(let r of n)if(typeof r=="string")try{let a=hOe(gOe(r.trim()));t.has(a)||(t.add(a),e.push(a))}catch(a){}return e}function yOe(n,e="Date string cannot be empty"){if(!n||n.trim().length===0)throw new Error(e);return n.trim()}function vOe(n){let e=n.match(mOe);if(!e)return!1;let[,t,r,a,i,s,o,,l,c,d]=e;return lee(Number(t),Number(r),Number(a))&&kOe(Number(i),Number(s),Number(o))&&TOe(l,c,d)}function lee(n,e,t){let r=new Date(Date.UTC(n,e-1,t,0,0,0,0));return r.getUTCFullYear()===n&&r.getUTCMonth()===e-1&&r.getUTCDate()===t}function kOe(n,e,t){return n>=0&&n<=23&&e>=0&&e<=59&&t>=0&&t<=59}function TOe(n,e,t){if(!n)return!0;let r=Number(e),a=Number(t);return!(r>14||a>59||r===14&&a!==0)}function cee(n){return n instanceof Date&&!Number.isNaN(n.getTime())}function lz(n,e){return n[e]}function uee(n){if(typeof n=="string")return n;if(Array.isArray(n))return n.map(e=>String(e)).join(", ");if(n!=null){if(typeof n=="object")return"";if(typeof n=="number"||typeof n=="boolean")return String(n)}}function zu(n,e=iee){return yee(An(n),e)}function Bu(n,e=see){return yee(An(n),e)}function a0(n){let e=[],t=new Set,r=a=>{let i=pee(String(a));!i||t.has(i)||(t.add(i),e.push(i))};return Array.isArray(n)?(n.forEach(r),e):(typeof n=="string"&&n.trim().length>0&&r(n),e)}function pee(n){let e=n.trim();return(e.startsWith("#")?e.slice(1).trim():e).replace(/\s+/g,"-")}function cz(n,e,t,r=!1,a=[],i=iee,s=see){if(!e)return{};let o={path:t};if(typeof e.id=="string"&&e.id.trim().length>0&&(o.id=e.id),e[n.title]!==void 0){let l=uee(e[n.title]);l!==void 0&&l.trim().length>0?o.title=l:o.title=nee(t)}else(r||t)&&(o.title=nee(t));if(e[n.status]!==void 0&&(o.status=zu(e[n.status],i)),e[n.priority]!==void 0&&(o.priority=Bu(e[n.priority],s)),e[n.due]!==void 0&&(o.due=An(e[n.due])),e[n.scheduled]!==void 0&&(o.scheduled=An(e[n.scheduled])),e[n.contexts]!==void 0&&(o.contexts=r0(e[n.contexts])),e[n.projects]!==void 0&&(o.projects=r0(e[n.projects])),e[n.attachments]!==void 0&&(o.attachments=pOe(e[n.attachments])),e[n.timeEstimate]!==void 0&&(o.timeEstimate=bOe(e[n.timeEstimate])),e[n.completedDate]!==void 0&&(o.completedDate=An(e[n.completedDate])),e[n.recurrence]!==void 0&&(o.recurrence=An(e[n.recurrence])),e[n.recurrenceAnchor]!==void 0){let l=e[n.recurrenceAnchor];l==="scheduled"||l==="completion"?o.recurrence_anchor=l:l!=null&&!vee(l)&&(o.recurrence_anchor="scheduled")}if(e[n.dateCreated]!==void 0&&(o.dateCreated=An(e[n.dateCreated])),e[n.dateModified]!==void 0&&(o.dateModified=An(e[n.dateModified])),e[n.timeEntries]!==void 0&&(o.timeEntries=Array.isArray(e[n.timeEntries])?e[n.timeEntries]:[]),e[n.completeInstances]!==void 0){let l=e[n.completeInstances];o.complete_instances=ree(Array.isArray(l)?l:[l])}if(e[n.skippedInstances]!==void 0){let l=e[n.skippedInstances];o.skipped_instances=ree(Array.isArray(l)?l:[l])}if(e[n.recurrenceParent]!==void 0&&(o.recurrence_parent=An(e[n.recurrenceParent])),e[n.occurrenceDate]!==void 0&&(o.occurrence_date=An(e[n.occurrenceDate])),e[n.occurrenceMaterialization]!==void 0){let l=An(e[n.occurrenceMaterialization]);(l==="manual"||l==="on_completion"||l==="rolling")&&(o.occurrence_materialization=l)}if(e[n.occurrenceNextTrigger]!==void 0){let l=An(e[n.occurrenceNextTrigger]);(l==="completion"||l==="completion_or_skip")&&(o.occurrence_next_trigger=l)}if(e[n.occurrenceTemplate]!==void 0&&(o.occurrence_template=An(e[n.occurrenceTemplate])),e[n.occurrencePastHorizon]!==void 0&&(o.occurrence_past_horizon=An(e[n.occurrencePastHorizon])),e[n.occurrenceFutureHorizon]!==void 0&&(o.occurrence_future_horizon=An(e[n.occurrenceFutureHorizon])),n.blockedBy&&e[n.blockedBy]!==void 0&&(o.blockedBy=hee(e[n.blockedBy])),e[n.icsEventId]!==void 0&&(o.icsEventId=r0(e[n.icsEventId])),e[n.googleCalendarEventId]!==void 0&&(o.googleCalendarEventId=An(e[n.googleCalendarEventId])),e[n.googleCalendarExceptionEventId]!==void 0&&(o.googleCalendarExceptionEventId=An(e[n.googleCalendarExceptionEventId])),e[n.googleCalendarExceptionOriginalScheduled]!==void 0&&(o.googleCalendarExceptionOriginalScheduled=An(e[n.googleCalendarExceptionOriginalScheduled])),e[n.googleCalendarMovedOriginalDates]!==void 0&&(o.googleCalendarMovedOriginalDates=r0(e[n.googleCalendarMovedOriginalDates])),e[n.reminders]!==void 0&&(o.reminders=wOe(e[n.reminders])),e[n.sortOrder]!==void 0&&(o.sortOrder=An(e[n.sortOrder])),e.tags!==void 0){let l=a0(e.tags);o.tags=l,o.archived=l.includes(oz(n.archiveTag))}if(a.length>0){let l={},c=o;for(let d of a)e[d.key]!==void 0&&(c[d.key]=e[d.key],l[d.key]=e[d.key]);Object.keys(l).length>0&&(o.customProperties={...o.customProperties,...l})}return o}function dz(n,e,t,r=!1,a=[]){let i={};if(e.title!==void 0&&!r&&(i[n.title]=e.title),e.status!==void 0&&(i[n.status]=mee(e.status)),e.priority!==void 0&&(i[n.priority]=e.priority),e.due!==void 0&&(i[n.due]=e.due),e.scheduled!==void 0&&(i[n.scheduled]=e.scheduled),e.contexts!==void 0&&(!Array.isArray(e.contexts)||e.contexts.length>0)&&(i[n.contexts]=e.contexts),e.projects!==void 0&&(!Array.isArray(e.projects)||e.projects.length>0)&&(i[n.projects]=e.projects),e.attachments!==void 0&&e.attachments.length>0&&(i[n.attachments]=e.attachments),e.timeEstimate!==void 0&&(i[n.timeEstimate]=e.timeEstimate),e.completedDate!==void 0&&(i[n.completedDate]=e.completedDate),e.recurrence!==void 0&&(i[n.recurrence]=e.recurrence),e.recurrence_anchor!==void 0&&(i[n.recurrenceAnchor]=e.recurrence_anchor),e.recurrence_parent!==void 0&&(i[n.recurrenceParent]=e.recurrence_parent),e.occurrence_date!==void 0&&(i[n.occurrenceDate]=e.occurrence_date),e.occurrence_materialization!==void 0&&(i[n.occurrenceMaterialization]=e.occurrence_materialization),e.occurrence_next_trigger!==void 0&&(i[n.occurrenceNextTrigger]=e.occurrence_next_trigger),e.occurrence_template!==void 0&&(i[n.occurrenceTemplate]=e.occurrence_template),e.occurrence_past_horizon!==void 0&&(i[n.occurrencePastHorizon]=e.occurrence_past_horizon),e.occurrence_future_horizon!==void 0&&(i[n.occurrenceFutureHorizon]=e.occurrence_future_horizon),e.dateCreated!==void 0&&(i[n.dateCreated]=e.dateCreated),e.dateModified!==void 0&&(i[n.dateModified]=e.dateModified),e.sortOrder!==void 0&&(i[n.sortOrder]=e.sortOrder),e.timeEntries!==void 0&&(i[n.timeEntries]=e.timeEntries),e.complete_instances!==void 0&&(i[n.completeInstances]=e.complete_instances),e.skipped_instances!==void 0&&e.skipped_instances.length>0&&(i[n.skippedInstances]=e.skipped_instances),e.blockedBy!==void 0){let u=Array.isArray(e.blockedBy)?e.blockedBy.map(hz).filter(p=>!!p):[];u.length>0&&(i[n.blockedBy]=gee(u))}e.icsEventId!==void 0&&e.icsEventId.length>0&&(i[n.icsEventId]=e.icsEventId),e.googleCalendarEventId!==void 0&&(i[n.googleCalendarEventId]=e.googleCalendarEventId),e.googleCalendarExceptionEventId!==void 0&&(i[n.googleCalendarExceptionEventId]=e.googleCalendarExceptionEventId),e.googleCalendarExceptionOriginalScheduled!==void 0&&(i[n.googleCalendarExceptionOriginalScheduled]=e.googleCalendarExceptionOriginalScheduled),e.googleCalendarMovedOriginalDates!==void 0&&e.googleCalendarMovedOriginalDates.length>0&&(i[n.googleCalendarMovedOriginalDates]=e.googleCalendarMovedOriginalDates),e.reminders!==void 0&&e.reminders.length>0&&(i[n.reminders]=e.reminders);let s=a0(e.tags),o=t?oz(t):"",l=oz(n.archiveTag);o&&!s.includes(o)&&s.push(o),e.archived===!0&&!s.includes(l)?s.push(l):e.archived===!1&&(s=s.filter(u=>u!==l)),s.length>0&&(i.tags=s);let c=e.customProperties,d=e;for(let u of a)Object.prototype.hasOwnProperty.call(d,u.key)&&d[u.key]!==void 0?i[u.key]=d[u.key]:c&&Object.prototype.hasOwnProperty.call(c,u.key)&&c[u.key]!==void 0&&(i[u.key]=c[u.key]);return i}function mee(n){let e=n.toLowerCase();return e==="true"||e==="false"?e==="true":n}function i0(n,e){for(let[t,r]of Object.entries(n))if(r===e)return t;return null}function uz(n,e){return i0(n,e)!==null}function pz(n,e,t){return n[t]===e}function mz(n,e){return e.map(t=>n[t])}function fz(n){let e=[],t=Object.keys(n);for(let a of t)(!n[a]||n[a].trim()==="")&&e.push(`Field "${a}" cannot be empty`);let r=Object.values(n);return r.length!==new Set(r).size&&e.push("Field mappings must have unique property names"),{valid:e.length===0,errors:e}}function fee(n){return dee.includes(n)}function hz(n){if(typeof n=="string"){let s=n0(n.trim());return s?{uid:s,reltype:sz}:null}if(!n||typeof n!="object")return null;let e=n,t=typeof e.uid=="string"?e.uid.trim():"";if(!t)return null;let r=typeof e.reltype=="string"?e.reltype.trim().toUpperCase():"",a=fee(r)?r:sz,i=typeof e.gap=="string"&&e.gap.trim().length>0?e.gap.trim():void 0;return i?{uid:n0(t),reltype:a,gap:i}:{uid:n0(t),reltype:a}}function hee(n){if(n==null)return;let e=(Array.isArray(n)?n:[n]).map(hz).filter(t=>!!t);return e.length>0?e:void 0}function gee(n){return n.map(e=>{let r={uid:e.uid.startsWith("[[")?e.uid:`[[${e.uid}]]`,reltype:e.reltype};return e.gap&&e.gap.trim().length>0&&(r.gap=e.gap),r})}function n0(n){let e=n.trim(),t=e.match(/^\[\[([^|\]#]+)(?:#[^\]|]+)?(?:\|[^\]]+)?\]\]$/);if(t)return t[1].trim();let r=e.match(/^\[[^\]]+\]\(([^)#]+)(?:#[^)]+)?\)$/);return r?decodeURI(r[1].trim()):e}function yee(n,e=[]){if(n===void 0||e.length===0)return n;let t=e.find(o=>o.value===n);if(t)return t.value;let r=az(e,o=>o.label===n);if(r)return r.value;let a=n.trim().toLocaleLowerCase();if(a.length===0)return n;let i=az(e,o=>o.value.trim().toLocaleLowerCase()===a);if(i)return i.value;let s=az(e,o=>o.label.trim().toLocaleLowerCase()===a);return s?s.value:n}function az(n,e){let t=n.filter(e);return t.length===1?t[0]:void 0}function An(n){if(n!=null){if(typeof n=="string")return vee(n)?void 0:n;if(typeof n=="number"||typeof n=="boolean")return String(n);if(Array.isArray(n))return n.length===1?An(n[0]):void 0}}function r0(n){return Array.isArray(n)?n.map(String):[String(n)]}function bOe(n){if(typeof n=="number")return n;if(typeof n=="string"&&n.trim()!==""){let e=Number(n);return Number.isNaN(e)?void 0:e}}function wOe(n){if(Array.isArray(n)){let e=n.filter(t=>t!=null);return e.length>0?e:void 0}return n!=null?[n]:void 0}function oz(n){var e;return(e=a0(n)[0])!=null?e:""}function nee(n){var e;return((e=n.split("/").pop())==null?void 0:e.replace(/\.md$/i,"").trim())||void 0}function vee(n){return typeof n=="string"&&n.trim().length===0}var aee,iee,see,iz,mOe,sz,dee,gz=y(()=>{aee={title:"title",status:"status",priority:"priority",due:"due",scheduled:"scheduled",contexts:"contexts",projects:"projects",attachments:"attachments",timeEstimate:"timeEstimate",completedDate:"completedDate",dateCreated:"dateCreated",dateModified:"dateModified",recurrence:"recurrence",recurrenceAnchor:"recurrence_anchor",recurrenceParent:"recurrence_parent",occurrenceDate:"occurrence_date",occurrenceMaterialization:"occurrence_materialization",occurrenceNextTrigger:"occurrence_next_trigger",occurrenceTemplate:"occurrence_template",occurrencePastHorizon:"occurrence_past_horizon",occurrenceFutureHorizon:"occurrence_future_horizon",archiveTag:"archived",timeEntries:"timeEntries",completeInstances:"complete_instances",skippedInstances:"skipped_instances",blockedBy:"blockedBy",pomodoros:"pomodoros",icsEventId:"icsEventId",icsEventTag:"ics_event",googleCalendarEventId:"googleCalendarEventId",googleCalendarExceptionEventId:"googleCalendarExceptionEventId",googleCalendarExceptionOriginalScheduled:"googleCalendarExceptionOriginalScheduled",googleCalendarMovedOriginalDates:"googleCalendarMovedOriginalDates",reminders:"reminders",sortOrder:"tasknotes_manual_order"},iee=[{id:"none",value:"none",label:"None",color:"#cccccc",isCompleted:!1,excludeFromCycle:!1,order:0,autoArchive:!1,autoArchiveDelay:5},{id:"open",value:"open",label:"Open",color:"#808080",isCompleted:!1,excludeFromCycle:!1,order:1,autoArchive:!1,autoArchiveDelay:5},{id:"in-progress",value:"in-progress",label:"In progress",color:"#0066cc",isCompleted:!1,excludeFromCycle:!1,order:2,autoArchive:!1,autoArchiveDelay:5},{id:"done",value:"done",label:"Done",color:"#00aa00",isCompleted:!0,excludeFromCycle:!1,order:3,autoArchive:!1,autoArchiveDelay:5}],see=[{id:"none",value:"none",label:"None",color:"#cccccc",weight:0},{id:"low",value:"low",label:"Low",color:"#00aa00",weight:1},{id:"normal",value:"normal",label:"Normal",color:"#ffaa00",weight:2},{id:"high",value:"high",label:"High",color:"#ff0000",weight:3}];iz=/^(\d{4})-(\d{2})-(\d{2})$/,mOe=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{1,3})?(?:Z|([+-])(\d{2}):(\d{2}))?$/;sz="FINISHTOSTART",dee=["FINISHTOSTART","FINISHTOFINISH","STARTTOSTART","STARTTOFINISH"]});var wb=y(()=>{gz()});var tf,yz=y(()=>{wb();tf=class{constructor(e,t=[],r=[],a=[]){this.mapping=e;this.userFields=t;this.statuses=r;this.priorities=a}updateUserFields(e){this.userFields=e}updateConfiguredValues(e,t){this.statuses=e,this.priorities=t}getUserFields(){return[...this.userFields]}toUserField(e){return lz(this.mapping,e)}mapFromFrontmatter(e,t,r){let a=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0;return cz(this.mapping,a,t,r,this.userFields,this.statuses,this.priorities)}mapToFrontmatter(e,t,r){return dz(this.mapping,e,t,r,this.userFields)}updateMapping(e){this.mapping=e}getMapping(){return{...this.mapping}}lookupMappingKey(e){return i0(this.mapping,e)}isRecognizedProperty(e){return uz(this.mapping,e)}isPropertyForField(e,t){return pz(this.mapping,e,t)}toUserFields(e){return mz(this.mapping,e)}fromUserField(e){return this.lookupMappingKey(e)}static validateMapping(e){return fz(e)}}});var Sb,s0=y(()=>{gz();Sb=aee});var Qg,bn,rf=y(()=>{Qg=["MO","TU","WE","TH","FR","SA","SU"],bn=(function(){function n(e,t){if(t===0)throw new Error("Can't create weekday with n == 0");this.weekday=e,this.n=t}return n.fromStr=function(e){return new n(Qg.indexOf(e))},n.prototype.nth=function(e){return this.n===e?this:new n(this.weekday,e)},n.prototype.equals=function(e){return this.weekday===e.weekday&&this.n===e.n},n.prototype.toString=function(){var e=Qg[this.weekday];return this.n&&(e=(this.n>0?"+":"")+String(this.n)+e),e},n.prototype.getJsWeekday=function(){return this.weekday===6?0:this.weekday+1},n})()});function nf(n,e,t){t===void 0&&(t=" ");var r=String(n);return e=e>>0,r.length>e?String(r):(e=e-r.length,e>t.length&&(t+=It(t,e/t.length)),t.slice(0,e)+String(r))}var Ar,ds,vz,ua,Hs,It,kee,Tee,_a,o0,us,wn,Ft,ii=y(()=>{rf();Ar=function(n){return n!=null},ds=function(n){return typeof n=="number"},vz=function(n){return typeof n=="string"&&Qg.includes(n)},ua=Array.isArray,Hs=function(n,e){e===void 0&&(e=n),arguments.length===1&&(e=n,n=0);for(var t=[],r=n;r{ii();Go=function(n,e,t,r,a,i){return r===void 0&&(r=0),a===void 0&&(a=0),i===void 0&&(i=0),new Date(Date.UTC(n,e-1,t,r,a,i))},SOe=[31,28,31,30,31,30,31,31,30,31,30,31],wee=1e3*60*60*24,l0=9999,See=Go(1970,1,1),COe=[6,0,1,2,3,4,5],Jg=function(n){return n%4===0&&n%100!==0||n%400===0},kz=function(n){return n instanceof Date},af=function(n){return kz(n)&&!isNaN(n.getTime())},xOe=function(n,e){var t=n.getTime(),r=e.getTime(),a=t-r;return Math.round(a/wee)},Cb=function(n){return xOe(n,See)},c0=function(n){return new Date(See.getTime()+n*wee)},EOe=function(n){var e=n.getUTCMonth();return e===1&&Jg(n.getUTCFullYear())?29:SOe[e]},md=function(n){return COe[n.getUTCDay()]},Tz=function(n,e){var t=Go(n,e+1,1);return[md(t),EOe(t)]},d0=function(n,e){return e=e||n,new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()))},u0=function(n){var e=new Date(n.getTime());return e},bz=function(n){for(var e=[],t=0;t{DOe=(function(){function n(e,t){this.minDate=null,this.maxDate=null,this._result=[],this.total=0,this.method=e,this.args=t,e==="between"?(this.maxDate=t.inc?t.before:new Date(t.before.getTime()-1),this.minDate=t.inc?t.after:new Date(t.after.getTime()+1)):e==="before"?this.maxDate=t.inc?t.dt:new Date(t.dt.getTime()-1):e==="after"&&(this.minDate=t.inc?t.dt:new Date(t.dt.getTime()+1))}return n.prototype.accept=function(e){++this.total;var t=this.minDate&&ethis.maxDate;if(this.method==="between"){if(t)return!0;if(r)return!1}else if(this.method==="before"){if(r)return!1}else if(this.method==="after")return t?!0:(this.add(e),!1);return this.add(e)},n.prototype.add=function(e){return this._result.push(e),!0},n.prototype.getValue=function(){var e=this._result;switch(this.method){case"all":case"between":return e;case"before":case"after":default:return e.length?e[e.length-1]:null}},n.prototype.clone=function(){return new n(this.method,this.args)},n})(),hd=DOe});function ey(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");wz(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function ce(n,e,t){if(t||arguments.length===2)for(var r=0,a=e.length,i;r{wz=function(n,e){return wz=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(t[a]=r[a])},wz(n,e)};pa=function(){return pa=Object.assign||function(e){for(var t,r=1,a=arguments.length;r{gd();p0();POe=(function(n){ey(e,n);function e(t,r,a){var i=n.call(this,t,r)||this;return i.iterator=a,i}return e.prototype.add=function(t){return this.iterator(t,this._result.length)?(this._result.push(t),!0):!1},e})(hd),Sz=POe});var AOe,sf,m0=y(()=>{AOe={dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],tokens:{SKIP:/^[ \r\n\t]+|^\.$/,number:/^[1-9][0-9]*/,numberAsText:/^(one|two|three)/i,every:/^every/i,"day(s)":/^days?/i,"weekday(s)":/^weekdays?/i,"week(s)":/^weeks?/i,"hour(s)":/^hours?/i,"minute(s)":/^minutes?/i,"month(s)":/^months?/i,"year(s)":/^years?/i,on:/^(on|in)/i,at:/^(at)/i,the:/^the/i,first:/^first/i,second:/^second/i,third:/^third/i,nth:/^([1-9][0-9]*)(\.|th|nd|rd|st)/i,last:/^last/i,for:/^for/i,"time(s)":/^times?/i,until:/^(un)?til/i,monday:/^mo(n(day)?)?/i,tuesday:/^tu(e(s(day)?)?)?/i,wednesday:/^we(d(n(esday)?)?)?/i,thursday:/^th(u(r(sday)?)?)?/i,friday:/^fr(i(day)?)?/i,saturday:/^sa(t(urday)?)?/i,sunday:/^su(n(day)?)?/i,january:/^jan(uary)?/i,february:/^feb(ruary)?/i,march:/^mar(ch)?/i,april:/^apr(il)?/i,may:/^may/i,june:/^june?/i,july:/^july?/i,august:/^aug(ust)?/i,september:/^sep(t(ember)?)?/i,october:/^oct(ober)?/i,november:/^nov(ember)?/i,december:/^dec(ember)?/i,comma:/^(,\s*|(and|or)\s*)+/i}},sf=AOe});var Eee,MOe,IOe,NOe,_l,Dee=y(()=>{m0();Vs();ii();Eee=function(n,e){return n.indexOf(e)!==-1},MOe=function(n){return n.toString()},IOe=function(n,e,t){return"".concat(e," ").concat(t,", ").concat(n)},NOe=(function(){function n(e,t,r,a){if(t===void 0&&(t=MOe),r===void 0&&(r=sf),a===void 0&&(a=IOe),this.text=[],this.language=r||sf,this.gettext=t,this.dateFormatter=a,this.rrule=e,this.options=e.options,this.origOptions=e.origOptions,this.origOptions.bymonthday){var i=[].concat(this.options.bymonthday),s=[].concat(this.options.bynmonthday);i.sort(function(d,u){return d-u}),s.sort(function(d,u){return u-d}),this.bymonthday=i.concat(s),this.bymonthday.length||(this.bymonthday=null)}if(Ar(this.origOptions.byweekday)){var o=ua(this.origOptions.byweekday)?this.origOptions.byweekday:[this.origOptions.byweekday],l=String(o);this.byweekday={allWeeks:o.filter(function(d){return!d.n}),someWeeks:o.filter(function(d){return!!d.n}),isWeekdays:l.indexOf("MO")!==-1&&l.indexOf("TU")!==-1&&l.indexOf("WE")!==-1&&l.indexOf("TH")!==-1&&l.indexOf("FR")!==-1&&l.indexOf("SA")===-1&&l.indexOf("SU")===-1,isEveryDay:l.indexOf("MO")!==-1&&l.indexOf("TU")!==-1&&l.indexOf("WE")!==-1&&l.indexOf("TH")!==-1&&l.indexOf("FR")!==-1&&l.indexOf("SA")!==-1&&l.indexOf("SU")!==-1};var c=function(d,u){return d.weekday-u.weekday};this.byweekday.allWeeks.sort(c),this.byweekday.someWeeks.sort(c),this.byweekday.allWeeks.length||(this.byweekday.allWeeks=null),this.byweekday.someWeeks.length||(this.byweekday.someWeeks=null)}else this.byweekday=null}return n.isFullyConvertible=function(e){var t=!0;if(!(e.options.freq in n.IMPLEMENTED)||e.origOptions.until&&e.origOptions.count)return!1;for(var r in e.origOptions){if(Eee(["dtstart","tzid","wkst","freq"],r))return!0;if(!Eee(n.IMPLEMENTED[e.options.freq],r))return!1}return t},n.prototype.isFullyConvertible=function(){return n.isFullyConvertible(this.rrule)},n.prototype.toString=function(){var e=this.gettext;if(!(this.options.freq in n.IMPLEMENTED))return e("RRule error: Unable to fully convert this rrule to text");if(this.text=[e("every")],this[ye.FREQUENCIES[this.options.freq]](),this.options.until){this.add(e("until"));var t=this.options.until;this.add(this.dateFormatter(t.getUTCFullYear(),this.language.monthNames[t.getUTCMonth()],t.getUTCDate()))}else this.options.count&&this.add(e("for")).add(this.options.count.toString()).add(this.plural(this.options.count)?e("times"):e("time"));return this.isFullyConvertible()||this.add(e("(~ approximate)")),this.text.join("")},n.prototype.HOURLY=function(){var e=this.gettext;this.options.interval!==1&&this.add(this.options.interval.toString()),this.add(this.plural(this.options.interval)?e("hours"):e("hour"))},n.prototype.MINUTELY=function(){var e=this.gettext;this.options.interval!==1&&this.add(this.options.interval.toString()),this.add(this.plural(this.options.interval)?e("minutes"):e("minute"))},n.prototype.DAILY=function(){var e=this.gettext;this.options.interval!==1&&this.add(this.options.interval.toString()),this.byweekday&&this.byweekday.isWeekdays?this.add(this.plural(this.options.interval)?e("weekdays"):e("weekday")):this.add(this.plural(this.options.interval)?e("days"):e("day")),this.origOptions.bymonth&&(this.add(e("in")),this._bymonth()),this.bymonthday?this._bymonthday():this.byweekday?this._byweekday():this.origOptions.byhour&&this._byhour()},n.prototype.WEEKLY=function(){var e=this.gettext;this.options.interval!==1&&this.add(this.options.interval.toString()).add(this.plural(this.options.interval)?e("weeks"):e("week")),this.byweekday&&this.byweekday.isWeekdays?this.options.interval===1?this.add(this.plural(this.options.interval)?e("weekdays"):e("weekday")):this.add(e("on")).add(e("weekdays")):this.byweekday&&this.byweekday.isEveryDay?this.add(this.plural(this.options.interval)?e("days"):e("day")):(this.options.interval===1&&this.add(e("week")),this.origOptions.bymonth&&(this.add(e("in")),this._bymonth()),this.bymonthday?this._bymonthday():this.byweekday&&this._byweekday(),this.origOptions.byhour&&this._byhour())},n.prototype.MONTHLY=function(){var e=this.gettext;this.origOptions.bymonth?(this.options.interval!==1&&(this.add(this.options.interval.toString()).add(e("months")),this.plural(this.options.interval)&&this.add(e("in"))),this._bymonth()):(this.options.interval!==1&&this.add(this.options.interval.toString()),this.add(this.plural(this.options.interval)?e("months"):e("month"))),this.bymonthday?this._bymonthday():this.byweekday&&this.byweekday.isWeekdays?this.add(e("on")).add(e("weekdays")):this.byweekday&&this._byweekday()},n.prototype.YEARLY=function(){var e=this.gettext;this.origOptions.bymonth?(this.options.interval!==1&&(this.add(this.options.interval.toString()),this.add(e("years"))),this._bymonth()):(this.options.interval!==1&&this.add(this.options.interval.toString()),this.add(this.plural(this.options.interval)?e("years"):e("year"))),this.bymonthday?this._bymonthday():this.byweekday&&this._byweekday(),this.options.byyearday&&this.add(e("on the")).add(this.list(this.options.byyearday,this.nth,e("and"))).add(e("day")),this.options.byweekno&&this.add(e("in")).add(this.plural(this.options.byweekno.length)?e("weeks"):e("week")).add(this.list(this.options.byweekno,void 0,e("and")))},n.prototype._bymonthday=function(){var e=this.gettext;this.byweekday&&this.byweekday.allWeeks?this.add(e("on")).add(this.list(this.byweekday.allWeeks,this.weekdaytext,e("or"))).add(e("the")).add(this.list(this.bymonthday,this.nth,e("or"))):this.add(e("on the")).add(this.list(this.bymonthday,this.nth,e("and")))},n.prototype._byweekday=function(){var e=this.gettext;this.byweekday.allWeeks&&!this.byweekday.isWeekdays&&this.add(e("on")).add(this.list(this.byweekday.allWeeks,this.weekdaytext)),this.byweekday.someWeeks&&(this.byweekday.allWeeks&&this.add(e("and")),this.add(e("on the")).add(this.list(this.byweekday.someWeeks,this.weekdaytext,e("and"))))},n.prototype._byhour=function(){var e=this.gettext;this.add(e("at")).add(this.list(this.origOptions.byhour,void 0,e("and")))},n.prototype._bymonth=function(){this.add(this.list(this.options.bymonth,this.monthtext,this.gettext("and")))},n.prototype.nth=function(e){e=parseInt(e.toString(),10);var t,r=this.gettext;if(e===-1)return r("last");var a=Math.abs(e);switch(a){case 1:case 21:case 31:t=a+r("st");break;case 2:case 22:t=a+r("nd");break;case 3:case 23:t=a+r("rd");break;default:t=a+r("th")}return e<0?t+" "+r("last"):t},n.prototype.monthtext=function(e){return this.language.monthNames[e-1]},n.prototype.weekdaytext=function(e){var t=ds(e)?(e+1)%7:e.getJsWeekday();return(e.n?this.nth(e.n)+" ":"")+this.language.dayNames[t]},n.prototype.plural=function(e){return e%100!==1},n.prototype.add=function(e){return this.text.push(" "),this.text.push(e),this},n.prototype.list=function(e,t,r,a){var i=this;a===void 0&&(a=","),ua(e)||(e=[e]);var s=function(l,c,d){for(var u="",p=0;p366)throw new Error("Nth out of range: "+p);return r.nextSymbol(),r.accept("last")?-p:p;default:return!1}}function d(){r.accept("on"),r.accept("the");var p=c();if(p)for(t.bymonthday=[p],r.nextSymbol();r.accept("comma");){if(p=c(),!p)throw new Error("Unexpected symbol "+r.symbol+"; expected monthday");t.bymonthday.push(p),r.nextSymbol()}}function u(){if(r.symbol==="until"){var p=Date.parse(r.text);if(!p)throw new Error("Cannot parse until date:"+r.text);t.until=new Date(p)}else r.accept("for")&&(t.count=parseInt(r.value[0],10),r.expect("number"))}}var ROe,Pee=y(()=>{m0();Vs();ROe=(function(){function n(e){this.done=!0,this.rules=e}return n.prototype.start=function(e){return this.text=e,this.done=!1,this.nextSymbol()},n.prototype.isDone=function(){return this.done&&this.symbol===null},n.prototype.nextSymbol=function(){var e,t;this.symbol=null,this.value=null;do{if(this.done)return!1;var r=void 0;e=null;for(var a in this.rules){r=this.rules[a];var i=r.exec(this.text);i&&(e===null||i[0].length>e[0].length)&&(e=i,t=a)}if(e!=null&&(this.text=this.text.substr(e[0].length),this.text===""&&(this.done=!0)),e==null){this.done=!0,this.symbol=null,this.value=null;return}}while(t==="SKIP");return this.symbol=t,this.value=e,!0},n.prototype.accept=function(e){if(this.symbol===e){if(this.value){var t=this.value;return this.nextSymbol(),t}return this.nextSymbol(),!0}return!1},n.prototype.acceptNumber=function(){return this.accept("number")},n.prototype.expect=function(e){if(this.accept(e))return!0;throw new Error("expected "+e+" but found "+this.symbol)},n})()});function Db(n){return n{(function(n){n[n.YEARLY=0]="YEARLY",n[n.MONTHLY=1]="MONTHLY",n[n.WEEKLY=2]="WEEKLY",n[n.DAILY=3]="DAILY",n[n.HOURLY=4]="HOURLY",n[n.MINUTELY=5]="MINUTELY",n[n.SECONDLY=6]="SECONDLY"})(gt||(gt={}))});var Aee,ty,Mee,Iee,Nee=y(()=>{Dee();Pee();Vs();yd();m0();Aee=function(n,e){return e===void 0&&(e=sf),new ye(Eb(n,e)||void 0)},ty=["count","until","interval","byweekday","bymonthday","bymonth"];_l.IMPLEMENTED=[];_l.IMPLEMENTED[gt.HOURLY]=ty;_l.IMPLEMENTED[gt.MINUTELY]=ty;_l.IMPLEMENTED[gt.DAILY]=["byhour"].concat(ty);_l.IMPLEMENTED[gt.WEEKLY]=ty;_l.IMPLEMENTED[gt.MONTHLY]=ty;_l.IMPLEMENTED[gt.YEARLY]=["byweekno","byyearday"].concat(ty);Mee=function(n,e,t,r){return new _l(n,e,t,r).toString()},Iee=_l.isFullyConvertible});var ry,Ree,f0=y(()=>{gd();yd();ii();Fa();ry=(function(){function n(e,t,r,a){this.hour=e,this.minute=t,this.second=r,this.millisecond=a||0}return n.prototype.getHours=function(){return this.hour},n.prototype.getMinutes=function(){return this.minute},n.prototype.getSeconds=function(){return this.second},n.prototype.getMilliseconds=function(){return this.millisecond},n.prototype.getTime=function(){return(this.hour*60*60+this.minute*60+this.second)*1e3+this.millisecond},n})(),Ree=(function(n){ey(e,n);function e(t,r,a,i,s,o,l){var c=n.call(this,i,s,o,l)||this;return c.year=t,c.month=r,c.day=a,c}return e.fromDate=function(t){return new this(t.getUTCFullYear(),t.getUTCMonth()+1,t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.valueOf()%1e3)},e.prototype.getWeekday=function(){return md(new Date(this.getTime()))},e.prototype.getTime=function(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond)).getTime()},e.prototype.getDay=function(){return this.day},e.prototype.getMonth=function(){return this.month},e.prototype.getYear=function(){return this.year},e.prototype.addYears=function(t){this.year+=t},e.prototype.addMonths=function(t){if(this.month+=t,this.month>12){var r=Math.floor(this.month/12),a=_a(this.month,12);this.month=a,this.year+=r,this.month===0&&(this.month=12,--this.year)}},e.prototype.addWeekly=function(t,r){r>this.getWeekday()?this.day+=-(this.getWeekday()+1+(6-r))+t*7:this.day+=-(this.getWeekday()-r)+t*7,this.fixDay()},e.prototype.addDaily=function(t){this.day+=t,this.fixDay()},e.prototype.addHours=function(t,r,a){for(r&&(this.hour+=Math.floor((23-this.hour)/t)*t);;){this.hour+=t;var i=o0(this.hour,24),s=i.div,o=i.mod;if(s&&(this.hour=o,this.addDaily(s)),us(a)||Ft(a,this.hour))break}},e.prototype.addMinutes=function(t,r,a,i){for(r&&(this.minute+=Math.floor((1439-(this.hour*60+this.minute))/t)*t);;){this.minute+=t;var s=o0(this.minute,60),o=s.div,l=s.mod;if(o&&(this.minute=l,this.addHours(o,!1,a)),(us(a)||Ft(a,this.hour))&&(us(i)||Ft(i,this.minute)))break}},e.prototype.addSeconds=function(t,r,a,i,s){for(r&&(this.second+=Math.floor((86399-(this.hour*3600+this.minute*60+this.second))/t)*t);;){this.second+=t;var o=o0(this.second,60),l=o.div,c=o.mod;if(l&&(this.second=c,this.addMinutes(l,!1,a,i)),(us(a)||Ft(a,this.hour))&&(us(i)||Ft(i,this.minute))&&(us(s)||Ft(s,this.second)))break}},e.prototype.fixDay=function(){if(!(this.day<=28)){var t=Tz(this.year,this.month-1)[1];if(!(this.day<=t))for(;this.day>t;){if(this.day-=t,++this.month,this.month===13&&(this.month=1,++this.year,this.year>l0))return;t=Tz(this.year,this.month-1)[1]}}},e.prototype.add=function(t,r){var a=t.freq,i=t.interval,s=t.wkst,o=t.byhour,l=t.byminute,c=t.bysecond;switch(a){case gt.YEARLY:return this.addYears(i);case gt.MONTHLY:return this.addMonths(i);case gt.WEEKLY:return this.addWeekly(i,s);case gt.DAILY:return this.addDaily(i);case gt.HOURLY:return this.addHours(i,r,o);case gt.MINUTELY:return this.addMinutes(i,r,o,l);case gt.SECONDLY:return this.addSeconds(i,r,o,l,c)}},e})(ry)});function Cz(n){for(var e=[],t=Object.keys(n),r=0,a=t;r=-366&&r<=366))throw new Error("bysetpos must be between 1 and 366, or between -366 and -1")}}if(!(e.byweekno||wn(e.byweekno)||wn(e.byyearday)||e.bymonthday||wn(e.bymonthday)||Ar(e.byweekday)||Ar(e.byeaster)))switch(e.freq){case ye.YEARLY:e.bymonth||(e.bymonth=e.dtstart.getUTCMonth()+1),e.bymonthday=e.dtstart.getUTCDate();break;case ye.MONTHLY:e.bymonthday=e.dtstart.getUTCDate();break;case ye.WEEKLY:e.byweekday=[md(e.dtstart)];break}if(Ar(e.bymonth)&&!ua(e.bymonth)&&(e.bymonth=[e.bymonth]),Ar(e.byyearday)&&!ua(e.byyearday)&&ds(e.byyearday)&&(e.byyearday=[e.byyearday]),!Ar(e.bymonthday))e.bymonthday=[],e.bynmonthday=[];else if(ua(e.bymonthday)){for(var a=[],i=[],t=0;t0?a.push(r):r<0&&i.push(r)}e.bymonthday=a,e.bynmonthday=i}else e.bymonthday<0?(e.bynmonthday=[e.bymonthday],e.bymonthday=[]):(e.bynmonthday=[],e.bymonthday=[e.bymonthday]);if(Ar(e.byweekno)&&!ua(e.byweekno)&&(e.byweekno=[e.byweekno]),!Ar(e.byweekday))e.bynweekday=null;else if(ds(e.byweekday))e.byweekday=[e.byweekday],e.bynweekday=null;else if(vz(e.byweekday))e.byweekday=[bn.fromStr(e.byweekday).weekday],e.bynweekday=null;else if(e.byweekday instanceof bn)!e.byweekday.n||e.freq>ye.MONTHLY?(e.byweekday=[e.byweekday.weekday],e.bynweekday=null):(e.bynweekday=[[e.byweekday.weekday,e.byweekday.n]],e.byweekday=null);else{for(var s=[],o=[],t=0;tye.MONTHLY?s.push(l.weekday):o.push([l.weekday,l.n])}e.byweekday=wn(s)?s:null,e.bynweekday=wn(o)?o:null}return Ar(e.byhour)?ds(e.byhour)&&(e.byhour=[e.byhour]):e.byhour=e.freq{gd();yd();ii();Vs();Fa();rf();f0()});function Mb(n){var e=n.split(` +`).map(_Oe).filter(function(t){return t!==null});return pa(pa({},e[0]),e[1])}function Ab(n){var e={},t=/DTSTART(?:;TZID=([^:=]+?))?(?::|=)([^;\s]+)/i.exec(n);if(!t)return e;var r=t[1],a=t[2];return r&&(e.tzid=r),e.dtstart=xb(a),e}function _Oe(n){if(n=n.replace(/^\s+|\s+$/,""),!n.length)return null;var e=/^([A-Z]+?)[:;]/.exec(n.toUpperCase());if(!e)return Oee(n);var t=e[1];switch(t.toUpperCase()){case"RRULE":case"EXRULE":return Oee(n);case"DTSTART":return Ab(n);default:throw new Error("Unsupported RFC prop ".concat(t," in ").concat(n))}}function Oee(n){var e=n.replace(/^RRULE:/i,""),t=Ab(e),r=n.replace(/^(?:RRULE|EXRULE):/i,"").split(";");return r.forEach(function(a){var i=a.split("="),s=i[0],o=i[1];switch(s.toUpperCase()){case"FREQ":t.freq=gt[o.toUpperCase()];break;case"WKST":t.wkst=Ws[o.toUpperCase()];break;case"COUNT":case"INTERVAL":case"BYSETPOS":case"BYMONTH":case"BYMONTHDAY":case"BYYEARDAY":case"BYWEEKNO":case"BYHOUR":case"BYMINUTE":case"BYSECOND":var l=FOe(o),c=s.toLowerCase();t[c]=l;break;case"BYWEEKDAY":case"BYDAY":t.byweekday=LOe(o);break;case"DTSTART":case"TZID":var d=Ab(n);t.tzid=d.tzid,t.dtstart=d.dtstart;break;case"UNTIL":t.until=xb(o);break;case"BYEASTER":t.byeaster=Number(o);break;default:throw new Error("Unknown RRULE property '"+s+"'")}}),t}function FOe(n){if(n.indexOf(",")!==-1){var e=n.split(",");return e.map(zee)}return zee(n)}function zee(n){return/^[+-]?\d+$/.test(n)?Number(n):n}function LOe(n){var e=n.split(",");return e.map(function(t){if(t.length===2)return Ws[t];var r=t.match(/^([+-]?\d{1,2})([A-Z]{2})$/);if(!r||r.length<3)throw new SyntaxError("Invalid weekday string: ".concat(t));var a=Number(r[1]),i=r[2],s=Ws[i].weekday;return new bn(s,a)})}var Ez=y(()=>{gd();yd();rf();Fa();Vs()});var of,h0=y(()=>{Fa();of=(function(){function n(e,t){if(isNaN(e.getTime()))throw new RangeError("Invalid date passed to DateWithZone");this.date=e,this.tzid=t}return Object.defineProperty(n.prototype,"isUTC",{get:function(){return!this.tzid||this.tzid.toUpperCase()==="UTC"},enumerable:!1,configurable:!0}),n.prototype.toString=function(){var e=Xg(this.date.getTime(),this.isUTC);return this.isUTC?":".concat(e):";TZID=".concat(this.tzid,":").concat(e)},n.prototype.getTime=function(){return this.date.getTime()},n.prototype.rezonedDate=function(){return this.isUTC?this.date:Cee(this.date,this.tzid)},n})()});function Ib(n){for(var e=[],t="",r=Object.keys(n),a=Object.keys(Pb),i=0;i{Vs();ii();rf();Fa();h0()});function zOe(n,e){return Array.isArray(n)?!Array.isArray(e)||n.length!==e.length?!1:n.every(function(t,r){return t.getTime()===e[r].getTime()}):n instanceof Date?e instanceof Date&&n.getTime()===e.getTime():n===e}var Bee,jee=y(()=>{p0();Fa();ii();Bee=(function(){function n(){this.all=!1,this.before=[],this.after=[],this.between=[]}return n.prototype._cacheAdd=function(e,t,r){t&&(t=t instanceof Date?u0(t):bz(t)),e==="all"?this.all=t:(r._value=t,this[e].push(r))},n.prototype._cacheGet=function(e,t){var r=!1,a=t?Object.keys(t):[],i=function(d){for(var u=0;u{gd();ii();$ee=ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce([],It(1,31),!0),It(2,28),!0),It(3,31),!0),It(4,30),!0),It(5,31),!0),It(6,30),!0),It(7,31),!0),It(8,31),!0),It(9,30),!0),It(10,31),!0),It(11,30),!0),It(12,31),!0),It(1,7),!0),Uee=ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce([],It(1,31),!0),It(2,29),!0),It(3,31),!0),It(4,30),!0),It(5,31),!0),It(6,30),!0),It(7,31),!0),It(8,31),!0),It(9,30),!0),It(10,31),!0),It(11,30),!0),It(12,31),!0),It(1,7),!0),BOe=Hs(1,29),jOe=Hs(1,30),ju=Hs(1,31),La=Hs(1,32),Hee=ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce([],La,!0),jOe,!0),La,!0),ju,!0),La,!0),ju,!0),La,!0),La,!0),ju,!0),La,!0),ju,!0),La,!0),La.slice(0,7),!0),Vee=ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce([],La,!0),BOe,!0),La,!0),ju,!0),La,!0),ju,!0),La,!0),La,!0),ju,!0),La,!0),ju,!0),La,!0),La.slice(0,7),!0),$Oe=Hs(-28,0),UOe=Hs(-29,0),$u=Hs(-30,0),Oa=Hs(-31,0),Wee=ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce([],Oa,!0),UOe,!0),Oa,!0),$u,!0),Oa,!0),$u,!0),Oa,!0),Oa,!0),$u,!0),Oa,!0),$u,!0),Oa,!0),Oa.slice(0,7),!0),qee=ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce(ce([],Oa,!0),$Oe,!0),Oa,!0),$u,!0),Oa,!0),$u,!0),Oa,!0),Oa,!0),$u,!0),Oa,!0),$u,!0),Oa,!0),Oa.slice(0,7),!0),Gee=[0,31,60,91,121,152,182,213,244,274,305,335,366],Yee=[0,31,59,90,120,151,181,212,243,273,304,334,365],Pz=(function(){for(var n=[],e=0;e<55;e++)n=n.concat(Hs(7));return n})()});function Zee(n,e){var t=Go(n,1,1),r=Jg(n)?366:365,a=Jg(n+1)?366:365,i=Cb(t),s=md(t),o=pa(pa({yearlen:r,nextyearlen:a,yearordinal:i,yearweekday:s},HOe(n)),{wnomask:null});if(us(e.byweekno))return o;o.wnomask=It(0,r+7);var l,c,d=l=_a(7-s+e.wkst,7);d>=4?(d=0,c=o.yearlen+_a(s-e.wkst,7)):c=r-d;for(var u=Math.floor(c/7),p=_a(c,7),m=Math.floor(u+p/4),f=0;f0&&h<=m){var g=void 0;h>1?(g=d+(h-1)*7,d!==l&&(g-=7-l)):g=d;for(var v=0;v<7&&(o.wnomask[g]=1,g++,o.wdaymask[g]!==e.wkst);v++);}}if(Ft(e.byweekno,1)){var g=d+m*7;if(d!==l&&(g-=7-l),g=4?(b=0,S=w+_a(T-e.wkst,7)):S=r-d,k=Math.floor(52+_a(S,7)/4)}if(Ft(e.byweekno,k))for(var g=0;g{gd();Fa();ii();Kee()});function Jee(n,e,t,r,a,i){var s={lastyear:n,lastmonth:e,nwdaymask:[]},o=[];if(i.freq===ye.YEARLY)if(us(i.bymonth))o=[[0,t]];else for(var l=0;l{Vs();ii()});function ete(n,e){e===void 0&&(e=0);var t=n%19,r=Math.floor(n/100),a=n%100,i=Math.floor(r/4),s=r%4,o=Math.floor((r+8)/25),l=Math.floor((r-o+1)/3),c=Math.floor(19*t+r-i-l+15)%30,d=Math.floor(a/4),u=a%4,p=Math.floor(32+2*s+2*d-c-u)%7,m=Math.floor((t+11*c+22*p)/451),f=Math.floor((c+p-7*m+114)/31),h=(c+p-7*m+114)%31+1,g=Date.UTC(n,f-1,h+e),v=Date.UTC(n,0,1);return[Math.ceil((g-v)/(1e3*60*60*24))]}var tte=y(()=>{});var VOe,rte,nte=y(()=>{ii();yd();Qee();Xee();tte();f0();Fa();VOe=(function(){function n(e){this.options=e}return n.prototype.rebuild=function(e,t){var r=this.options;if(e!==this.lastyear&&(this.yearinfo=Zee(e,r)),wn(r.bynweekday)&&(t!==this.lastmonth||e!==this.lastyear)){var a=this.yearinfo,i=a.yearlen,s=a.mrange,o=a.wdaymask;this.monthinfo=Jee(e,t,i,s,o,r)}Ar(r.byeaster)&&(this.eastermask=ete(e,r.byeaster))},Object.defineProperty(n.prototype,"lastyear",{get:function(){return this.monthinfo?this.monthinfo.lastyear:null},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"lastmonth",{get:function(){return this.monthinfo?this.monthinfo.lastmonth:null},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"yearlen",{get:function(){return this.yearinfo.yearlen},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"yearordinal",{get:function(){return this.yearinfo.yearordinal},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"mrange",{get:function(){return this.yearinfo.mrange},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"wdaymask",{get:function(){return this.yearinfo.wdaymask},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"mmask",{get:function(){return this.yearinfo.mmask},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"wnomask",{get:function(){return this.yearinfo.wnomask},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"nwdaymask",{get:function(){return this.monthinfo?this.monthinfo.nwdaymask:[]},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"nextyearlen",{get:function(){return this.yearinfo.nextyearlen},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"mdaymask",{get:function(){return this.yearinfo.mdaymask},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"nmdaymask",{get:function(){return this.yearinfo.nmdaymask},enumerable:!1,configurable:!0}),n.prototype.ydayset=function(){return[Hs(this.yearlen),0,this.yearlen]},n.prototype.mdayset=function(e,t){for(var r=this.mrange[t-1],a=this.mrange[t],i=It(null,this.yearlen),s=r;s{Fa();ii()});function g0(n,e){var t=e.dtstart,r=e.freq,a=e.interval,i=e.until,s=e.bysetpos,o=e.count;if(o===0||a===0)return vd(n);var l=Ree.fromDate(t),c=new rte(e);c.rebuild(l.year,l.month);for(var d=GOe(c,l,e);;){var u=c.getdayset(r)(l.year,l.month,l.day),p=u[0],m=u[1],f=u[2],h=qOe(p,m,f,c,e);if(wn(s))for(var g=ate(s,d,m,f,c,p),v=0;vi)return vd(n);if(k>=t){var T=ste(k,e);if(!n.accept(T)||o&&(--o,!o))return vd(n)}}else for(var v=m;vi)return vd(n);if(k>=t){var T=ste(k,e);if(!n.accept(T)||o&&(--o,!o))return vd(n)}}}if(e.interval===0||(l.add(e,h),l.year>l0))return vd(n);Db(r)||(d=c.gettimeset(r)(l.hour,l.minute,l.second,0)),c.rebuild(l.year,l.month)}}function WOe(n,e,t){var r=t.bymonth,a=t.byweekno,i=t.byweekday,s=t.byeaster,o=t.bymonthday,l=t.bynmonthday,c=t.byyearday;return wn(r)&&!Ft(r,n.mmask[e])||wn(a)&&!n.wnomask[e]||wn(i)&&!Ft(i,n.wdaymask[e])||wn(n.nwdaymask)&&!n.nwdaymask[e]||s!==null&&!Ft(n.eastermask,e)||(wn(o)||wn(l))&&!Ft(o,n.mdaymask[e])&&!Ft(l,n.nmdaymask[e])||wn(c)&&(e=n.yearlen&&!Ft(c,e+1-n.yearlen)&&!Ft(c,-n.nextyearlen+e-n.yearlen))}function ste(n,e){return new of(n,e.tzid).rezonedDate()}function vd(n){return n.getValue()}function qOe(n,e,t,r,a){for(var i=!1,s=e;s=ye.HOURLY&&wn(a)&&!Ft(a,e.hour)||r>=ye.MINUTELY&&wn(i)&&!Ft(i,e.minute)||r>=ye.SECONDLY&&wn(s)&&!Ft(s,e.second)?[]:n.gettimeset(r)(e.hour,e.minute,e.second,e.millisecond)}var Az=y(()=>{yd();Fa();nte();Vs();xz();ii();h0();ite();f0()});var Ws,Pb,Lee,ye,Vs=y(()=>{Fa();p0();xee();Nee();yd();xz();Ez();Dz();jee();rf();Az();Ws={MO:new bn(0),TU:new bn(1),WE:new bn(2),TH:new bn(3),FR:new bn(4),SA:new bn(5),SU:new bn(6)},Pb={freq:gt.YEARLY,dtstart:null,interval:1,wkst:Ws.MO,count:null,until:null,tzid:null,bysetpos:null,bymonth:null,bymonthday:null,bynmonthday:null,byyearday:null,byweekno:null,byweekday:null,bynweekday:null,byhour:null,byminute:null,bysecond:null,byeaster:null},Lee=Object.keys(Pb),ye=(function(){function n(e,t){e===void 0&&(e={}),t===void 0&&(t=!1),this._cache=t?null:new Bee,this.origOptions=Cz(e);var r=_ee(e).parsedOptions;this.options=r}return n.parseText=function(e,t){return Eb(e,t)},n.fromText=function(e,t){return Aee(e,t)},n.fromString=function(e){return new n(n.parseString(e)||void 0)},n.prototype._iter=function(e){return g0(e,this.options)},n.prototype._cacheGet=function(e,t){return this._cache?this._cache._cacheGet(e,t):!1},n.prototype._cacheAdd=function(e,t,r){if(this._cache)return this._cache._cacheAdd(e,t,r)},n.prototype.all=function(e){if(e)return this._iter(new Sz("all",{},e));var t=this._cacheGet("all");return t===!1&&(t=this._iter(new hd("all",{})),this._cacheAdd("all",t)),t},n.prototype.between=function(e,t,r,a){if(r===void 0&&(r=!1),!af(e)||!af(t))throw new Error("Invalid date passed in to RRule.between");var i={before:t,after:e,inc:r};if(a)return this._iter(new Sz("between",i,a));var s=this._cacheGet("between",i);return s===!1&&(s=this._iter(new hd("between",i)),this._cacheAdd("between",s,i)),s},n.prototype.before=function(e,t){if(t===void 0&&(t=!1),!af(e))throw new Error("Invalid date passed in to RRule.before");var r={dt:e,inc:t},a=this._cacheGet("before",r);return a===!1&&(a=this._iter(new hd("before",r)),this._cacheAdd("before",a,r)),a},n.prototype.after=function(e,t){if(t===void 0&&(t=!1),!af(e))throw new Error("Invalid date passed in to RRule.after");var r={dt:e,inc:t},a=this._cacheGet("after",r);return a===!1&&(a=this._iter(new hd("after",r)),this._cacheAdd("after",a,r)),a},n.prototype.count=function(){return this.all().length},n.prototype.toString=function(){return Ib(this.origOptions)},n.prototype.toText=function(e,t,r){return Mee(this,e,t,r)},n.prototype.isFullyConvertibleToText=function(){return Iee(this)},n.prototype.clone=function(){return new n(this.origOptions)},n.FREQUENCIES=["YEARLY","MONTHLY","WEEKLY","DAILY","HOURLY","MINUTELY","SECONDLY"],n.YEARLY=gt.YEARLY,n.MONTHLY=gt.MONTHLY,n.WEEKLY=gt.WEEKLY,n.DAILY=gt.DAILY,n.HOURLY=gt.HOURLY,n.MINUTELY=gt.MINUTELY,n.SECONDLY=gt.SECONDLY,n.MO=Ws.MO,n.TU=Ws.TU,n.WE=Ws.WE,n.TH=Ws.TH,n.FR=Ws.FR,n.SA=Ws.SA,n.SU=Ws.SU,n.parseString=Mb,n.optionsToString=Ib,n})()});function ote(n,e,t,r,a,i){var s={},o=n.accept;function l(p,m){t.forEach(function(f){f.between(p,m,!0).forEach(function(h){s[Number(h)]=!0})})}a.forEach(function(p){var m=new of(p,i).rezonedDate();s[Number(m)]=!0}),n.accept=function(p){var m=Number(p);return isNaN(m)?o.call(this,p):!s[m]&&(l(new Date(m-1),new Date(m+1)),!s[m])?(s[m]=!0,o.call(this,p)):!0},n.method==="between"&&(l(n.args.after,n.args.before),n.accept=function(p){var m=Number(p);return s[m]?!0:(s[m]=!0,o.call(this,p))});for(var c=0;c{h0();Az();Fa()});function YOe(n,e){var t=[],r=[],a=[],i=[],s=Ab(n),o=s.dtstart,l=s.tzid,c=XOe(n,e.unfold);return c.forEach(function(d){var u;if(d){var p=JOe(d),m=p.name,f=p.parms,h=p.value;switch(m.toUpperCase()){case"RRULE":if(f.length)throw new Error("unsupported RRULE parm: ".concat(f.join(",")));t.push(Mb(d));break;case"RDATE":var g=(u=/RDATE(?:;TZID=([^:=]+))?/i.exec(d))!==null&&u!==void 0?u:[],v=g[1];v&&!l&&(l=v),r=r.concat(dte(h,f));break;case"EXRULE":if(f.length)throw new Error("unsupported EXRULE parm: ".concat(f.join(",")));a.push(Mb(h));break;case"EXDATE":i=i.concat(dte(h,f));break;case"DTSTART":break;default:throw new Error("unsupported property: "+m)}}}),{dtstart:o,tzid:l,rrulevals:t,rdatevals:r,exrulevals:a,exdatevals:i}}function KOe(n,e){var t=YOe(n,e),r=t.rrulevals,a=t.rdatevals,i=t.exrulevals,s=t.exdatevals,o=t.dtstart,l=t.tzid,c=e.cache===!1;if(e.compatible&&(e.forceset=!0,e.unfold=!0),e.forceset||r.length>1||a.length||i.length||s.length){var d=new y0(c);return d.dtstart(o),d.tzid(l||void 0),r.forEach(function(p){d.rrule(new ye(Mz(p,o,l),c))}),a.forEach(function(p){d.rdate(p)}),i.forEach(function(p){d.exrule(new ye(Mz(p,o,l),c))}),s.forEach(function(p){d.exdate(p)}),e.compatible&&e.dtstart&&d.rdate(o),d}var u=r[0]||{};return new ye(Mz(u,u.dtstart||e.dtstart||o,u.tzid||e.tzid||l),c)}function Nb(n,e){return e===void 0&&(e={}),KOe(n,ZOe(e))}function Mz(n,e,t){return pa(pa({},n),{dtstart:e,tzid:t})}function ZOe(n){var e=[],t=Object.keys(n),r=Object.keys(cte);if(t.forEach(function(a){Ft(r,a)||e.push(a)}),e.length)throw new Error("Invalid options: "+e.join(", "));return pa(pa({},cte),n)}function QOe(n){if(n.indexOf(":")===-1)return{name:"RRULE",value:n};var e=Tee(n,":",1),t=e[0],r=e[1];return{name:t,value:r}}function JOe(n){var e=QOe(n),t=e.name,r=e.value,a=t.split(";");if(!a)throw new Error("empty property name");return{name:a[0].toUpperCase(),parms:a.slice(1),value:r}}function XOe(n,e){if(e===void 0&&(e=!1),n=n&&n.trim(),!n)throw new Error("Invalid empty string");if(!e)return n.split(/\s/);for(var t=n.split(` +`),r=0;r0&&a[0]===" "?(t[r-1]+=a.slice(1),t.splice(r,1)):r+=1:t.splice(r,1)}return t}function e1e(n){n.forEach(function(e){if(!/(VALUE=DATE(-TIME)?)|(TZID=)/.test(e))throw new Error("unsupported RDATE/EXDATE parm: "+e)})}function dte(n,e){return e1e(e),n.split(",").map(function(t){return xb(t)})}var cte,Iz=y(()=>{gd();Vs();Nz();Fa();ii();Ez();cte={dtstart:null,cache:!1,unfold:!1,forceset:!1,compatible:!1,tzid:null}});function ute(n){var e=this;return function(t){if(t!==void 0&&(e["_".concat(n)]=t),e["_".concat(n)]!==void 0)return e["_".concat(n)];for(var r=0;r{gd();Vs();Fa();ii();lte();Iz();Dz();y0=(function(n){ey(e,n);function e(t){t===void 0&&(t=!1);var r=n.call(this,{},t)||this;return r.dtstart=ute.apply(r,["dtstart"]),r.tzid=ute.apply(r,["tzid"]),r._rrule=[],r._rdate=[],r._exrule=[],r._exdate=[],r}return e.prototype._iter=function(t){return ote(t,this._rrule,this._exrule,this._rdate,this._exdate,this.tzid())},e.prototype.rrule=function(t){pte(t,this._rrule)},e.prototype.exrule=function(t){pte(t,this._exrule)},e.prototype.rdate=function(t){mte(t,this._rdate)},e.prototype.exdate=function(t){mte(t,this._exdate)},e.prototype.rrules=function(){return this._rrule.map(function(t){return Nb(t.toString())})},e.prototype.exrules=function(){return this._exrule.map(function(t){return Nb(t.toString())})},e.prototype.rdates=function(){return this._rdate.map(function(t){return new Date(t.getTime())})},e.prototype.exdates=function(){return this._exdate.map(function(t){return new Date(t.getTime())})},e.prototype.valueOf=function(){var t=[];return!this._rrule.length&&this._dtstart&&(t=t.concat(Ib({dtstart:this._dtstart}))),this._rrule.forEach(function(r){t=t.concat(r.toString().split(` +`))}),this._exrule.forEach(function(r){t=t.concat(r.toString().split(` +`).map(function(a){return a.replace(/^RRULE:/,"EXRULE:")}).filter(function(a){return!/^DTSTART/.test(a)}))}),this._rdate.length&&t.push(fte("RDATE",this._rdate,this.tzid())),this._exdate.length&&t.push(fte("EXDATE",this._exdate,this.tzid())),t},e.prototype.toString=function(){return this.valueOf().join(` +`)},e.prototype.clone=function(){var t=new e(!!this._cache);return this._rrule.forEach(function(r){return t.rrule(r.clone())}),this._exrule.forEach(function(r){return t.exrule(r.clone())}),this._rdate.forEach(function(r){return t.rdate(new Date(r.getTime()))}),this._exdate.forEach(function(r){return t.exdate(new Date(r.getTime()))}),t},e})(ye)});var Uu={};Xe(Uu,{ALL_WEEKDAYS:()=>Qg,Frequency:()=>gt,RRule:()=>ye,RRuleSet:()=>y0,Weekday:()=>bn,datetime:()=>Go,rrulestr:()=>Nb});var ny=y(()=>{Vs();Nz();Iz();yd();rf();Fa()});function Td(n){let e=yte(n),t=e.match(v0);if(t){let[,a,i,s]=t,o=Number(a),l=Number(i),c=Number(s);if(!kte(o,l,c))throw new Error(`Invalid date "${n}".`);return new Date(Date.UTC(o,l-1,c,0,0,0,0))}if(!vte(e))throw new Error(`Invalid date "${n}".`);let r=new Date(e);if(!k0(r))throw new Error(`Invalid date "${n}".`);return r}function r1e(n){let e=yte(n),t=e.match(v0);if(t){let[,a,i,s]=t,o=Number(a),l=Number(i),c=Number(s),d=new Date(o,l-1,c,0,0,0,0);if(!k0(d)||d.getFullYear()!==o||d.getMonth()!==l-1||d.getDate()!==c)throw new Error(`Invalid date "${n}".`);return d}if(!vte(e))throw new Error(`Invalid date "${n}".`);let r=new Date(e);if(!k0(r))throw new Error(`Invalid date "${n}".`);return r}function kd(n){if(!k0(n))return"";let e=n.getUTCFullYear(),t=String(n.getUTCMonth()+1).padStart(2,"0"),r=String(n.getUTCDate()).padStart(2,"0");return`${e}-${t}-${r}`}function n1e(n){return kd(n)}function a1e(){let n=new Date,e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),r=String(n.getDate()).padStart(2,"0");return`${e}-${t}-${r}`}function _z(n){return Td(Fz(n))}function i1e(n){return n?/T\d{2}:\d{2}/.test(n):!1}function Fz(n){if(!n)return"";let e=n.trim();if(v0.test(e))return e;let t=e.indexOf("T");if(t>-1)return e.slice(0,t);let r=e.indexOf(" ");return r>-1&&v0.test(e.slice(0,r))?e.slice(0,r):kd(Td(e))}function yte(n,e="Date string cannot be empty"){if(!n||n.trim().length===0)throw new Error(e);return n.trim()}function vte(n){let e=n.match(t1e);if(!e)return!1;let[,t,r,a,i,s,o,,l,c,d]=e;return kte(Number(t),Number(r),Number(a))&&s1e(Number(i),Number(s),Number(o))&&o1e(l,c,d)}function kte(n,e,t){let r=new Date(Date.UTC(n,e-1,t,0,0,0,0));return r.getUTCFullYear()===n&&r.getUTCMonth()===e-1&&r.getUTCDate()===t}function s1e(n,e,t){return n>=0&&n<=23&&e>=0&&e<=59&&t>=0&&t<=59}function o1e(n,e,t){if(!n)return!0;let r=Number(e),a=Number(t);return!(r>14||a>59||r===14&&a!==0)}function k0(n){return n instanceof Date&&!Number.isNaN(n.getTime())}function Oz(n,e){if(!n.recurrence||typeof n.recurrence!="string")return!0;try{let t=xte(n);if(!t)return!1;let r=_z(n1e(e));return t.between(r,new Date(r.getTime()+1440*60*1e3-1),!0).length>0}catch(t){return!0}}function T0(n,e,t="done"){if(!n.recurrence)return n.status||"open";let r=kd(e);return(Array.isArray(n.complete_instances)?n.complete_instances:[]).includes(r)?t:n.status||"open"}function Hu(n,e,t){if(!n.recurrence||typeof n.recurrence!="string")return[];try{let r=xte(n);if(!r)return[];let a=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,0,0)),i=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),23,59,59,999));return r.between(a,i,!0)}catch(r){let a=[],i=new Date(e);for(;i<=t;)Oz(n,i)&&a.push(new Date(i)),i.setUTCDate(i.getUTCDate()+1);return a}}function Tte(n){if(!n.recurrence||typeof n.recurrence!="string")return null;let e=n.recurrence.match(/(?:^|;)COUNT=(\d+)(?:;|$)/);if(e){let t=Number.parseInt(e[1],10);return Number.isFinite(t)&&t>0?t:null}if(!/(?:^|;)UNTIL=/.test(n.recurrence))return null;try{let t=Ete(n),r=c1e(n.recurrence);if(!t||!r||r=l1e?null:a.length>0?a.length:null}catch(t){return null}}function zz(n,e={}){return n.recurrence?(n.recurrence_anchor||"scheduled")==="completion"?p1e(n,e):u1e(n,e):null}function bte(n,e=!0,t={}){let r=zz(n,t),a=null,i=null,s=null;if(r){try{let o=n.scheduled?Td(Fz(n.scheduled)):null,l=n.due?Td(Fz(n.due)):null;if(o&&l){let c=!e&&l.getTime()=t)return c}return null}function p1e(n,e){if(!n.recurrence||typeof n.recurrence!="string")return null;let t=Td(e.today||gte()),r=Pte(n.recurrence),a=Bz(n.recurrence),i=a||t,s=new Date(i.getTime()+r*24*60*60*1e3),o=Hu(n,i,s),l=new Set(n.skipped_instances||[]),c=a?a.getTime():0;for(let d of o){let u=kd(d);if(d.getTime()>c&&d>=t&&!l.has(u))return d}return null}var v0,t1e,gte,Rz,hte,Lz,l1e,jz=y(()=>{ny();v0=/^(\d{4})-(\d{2})-(\d{2})$/,t1e=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{1,3})?(?:Z|([+-])(\d{2}):(\d{2}))?$/;gte=a1e;Rz=Reflect.get(Uu,"default"),Lz=(hte=ye)!=null?hte:Rz==null?void 0:Rz.RRule,l1e=1e4});var Gz={};Xe(Gz,{NATURAL_LANGUAGE_DATE_PATTERNS:()=>Rb,addDaysToDateString:()=>lf,addDaysToDateTime:()=>ay,addMonthsToDateString:()=>g1e,addWeeksToDateString:()=>Uz,addYearsToDateString:()=>y1e,combineDateAndTime:()=>fa,convertUTCToLocalCalendarDate:()=>bd,createSafeDate:()=>h1e,createSafeUTCDate:()=>w0,createTimeFormatHelper:()=>x1e,createUTCDateForRRule:()=>Vu,createUTCDateFromLocalCalendarDate:()=>Br,formatDateAsUTCString:()=>M1e,formatDateForDisplay:()=>wd,formatDateForStorage:()=>ae,formatDateStringTime:()=>Rte,formatDateTime:()=>Nte,formatDateTimeForDisplay:()=>Sn,formatTime:()=>Wu,formatTimestampForDisplay:()=>S0,generateUTCCalendarDates:()=>Wz,getCurrentDateString:()=>Yo,getCurrentDateTimeString:()=>P1e,getCurrentTimestamp:()=>qe,getDatePart:()=>re,getEndOfMonthString:()=>b1e,getEndOfWeekString:()=>k1e,getEndOfYearString:()=>S1e,getNaturalLanguageDateSuggestions:()=>N1e,getStartOfMonthString:()=>T1e,getStartOfWeekString:()=>v1e,getStartOfYearString:()=>w1e,getTimePart:()=>si,getTodayLocal:()=>Xt,getTodayString:()=>zr,getUTCEndOfMonth:()=>D0,getUTCEndOfWeek:()=>qz,getUTCStartOfMonth:()=>E0,getUTCStartOfWeek:()=>x0,hasTimeComponent:()=>Jt,isBeforeDateSafe:()=>cf,isBeforeDateTimeAware:()=>Sd,isNaturalLanguageDate:()=>P0,isOverdueTimeAware:()=>ps,isPastDate:()=>Hz,isSameDateSafe:()=>qs,isToday:()=>_b,isTodayTimeAware:()=>C0,isTodayUTC:()=>Vz,isValidDateInput:()=>I1e,normalizeCalendarBoundariesToUTC:()=>A1e,normalizeDateString:()=>f1e,parseDate:()=>m1e,parseDateAsLocal:()=>df,parseDateToLocal:()=>et,parseDateToUTC:()=>st,parseTimestamp:()=>Ite,resolveNaturalLanguageDate:()=>Fl,startOfDayForDateString:()=>C1e,validateCompleteInstances:()=>D1e,validateDateInput:()=>$z,validateDateTimeInput:()=>E1e});function ma(n){if(!n){let t=new Error("Date string cannot be empty");throw Ve.error("Date parsing error:",{category:"validation",operation:"date-parsing",details:{dateString:n},error:t.message}),t}let e=n.trim();try{let t=e.match(/^(\d{4}-\d{2}-\d{2})\s+(Mon|Tue|Wed|Thu|Fri|Sat|Sun|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)$/i);if(t){let r=t[1];return ma(r)}if(e.startsWith("T")&&/^T\d{2}:\d{2}(:\d{2})?/.test(e)){let r=new Error(`Invalid date format - time without date: ${n}`);throw Ve.warn("Date parsing error - incomplete time format:",{category:"validation",operation:"date-parsing-incomplete-time-format",details:{original:n,trimmed:e},error:r.message}),r}if(/^\d{4}-W\d{2}$/.test(e)){let[r,a]=e.split("-W"),i=parseInt(r,10),s=parseInt(a,10);if(isNaN(i)||isNaN(s)){let u=new Error(`Invalid numeric values in ISO week format: ${n}`);throw Ve.warn("Date parsing error - invalid ISO week numbers:",{category:"validation",operation:"date-parsing-invalid-iso-week-numbers",details:{original:n,year:r,week:a,yearNum:i,weekNum:s}}),u}if(s<1||s>53){let u=new Error(`Invalid week number in ISO week format: ${n} (week must be 1-53)`);throw Ve.warn("Date parsing error - week number out of range:",{category:"validation",operation:"date-parsing-week-number-out-of-range",details:{original:n,weekNum:s},error:u.message}),u}let o=new Date(i,0,4),l=o.getDay(),c=new Date(o);c.setDate(o.getDate()-(l===0?6:l-1));let d=new Date(c);if(d.setDate(c.getDate()+(s-1)*7),!ta(d)){let u=new Error(`Failed to calculate date from ISO week format: ${n}`);throw Ve.error("Date parsing error - ISO week calculation failed:",{category:"validation",operation:"date-parsing-iso-week-calculation",details:{original:n,yearNum:i,weekNum:s,jan4:o.toISOString(),targetWeekMonday:d.toString()}}),u}return d}if(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}(:\d{2})?/.test(e)){let r=e.replace(" ","T"),a=Na(r);if(!ta(a)){let i=new Error(`Invalid space-separated datetime: ${n}`);throw Ve.warn("Date parsing error - space-separated datetime invalid:",{category:"validation",operation:"date-parsing-space-separated-datetime-invalid",details:{original:n,converted:r},error:i.message}),i}return a}if(e.includes("T")||e.includes("Z")||e.match(/[+-]\d{2}:\d{2}$/)){let r=Na(e);if(!ta(r)){let a=new Error(`Invalid timezone-aware date: ${n}`);throw Ve.warn("Date parsing error - timezone-aware format invalid:",{category:"validation",operation:"date-parsing-timezone-aware-format-invalid",details:{original:n,trimmed:e},error:a.message}),a}return r}else{let r=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!r){let l=new Error(`Invalid date-only string: ${n} (expected format: yyyy-MM-dd)`);throw Ve.warn("Date parsing error - date-only format invalid:",{category:"validation",operation:"date-parsing-date-only-format-invalid",details:{original:n,trimmed:e,expectedFormat:"yyyy-MM-dd"},error:l.message}),l}let[,a,i,s]=r,o=new Date(parseInt(a,10),parseInt(i,10)-1,parseInt(s,10));if(!ta(o)||o.getFullYear()!==parseInt(a,10)||o.getMonth()!==parseInt(i,10)-1||o.getDate()!==parseInt(s,10)){let l=new Error(`Invalid date values: ${n}`);throw Ve.warn("Date parsing error - invalid date values:",{category:"validation",operation:"date-parsing-invalid-date-values",details:{original:n,year:a,month:i,day:s},error:l.message}),l}return o}}catch(t){if(t instanceof Error&&t.message.includes("Invalid date"))throw t;let r=new Error(`Unexpected error parsing date "${n}": ${t instanceof Error?t.message:String(t)}`);throw Ve.error("Unexpected date parsing error:",{category:"validation",operation:"unexpected-date-parsing",details:{original:n,trimmed:e,stack:t instanceof Error?t.stack:void 0},error:t instanceof Error?t.message:String(t)}),r}}function st(n){if(!n){let t=new Error("Date string cannot be empty");throw Ve.error("Date parsing error:",{category:"validation",operation:"date-parsing",details:{dateString:n},error:t.message}),t}let e=n.trim();try{let t=e.match(/^(\d{4}-\d{2}-\d{2})\s+(Mon|Tue|Wed|Thu|Fri|Sat|Sun|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)$/i);if(t){let a=t[1];return st(a)}let r=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(r){let[,a,i,s]=r,o=parseInt(a,10),l=parseInt(i,10),c=parseInt(s,10);if(l<1||l>12)throw new Error(`Invalid month in date: ${n}`);if(c<1||c>31)throw new Error(`Invalid day in date: ${n}`);let d=new Date(Date.UTC(o,l-1,c));if(d.getUTCFullYear()!==o||d.getUTCMonth()!==l-1||d.getUTCDate()!==c)throw new Error(`Invalid date values: ${n}`);return d}return ma(e)}catch(t){let r=new Error(`Failed to parse date to UTC: ${e}`);throw Ve.error("Date parsing error:",{category:"validation",operation:"date-parsing",details:{dateString:n,trimmed:e,stack:t instanceof Error?t.stack:void 0},error:t instanceof Error?t.message:String(t)}),r}}function et(n){return ma(n)}function m1e(n){return ma(n)}function qs(n,e){try{let t=re(n),r=re(e),a=st(t),i=st(r);return a.getTime()===i.getTime()}catch(t){return Ve.error("Error comparing dates:",{category:"validation",operation:"comparing-dates",details:{date1:n,date2:e},error:t}),!1}}function cf(n,e){try{let t=re(n),r=re(e),a=st(t),i=st(r);return a.getTime()=0?"+":"-",r=m=>String(Math.abs(m)).padStart(2,"0"),a=r(Math.floor(Math.abs(e)/60)),i=r(Math.abs(e)%60),s=n.getFullYear(),o=r(n.getMonth()+1),l=r(n.getDate()),c=r(n.getHours()),d=r(n.getMinutes()),u=r(n.getSeconds()),p=String(n.getMilliseconds()).padStart(3,"0");return`${s}-${o}-${l}T${c}:${d}:${u}.${p}${t}${a}:${i}`}function Yo(){let n=new Date,e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),r=String(n.getDate()).padStart(2,"0");return`${e}-${t}-${r}`}function Ite(n){try{if(!n)throw new Error("Timestamp string cannot be empty");let e=Na(n);if(!ta(e))throw new Error(`Invalid timestamp: ${n}`);return e}catch(e){throw Ve.error("Error parsing timestamp:",{category:"validation",operation:"parsing-timestamp",details:{timestampString:n},error:e}),e}}function S0(n,e,t="24"){if(!n)return n;try{let r=Ite(n);return ta(r)?D(r,e||(t==="12"?"MMM d, yyyy h:mm a":"MMM d, yyyy HH:mm")):n}catch(r){return Ve.error("Error formatting timestamp for display:",{category:"validation",operation:"formatting-timestamp-display",details:{timestampString:n},error:r}),n}}function Jt(n){return n?/T\d{2}:\d{2}/.test(n):!1}function re(n){if(!n)return"";try{if(/^\d{4}-\d{2}-\d{2}$/.test(n))return n;let e=n.indexOf("T");if(e>-1)return n.substring(0,e);let t=st(n);return ae(t)}catch(e){return Ve.error("Error extracting date part:",{category:"validation",operation:"extracting-date-part",details:{dateString:n},error:e}),n}}function si(n){if(!n||!Jt(n))return null;try{let e=ma(n);return D(e,"HH:mm")}catch(e){return Ve.error("Error extracting time part:",{category:"validation",operation:"extracting-time-part",details:{dateString:n},error:e}),null}}function Wu(n,e="24"){return ta(n)?D(n,e==="12"?"h:mm a":"HH:mm"):(Ve.warn("Invalid date provided to formatTime:",{category:"validation",operation:"invalid-date-provided-formattime",details:{value:n}}),"")}function Nte(n,e="24"){return ta(n)?D(n,e==="12"?"MMM d, yyyy h:mm a":"MMM d, yyyy HH:mm"):(Ve.warn("Invalid date provided to formatDateTime:",{category:"validation",operation:"invalid-date-provided-formatdatetime",details:{value:n}}),"")}function Rte(n,e="24"){if(!n||!Jt(n))return n;try{let t=et(n);return Wu(t,e)}catch(t){return Ve.error("Error formatting date string time:",{category:"validation",operation:"formatting-date-string-time",details:{dateString:n},error:t}),n}}function x1e(n){return{formatDateTimeForDisplay:(e,t={})=>Sn(e,{...t,userTimeFormat:n}),formatTime:e=>Wu(e,n),formatDateTime:e=>Nte(e,n),formatDateStringTime:e=>Rte(e,n)}}function fa(n,e){if(!n)return"";if(!e)return n;try{let t=n.match(/^(\d{4}-\d{2}-\d{2})$/);if(t)return/^\d{2}:\d{2}$/.test(e)?`${t[1]}T${e}`:(Ve.warn("Invalid time format, expected HH:mm:",{category:"validation",operation:"invalid-time-format-expected-hh-mm",details:{value:e}}),n);let r=re(n);return!r||!/^\d{4}-\d{2}-\d{2}$/.test(r)?(Ve.warn("Invalid date part from dateString:",{category:"validation",operation:"invalid-date-part-datestring",details:{dateString:n,datePart:r}}),n):/^\d{2}:\d{2}$/.test(e)?`${r}T${e}`:(Ve.warn("Invalid time format, expected HH:mm:",{category:"validation",operation:"invalid-time-format-expected-hh-mm",details:{value:e}}),n)}catch(t){return Ve.error("Error combining date and time:",{category:"validation",operation:"combining-date-and-time",details:{dateString:n,timeString:e},error:t}),n}}function Sn(n,e={}){if(!n)return"";let{dateFormat:t="MMM d, yyyy",timeFormat:r,showTime:a=!0,userTimeFormat:i="24"}=e,s=r||(i==="12"?"h:mm a":"HH:mm");try{let o=ma(n);return Jt(n)&&a?!t||t.trim()===""?D(o,s):D(o,`${t} ${s}`):!t||t.trim()===""?"":D(o,t)}catch(o){return Ve.error("Error formatting datetime for display:",{category:"validation",operation:"formatting-datetime-display",details:{dateString:n},error:o}),n}}function Sd(n,e){try{let t=st(n),r=st(e),a=t,i=r;if(Jt(n)){let s=si(n);if(s){let[o,l]=s.split(":").map(Number);a=new Date(t),a.setUTCHours(o,l,0,0)}}if(Jt(e)){let s=si(e);if(s){let[o,l]=s.split(":").map(Number);i=new Date(r),i.setUTCHours(o,l,0,0)}}return Jt(n)&&!Jt(e)?(i=new Date(r),i.setUTCHours(23,59,59,999)):!Jt(n)&&Jt(e)&&(a=new Date(t),a.setUTCHours(23,59,59,999)),a.getTime(){if(typeof e!="string"||!e.trim())return!1;let t=e.trim();if(t.startsWith("T")&&/^T\d{2}:\d{2}(:\d{2})?/.test(t)||!/^\d{4}-\d{2}-\d{2}$/.test(t))return!1;try{return ma(t),!0}catch(r){return Ve.warn("Invalid complete_instances entry (date parsing failed):",{category:"validation",operation:"invalid-complete-instances-entry-date-parsing",details:{value:e},error:r}),!1}}).map(e=>e.trim()):[]}function P1e(){return D(new Date,"yyyy-MM-dd'T'HH:mm")}function ay(n,e){try{let t=ma(n),r=Jm(t,e);return Jt(n)?D(r,"yyyy-MM-dd'T'HH:mm"):D(r,"yyyy-MM-dd")}catch(t){throw Ve.error("Error adding days to datetime:",{category:"validation",operation:"adding-days-datetime",details:{dateString:n,days:e},error:t}),t}}function Vu(n){try{let e=n.match(/^(\d{4})-(\d{2})-(\d{2})/);if(!e)throw new Error(`Invalid date format for RRULE: ${n}`);let[,t,r,a]=e,i=parseInt(t,10),s=parseInt(r,10),o=parseInt(a,10);if(s<1||s>12)throw new Error(`Invalid month in date: ${n}`);if(o<1||o>31)throw new Error(`Invalid day in date: ${n}`);let l=new Date(Date.UTC(i,s-1,o));if(l.getUTCFullYear()!==i||l.getUTCMonth()!==s-1||l.getUTCDate()!==o)throw new Error(`Invalid date values: ${n}`);return l}catch(e){throw Ve.error("Error creating UTC date for RRULE:",{category:"validation",operation:"creating-utc-date-rrule",details:{dateString:n},error:e}),e}}function Br(n){let e=n.getFullYear(),t=n.getMonth(),r=n.getDate();return new Date(Date.UTC(e,t,r,0,0,0,0))}function Vz(n){try{let e=Xt(),t=Br(e);return n.getUTCFullYear()===t.getUTCFullYear()&&n.getUTCMonth()===t.getUTCMonth()&&n.getUTCDate()===t.getUTCDate()}catch(e){return Ve.error("Error in isTodayUTC:",{category:"validation",operation:"istodayutc",error:e}),!1}}function A1e(n,e){try{let t=D(n,"yyyy-MM-dd"),r=D(e,"yyyy-MM-dd"),a=Vu(t),i=Vu(r);return{utcStart:a,utcEnd:i}}catch(t){throw Ve.error("Error normalizing calendar boundaries to UTC:",{category:"provider",operation:"normalizing-calendar-boundaries-utc",details:{startDate:n,endDate:e},error:t}),t}}function M1e(n){try{let e=n.getUTCFullYear(),t=String(n.getUTCMonth()+1).padStart(2,"0"),r=String(n.getUTCDate()).padStart(2,"0");return`${e}-${t}-${r}`}catch(e){return Ve.error("Error formatting date as UTC string:",{category:"validation",operation:"formatting-date-as-utc-string",details:{date:n},error:e}),n.toISOString().split("T")[0]}}function ae(n){try{if(!n||!(n instanceof Date)||isNaN(n.getTime()))return Ve.warn("formatDateForStorage received invalid date:",{category:"validation",operation:"formatdateforstorage-received-invalid-date",details:{value:n}}),"";let e=n.getUTCFullYear(),t=String(n.getUTCMonth()+1).padStart(2,"0"),r=String(n.getUTCDate()).padStart(2,"0");return`${e}-${t}-${r}`}catch(e){return Ve.error("Error formatting date for storage:",{category:"validation",operation:"formatting-date-storage",details:{date:n},error:e}),""}}function Wz(n,e){let t=[],r=ae(n),a=ae(e),i=Vu(r),s=Vu(a);for(;i<=s;)t.push(new Date(i)),i.setUTCDate(i.getUTCDate()+1);return t}function x0(n,e=1){let t=Vu(ae(n)),a=(t.getUTCDay()-e+7)%7,i=new Date(t);return i.setUTCDate(i.getUTCDate()-a),i}function qz(n,e=1){let t=x0(n,e),r=new Date(t);return r.setUTCDate(r.getUTCDate()+6),r}function E0(n){let e=Vu(ae(n));return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1))}function D0(n){let e=Vu(ae(n));return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth()+1,0))}function P0(n){if(!n||typeof n!="string")return!1;let e=n.toLowerCase().trim().replace(/\s+/g," ");return e in Rb?!0:[/^in\s+(\d+)\s+(days?)$/,/^(\d+)\s+(days?)\s+ago$/,/^in\s+(\d+)\s+(weeks?)$/,/^(\d+)\s+(weeks?)\s+ago$/].some(r=>r.test(e))}function I1e(n){if(typeof n!="string")return!1;let e=n.trim();if(e===""||P0(e))return!0;try{let t=ma(e);return ta(t)}catch(t){return!1}}function Fl(n){if(!n||typeof n!="string")return n;let e=n.toLowerCase().trim().replace(/\s+/g," ");if(e in Rb)try{return Rb[e]()}catch(t){return Ve.error("Error resolving natural language date:",{category:"validation",operation:"resolving-natural-language-date",details:{value:n},error:t}),n}try{let t=e.match(/^in\s+(\d+)\s+(days?)$/);if(t){let r=parseInt(t[1],10);return lf(zr(),r)}if(t=e.match(/^(\d+)\s+(days?)\s+ago$/),t){let r=parseInt(t[1],10);return lf(zr(),-r)}if(t=e.match(/^in\s+(\d+)\s+(weeks?)$/),t){let r=parseInt(t[1],10);return Uz(zr(),r)}if(t=e.match(/^(\d+)\s+(weeks?)\s+ago$/),t){let r=parseInt(t[1],10);return Uz(zr(),-r)}}catch(t){Ve.error("Error parsing relative natural language date:",{category:"validation",operation:"parsing-relative-natural-language-date",details:{value:n},error:t})}return n}function N1e(){let n=Object.keys(Rb),e=["in 3 days","2 days ago","in 1 week","2 weeks ago"];return[...n,...e].sort()}var Ve,Rb,xe=y(()=>{Cr();q();Ve=M({tag:"Utils/DateUtils"});Rb={today:()=>zr(),tomorrow:()=>lf(zr(),1),yesterday:()=>lf(zr(),-1),"next week":()=>lf(zr(),7),"last week":()=>lf(zr(),-7)}});function uf(n){return Ste(Lte(n))}function Fte(n,e,t){return Cte(Lte(n),e,t)}function Fb(n,e){var t;return zz(n,{today:(t=e==null?void 0:e.minOccurrenceDate)!=null?t:zr()})}function Cd(n,e=!0,t){var r;return bte(n,e,{today:(r=t==null?void 0:t.minOccurrenceDate)!=null?r:zr()})}function Lte(n){let e=_te(n.scheduled),t=_te(n.dateCreated);return e===n.scheduled&&t===n.dateCreated?n:{...n,scheduled:e,dateCreated:t}}function _te(n){if(!n)return n;let e=n.trim().match(/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2})(Z|[+-]\d{2}:\d{2})?$/);if(!e)return n;let[,t,r,a=""]=e;return`${t}T${r}:00${a}`}var pf=y(()=>{jz();jz();xe()});function hr(n,e=""){var a;let t=(a=n==null?void 0:n.trim())!=null?a:"";if(!t)return e;let r=t.toLowerCase();if(Yz.has(r))return`var(--color-${r})`;if(r==="accent")return"var(--color-accent)";if(r.startsWith("color-")){let i=r.slice(6);if(Yz.has(i)||i==="accent")return`var(--${r})`}return r.startsWith("--")?`var(${t})`:t}function xd(n){var i;let e=(i=n==null?void 0:n.trim())!=null?i:"",t=e.match(R1e);if(!t)return e;let r=t[1].toLowerCase();if(r==="--color-accent")return"accent";let a=r.replace(/^--color-/,"");return Yz.has(a)?a:e}function Ed(n){return hr(n).startsWith("var(")}function M0(n){let e=hr(n);return e?!!(_1e.test(e)||Ed(e)||zte.test(e)):!1}function iy(n,e){let t=hr(n);if(!t)return`rgba(128, 128, 128, ${e})`;if(Ed(t)||zte.test(t))return`color-mix(in srgb, ${t} ${Math.round(e*100)}%, transparent)`;let r=t.replace("#","");if(/^[0-9a-f]{3}$/i.test(r)){let o=parseInt(r[0]+r[0],16),l=parseInt(r[1]+r[1],16),c=parseInt(r[2]+r[2],16);return`rgba(${o}, ${l}, ${c}, ${e})`}if(!/^[0-9a-f]{6}$/i.test(r))return`rgba(128, 128, 128, ${e})`;let a=parseInt(r.substring(0,2),16),i=parseInt(r.substring(2,4),16),s=parseInt(r.substring(4,6),16);return`rgba(${a}, ${i}, ${s}, ${e})`}var Ote,Yz,R1e,_1e,zte,A0,Bte,Ll=y(()=>{Ote=["red","orange","yellow","green","cyan","blue","purple","pink"],Yz=new Set(Ote),R1e=/^var\(\s*(--[a-z0-9_-]+)\s*\)$/i,_1e=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i,zte=/^(?:rgb|rgba|hsl|hsla|oklch|lab|color|color-mix)\(/i,A0="#6366f1, red, blue, cyan",Bte=[...Ote,"accent","var(--color-accent)"]});async function sy(n,e){var a;let r=((a=I0.get(n))!=null?a:Promise.resolve()).catch(()=>{}).then(e);I0.set(n,r);try{return await r}finally{I0.get(n)===r&&I0.delete(n)}}async function yr(n,e,t){await sy(e,()=>Lb(n,e,t))}async function Lb(n,e,t){await n.fileManager.processFrontMatter(e,t)}async function Ob(n,e,t){return sy(e,()=>zb(n,e,t))}async function zb(n,e,t){return n.vault.process(e,t)}async function mf(n,e,t){return n.vault.create(e,t)}async function Bb(n,e){await n.vault.createFolder(e)}async function Gs(n,e,t){await sy(e,()=>n.vault.modify(e,t))}async function Kz(n,e,t){await n.vault.rename(e,t)}var I0,Zz=y(()=>{I0=new WeakMap});function Ute(n){return window.moment(n)}function N0(n){if(!n.startsWith("---"))return{};let e=n.indexOf("---",3);if(e===-1)return{};let t=n.substring(3,e);try{return(0,hf.parseYaml)(t)||{}}catch(r){return ff.error("Error parsing frontmatter:",{category:"validation",operation:"parsing-frontmatter",error:r}),{}}}async function qu(n,e){try{let r=(0,hf.normalizePath)(e).split("/").filter(i=>i.length>0),a="";for(let i of r)if(a=a?`${a}/${i}`:i,!await n.adapter.exists(a))try{await n.createFolder(a)}catch(s){if(!await n.adapter.exists(a))throw new Error(`Failed to create folder "${a}"`)}}catch(t){let r=t instanceof Error?t.message:String(t),a=t instanceof Error?t.stack:void 0;ff.error("Error creating folder structure:",{category:"internal",operation:"creating-folder-structure",details:{stack:a,folderPath:e,normalizedPath:(0,hf.normalizePath)(e)},error:r});let i=new Error(`Failed to create folder "${e}": ${r}`);throw a&&(i.stack=a),i}}function F1e(n,e){try{let t=new Date(n),r=new Date(e);if(isNaN(t.getTime())||isNaN(r.getTime()))return ff.error("Invalid timestamps for duration calculation:",{category:"validation",operation:"invalid-timestamps-duration-calculation",details:{startTime:n,endTime:e}}),0;if(r<=t)return ff.error("End time is not after start time:",{category:"internal",operation:"end-time-not-start-time",details:{startTime:n,endTime:e}}),0;let a=r.getTime()-t.getTime(),i=Math.round(a/(1e3*60));return Math.max(0,i)}catch(t){return ff.error("Error calculating duration:",{category:"internal",operation:"calculating-duration",details:{startTime:n,endTime:e},error:t}),0}}function oi(n){return!n||!Array.isArray(n)?0:n.reduce((e,t)=>{if(!t.startTime||!t.endTime)return e;let r=F1e(t.startTime,t.endTime);return e+r},0)}function R0(n){return!n||!Array.isArray(n)?null:n.find(e=>e.startTime&&!e.endTime)||null}function _0(n){if(!n||n===0||isNaN(n))return"0m";let e=Math.floor(n/60),t=n%60;return e===0?`${t}m`:t===0?`${e}h`:`${e}h ${t}m`}function jb(n){if(n==="none")return"";let e=new Date,t;switch(n){case"today":t=e;break;case"tomorrow":t=new Date(e),t.setDate(e.getDate()+1);break;case"next-week":t=new Date(e),t.setDate(e.getDate()+7);break;default:return""}return D(t,"yyyy-MM-dd")}function L1e(n){return typeof n=="string"&&/^([01]\d|2[0-3]):[0-5]\d$/.test(n)}function Ol(n,e){let t=jb(n);return!t||!L1e(e)?t:fa(t,e)}function Qz(n,e){return n.getUTCFullYear()===e.getUTCFullYear()&&n.getUTCMonth()===e.getUTCMonth()&&n.getUTCDate()===e.getUTCDate()}function Hte(n,e,t,r,a,i,s){var d;let o=n.metadataCache.getFileCache(r),l=o==null?void 0:o.frontmatter;if(l)if(a){let u=a.mapFromFrontmatter(l,t,i);return{title:u.title||"Untitled task",status:u.status||s||"open",priority:u.priority||"normal",due:u.due,scheduled:u.scheduled,path:t,archived:u.archived||!1,tags:u.tags||[],contexts:u.contexts||[],projects:u.projects||[],attachments:u.attachments||[],recurrence:u.recurrence,complete_instances:u.complete_instances,completedDate:u.completedDate,timeEstimate:u.timeEstimate,timeEntries:u.timeEntries,dateCreated:u.dateCreated,dateModified:u.dateModified,reminders:u.reminders}}else{let p=new tf(Sb).mapFromFrontmatter(l,t,i);return{title:p.title||"Untitled task",status:p.status||s||"open",priority:p.priority||"normal",due:p.due,scheduled:p.scheduled,path:t,archived:p.archived||!1,tags:p.tags||[],contexts:p.contexts||[],projects:p.projects||[],attachments:p.attachments||[],recurrence:p.recurrence,complete_instances:p.complete_instances,completedDate:p.completedDate,timeEstimate:p.timeEstimate,timeEntries:p.timeEntries,dateCreated:p.dateCreated,dateModified:p.dateModified,reminders:p.reminders}}return{title:((d=t.split("/").pop())==null?void 0:d.replace(".md",""))||"Untitled",status:s||"open",priority:"normal",path:t,archived:!1,reminders:[]}}function Gu(n){if(n.startsWith("---")){let e=n.match(/^---\s*\r?\n([\s\S]*?)\r?\n---\s*\r?\n?([\s\S]*)$/);if(e)return{frontmatter:e[1],body:e[2]||""}}return{frontmatter:null,body:n}}function Vte(n){let e=/^(\s*)([-*+]|\d+\.)(\s+\[)[xX](\].*)/gm,t=!1;return{content:n.replace(e,(a,i,s,o,l)=>(t=!0,`${i}${s}${o} ${l}`)),changed:t}}function F0(n,e){return Oz(n,e)}function oy(n,e,t){return T0(n,e,t)}function ly(n,e,t){return Hu(n,e,t)}function Wte(n){return Tte(n)}function qte(n,e=!0){return Cd(n,e)}function Gte(n){return wte(n)}function jte(n,e=!1){if(e&&n==="24:00")return $te;let t=/^([0-1]?[0-9]|2[0-3]):([0-5][0-9])$/.exec(n);return t?Number(t[1])*60+Number(t[2]):null}function O1e(n){if(!n||typeof n!="object")return!1;let e=n;if(!e.id||typeof e.id!="string"||!e.title||typeof e.title!="string"||!e.startTime||typeof e.startTime!="string"||!e.endTime||typeof e.endTime!="string")return!1;let t=jte(e.startTime),r=jte(e.endTime,!0);if(t===null||r===null||(e.endTime==="00:00"&&t>0?$te:r)<=t||e.attachments&&!Array.isArray(e.attachments))return!1;if(e.attachments){for(let i of e.attachments)if(typeof i!="string"||!i.trim())return!1}return!(e.color&&typeof e.color!="string"||e.description&&typeof e.description!="string")}function z1e(n,e){try{let t=N0(n);if(!t||!t.timeblocks||!Array.isArray(t.timeblocks))return[];let r=[];for(let a of t.timeblocks)O1e(a)?r.push(a):ff.warn(`Invalid timeblock in ${e}:`,{category:"validation",operation:"invalid-timeblock",details:{value:a}});return r}catch(t){return ff.error(`Error extracting timeblocks from ${e}:`,{category:"internal",operation:"extracting-timeblocks",error:t}),[]}}function Jz(){return`tb-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}function B1e(n,e,t){return{...n,id:Jz(),startTime:e,endTime:t,attachments:n.attachments?[...n.attachments]:void 0}}async function Xz(n,e,t,r,a,i){let{getDailyNote:s,getAllDailyNotes:o,appHasDailyNotesPluginLoaded:l}=await Promise.resolve().then(()=>tt(od()));if(!l())throw new Error("Daily Notes plugin is not enabled");let c=o(),d=Ute(t),u=s(d,c);if(!u)throw new Error(`Daily note for ${t} not found`);let p=await n.vault.read(u),m=z1e(p,u.path),f=m.findIndex(v=>v.id===e);if(f===-1)throw new Error(`Timeblock ${e} not found`);let h=m[f];if(t===r){await j1e(n,u,e,a,i);return}await $1e(n,u,e);let g={...h,startTime:a,endTime:i};await Kte(n,r,g)}async function Yte(n,e,t,r,a){let i=B1e(t,r,a);return await Kte(n,e,i),i}async function j1e(n,e,t,r,a){let i=await n.vault.read(e),s=N0(i)||{};if(!s.timeblocks||!Array.isArray(s.timeblocks))throw new Error("No timeblocks found in frontmatter");let o=s.timeblocks.findIndex(l=>l.id===t);if(o===-1)throw new Error(`Timeblock ${t} not found`);s.timeblocks[o].startTime=r,s.timeblocks[o].endTime=a,await eB(n,e,s,i)}async function $1e(n,e,t){let r=await n.vault.read(e),a=N0(r)||{};!a.timeblocks||!Array.isArray(a.timeblocks)||(a.timeblocks=a.timeblocks.filter(i=>i.id!==t),await eB(n,e,a,r))}async function Kte(n,e,t){let{createDailyNote:r,getDailyNote:a,getAllDailyNotes:i}=await Promise.resolve().then(()=>tt(od())),s=Ute(e),o=i(),l=a(s,o);if(!l){try{l=await r(s)}catch(u){let p=u instanceof Error?u.message:String(u);throw new Error(`Failed to create daily note: ${p}. Please check your Daily Notes plugin configuration and ensure the daily notes folder exists.`)}if(!l)throw new Error("Failed to create daily note. Please check your Daily Notes plugin configuration and ensure the daily notes folder exists.")}let c=await n.vault.read(l),d=N0(c)||{};d.timeblocks||(d.timeblocks=[]),d.timeblocks.push(t),await eB(n,l,d,c)}async function eB(n,e,t,r){let a=r;if(r.startsWith("---")){let o=r.indexOf("---",3);o!==-1&&(a=r.substring(o+3))}let s=`--- +${(0,hf.stringifyYaml)(t)}---${a}`;await Gs(n,e,s)}function Ko(n){return!n||!Array.isArray(n)?[]:n.filter(e=>{if(typeof e!="string")return!1;let t=e.trim();return!(t.length===0||t==='""'||t==="''")})}function Zte(n,e){return b0(n,e)}function Qte(n,e,t){return Fte(n,e,t)}function ha(n){return!n||typeof n!="string"?"":n.split(",").map(e=>gb(e)).filter(e=>e.length>0).join(", ")}function Dd(n){return!n||typeof n!="string"?"":n.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase()}var hf,ff,$te,yt=y(()=>{hf=require("obsidian");Cr();yz();s0();pf();xe();Yg();Ll();q();Zz();ff=M({tag:"Utils/Helpers"}),$te=1440});function Y(n){var e;if(n==null)return"";if(typeof n=="string")return n;if(typeof n=="number")return Number.prototype.toString.call(n);if(typeof n=="bigint")return BigInt.prototype.toString.call(n);if(typeof n=="boolean")return n?"true":"false";if(typeof n=="symbol")return(e=n.description)!=null?e:"";if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return n.map(t=>Y(t)).filter(t=>t.length>0).join(", ");try{let t=JSON.stringify(n);return typeof t=="string"?t:""}catch(t){return""}}function L0(n){return Array.isArray(n)?n.map(e=>Y(e)):[Y(n)]}var dr=y(()=>{});var aEt,Yu,O0=y(()=>{dr();q();aEt=M({tag:"Utils/ProjectMetadataResolver"}),Yu=class{constructor(e){this.deps=e}buildMetadataRows(e,t,r){var s;let a=[],i=Math.min(e.length,3);for(let o=0;o0&&a.push(d.join(" "))}catch(c){}}return a}stringifyFmValue(e){if(e==null)return"";if(Array.isArray(e))return e.map(a=>this.stringifyFmValue(a)).filter(Boolean).join(", ");let t=typeof e;if(t==="string"){let a=e.trim(),i=a.match(/^\[\[([^\]]+)\]\]$/);if(i){let l=i[1].split("|");if(l.length>1&&l[1].trim())return l[1].trim();let c=l[0].split("#")[0].trim();return(c.split("/").pop()||c).replace(/\.md$/i,"")}let s=a.match(/^\[([^\]]+)\]\(([^)]+)\)$/);return s?s[1].trim():a}if(t==="number"||t==="boolean")return Y(e);if(t==="object"){let r=e;if(typeof r.path=="string"){let a=r.path;return(a.split("/").pop()||a).replace(/\.md$/i,"")}return""}return""}resolve(e,t){if(!e)return"";if(e.startsWith("file."))switch(e){case"file.basename":return t.basename||"";case"file.name":return t.name||"";case"file.path":return t.path||"";case"file.parent":return t.parent||"";default:return""}if(e==="title")return t.title||"";if(e==="aliases"){let i=t.aliases||[];return i.length?i.join(", "):""}let r=e;e.startsWith("frontmatter:")&&(r=e.slice(12));let a=this.deps.getFrontmatter(t)||{};return this.stringifyFmValue(a[r])}}});function U1e(n){let e=[],t="",r=0;for(;ra.length>0)}function H1e(n){return n.replace(/\\\|/g,"|").replace(/\\\)/g,")")}function zl(n){let e=[];if(!n)return e;let t=/\{([^}]*)\}/g,r,a=0;for(;(r=t.exec(n))!==null;){let s=n.slice(a,r.index);s.length>0&&e.push({property:`literal:${s}`,showName:!1}),a=t.lastIndex;let o=r[1].trim();if(!o)continue;let l=U1e(o);if(l.length===0)continue;let c=l[0];if(!c)throw new Error("Missing property name in token");let d={property:c,showName:!1};for(let u=1;u0&&e.push({property:`literal:${i}`,showName:!1}),e}var $b=y(()=>{});function Jte(n){return n!=null?n.trim():""}function V1e(n){let e=Jte(n);return e.length>0?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function W1e(n){return n?n.trim():""}function cy(n){let e=W1e(n==null?void 0:n.propertyKey),t=Jte(n==null?void 0:n.propertyValue);return{key:e,value:t,enabled:e.length>0}}function dy(n,e){if(!e.enabled)return!0;if(!n||typeof n!="object"||!(e.key in n))return!1;let t=n[e.key],r=V1e(e.value);if(r.length===0)return t!=null;let a=new Set(r.map(s=>s.toLowerCase())),i=s=>{if(s==null)return!1;if(Array.isArray(s))return s.some(o=>i(o));if(typeof s=="string")return a.has(s.trim().toLowerCase());if(typeof s=="number"||typeof s=="boolean")return a.has(String(s).toLowerCase());if(typeof s=="object")try{return a.has(JSON.stringify(s).toLowerCase())}catch(o){return!1}return a.has(Y(s).toLowerCase())};return i(t)}var z0=y(()=>{dr()});var ga,Pd,gf,ir,Ad=y(()=>{xe();ga=class extends Error{constructor(t,r,a){super(t);this.field=r;this.nodeId=a;this.name="FilterValidationError"}},Pd=class extends Error{constructor(t,r){super(t);this.nodeId=r;this.name="FilterEvaluationError"}},gf=class gf{static generateId(){return`filter_${Date.now()}_${++this.idCounter}`}static deepCloneFilterQuery(e){return JSON.parse(JSON.stringify(e))}static validateFilterNode(e,t=!0){if(!e||typeof e!="object")throw new ga("Filter node must be an object");if(!("id"in e)||!e.id||typeof e.id!="string")throw new ga("Filter node must have a valid string ID",void 0,"id"in e?String(e.id):"unknown");if(e.type==="condition")this.validateCondition(e,t);else if(e.type==="group")this.validateGroup(e,t);else{let r=e;throw new ga(`Unknown filter node type: ${String(r.type)}`,void 0,typeof r.id=="string"?r.id:void 0)}}static validateCondition(e,t=!0){if(typeof e.property!="string")throw new ga("Condition must have a valid property","property",e.id);if(t&&e.property==="")throw new ga("Property must be selected","property",e.id);if(e.property==="")return;if(!e.operator||typeof e.operator!="string")throw new ga("Condition must have a valid operator","operator",e.id);if(!this.getValidOperatorsForProperty(e.property).includes(e.operator))throw new ga(`Operator '${e.operator}' is not valid for property '${e.property}'`,"operator",e.id);if(t&&this.operatorRequiresValue(e.operator)&&(e.value===null||e.value===void 0||e.value===""))throw new ga(`Operator '${e.operator}' requires a value`,"value",e.id)}static validateGroup(e,t=!0){if(!e.conjunction||!["and","or"].includes(e.conjunction))throw new ga("Group must have a valid conjunction (and/or)","conjunction",e.id);if(!Array.isArray(e.children))throw new ga("Group must have a children array","children",e.id);e.children.forEach((r,a)=>{try{this.validateFilterNode(r,t)}catch(i){throw i instanceof ga?new ga(`Child ${a}: ${i.message}`,i.field,e.id):i}})}static getValidOperatorsForProperty(e){return typeof e=="string"&&e.startsWith("user:")?["is","is-not","contains","does-not-contain","is-before","is-after","is-on-or-before","is-on-or-after","is-empty","is-not-empty","is-checked","is-not-checked","is-greater-than","is-less-than","is-greater-than-or-equal","is-less-than-or-equal"]:{"":[],title:["is","is-not","contains","does-not-contain","is-empty","is-not-empty"],path:["contains","does-not-contain","is-empty","is-not-empty"],status:["is","is-not","is-empty","is-not-empty"],priority:["is","is-not","is-empty","is-not-empty"],tags:["contains","does-not-contain","is-empty","is-not-empty"],contexts:["contains","does-not-contain","is-empty","is-not-empty"],projects:["contains","does-not-contain","is-empty","is-not-empty"],blockedBy:["contains","does-not-contain","is-empty","is-not-empty"],blocking:["contains","does-not-contain","is-empty","is-not-empty"],due:["is","is-not","is-before","is-after","is-on-or-before","is-on-or-after","is-empty","is-not-empty"],scheduled:["is","is-not","is-before","is-after","is-on-or-before","is-on-or-after","is-empty","is-not-empty"],completedDate:["is","is-not","is-before","is-after","is-on-or-before","is-on-or-after","is-empty","is-not-empty"],dateCreated:["is","is-not","is-before","is-after","is-on-or-before","is-on-or-after","is-empty","is-not-empty"],dateModified:["is","is-not","is-before","is-after","is-on-or-before","is-on-or-after","is-empty","is-not-empty"],archived:["is-checked","is-not-checked"],hasSubtasks:["is-checked","is-not-checked"],"dependencies.isBlocked":["is-checked","is-not-checked"],"dependencies.isBlocking":["is-checked","is-not-checked"],timeEstimate:["is","is-not","is-greater-than","is-less-than","is-greater-than-or-equal","is-less-than-or-equal"],recurrence:["is-empty","is-not-empty"],"status.isCompleted":["is-checked","is-not-checked"]}[e]||[]}static isFilterNodeComplete(e){try{return this.validateFilterNode(e,!0),!0}catch(t){return!1}}static operatorRequiresValue(e){return!["is-empty","is-not-empty","is-checked","is-not-checked"].includes(e)}static getTaskPropertyValue(e,t){var r;switch(t){case"title":return e.title;case"path":return e.path;case"status":return e.status;case"priority":return e.priority;case"tags":return e.tags||[];case"contexts":return e.contexts||[];case"projects":return e.projects||[];case"blockedBy":return((r=e.blockedBy)==null?void 0:r.map(a=>a.uid))||[];case"blocking":return e.blocking||[];case"due":return e.due;case"scheduled":return e.scheduled;case"completedDate":return e.completedDate;case"dateCreated":return e.dateCreated;case"dateModified":return e.dateModified;case"archived":return e.archived;case"hasSubtasks":return e.hasSubtasks===!0;case"timeEstimate":return e.timeEstimate;case"recurrence":return e.recurrence;case"status.isCompleted":return;case"dependencies.isBlocked":return e.isBlocked===!0;case"dependencies.isBlocking":return e.isBlocking===!0;default:throw new Pd(`Unknown property: ${t}`)}}static applyOperator(e,t,r,a,i){try{switch(t){case"is":return this.isEqual(e,r,i);case"is-not":return!this.isEqual(e,r,i);case"contains":return this.contains(e,r,i);case"does-not-contain":return!this.contains(e,r,i);case"is-before":return this.isBefore(e,r);case"is-after":return this.isAfter(e,r);case"is-on-or-before":return this.isOnOrBefore(e,r);case"is-on-or-after":return this.isOnOrAfter(e,r);case"is-empty":return this.isEmpty(e);case"is-not-empty":return!this.isEmpty(e);case"is-checked":return e===!0;case"is-not-checked":return e!==!0;case"is-greater-than":return this.isGreaterThan(e,r);case"is-less-than":return this.isLessThan(e,r);case"is-greater-than-or-equal":return this.isGreaterThanOrEqual(e,r);case"is-less-than-or-equal":return this.isLessThanOrEqual(e,r);default:throw new Pd("Unknown operator",a)}}catch(s){throw s instanceof Pd?s:new Pd(`Error applying operator '${t}': ${s.message}`,a)}}static isEqual(e,t,r){if(r&&this.isDateProperty(r)&&typeof e=="string"&&typeof t=="string"&&(e||P0(t)))return this.isEqualDate(e,t);let a=(i,s)=>this.hasNumericComparison(i,s)?this.toFiniteNumber(i)===this.toFiniteNumber(s):i===s;return Array.isArray(e)?Array.isArray(t)?e.some(i=>t.some(s=>a(i,s))):e.some(i=>a(i,t)):Array.isArray(t)?t.some(i=>a(e,i)):a(e,t)}static hasNumericComparison(e,t){return!(typeof e=="number")&&!(typeof t=="number")?!1:this.toFiniteNumber(e)!==void 0&&this.toFiniteNumber(t)!==void 0}static toFiniteNumber(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string")return;let t=e.trim();if(!t)return;let r=Number(t);return Number.isFinite(r)?r:void 0}static matchesHierarchicalTag(e,t){if(!e||!t)return!1;let r=e.toLowerCase(),a=t.toLowerCase();return!!(r===a||r.startsWith(a+"/")||r.includes(a))}static matchesHierarchicalTagExact(e,t){if(!e||!t)return!1;let r=e.toLowerCase(),a=t.toLowerCase();return!!(r===a||r.startsWith(a+"/"))}static matchesTagConditions(e,t){if(!Array.isArray(e)||!Array.isArray(t))return!1;if(t.length===0)return!0;let r=[],a=[];for(let i of t)if(typeof i=="string"&&i.startsWith("-")){let s=i.slice(1);s&&a.push(s)}else typeof i=="string"&&r.push(i);for(let i of a)if(e.some(o=>this.matchesHierarchicalTag(o,i)))return!1;return r.length>0?r.some(i=>e.some(s=>this.matchesHierarchicalTag(s,i))):!0}static contains(e,t,r){if(Array.isArray(e))if(Array.isArray(t))if(r==="tags"){let a=e.filter(s=>typeof s=="string"),i=t.filter(s=>typeof s=="string");return gf.matchesTagConditions(a,i)}else return t.some(a=>e.some(i=>typeof i=="string"&&typeof a=="string"&&i.toLowerCase().includes(a.toLowerCase())));else{let a=typeof t=="string"?t:String(t!=null?t:"");if(r==="tags"){let i=e.filter(s=>typeof s=="string");return gf.matchesTagConditions(i,[a])}else{let i=a.toLowerCase();return e.some(s=>typeof s=="string"&&s.toLowerCase().includes(i))}}else if(typeof e=="string")if(Array.isArray(t))if(r==="tags"){let a=t.filter(i=>typeof i=="string");return gf.matchesTagConditions([e],a)}else return t.some(a=>typeof a=="string"&&e.toLowerCase().includes(a.toLowerCase()));else return r==="tags"&&typeof t=="string"?gf.matchesTagConditions([e],[t]):typeof t=="string"&&e.toLowerCase().includes(t.toLowerCase());return!1}static isBefore(e,t){if(!e||!t)return!1;try{let r=Fl(t);return Sd(e,r)}catch(r){return!1}}static isAfter(e,t){if(!e||!t)return!1;try{let r=Fl(t);return Sd(r,e)}catch(r){return!1}}static isOnOrBefore(e,t){if(!e||!t)return!1;try{let r=Fl(t);return Sd(e,r)||qs(re(e),re(r))}catch(r){return!1}}static isOnOrAfter(e,t){if(!e||!t)return!1;try{let r=Fl(t);return Sd(r,e)||qs(re(e),re(r))}catch(r){return!1}}static isDateProperty(e){return["due","scheduled","completedDate","dateCreated","dateModified"].includes(e)}static isEqualDate(e,t){try{let r=Fl(t);return qs(re(e),re(r))}catch(r){return!1}}static isEmpty(e){return e==null?!0:typeof e=="string"?e.trim()==="":Array.isArray(e)?e.length===0?!0:e.every(t=>{if(typeof t!="string")return!1;let r=t.trim();return r.length===0||r==='""'||r==="''"}):!1}static isGreaterThan(e,t){let r=typeof e=="number"?e:parseFloat(e),a=typeof t=="number"?t:parseFloat(t);return isNaN(r)||isNaN(a)?!1:r>a}static isLessThan(e,t){let r=typeof e=="number"?e:parseFloat(e),a=typeof t=="number"?t:parseFloat(t);return isNaN(r)||isNaN(a)?!1:r=a}static isLessThanOrEqual(e,t){let r=typeof e=="number"?e:parseFloat(e),a=typeof t=="number"?t:parseFloat(t);return isNaN(r)||isNaN(a)?!1:r<=a}};gf.idCounter=0;ir=gf});function uy(n){var r,a,i;let e=new Set;for(let s of(r=n==null?void 0:n.tags)!=null?r:[])rB(e,s.tag);let t=(a=n==null?void 0:n.frontmatter)!=null?a:null;for(let s of(i=(0,Xte.parseFrontMatterTags)(t))!=null?i:[])rB(e,s);return tB(e,t==null?void 0:t.tags),tB(e,t==null?void 0:t.tag),Array.from(e)}function tB(n,e){if(Array.isArray(e)){for(let t of e)tB(n,t);return}if(typeof e=="string")for(let t of e.split(/[,\s]+/))rB(n,t)}function rB(n,e){if(typeof e!="string")return;let t=e.trim().replace(/^#/,"");t&&n.add(t)}var Xte,B0=y(()=>{Xte=require("obsidian")});function Ub(n,e){if(!n||!e)return 0;let t=n.toLowerCase().split(" ").filter(Boolean),r=e.toLowerCase(),a=0,i=0;for(let s=0;s0&&l===a&&(i+=5),a=l+o.length}return i}var ere=y(()=>{});var aB={};Xe(aB,{FileSuggestHelper:()=>nB,getActiveFolderPath:()=>j0,isPathInIncludedFolders:()=>$0,resolveIncludeFolders:()=>nre});function q1e(n){var t;let e=(t=n==null?void 0:n.app)==null?void 0:t.vault;return typeof(e==null?void 0:e.getFiles)=="function"?e.getFiles():typeof(e==null?void 0:e.getMarkdownFiles)=="function"?e.getMarkdownFiles():[]}function G1e(n,e){var t,r;if(e.extension==="md"){let a=(r=(t=n.app.metadataCache).fileToLinktext)==null?void 0:r.call(t,e,"",!0);return typeof a=="string"&&a.trim()?a:e.basename}return e.name||e.path.split("/").pop()||e.basename}function rre(n){return n.trim().replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"")}function Y1e(n,e=""){let t=rre(e).split("/").filter(Boolean);for(let r of n.replace(/\\/g,"/").split("/"))!r||r==="."||(r===".."?t.pop():t.push(r));return t.join("/")}function K1e(n,e){let t=rre(n);return t==="."||t===".."||t.startsWith("./")||t.startsWith("../")?Y1e(t,e):t}function j0(n){var t,r,a,i;let e=(a=(r=(t=n==null?void 0:n.app)==null?void 0:t.workspace)==null?void 0:r.getActiveFile)==null?void 0:a.call(r);if(((i=e==null?void 0:e.parent)==null?void 0:i.path)!==void 0)return e.parent.path;if(typeof(e==null?void 0:e.path)=="string")return e.path.split("/").slice(0,-1).join("/")}function nre(n,e){return n.filter(t=>t.trim().length>0).map(t=>K1e(t,e))}function $0(n,e,t){return nre(e,t).some(a=>a===""||n===a||n.startsWith(`${a}/`))}var tre,nB,Hb=y(()=>{tre=require("obsidian");ere();$b();z0();Ad();hb();B0();nB={async suggest(n,e,t=20,r,a=j0(n)){var o,l;let i=async()=>{var b,w,S,C,x,E,_;let c=q1e(n),d=[],u=Il((b=n.settings)==null?void 0:b.excludedFolders),p=((C=(S=(w=n.settings)==null?void 0:w.projectAutosuggest)==null?void 0:S.rows)!=null?C:[]).slice(0,3),m=new Set;for(let F of p)try{let I=zl(F);for(let A of I)A.searchable&&!A.property.startsWith("literal:")&&m.add(A.property)}catch(I){}let f=(e||"").toLowerCase(),h=(x=r==null?void 0:r.requiredTags)!=null?x:[],g=(E=r==null?void 0:r.includeFolders)!=null?E:[],v=cy(r);for(let F of c){if(qg(F.path,u))continue;let I=n.app.metadataCache.getFileCache(F);if(h.length>0&&!ir.matchesTagConditions(uy(I),h)||g.length>0&&!$0(F.path,g,a))continue;if(v.enabled){let X=I==null?void 0:I.frontmatter;if(!dy(X,v))continue}let A=F.basename,R="";if(I!=null&&I.frontmatter){let X=n.fieldMapper.mapFromFrontmatter(I.frontmatter,F.path,n.settings.storeTitleInFilename);R=typeof X.title=="string"?X.title:""}let O=I!=null&&I.frontmatter?(0,tre.parseFrontMatterAliases)(I.frontmatter)||[]:[],U=0,oe=f.length>0?Ub(e,A):1;if(oe>0&&(U=Math.max(U,oe+15)),R){let X=Ub(e,R);X>0&&(U=Math.max(U,X+5))}if(Array.isArray(O)){for(let X of O)if(typeof X=="string"){let de=Ub(e,X);de>0&&(U=Math.max(U,de))}}if(m.size>0){let X=(I==null?void 0:I.frontmatter)||{};for(let de of m){let Oe="";if(de==="file.path")Oe=F.path;else if(de==="file.parent")Oe=((_=F.parent)==null?void 0:_.path)||"";else if(de==="file.basename")Oe=A;else if(de==="title")Oe=R;else if(de==="aliases")Oe=(Array.isArray(O)?O.filter(Z=>typeof Z=="string"):[]).join(" ");else{let Q=X[de];Q!=null&&(Array.isArray(Q)?Oe=Q.filter(Z=>typeof Z=="string").join(" "):typeof Q=="object"?Oe=JSON.stringify(Q):(typeof Q=="string"||typeof Q=="number"||typeof Q=="boolean")&&(Oe=String(Q)))}if(Oe){let Q=Ub(e,Oe),Z=Q>0?Q:Oe.toLowerCase().includes(f)?30:0;Z>0&&(U=Math.max(U,Z))}}}if(U>0){let X=[];R&&R!==A&&X.push(`title: ${R}`);let de=Array.isArray(O)?O.filter(Q=>typeof Q=="string"):[];de.length&&X.push(`aliases: ${de.join(", ")}`);let Oe=X.length?`${A} [${X.join(" | ")}]`:A;d.push({insertText:G1e(n,F),displayText:Oe,path:F.path,score:U})}}d.sort((F,I)=>I.score-F.score);let k=[],T=new Set;for(let F of d)if(!T.has(F.insertText)&&(k.push(F),T.add(F.insertText),k.length>=t))break;return k},s=(l=(o=n.settings)==null?void 0:o.suggestionDebounceMs)!=null?l:0;return s?new Promise(c=>{let d=n;d.__fileSuggestTimer&&window.clearTimeout(d.__fileSuggestTimer),d.__fileSuggestTimer=window.setTimeout(()=>{(async()=>{let u=await i();c(u)})()},s)}):i()}}});var Bl,Z1e,Ys,py=y(()=>{Bl=require("obsidian");O0();$b();z0();Ad();B0();Hb();q();Z1e=M({tag:"Modals/ProjectSelectModal"}),Ys=class extends Bl.FuzzySuggestModal{constructor(e,t,r){super(e),this.plugin=t,this.onChoose=r,this.setPlaceholder("Type to search for project notes..."),this.setInstructions([{command:"↑↓",purpose:"to navigate"},{command:"↵",purpose:"to select"},{command:"esc",purpose:"to cancel"}])}getItems(){var s,o,l,c,d,u,p;let e=this.app.vault.getAllLoadedFiles().filter(m=>m instanceof Bl.TFile&&m.extension==="md"&&!m.path.includes(".trash")),t=(l=(o=(s=this.plugin.settings)==null?void 0:s.projectAutosuggest)==null?void 0:o.requiredTags)!=null?l:[],r=(u=(d=(c=this.plugin.settings)==null?void 0:c.projectAutosuggest)==null?void 0:d.includeFolders)!=null?u:[],a=cy((p=this.plugin.settings)==null?void 0:p.projectAutosuggest),i=j0(this.plugin);return t.length===0&&r.length===0&&!a.enabled?e:e.filter(m=>{if(!(m instanceof Bl.TFile))return!1;let f=this.app.metadataCache.getFileCache(m);if(t.length>0&&!ir.matchesTagConditions(uy(f),t)||r.length>0&&!$0(m.path,r,i))return!1;if(a.enabled){let h=f==null?void 0:f.frontmatter;if(!dy(h,a))return!1}return!0})}getItemText(e){var s,o,l,c;if(!(e instanceof Bl.TFile))return e.name;let t=`${e.name} ${e.path}`,r=(l=(o=(s=this.plugin.settings)==null?void 0:s.projectAutosuggest)==null?void 0:o.rows)!=null?l:[],a=new Set;for(let d of r)try{let u=zl(d);for(let p of u)p.searchable&&!p.property.startsWith("literal:")&&a.add(p.property)}catch(u){}let i=this.app.metadataCache.getFileCache(e);if(i!=null&&i.frontmatter){let d=this.plugin.fieldMapper.mapFromFrontmatter(i.frontmatter,e.path,this.plugin.settings.storeTitleInFilename),u=typeof d.title=="string"?d.title:"";u&&(t+=` ${u}`);let p=(0,Bl.parseFrontMatterAliases)(i.frontmatter)||[];Array.isArray(p)&&p.length>0&&(t+=` ${p.join(" ")}`);for(let m of a){let f="";switch(m){case"file.path":f=e.path;break;case"file.parent":f=((c=e.parent)==null?void 0:c.name)||"";break;case"file.basename":f=e.basename;break;case"title":case"aliases":break;default:{let h=i.frontmatter[m];h!=null&&(f=Array.isArray(h)?h.join(" "):String(h));break}}f&&(t+=` ${f}`)}}return t}renderSuggestion(e,t){var s,o,l,c;let r=e.item;if(t.empty(),!(r instanceof Bl.TFile)){t.textContent=r.name;return}let a=t.createDiv({cls:"project-suggestion"}),i=((l=(o=(s=this.plugin.settings)==null?void 0:s.projectAutosuggest)==null?void 0:o.rows)!=null?l:[]).slice(0,3);if(i.length===0){a.createSpan({cls:"project-name",text:r.basename});return}try{let d=this.app.metadataCache.getFileCache(r),u=(d==null?void 0:d.frontmatter)||{},p=this.plugin.fieldMapper.mapFromFrontmatter(u,r.path,this.plugin.settings.storeTitleInFilename),m=typeof p.title=="string"?p.title:"",f=(0,Bl.parseFrontMatterAliases)(u)||[],h=Array.isArray(f)?f.filter(T=>typeof T=="string"):[],g={basename:r.basename,name:r.name,path:r.path,parent:((c=r.parent)==null?void 0:c.path)||"",title:m,aliases:h,frontmatter:u},v=new Yu({getFrontmatter:()=>u});a.createDiv({cls:"project-name",text:r.basename});let k=v.buildMetadataRows(i,g,zl);for(let T of k){let b=a.createDiv({cls:"project-meta"});b.textContent=T}}catch(d){Z1e.error("Error rendering project suggestion:",{category:"internal",operation:"rendering-project-suggestion",error:d}),a.createSpan({cls:"project-name",text:r.basename})}}onChooseItem(e,t){this.onChoose(e)}}});function ms(n){if(n==null)return[];let e=[],t="",r=0,a=null;for(let s=0;s0){r--,t+="]]",s++;continue}if(!r&&(o==='"'||o==="'")){a===null?a=o:a===o&&(a=null),t+=o;continue}if(o===","&&r===0&&a===null){let c=t.trim();c&&e.push(c),t="";continue}t+=o}let i=t.trim();return i&&e.push(i),e}var Ku=y(()=>{});function U0(n){let e=n.search(/[#^]/);return(e===-1?n:n.slice(0,e)).trim()}function vt(n){if(!n)return n;let e=n.trim();if(e.startsWith("<")&&e.endsWith(">")){let r=e.slice(1,-1).trim(),a=/\.md$/i.test(r);try{r=decodeURIComponent(r)}catch(s){are.debug("Failed to decode URI component:",{category:"internal",operation:"decode-uri-component",details:{value:r},error:s})}let i=U0(r);return a?r:i||r}if(e.startsWith("[[")&&e.endsWith("]]")){let r=e.slice(2,-2).trim(),a=r.indexOf("|"),i=a!==-1?r.substring(0,a):r;return U0(i)}let t=e.match(/^\[([^\]]*)\]\(([^)]+)\)$/);if(t){let r=t[2].trim();r.startsWith("<")&&r.endsWith(">")&&(r=r.slice(1,-1).trim());let a=/\.md$/i.test(r);try{r=decodeURIComponent(r)}catch(s){are.debug("Failed to decode URI component:",{category:"internal",operation:"decode-uri-component",details:{value:r},error:s})}let i=U0(r);return a?r:i}return e}function Zo(n,e){if(!n)return"";let t=n.trim(),r=t.match(/^\[([^\]]+)\]\(([^)]+)\)$/);if(r){let a=r[1].trim(),i=r[2].trim(),s=vt(i),o=ire(s,e,a);if(o)return o;if(a)return a;let l=s.replace(/\.md$/i,""),c=l.split("/");return c[c.length-1]||l}if(t.startsWith("[[")&&t.endsWith("]]")){let a=t.slice(2,-2).trim(),i=a.indexOf("|");if(i!==-1){let d=a.slice(i+1).trim();if(d)return d}let s=U0(a.split("|")[0]||a)||vt(t),o=ire(s,e);if(o)return o;let l=s.replace(/\.md$/i,""),c=l.split("/");return c[c.length-1]||l}return t}function ire(n,e,t){let r=e==null?void 0:e.metadataCache.getFirstLinkpathDest(n,"");if(!r)return null;let a=Q1e(r,e);return a&&J1e(t,r,n)?a:(t==null?void 0:t.trim())||r.basename}function Q1e(n,e){var a,i,s,o;let t=(s=e==null?void 0:e.metadataCache.getFileCache(n))!=null?s:(i=(a=e==null?void 0:e.metadataCache)==null?void 0:a.getCache)==null?void 0:i.call(a,n.path),r=(o=t==null?void 0:t.frontmatter)==null?void 0:o.title;return typeof r=="string"&&r.trim().length>0?r.trim():null}function J1e(n,e,t){let r=(n==null?void 0:n.trim())||"";if(!r)return!0;let a=e.path.replace(/\.md$/i,""),i=t.replace(/\.md$/i,"");return new Set([e.name,e.basename,e.path,a,t,i]).has(r)}function Qo(n,e,t,r,a,i){if(i)return n.fileManager.generateMarkdownLink(e,t,r||"",a||"");let o=`[[${n.metadataCache.fileToLinktext(e,t,!0)}`;return r&&(o+=r),a&&(o+=`|${a}`),o+="]]",o}function H0(n,e,t,r,a){return Qo(n,e,t,"",r,a)}var are,Cn=y(()=>{q();are=M({tag:"Utils/LinkUtils"})});function eze(n){return X1e.includes(n)}function iB(n){if(typeof n=="string")return n;if(typeof n=="object"&&n!==null){let e=n.uid;return typeof e=="string"?e:""}return""}function Ai(n){if(typeof n=="string"){let e=n.trim();return e?{uid:vt(e),reltype:Pi}:null}if(typeof n=="object"&&n!==null){let e=n,t=typeof e.uid=="string"?e.uid.trim():"";if(!t)return null;let r=vt(t),a=typeof e.reltype=="string"?e.reltype.trim().toUpperCase():"",i=eze(a)?a:Pi,s=typeof e.gap=="string"&&e.gap.trim().length>0?e.gap.trim():void 0;return s?{uid:r,reltype:i,gap:s}:{uid:r,reltype:i}}return null}function yf(n){if(n==null)return;let e=Array.isArray(n)?n:[n],t=[];for(let r of e){let a=Ai(r);a&&t.push(a)}return t.length>0?t:void 0}function sre(n){return n.map(e=>{let r={uid:e.uid.startsWith("[[")?e.uid:`[[${e.uid}]]`,reltype:e.reltype};return e.gap&&e.gap.trim().length>0&&(r.gap=e.gap),r})}function Jo(n,e,t){let r=iB(t);if(!r)return null;let a=vt(r);if(!a)return null;let i=new Set;i.add(a),a.endsWith(".md")&&i.add(a.replace(/\.md$/i,""));let s=(0,my.parseLinktext)(a);s.path&&s.path!==a&&i.add(s.path);for(let o of i){let l=n.metadataCache.getFirstLinkpathDest(o,e);if(l instanceof my.TFile)return{path:l.path,file:l};let c=n.vault.getAbstractFileByPath(o);if(c instanceof my.TFile)return{path:c.path,file:c}}return null}function Ks(n,e,t,r){let a=n.vault.getAbstractFileByPath(t);return a instanceof my.TFile?Qo(n,a,e,"","",r):`[[${(t.split("/").pop()||t).replace(/\.md$/i,"")}]]`}var my,Pi,X1e,Zs=y(()=>{my=require("obsidian");Ku();Cn();Pi="FINISHTOSTART",X1e=["FINISHTOSTART","FINISHTOFINISH","STARTTOSTART","STARTTOFINISH"]});function V0(n,e){var t;return new ore.Setting(n).setName(e.label).addButton(r=>{r.setButtonText(e.buttonText).setTooltip(e.buttonTooltip).onClick(e.onButtonClick),r.buttonEl.addClasses(["tn-btn","tn-btn--ghost"])}),(t=e.listElement)!=null?t:n.createDiv({cls:"task-projects-list"})}function lre(n,e){return V0(e.container,{label:n.translate("modals.task.organization.projects"),buttonText:n.translate("modals.task.organization.addToProjectButton"),buttonTooltip:n.translate("modals.task.projectsTooltip"),onButtonClick:e.onButtonClick,listElement:e.listElement})}function cre(n,e){return V0(e.container,{label:n.translate("modals.task.organization.subtasks"),buttonText:n.translate("modals.task.organization.addSubtasksButton"),buttonTooltip:n.translate("modals.task.organization.addSubtasksTooltip"),onButtonClick:e.onButtonClick,listElement:e.listElement})}function dre(n,e){return V0(e.container,{label:n.translate("modals.task.dependencies.blockedBy"),buttonText:n.translate("modals.task.dependencies.addTaskButton"),buttonTooltip:n.translate("modals.task.dependencies.selectTaskTooltip"),onButtonClick:e.onButtonClick,listElement:e.listElement})}function ure(n,e){return V0(e.container,{label:n.translate("modals.task.dependencies.blocking"),buttonText:n.translate("modals.task.dependencies.addTaskButton"),buttonTooltip:n.translate("modals.task.dependencies.selectTaskTooltip"),onButtonClick:e.onButtonClick,listElement:e.listElement})}var ore,pre=y(()=>{ore=require("obsidian")});function fre(n){let{task:e,plugin:t,excludeSelector:r,onSingleClick:a,onDoubleClick:i,contextMenuHandler:s,createBatchContextMenu:o,navigationSubpath:l}=n,c=r?`${mre}, ${r}`:mre,d=null,u=(S=!1)=>{let C=t.app.vault.getAbstractFileByPath(e.path);C instanceof sB.TFile&&(l?t.app.workspace.openLinkText(e.path+l,"",S):S?t.app.workspace.openLinkText(e.path,"",!0):t.app.workspace.getLeaf(!1).openFile(C))},p=async()=>{await t.openTaskEditModal(e)},m=async S=>{if(a){await a(S);return}if(S.ctrlKey||S.metaKey){u(!0);return}let C=t.settings.singleClickAction;C==="edit"?await p():C==="openNote"&&u(!1)},f=async S=>{if(i){await i(S);return}let C=t.settings.doubleClickAction;C==="edit"?await p():C==="openNote"&&u()},h=async S=>{if(S.target.closest(c))return;let x=t.taskSelectionService;if(x){if(S.shiftKey){S.stopPropagation(),x.isSelectionModeActive()||x.enterSelectionMode(),x.toggleSelection(e.path);return}x.isSelectionModeActive()&&(x.clearSelection(),x.exitSelectionMode())}if(S.stopPropagation(),t.settings.doubleClickAction==="none"){await m(S);return}d?(window.clearTimeout(d),d=null,await f(S)):d=window.setTimeout(()=>{d=null,m(S)},250)},g=S=>{h(S)},v=S=>{S.button!==1||S.target.closest(c)||(S.preventDefault(),S.stopPropagation(),d&&(window.clearTimeout(d),d=null),u(!0))},k=S=>{v(S)},T=S=>{},b=async S=>{S.preventDefault(),S.stopPropagation();let C=t.taskSelectionService;if(S.shiftKey&&C){if(C.isSelectionModeActive()||C.enterSelectionMode(),C.isSelected(e.path)||C.addToSelection(e.path),C.getSelectionCount()>0){let x=o==null?void 0:o(C.getSelectedPaths(),()=>{});x==null||x.show(S)}return}if(C&&C.getSelectionCount()>1){C.isSelected(e.path)||C.addToSelection(e.path);let x=o==null?void 0:o(C.getSelectedPaths(),()=>{});x==null||x.show(S);return}C!=null&&C.isSelectionModeActive()&&(C.clearSelection(),C.exitSelectionMode()),s&&await s(S)};return{clickHandler:g,auxclickHandler:k,dblclickHandler:T,contextmenuHandler:S=>{b(S)},cleanup:()=>{d&&(window.clearTimeout(d),d=null)}}}function hre(n,e){return t=>{e.app.vault.getAbstractFileByPath(n.path)&&e.app.workspace.trigger("hover-link",{event:t,source:"tasknotes-task-card",hoverParent:t.currentTarget,targetEl:t.currentTarget,linktext:n.path,sourcePath:n.path})}}async function gre(n,e,t,r,a){let i=(d=!1)=>{let u=e.app.vault.getAbstractFileByPath(n.path);u instanceof sB.TFile&&(d?e.app.workspace.openLinkText(n.path,"",!0):e.app.workspace.getLeaf(!1).openFile(u))},s=async()=>{await e.openTaskEditModal(n,a?()=>a():void 0)},o=async d=>{if(d.ctrlKey||d.metaKey){i(!0);return}let u=e.settings.singleClickAction;u==="edit"?await s():u==="openNote"&&i(!1)},l=async d=>{let u=e.settings.doubleClickAction;u==="edit"?await s():u==="openNote"&&i()};if(e.settings.doubleClickAction==="none"){await o(t);return}let c=W0.get(r);if(c)window.clearTimeout(c),W0.delete(r),await l(t);else{let d=window.setTimeout(()=>{W0.delete(r),o(t)},250);W0.set(r,d)}}var sB,mre,W0,oB=y(()=>{sB=require("obsidian"),mre=["a","button","input","textarea","select",'[role="button"]','[data-tn-no-drag="true"]','[data-tn-click-exclude="true"]',".tag"].join(", ");W0=new Map});var yre,ra,Md=y(()=>{yre=require("obsidian"),ra=class extends yre.Menu{show(e){var t;if(e.instanceOf(MouseEvent))this.showAtMouseEvent(e);else if(e.instanceOf(KeyboardEvent)){let r=e.currentTarget;if(!r||!((t=r.instanceOf)!=null&&t.call(r,HTMLElement)))return;this.showAtPosition({x:r.getBoundingClientRect().left,y:r.getBoundingClientRect().bottom+4})}}}});function vre(n){if(!n||typeof n!="object")return null;let e=n;return e.nodeType!==1||typeof e.closest!="function"?null:e}function tze(n){let e=n.instanceOf;return typeof e=="function"?e.call(n,MouseEvent)===!0:n instanceof MouseEvent}function G0(){let n=fy;fy=null,q0=null,n==null||n.hide()}function nze(n){var t;let e=vre(n.target);return(t=e==null?void 0:e.closest(rze))!=null?t:e}function kre(n,e,t){if(e&&fy&&q0===e){G0();return}G0(),fy=n,q0=e,n.onHide(()=>{fy===n&&(fy=null,q0=null)}),t()}function za(n,e){kre(n,nze(e),()=>{var r;if(tze(e)){n.showAtMouseEvent(e);return}let t=vre(e.currentTarget);((r=t==null?void 0:t.instanceOf)!=null&&r.call(t,HTMLElement)||t instanceof HTMLElement)&&n.showAtPosition({x:t.getBoundingClientRect().left,y:t.getBoundingClientRect().bottom+4},t.ownerDocument)})}function jl(n,e){kre(n,e,()=>{n.showAtPosition({x:e.getBoundingClientRect().left,y:e.getBoundingClientRect().bottom+4},e.ownerDocument)})}var rze,fy,q0,Id=y(()=>{rze='[data-tn-action], [data-type], [role="button"], button, .clickable-icon',fy=null,q0=null});var Tre=y(()=>{});var bre,lB=y(()=>{bre={triggers:[{propertyId:"tags",trigger:"#",enabled:!0},{propertyId:"contexts",trigger:"@",enabled:!0},{propertyId:"projects",trigger:"+",enabled:!0},{propertyId:"status",trigger:"*",enabled:!0},{propertyId:"priority",trigger:"!",enabled:!1}]}});var wre,Sre=y(()=>{wre={code:"en",name:"English",chronoLocale:"en",dateTriggers:{due:["due","deadline","must be done by","by"],scheduled:["scheduled for","start on","begin on","work on","on","scheduled","start"]},recurrence:{frequencies:{daily:["daily","every day"],weekly:["weekly","every week"],monthly:["monthly","every month"],yearly:["yearly","annually","every year"]},every:["every"],other:["other"],weekdays:{monday:["monday"],tuesday:["tuesday"],wednesday:["wednesday"],thursday:["thursday"],friday:["friday"],saturday:["saturday"],sunday:["sunday"]},pluralWeekdays:{monday:["mondays"],tuesday:["tuesdays"],wednesday:["wednesdays"],thursday:["thursdays"],friday:["fridays"],saturday:["saturdays"],sunday:["sundays"]},ordinals:{first:["first"],second:["second"],third:["third"],fourth:["fourth"],last:["last"]},periods:{day:["day","days"],week:["week","weeks"],month:["month","months"],year:["year","years"]}},timeEstimate:{hours:["h","hr","hrs","hour","hours"],minutes:["m","min","mins","minute","minutes"]},fallbackStatus:{open:["todo","to do","open"],inProgress:["in progress","in-progress","doing"],done:["done","completed","finished"],cancelled:["cancelled","canceled"],waiting:["waiting","blocked","on hold"]},fallbackPriority:{urgent:["urgent","critical","highest"],high:["high","important"],normal:["medium","normal"],low:["low","minor"]}}});var Cre,xre=y(()=>{Cre={code:"es",name:"Español",chronoLocale:"es",dateTriggers:{due:["vence","fecha límite","debe terminarse","para el","antes del"],scheduled:["programado para","programado el","comenzar el","empezar el","trabajar en","el"]},recurrence:{frequencies:{daily:["diario","diaria","diariamente","cada día","todos los días","a diario"],weekly:["semanal","semanalmente","cada semana","todas las semanas","por semana"],monthly:["mensual","mensualmente","cada mes","todos los meses","por mes"],yearly:["anual","anualmente","cada año","todos los años","por año"]},every:["cada","todos los","todas las"],other:["otro","otra"],weekdays:{monday:["lunes"],tuesday:["martes"],wednesday:["miércoles"],thursday:["jueves"],friday:["viernes"],saturday:["sábado"],sunday:["domingo"]},pluralWeekdays:{monday:["lunes"],tuesday:["martes"],wednesday:["miércoles"],thursday:["jueves"],friday:["viernes"],saturday:["sábados"],sunday:["domingos"]},ordinals:{first:["primer","primera","primero"],second:["segundo","segunda"],third:["tercer","tercera","tercero"],fourth:["cuarto","cuarta"],last:["último","última"]},periods:{day:["día","días"],week:["semana","semanas"],month:["mes","meses"],year:["año","años"]}},timeEstimate:{hours:["h","hr","hrs","hora","horas"],minutes:["m","min","mins","minuto","minutos"]},fallbackStatus:{open:["pendiente","por hacer","abierto","todo"],inProgress:["en progreso","en curso","haciendo","trabajando"],done:["hecho","terminado","completado","finalizado"],cancelled:["cancelado","anulado"],waiting:["esperando","bloqueado","en espera"]},fallbackPriority:{urgent:["urgente","crítico","crítica","máximo","máxima","prioritario","prioritaria"],high:["alto","alta","importante","elevado","elevada"],normal:["medio","media","normal","regular","estándar"],low:["bajo","baja","menor","mínimo","mínima"]}}});var Ere,Dre=y(()=>{Ere={code:"fr",name:"Français",chronoLocale:"fr",dateTriggers:{due:["échéance","date limite","doit être terminé","pour le","avant le"],scheduled:["programmé pour","programmé le","commencer le","débuter le","travailler sur","le"]},recurrence:{frequencies:{daily:["quotidien","quotidienne","quotidiennement","chaque jour","tous les jours","journalier","journalière"],weekly:["hebdomadaire","chaque semaine","toutes les semaines","par semaine"],monthly:["mensuel","mensuelle","mensuellement","chaque mois","tous les mois","par mois"],yearly:["annuel","annuelle","annuellement","chaque année","tous les ans","par an","par année"]},every:["chaque","tous les","toutes les"],other:["autre"],weekdays:{monday:["lundi"],tuesday:["mardi"],wednesday:["mercredi"],thursday:["jeudi"],friday:["vendredi"],saturday:["samedi"],sunday:["dimanche"]},pluralWeekdays:{monday:["lundis"],tuesday:["mardis"],wednesday:["mercredis"],thursday:["jeudis"],friday:["vendredis"],saturday:["samedis"],sunday:["dimanches"]},ordinals:{first:["premier","première"],second:["deuxième","second","seconde"],third:["troisième"],fourth:["quatrième"],last:["dernier","dernière"]},periods:{day:["jour","jours"],week:["semaine","semaines"],month:["mois"],year:["an","ans","année","années"]}},timeEstimate:{hours:["h","hr","hrs","heure","heures"],minutes:["m","min","mins","minute","minutes"]},fallbackStatus:{open:["à faire","ouvert","en attente","todo"],inProgress:["en cours","en progression","en train de faire"],done:["terminé","fini","accompli","fait"],cancelled:["annulé","abandonné"],waiting:["en attente","bloqué","suspendu"]},fallbackPriority:{urgent:["urgent","urgente","critique","maximum","prioritaire"],high:["élevé","élevée","haut","haute","important","importante","supérieur","supérieure"],normal:["moyen","moyenne","normal","normale","standard","régulier","régulière"],low:["faible","bas","basse","mineur","mineure","minimum"]}}});var Pre,Are=y(()=>{Pre={code:"de",name:"Deutsch",chronoLocale:"de",dateTriggers:{due:["fällig","termin","abgabe","deadline","bis zum","bis"],scheduled:["geplant für","geplant am","beginnen am","anfangen am","arbeiten an","am","geplant","starten"]},recurrence:{frequencies:{daily:["täglich","jeden Tag","alle Tage","tagaus tagein"],weekly:["wöchentlich","jede Woche","alle Wochen"],monthly:["monatlich","jeden Monat","alle Monate"],yearly:["jährlich","jedes Jahr","alle Jahre"]},every:["jede","jeden","jedes","alle"],other:["andere","anderen","anderes"],weekdays:{monday:["montag"],tuesday:["dienstag"],wednesday:["mittwoch"],thursday:["donnerstag"],friday:["freitag"],saturday:["samstag"],sunday:["sonntag"]},pluralWeekdays:{monday:["montags"],tuesday:["dienstags"],wednesday:["mittwochs"],thursday:["donnerstags"],friday:["freitags"],saturday:["samstags"],sunday:["sonntags"]},ordinals:{first:["erste","ersten","erster"],second:["zweite","zweiten","zweiter"],third:["dritte","dritten","dritter"],fourth:["vierte","vierten","vierter"],last:["letzte","letzten","letzter"]},periods:{day:["tag","tage"],week:["woche","wochen"],month:["monat","monate"],year:["jahr","jahre"]}},timeEstimate:{hours:["h","std","stunde","stunden"],minutes:["m","min","minute","minuten"]},fallbackStatus:{open:["offen","zu erledigen","ausstehend","todo"],inProgress:["in bearbeitung","wird bearbeitet","läuft","in arbeit"],done:["erledigt","fertig","abgeschlossen","gemacht"],cancelled:["abgebrochen","storniert","abgesagt"],waiting:["wartend","warten","blockiert","pausiert"]},fallbackPriority:{urgent:["dringend","eilig","kritisch","sofort","höchste"],high:["hoch","hohe","wichtig","prioritär"],normal:["normal","mittel","mittlere","standard"],low:["niedrig","niedrige","gering","geringe"]}}});var Mre,Ire=y(()=>{Mre={code:"ru",name:"Русский",chronoLocale:"ru",dateTriggers:{due:["срок","дедлайн","до","к","сдать до"],scheduled:["запланировано на","начать","работать над","на"]},recurrence:{frequencies:{daily:["ежедневно","каждый день","ежедневный","каждодневный"],weekly:["еженедельно","каждую неделю","еженедельный"],monthly:["ежемесячно","каждый месяц","ежемесячный"],yearly:["ежегодно","каждый год","ежегодный"]},every:["каждый","каждую","каждое","все"],other:["другой","другую","другое"],weekdays:{monday:["понедельник"],tuesday:["вторник"],wednesday:["среда"],thursday:["четверг"],friday:["пятница"],saturday:["суббота"],sunday:["воскресенье"]},pluralWeekdays:{monday:["по понедельникам"],tuesday:["по вторникам"],wednesday:["по средам"],thursday:["по четвергам"],friday:["по пятницам"],saturday:["по субботам"],sunday:["по воскресеньям"]},ordinals:{first:["первый","первая","первое"],second:["второй","вторая","второе"],third:["третий","третья","третье"],fourth:["четвертый","четвертая","четвертое"],last:["последний","последняя","последнее"]},periods:{day:["день","дни"],week:["неделя","недели"],month:["месяц","месяцы"],year:["год","годы"]}},timeEstimate:{hours:["ч","час","часа","часов"],minutes:["м","мин","минута","минуты","минут"]},fallbackStatus:{open:["открыто","к выполнению","новое","todo"],inProgress:["в работе","выполняется","в процессе"],done:["выполнено","готово","завершено","сделано"],cancelled:["отменено","отменён","отменена"],waiting:["ожидание","заблокировано","на паузе"]},fallbackPriority:{urgent:["срочно","критично","экстренно","немедленно"],high:["высокий","высокая","важно","приоритетно"],normal:["нормальный","нормальная","средний","средняя"],low:["низкий","низкая","неважно","можно позже"]}}});var Nre,Rre=y(()=>{Nre={code:"zh",name:"中文",chronoLocale:"zh",dateTriggers:{due:["截止","到期","期限","在","之前"],scheduled:["安排在","计划在","开始在","在"]},recurrence:{frequencies:{daily:["每天","每日","天天","日常"],weekly:["每周","每星期","周周"],monthly:["每月","每个月","月月"],yearly:["每年","年年","每一年"]},every:["每","每个","每一个"],other:["其他","另一个"],weekdays:{monday:["周一","星期一","礼拜一"],tuesday:["周二","星期二","礼拜二"],wednesday:["周三","星期三","礼拜三"],thursday:["周四","星期四","礼拜四"],friday:["周五","星期五","礼拜五"],saturday:["周六","星期六","礼拜六"],sunday:["周日","星期日","礼拜日"]},pluralWeekdays:{monday:["周一","星期一","礼拜一"],tuesday:["周二","星期二","礼拜二"],wednesday:["周三","星期三","礼拜三"],thursday:["周四","星期四","礼拜四"],friday:["周五","星期五","礼拜五"],saturday:["周六","星期六","礼拜六"],sunday:["周日","星期日","礼拜日"]},ordinals:{first:["第一个","第一","首个"],second:["第二个","第二"],third:["第三个","第三"],fourth:["第四个","第四"],last:["最后一个","最后","末尾"]},periods:{day:["天","日"],week:["周","星期"],month:["月","个月"],year:["年"]}},timeEstimate:{hours:["小时","时","个小时"],minutes:["分钟","分","个分钟"]},fallbackStatus:{open:["待办","未完成","开放","新建"],inProgress:["进行中","正在处理","处理中","工作中"],done:["完成","已完成","结束","搞定"],cancelled:["取消","已取消","废弃"],waiting:["等待","暂停","阻塞","待定"]},fallbackPriority:{urgent:["紧急","急迫","立即","马上"],high:["高","重要","高优先级"],normal:["正常","普通","中等","标准"],low:["低","不重要","低优先级","次要"]}}});var _re,Fre=y(()=>{_re={code:"ja",name:"日本語",chronoLocale:"ja",dateTriggers:{due:["期限","締切","〆切","まで","までに","に"],scheduled:["予定","計画","開始","から","に開始","を開始"]},recurrence:{frequencies:{daily:["毎日","日々","毎日毎日","連日"],weekly:["毎週","週毎","週一","毎週毎週"],monthly:["毎月","月毎","月一","毎月毎月"],yearly:["毎年","年毎","年一","毎年毎年","年次"]},every:["毎","各","全て"],other:["他の","別の","異なる"],weekdays:{monday:["月曜日","月曜","月","げつようび"],tuesday:["火曜日","火曜","火","かようび"],wednesday:["水曜日","水曜","水","すいようび"],thursday:["木曜日","木曜","木","もくようび"],friday:["金曜日","金曜","金","きんようび"],saturday:["土曜日","土曜","土","どようび"],sunday:["日曜日","日曜","日","にちようび"]},pluralWeekdays:{monday:["月曜日","月曜","月","げつようび"],tuesday:["火曜日","火曜","火","かようび"],wednesday:["水曜日","水曜","水","すいようび"],thursday:["木曜日","木曜","木","もくようび"],friday:["金曜日","金曜","金","きんようび"],saturday:["土曜日","土曜","土","どようび"],sunday:["日曜日","日曜","日","にちようび"]},ordinals:{first:["最初の","第一の","一番目の","初回"],second:["二番目の","第二の","次の"],third:["三番目の","第三の"],fourth:["四番目の","第四の"],last:["最後の","最終の","終わりの"]},periods:{day:["日","日間"],week:["週","週間"],month:["月","月間","ヶ月"],year:["年","年間"]}},timeEstimate:{hours:["時間","時","じかん"],minutes:["分","分間","ふん","ぷん"]},fallbackStatus:{open:["未着手","新規","オープン","開始前","待機"],inProgress:["進行中","作業中","実行中","処理中","進行"],done:["完了","終了","済み","終わり","達成"],cancelled:["キャンセル","中止","取消","廃止","停止"],waiting:["待機","保留","ブロック","一時停止","待ち"]},fallbackPriority:{urgent:["緊急","至急","急務","最優先","すぐに"],high:["高","重要","高優先度","重点"],normal:["普通","通常","標準","一般","ノーマル"],low:["低","軽微","後回し","低優先度","余裕"]}}});var Lre,Ore=y(()=>{Lre={code:"it",name:"Italiano",chronoLocale:"it",dateTriggers:{due:["scadenza","entro","entro il","deve essere fatto entro","per il","termine"],scheduled:["programmato per","programmato il","iniziare il","lavorare su","il","per"]},recurrence:{frequencies:{daily:["giornaliero","giornaliera","quotidiano","quotidiana","ogni giorno","tutti i giorni","giornalmente"],weekly:["settimanale","ogni settimana","tutte le settimane","settimanalmente","alla settimana"],monthly:["mensile","ogni mese","tutti i mesi","mensilmente","al mese"],yearly:["annuale","ogni anno","tutti gli anni","annualmente","all'anno"]},every:["ogni","tutti i","tutte le"],other:["altro","altra","altri","altre"],weekdays:{monday:["lunedì"],tuesday:["martedì"],wednesday:["mercoledì"],thursday:["giovedì"],friday:["venerdì"],saturday:["sabato"],sunday:["domenica"]},pluralWeekdays:{monday:["lunedì"],tuesday:["martedì"],wednesday:["mercoledì"],thursday:["giovedì"],friday:["venerdì"],saturday:["sabati"],sunday:["domeniche"]},ordinals:{first:["primo","prima"],second:["secondo","seconda"],third:["terzo","terza"],fourth:["quarto","quarta"],last:["ultimo","ultima"]},periods:{day:["giorno","giorni"],week:["settimana","settimane"],month:["mese","mesi"],year:["anno","anni"]}},timeEstimate:{hours:["h","hr","ore","ora","o"],minutes:["m","min","minuto","minuti"]},fallbackStatus:{open:["da fare","aperto","pendente","todo","in sospeso"],inProgress:["in corso","in progresso","facendo","lavorando"],done:["fatto","completato","finito","terminato","chiuso"],cancelled:["cancellato","annullato","rimosso"],waiting:["in attesa","aspettando","bloccato","fermo"]},fallbackPriority:{urgent:["urgente","critico","critica","massimo","massima","prioritario","prioritaria"],high:["alto","alta","importante","elevato","elevata"],normal:["medio","media","normale","regolare","standard"],low:["basso","bassa","minore","minimo","minima"]}}});var zre,Bre=y(()=>{zre={code:"nl",name:"Nederlands",chronoLocale:"nl",dateTriggers:{due:["vervalt op","deadline","moet klaar zijn op","tegen","uiterlijk","voor"],scheduled:["gepland voor","gepland op","beginnen op","werken aan","op","voor"]},recurrence:{frequencies:{daily:["dagelijks","elke dag","alle dagen","per dag"],weekly:["wekelijks","elke week","alle weken","per week"],monthly:["maandelijks","elke maand","alle maanden","per maand"],yearly:["jaarlijks","elk jaar","alle jaren","per jaar"]},every:["elke","alle","iedere"],other:["andere","ander"],weekdays:{monday:["maandag"],tuesday:["dinsdag"],wednesday:["woensdag"],thursday:["donderdag"],friday:["vrijdag"],saturday:["zaterdag"],sunday:["zondag"]},pluralWeekdays:{monday:["maandagen"],tuesday:["dinsdagen"],wednesday:["woensdagen"],thursday:["donderdagen"],friday:["vrijdagen"],saturday:["zaterdagen"],sunday:["zondagen"]},ordinals:{first:["eerste"],second:["tweede"],third:["derde"],fourth:["vierde"],last:["laatste"]},periods:{day:["dag","dagen"],week:["week","weken"],month:["maand","maanden"],year:["jaar","jaren"]}},timeEstimate:{hours:["u","uur","uren","h"],minutes:["m","min","minuut","minuten"]},fallbackStatus:{open:["te doen","open","nog te doen","todo","openstaand"],inProgress:["bezig","in behandeling","aan het werk","lopend","in uitvoering"],done:["klaar","voltooid","gedaan","afgerond","gesloten"],cancelled:["geannuleerd","afgezegd","ingetrokken"],waiting:["wachtend","in de wacht","geblokkeerd","uitgesteld"]},fallbackPriority:{urgent:["urgent","kritiek","hoogste","spoed","direct"],high:["hoog","hoge","belangrijk","belangrijke"],normal:["normaal","normale","gemiddeld","standaard"],low:["laag","lage","klein","kleine","onbelangrijk"]}}});var jre,$re=y(()=>{jre={code:"pt",name:"Português",chronoLocale:"pt",dateTriggers:{due:["vencimento","prazo","deve estar pronto até","até","para","limite"],scheduled:["programado para","agendado para","começar em","trabalhar em","em","no"]},recurrence:{frequencies:{daily:["diário","diária","diariamente","todos os dias","cada dia","por dia"],weekly:["semanal","semanalmente","toda semana","todas as semanas","por semana"],monthly:["mensal","mensalmente","todo mês","todos os meses","por mês"],yearly:["anual","anualmente","todo ano","todos os anos","por ano"]},every:["todo","toda","todos","todas","cada"],other:["outro","outra","outros","outras"],weekdays:{monday:["segunda","segunda-feira"],tuesday:["terça","terça-feira"],wednesday:["quarta","quarta-feira"],thursday:["quinta","quinta-feira"],friday:["sexta","sexta-feira"],saturday:["sábado"],sunday:["domingo"]},pluralWeekdays:{monday:["segundas","segundas-feiras"],tuesday:["terças","terças-feiras"],wednesday:["quartas","quartas-feiras"],thursday:["quintas","quintas-feiras"],friday:["sextas","sextas-feiras"],saturday:["sábados"],sunday:["domingos"]},ordinals:{first:["primeiro","primeira"],second:["segundo","segunda"],third:["terceiro","terceira"],fourth:["quarto","quarta"],last:["último","última"]},periods:{day:["dia","dias"],week:["semana","semanas"],month:["mês","meses"],year:["ano","anos"]}},timeEstimate:{hours:["h","hr","hora","horas"],minutes:["m","min","minuto","minutos"]},fallbackStatus:{open:["a fazer","pendente","aberto","todo","por fazer"],inProgress:["em andamento","em progresso","fazendo","trabalhando","executando"],done:["feito","concluído","terminado","finalizado","completo"],cancelled:["cancelado","anulado","suspenso"],waiting:["aguardando","esperando","bloqueado","em espera"]},fallbackPriority:{urgent:["urgente","crítico","crítica","máximo","máxima","prioritário","prioritária"],high:["alto","alta","importante","elevado","elevada"],normal:["médio","média","normal","regular","padrão"],low:["baixo","baixa","menor","mínimo","mínima"]}}});var Ure,Hre=y(()=>{Ure={code:"sv",name:"Svenska",chronoLocale:"sv",dateTriggers:{due:["förfaller","deadline","måste vara klar","senast","till","innan"],scheduled:["schemalagd","planerad för","börja","arbeta med","den","på"]},recurrence:{frequencies:{daily:["dagligen","varje dag","alla dagar","per dag"],weekly:["veckovis","varje vecka","alla veckor","per vecka"],monthly:["månadsvis","varje månad","alla månader","per månad"],yearly:["årligen","varje år","alla år","per år"]},every:["varje","alla","var"],other:["annan","annat","andra"],weekdays:{monday:["måndag"],tuesday:["tisdag"],wednesday:["onsdag"],thursday:["torsdag"],friday:["fredag"],saturday:["lördag"],sunday:["söndag"]},pluralWeekdays:{monday:["måndagar"],tuesday:["tisdagar"],wednesday:["onsdagar"],thursday:["torsdagar"],friday:["fredagar"],saturday:["lördagar"],sunday:["söndagar"]},ordinals:{first:["första"],second:["andra"],third:["tredje"],fourth:["fjärde"],last:["sista"]},periods:{day:["dag","dagar"],week:["vecka","veckor"],month:["månad","månader"],year:["år"]}},timeEstimate:{hours:["t","tim","timme","timmar","h"],minutes:["m","min","minut","minuter"]},fallbackStatus:{open:["att göra","öppen","kvar","todo","väntande"],inProgress:["pågående","arbetar","gör","i process","under arbete"],done:["klar","färdig","slutförd","avslutad","gjord"],cancelled:["avbruten","inställd","avbokad"],waiting:["väntar","blockerad","pausad","vilande"]},fallbackPriority:{urgent:["brådskande","kritisk","högsta","akut","omedelbar"],high:["hög","viktig","förhöjd","prioriterad"],normal:["normal","medel","standard","vanlig"],low:["låg","mindre","minimal","obetydlig"]}}});var Vre,Wre=y(()=>{Vre={code:"uk",name:"Українська",chronoLocale:"uk",dateTriggers:{due:["термін","дедлайн","має бути готово до","до","не пізніше","крайній термін"],scheduled:["заплановано на","запланований","почати","працювати над","на","в"]},recurrence:{frequencies:{daily:["щодня","щоденно","кожен день","всі дні","на день"],weekly:["щотижня","щотижнево","кожен тиждень","всі тижні","на тиждень"],monthly:["щомісяця","щомісячно","кожен місяць","всі місяці","на місяць"],yearly:["щороку","щорічно","кожен рік","всі роки","на рік"]},every:["кожен","кожна","кожне","всі"],other:["інший","інша","інше","інші"],weekdays:{monday:["понеділок"],tuesday:["вівторок"],wednesday:["середа"],thursday:["четвер"],friday:["п'ятниця"],saturday:["субота"],sunday:["неділя"]},pluralWeekdays:{monday:["понеділки"],tuesday:["вівторки"],wednesday:["середи"],thursday:["четверги"],friday:["п'ятниці"],saturday:["суботи"],sunday:["неділі"]},ordinals:{first:["перший","перша","перше"],second:["другий","друга","друге"],third:["третій","третя","третє"],fourth:["четвертий","четверта","четверте"],last:["останній","остання","останнє"]},periods:{day:["день","дні","днів"],week:["тиждень","тижні","тижнів"],month:["місяць","місяці","місяців"],year:["рік","роки","років"]}},timeEstimate:{hours:["г","год","година","години","годин"],minutes:["хв","мін","хвилина","хвилини","хвилин"]},fallbackStatus:{open:["зробити","відкритий","очікує","todo","в очікуванні"],inProgress:["в роботі","виконується","роблю","працюю","в процесі"],done:["готово","виконано","завершено","закінчено","зроблено"],cancelled:["скасовано","відмінено","припинено"],waiting:["чекаю","очікую","заблоковано","призупинено"]},fallbackPriority:{urgent:["терміново","критично","найвищий","невідкладно","пріоритетно"],high:["високий","висока","важливо","підвищений"],normal:["середній","середня","нормально","звичайно","стандартно"],low:["низький","низька","менший","мінімальний","незначний"]}}});var qre=y(()=>{});function Yre(n){return Gre[n]||Gre.en}var Gre,cB=y(()=>{Sre();xre();Dre();Are();Ire();Rre();Fre();Ore();Bre();$re();Hre();Wre();qre();Gre={en:wre,es:Cre,fr:Ere,de:Pre,ru:Mre,zh:Nre,ja:_re,it:Lre,nl:zre,pt:jre,sv:Ure,uk:Vre}});var Y0,dB=y(()=>{Y0=class{constructor(e,t=[]){this.config=e,this.userFields=t,this.triggerMap=new Map,this.propertyMap=new Map,this.buildMaps()}buildMaps(){this.triggerMap.clear(),this.propertyMap.clear();for(let e of this.config.triggers)e.enabled&&(this.triggerMap.set(e.trigger,e),this.propertyMap.set(e.propertyId,e))}getTriggerForProperty(e){return this.propertyMap.get(e)}getPropertyForTrigger(e){var t;return(t=this.triggerMap.get(e))==null?void 0:t.propertyId}getAllEnabledTriggers(){return this.config.triggers.filter(e=>e.enabled)}getTriggersOrderedByLength(){return this.getAllEnabledTriggers().sort((e,t)=>t.trigger.length-e.trigger.length)}usesNativeTagSuggester(){let e=this.getTriggerForProperty("tags");return(e==null?void 0:e.trigger)==="#"&&(e==null?void 0:e.enabled)}getTagTrigger(){let e=this.getTriggerForProperty("tags");return e!=null&&e.enabled?e.trigger:void 0}getContextTrigger(){let e=this.getTriggerForProperty("contexts");return e!=null&&e.enabled?e.trigger:void 0}getProjectTrigger(){let e=this.getTriggerForProperty("projects");return e!=null&&e.enabled?e.trigger:void 0}getStatusTrigger(){let e=this.getTriggerForProperty("status");return e!=null&&e.enabled?e.trigger:void 0}getPriorityTrigger(){let e=this.getTriggerForProperty("priority");return e!=null&&e.enabled?e.trigger:void 0}getUserField(e){return this.userFields.find(t=>t.id===e)}isUserField(e){return this.userFields.some(t=>t.id===e)}getSuggesterType(e){if(e==="tags")return this.usesNativeTagSuggester()?"native-tag":"list";if(e==="contexts")return"list";if(e==="projects")return"file";if(e==="status")return"status";if(e==="priority")return"priority";let t=this.getUserField(e);if(t)switch(t.type){case"text":return t.autosuggestFilter?"file":"list";case"list":return"list";case"boolean":return"boolean";default:return"none"}return"none"}updateConfig(e){this.config=e,this.buildMaps()}updateUserFields(e){this.userFields=e}}});var Kre=te((uB,pB)=>{(function(n,e){typeof uB=="object"&&typeof pB!="undefined"?pB.exports=e():typeof define=="function"&&define.amd?define(e):(n=typeof globalThis!="undefined"?globalThis:n||self).dayjs_plugin_quarterOfYear=e()})(uB,(function(){"use strict";var n="month",e="quarter";return function(t,r){var a=r.prototype;a.quarter=function(o){return this.$utils().u(o)?Math.ceil((this.month()+1)/3):this.month(this.month()%3+3*(o-1))};var i=a.add;a.add=function(o,l){return o=Number(o),this.$utils().p(l)===e?this.add(3*o,n):i.bind(this)(o,l)};var s=a.startOf;a.startOf=function(o,l){var c=this.$utils(),d=!!c.u(l)||l;if(c.p(o)===e){var u=this.quarter()-1;return d?this.month(3*u).startOf(n).startOf("day"):this.month(3*u+2).endOf(n).endOf("day")}return s.bind(this)(o,l)}}}))});var Ht=te((mB,fB)=>{(function(n,e){typeof mB=="object"&&typeof fB!="undefined"?fB.exports=e():typeof define=="function"&&define.amd?define(e):(n=typeof globalThis!="undefined"?globalThis:n||self).dayjs=e()})(mB,(function(){"use strict";var n=1e3,e=6e4,t=36e5,r="millisecond",a="second",i="minute",s="hour",o="day",l="week",c="month",d="quarter",u="year",p="date",m="Invalid Date",f=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,h=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,g={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(I){var A=["th","st","nd","rd"],R=I%100;return"["+I+(A[(R-20)%10]||A[R]||A[0])+"]"}},v=function(I,A,R){var O=String(I);return!O||O.length>=A?I:""+Array(A+1-O.length).join(R)+I},k={s:v,z:function(I){var A=-I.utcOffset(),R=Math.abs(A),O=Math.floor(R/60),U=R%60;return(A<=0?"+":"-")+v(O,2,"0")+":"+v(U,2,"0")},m:function I(A,R){if(A.date()1)return I(oe[0])}else{var X=A.name;b[X]=A,U=X}return!O&&U&&(T=U),U||!O&&T},x=function(I,A){if(S(I))return I.clone();var R=typeof A=="object"?A:{};return R.date=I,R.args=arguments,new _(R)},E=k;E.l=C,E.i=S,E.w=function(I,A){return x(I,{locale:A.$L,utc:A.$u,x:A.$x,$offset:A.$offset})};var _=(function(){function I(R){this.$L=C(R.locale,null,!0),this.parse(R),this.$x=this.$x||R.x||{},this[w]=!0}var A=I.prototype;return A.parse=function(R){this.$d=(function(O){var U=O.date,pe=O.utc;if(U===null)return new Date(NaN);if(E.u(U))return new Date;if(U instanceof Date)return new Date(U);if(typeof U=="string"&&!/Z$/i.test(U)){var oe=U.match(f);if(oe){var X=oe[2]-1||0,de=(oe[7]||"0").substring(0,3);return pe?new Date(Date.UTC(oe[1],X,oe[3]||1,oe[4]||0,oe[5]||0,oe[6]||0,de)):new Date(oe[1],X,oe[3]||1,oe[4]||0,oe[5]||0,oe[6]||0,de)}}return new Date(U)})(R),this.init()},A.init=function(){var R=this.$d;this.$y=R.getFullYear(),this.$M=R.getMonth(),this.$D=R.getDate(),this.$W=R.getDay(),this.$H=R.getHours(),this.$m=R.getMinutes(),this.$s=R.getSeconds(),this.$ms=R.getMilliseconds()},A.$utils=function(){return E},A.isValid=function(){return this.$d.toString()!==m},A.isSame=function(R,O){var U=x(R);return this.startOf(O)<=U&&U<=this.endOf(O)},A.isAfter=function(R,O){return x(R){(function(n){n[n.AM=0]="AM",n[n.PM=1]="PM"})(j||(j={}));(function(n){n[n.SUNDAY=0]="SUNDAY",n[n.MONDAY=1]="MONDAY",n[n.TUESDAY=2]="TUESDAY",n[n.WEDNESDAY=3]="WEDNESDAY",n[n.THURSDAY=4]="THURSDAY",n[n.FRIDAY=5]="FRIDAY",n[n.SATURDAY=6]="SATURDAY"})(We||(We={}));(function(n){n[n.JANUARY=1]="JANUARY",n[n.FEBRUARY=2]="FEBRUARY",n[n.MARCH=3]="MARCH",n[n.APRIL=4]="APRIL",n[n.MAY=5]="MAY",n[n.JUNE=6]="JUNE",n[n.JULY=7]="JULY",n[n.AUGUST=8]="AUGUST",n[n.SEPTEMBER=9]="SEPTEMBER",n[n.OCTOBER=10]="OCTOBER",n[n.NOVEMBER=11]="NOVEMBER",n[n.DECEMBER=12]="DECEMBER"})(fs||(fs={}))});function Zre(n,e){n.assign("day",e.getDate()),n.assign("month",e.getMonth()+1),n.assign("year",e.getFullYear())}function Qre(n,e){n.assign("hour",e.getHours()),n.assign("minute",e.getMinutes()),n.assign("second",e.getSeconds()),n.assign("millisecond",e.getMilliseconds()),n.assign("meridiem",e.getHours()<12?j.AM:j.PM)}function K0(n,e){n.imply("day",e.getDate()),n.imply("month",e.getMonth()+1),n.imply("year",e.getFullYear())}function Jre(n,e){n.imply("hour",e.getHours()),n.imply("minute",e.getMinutes()),n.imply("second",e.getSeconds()),n.imply("millisecond",e.getMilliseconds()),n.imply("meridiem",e.getHours()<12?j.AM:j.PM)}var hB=y(()=>{Nt()});function Zu(n,e,t,r,a=0){let i=0,s=0;for(;s{gB=tt(Ht(),1);Nt();ize={ACDT:630,ACST:570,ADT:-180,AEDT:660,AEST:600,AFT:270,AKDT:-480,AKST:-540,ALMT:360,AMST:-180,AMT:-240,ANAST:720,ANAT:720,AQTT:300,ART:-180,AST:-240,AWDT:540,AWST:480,AZOST:0,AZOT:-60,AZST:300,AZT:240,BNT:480,BOT:-240,BRST:-120,BRT:-180,BST:60,BTT:360,CAST:480,CAT:120,CCT:390,CDT:-300,CEST:120,CET:{timezoneOffsetDuringDst:120,timezoneOffsetNonDst:60,dstStart:n=>Xre(n,fs.MARCH,We.SUNDAY,2),dstEnd:n=>Xre(n,fs.OCTOBER,We.SUNDAY,3)},CHADT:825,CHAST:765,CKT:-600,CLST:-180,CLT:-240,COT:-300,CST:-360,CT:{timezoneOffsetDuringDst:-300,timezoneOffsetNonDst:-360,dstStart:n=>Zu(n,fs.MARCH,We.SUNDAY,2,2),dstEnd:n=>Zu(n,fs.NOVEMBER,We.SUNDAY,1,2)},CVT:-60,CXT:420,ChST:600,DAVT:420,EASST:-300,EAST:-360,EAT:180,ECT:-300,EDT:-240,EEST:180,EET:120,EGST:0,EGT:-60,EST:-300,ET:{timezoneOffsetDuringDst:-240,timezoneOffsetNonDst:-300,dstStart:n=>Zu(n,fs.MARCH,We.SUNDAY,2,2),dstEnd:n=>Zu(n,fs.NOVEMBER,We.SUNDAY,1,2)},FJST:780,FJT:720,FKST:-180,FKT:-240,FNT:-120,GALT:-360,GAMT:-540,GET:240,GFT:-180,GILT:720,GMT:0,GST:240,GYT:-240,HAA:-180,HAC:-300,HADT:-540,HAE:-240,HAP:-420,HAR:-360,HAST:-600,HAT:-90,HAY:-480,HKT:480,HLV:-210,HNA:-240,HNC:-360,HNE:-300,HNP:-480,HNR:-420,HNT:-150,HNY:-540,HOVT:420,ICT:420,IDT:180,IOT:360,IRDT:270,IRKST:540,IRKT:540,IRST:210,IST:330,JST:540,KGT:360,KRAST:480,KRAT:480,KST:540,KUYT:240,LHDT:660,LHST:630,LINT:840,MAGST:720,MAGT:720,MART:-510,MAWT:300,MDT:-360,MESZ:120,MEZ:60,MHT:720,MMT:390,MSD:240,MSK:180,MST:-420,MT:{timezoneOffsetDuringDst:-360,timezoneOffsetNonDst:-420,dstStart:n=>Zu(n,fs.MARCH,We.SUNDAY,2,2),dstEnd:n=>Zu(n,fs.NOVEMBER,We.SUNDAY,1,2)},MUT:240,MVT:300,MYT:480,NCT:660,NDT:-90,NFT:690,NOVST:420,NOVT:360,NPT:345,NST:-150,NUT:-660,NZDT:780,NZST:720,OMSST:420,OMST:420,PDT:-420,PET:-300,PETST:720,PETT:720,PGT:600,PHOT:780,PHT:480,PKT:300,PMDT:-120,PMST:-180,PONT:660,PST:-480,PT:{timezoneOffsetDuringDst:-420,timezoneOffsetNonDst:-480,dstStart:n=>Zu(n,fs.MARCH,We.SUNDAY,2,2),dstEnd:n=>Zu(n,fs.NOVEMBER,We.SUNDAY,1,2)},PWT:540,PYST:-180,PYT:-240,RET:240,SAMT:240,SAST:120,SBT:660,SCT:240,SGT:480,SRT:-180,SST:-660,TAHT:-600,TFT:300,TJT:300,TKT:780,TLT:540,TMT:300,TVT:720,ULAT:480,UTC:0,UYST:-120,UYT:-180,UZT:300,VET:-210,VLAST:660,VLAT:660,VUT:660,WAST:120,WAT:60,WEST:60,WESZ:60,WET:0,WEZ:0,WFT:720,WGST:-120,WGT:-180,WIB:420,WIT:540,WITA:480,WST:780,WT:0,YAKST:600,YAKT:600,YAPT:600,YEKST:360,YEKT:360}});function ene(n,e){var r,a,i,s,o,l,c;let t=new Date(n);if(e.y&&(e.year=e.y,delete e.y),e.mo&&(e.month=e.mo,delete e.mo),e.M&&(e.month=e.M,delete e.M),e.w&&(e.week=e.w,delete e.w),e.d&&(e.day=e.d,delete e.d),e.h&&(e.hour=e.h,delete e.h),e.m&&(e.minute=e.m,delete e.m),e.s&&(e.second=e.s,delete e.s),e.ms&&(e.millisecond=e.ms,delete e.ms),"year"in e){let d=Math.floor(e.year);t.setFullYear(t.getFullYear()+d);let u=e.year-d;u>0&&(e.month=(r=e==null?void 0:e.month)!=null?r:0,e.month+=u*12)}if("quarter"in e){let d=Math.floor(e.quarter);t.setMonth(t.getMonth()+d*3)}if("month"in e){let d=Math.floor(e.month);t.setMonth(t.getMonth()+d);let u=e.month-d;u>0&&(e.week=(a=e==null?void 0:e.week)!=null?a:0,e.week+=u*4)}if("week"in e){let d=Math.floor(e.week);t.setDate(t.getDate()+d*7);let u=e.week-d;u>0&&(e.day=(i=e==null?void 0:e.day)!=null?i:0,e.day+=Math.round(u*7))}if("day"in e){let d=Math.floor(e.day);t.setDate(t.getDate()+d);let u=e.day-d;u>0&&(e.hour=(s=e==null?void 0:e.hour)!=null?s:0,e.hour+=Math.round(u*24))}if("hour"in e){let d=Math.floor(e.hour);t.setHours(t.getHours()+d);let u=e.hour-d;u>0&&(e.minute=(o=e==null?void 0:e.minute)!=null?o:0,e.minute+=Math.round(u*60))}if("minute"in e){let d=Math.floor(e.minute);t.setMinutes(t.getMinutes()+d);let u=e.minute-d;u>0&&(e.second=(l=e==null?void 0:e.second)!=null?l:0,e.second+=Math.round(u*60))}if("second"in e){let d=Math.floor(e.second);t.setSeconds(t.getSeconds()+d);let u=e.second-d;u>0&&(e.millisecond=(c=e==null?void 0:e.millisecond)!=null?c:0,e.millisecond+=Math.round(u*1e3))}if("millisecond"in e){let d=Math.floor(e.millisecond);t.setMilliseconds(t.getMilliseconds()+d)}return t}function hy(n){let e={};for(let t in n)e[t]=-n[t];return e}var Vb=y(()=>{});var tne,vB,Vt,K,Lt,ot=y(()=>{tne=tt(Kre(),1),vB=tt(Ht(),1);hB();yB();Vb();vB.default.extend(tne.default);Vt=class n{constructor(e,t){z(this,"instant");z(this,"timezoneOffset");this.instant=e!=null?e:new Date,this.timezoneOffset=t!=null?t:null}static fromDate(e){return new n(e)}static fromInput(e,t){var i;if(e instanceof Date)return n.fromDate(e);let r=(i=e==null?void 0:e.instant)!=null?i:new Date,a=Z0(e==null?void 0:e.timezone,r,t);return new n(r,a)}getDateWithAdjustedTimezone(){let e=new Date(this.instant);return this.timezoneOffset!==null&&e.setMinutes(e.getMinutes()-this.getSystemTimezoneAdjustmentMinute(this.instant)),e}getSystemTimezoneAdjustmentMinute(e,t){var i;(!e||e.getTime()<0)&&(e=new Date);let r=-e.getTimezoneOffset(),a=(i=t!=null?t:this.timezoneOffset)!=null?i:r;return r-a}getTimezoneOffset(){var e;return(e=this.timezoneOffset)!=null?e:-this.instant.getTimezoneOffset()}},K=class n{constructor(e,t){z(this,"knownValues");z(this,"impliedValues");z(this,"reference");z(this,"_tags",new Set);if(this.reference=e,this.knownValues={},this.impliedValues={},t)for(let a in t)this.knownValues[a]=t[a];let r=e.getDateWithAdjustedTimezone();this.imply("day",r.getDate()),this.imply("month",r.getMonth()+1),this.imply("year",r.getFullYear()),this.imply("hour",12),this.imply("minute",0),this.imply("second",0),this.imply("millisecond",0)}get(e){return e in this.knownValues?this.knownValues[e]:e in this.impliedValues?this.impliedValues[e]:null}isCertain(e){return e in this.knownValues}getCertainComponents(){return Object.keys(this.knownValues)}imply(e,t){return e in this.knownValues?this:(this.impliedValues[e]=t,this)}assign(e,t){return this.knownValues[e]=t,delete this.impliedValues[e],this}delete(e){delete this.knownValues[e],delete this.impliedValues[e]}clone(){let e=new n(this.reference);e.knownValues={},e.impliedValues={};for(let t in this.knownValues)e.knownValues[t]=this.knownValues[t];for(let t in this.impliedValues)e.impliedValues[t]=this.impliedValues[t];return e}isOnlyDate(){return!this.isCertain("hour")&&!this.isCertain("minute")&&!this.isCertain("second")}isOnlyTime(){return!this.isCertain("weekday")&&!this.isCertain("day")&&!this.isCertain("month")&&!this.isCertain("year")}isOnlyWeekdayComponent(){return this.isCertain("weekday")&&!this.isCertain("day")&&!this.isCertain("month")}isDateWithUnknownYear(){return this.isCertain("month")&&!this.isCertain("year")}isValidDate(){let e=this.dateWithoutTimezoneAdjustment();return!(e.getFullYear()!==this.get("year")||e.getMonth()!==this.get("month")-1||e.getDate()!==this.get("day")||this.get("hour")!=null&&e.getHours()!=this.get("hour")||this.get("minute")!=null&&e.getMinutes()!=this.get("minute"))}toString(){return`[ParsingComponents { + tags: ${JSON.stringify(Array.from(this._tags).sort())}, + knownValues: ${JSON.stringify(this.knownValues)}, + impliedValues: ${JSON.stringify(this.impliedValues)}}, + reference: ${JSON.stringify(this.reference)}]`}dayjs(){return(0,vB.default)(this.dateWithoutTimezoneAdjustment())}date(){let e=this.dateWithoutTimezoneAdjustment(),t=this.reference.getSystemTimezoneAdjustmentMinute(e,this.get("timezoneOffset"));return new Date(e.getTime()+t*6e4)}addTag(e){return this._tags.add(e),this}addTags(e){for(let t of e)this._tags.add(t);return this}tags(){return new Set(this._tags)}dateWithoutTimezoneAdjustment(){let e=new Date(this.get("year"),this.get("month")-1,this.get("day"),this.get("hour"),this.get("minute"),this.get("second"),this.get("millisecond"));return e.setFullYear(this.get("year")),e}static createRelativeFromReference(e,t){let r=ene(e.getDateWithAdjustedTimezone(),t),a=new n(e);return a.addTag("result/relativeDate"),t.hour||t.minute||t.second?(a.addTag("result/relativeDateAndTime"),Qre(a,r),Zre(a,r),a.assign("timezoneOffset",e.getTimezoneOffset())):(Jre(a,r),a.imply("timezoneOffset",e.getTimezoneOffset()),t.day?(a.assign("day",r.getDate()),a.assign("month",r.getMonth()+1),a.assign("year",r.getFullYear()),a.assign("weekday",r.getDay())):t.week?(a.assign("day",r.getDate()),a.assign("month",r.getMonth()+1),a.assign("year",r.getFullYear()),a.imply("weekday",r.getDay())):(a.imply("day",r.getDate()),t.month?(a.assign("month",r.getMonth()+1),a.assign("year",r.getFullYear())):(a.imply("month",r.getMonth()+1),t.year?a.assign("year",r.getFullYear()):a.imply("year",r.getFullYear())))),a}},Lt=class n{constructor(e,t,r,a,i){z(this,"refDate");z(this,"index");z(this,"text");z(this,"reference");z(this,"start");z(this,"end");this.reference=e,this.refDate=e.instant,this.index=t,this.text=r,this.start=a||new K(e),this.end=i}clone(){let e=new n(this.reference,this.index,this.text);return e.start=this.start?this.start.clone():null,e.end=this.end?this.end.clone():null,e}date(){return this.start.date()}addTag(e){return this.start.addTag(e),this.end&&this.end.addTag(e),this}addTags(e){return this.start.addTags(e),this.end&&this.end.addTags(e),this}tags(){let e=new Set(this.start.tags());if(this.end)for(let t of this.end.tags())e.add(t);return e}toString(){let e=Array.from(this.tags()).sort();return`[ParsingResult {index: ${this.index}, text: '${this.text}', tags: ${JSON.stringify(e)} ...}]`}}});function li(n,e,t="\\s{0,5},?\\s{0,5}"){let r=e.replace(/\((?!\?)/g,"(?:");return`${n}${r}(?:${t}${r}){0,10}`}function sze(n){let e;return n instanceof Array?e=[...n]:n instanceof Map?e=Array.from(n.keys()):e=Object.keys(n),e}function ie(n){return`(?:${sze(n).sort((t,r)=>r.length-t.length).join("|").replace(/\./g,"\\.")})`}var xt=y(()=>{});function Mi(n){return n<100&&(n>50?n=n+1900:n=n+2e3),n}function er(n,e,t){let r=(0,rne.default)(n),a=r;a=a.month(t-1),a=a.date(e),a=a.year(r.year());let i=a.add(1,"y"),s=a.add(-1,"y");return Math.abs(i.diff(r)){rne=tt(Ht(),1)});function oze(n){let e=n.toLowerCase();return kB[e]!==void 0?kB[e]:e==="a"||e==="an"||e=="the"?1:e.match(/few/)?3:e.match(/half/)?.5:e.match(/couple/)?2:e.match(/several/)?7:parseFloat(e)}function yy(n){let e=n.toLowerCase();return TB[e]!==void 0?TB[e]:(e=e.replace(/(?:st|nd|rd|th)$/i,""),parseInt(e))}function Ju(n){if(/BE/i.test(n))return n=n.replace(/BE/i,""),parseInt(n)-543;if(/BCE?/i.test(n))return n=n.replace(/BCE?/i,""),-parseInt(n);if(/(AD|CE)/i.test(n))return n=n.replace(/(AD|CE)/i,""),parseInt(n);let e=parseInt(n);return Mi(e)}function Js(n){let e={},t=n,r=nne.exec(t);for(;r;)cze(e,r),t=t.substring(r[0].length).trim(),r=nne.exec(t);return Object.keys(e).length==0?null:e}function cze(n,e){if(e[0].match(/^[a-zA-Z]+$/))return;let t=oze(e[1]),r=Wb[e[2].toLowerCase()];n[r]=t}var Q0,bB,Qs,kB,TB,ane,Wb,ine,gy,Qu,sne,nne,lze,one,Nd,Xu,Un=y(()=>{xt();mn();Q0={sunday:0,sun:0,"sun.":0,monday:1,mon:1,"mon.":1,tuesday:2,tue:2,"tue.":2,wednesday:3,wed:3,"wed.":3,thursday:4,thurs:4,"thurs.":4,thur:4,"thur.":4,thu:4,"thu.":4,friday:5,fri:5,"fri.":5,saturday:6,sat:6,"sat.":6},bB={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},Qs={...bB,jan:1,"jan.":1,feb:2,"feb.":2,mar:3,"mar.":3,apr:4,"apr.":4,jun:6,"jun.":6,jul:7,"jul.":7,aug:8,"aug.":8,sep:9,"sep.":9,sept:9,"sept.":9,oct:10,"oct.":10,nov:11,"nov.":11,dec:12,"dec.":12},kB={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},TB={first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,twentieth:20,"twenty first":21,"twenty-first":21,"twenty second":22,"twenty-second":22,"twenty third":23,"twenty-third":23,"twenty fourth":24,"twenty-fourth":24,"twenty fifth":25,"twenty-fifth":25,"twenty sixth":26,"twenty-sixth":26,"twenty seventh":27,"twenty-seventh":27,"twenty eighth":28,"twenty-eighth":28,"twenty ninth":29,"twenty-ninth":29,thirtieth:30,"thirty first":31,"thirty-first":31},ane={second:"second",seconds:"second",minute:"minute",minutes:"minute",hour:"hour",hours:"hour",day:"d",days:"d",week:"week",weeks:"week",month:"month",months:"month",quarter:"quarter",quarters:"quarter",year:"year",years:"year"},Wb={s:"second",sec:"second",second:"second",seconds:"second",m:"minute",min:"minute",mins:"minute",minute:"minute",minutes:"minute",h:"hour",hr:"hour",hrs:"hour",hour:"hour",hours:"hour",d:"d",day:"d",days:"d",w:"w",week:"week",weeks:"week",mo:"month",mon:"month",mos:"month",month:"month",months:"month",qtr:"quarter",quarter:"quarter",quarters:"quarter",y:"year",yr:"year",year:"year",years:"year",...ane},ine=`(?:${ie(kB)}|[0-9]+|[0-9]+\\.[0-9]+|half(?:\\s{0,2}an?)?|an?\\b(?:\\s{0,2}few)?|few|several|the|a?\\s{0,2}couple\\s{0,2}(?:of)?)`;gy=`(?:${ie(TB)}|[0-9]{1,2}(?:st|nd|rd|th)?)`;Qu="(?:[1-9][0-9]{0,3}\\s{0,2}(?:BE|AD|BC|BCE|CE)|[1-2][0-9]{3}|[5-9][0-9]|2[0-5])";sne=`(${ine})\\s{0,3}(${ie(Wb)})`,nne=new RegExp(sne,"i"),lze=`(${ine})\\s{0,3}(${ie(ane)})`,one="\\s{0,5},?(?:\\s*and)?\\s{0,5}",Nd=li("(?:(?:about|around)\\s{0,3})?",sne,one),Xu=li("(?:(?:about|around)\\s{0,3})?",lze,one)});var H,we=y(()=>{H=class{constructor(){z(this,"cachedInnerPattern",null);z(this,"cachedPattern",null)}innerPatternHasChange(e,t){return this.innerPattern(e)!==t}patternLeftBoundary(){return"(\\W|^)"}pattern(e){return this.cachedInnerPattern&&!this.innerPatternHasChange(e,this.cachedInnerPattern)?this.cachedPattern:(this.cachedInnerPattern=this.innerPattern(e),this.cachedPattern=new RegExp(`${this.patternLeftBoundary()}${this.cachedInnerPattern.source}`,this.cachedInnerPattern.flags),this.cachedPattern)}extract(e,t){var a;let r=(a=t[1])!=null?a:"";t.index=t.index+r.length,t[0]=t[0].substring(r.length);for(let i=2;i{Un();ot();we();dze=new RegExp(`(?:(?:within|in|for)\\s*)?(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${Nd})(?=\\W|$)`,"i"),uze=new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${Nd})(?=\\W|$)`,"i"),pze=new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${Xu})(?=\\W|$)`,"i"),qb=class extends H{constructor(t){super();z(this,"strictMode");this.strictMode=t}innerPattern(t){return this.strictMode?pze:t.option.forwardDate?dze:uze}innerExtract(t,r){if(r[0].match(/^for\s*the\s*\w+/))return null;let a=Js(r[1]);return a?(t.debug(()=>{console.log(a),console.log(K.createRelativeFromReference(t.reference,a))}),K.createRelativeFromReference(t.reference,a)):null}}});var mze,cne,dne,fze,une,Gb,pne=y(()=>{mn();Un();Un();Un();xt();we();mze=new RegExp(`(?:on\\s{0,3})?(${gy})(?:\\s{0,3}(?:to|\\-|\\–|until|through|till)?\\s{0,3}(${gy}))?(?:-|/|\\s{0,3}(?:of)?\\s{0,3})(${ie(Qs)})(?:(?:-|/|,?\\s{0,3})(${Qu}(?!\\w)))?(?=\\W|$)`,"i"),cne=1,dne=2,fze=3,une=4,Gb=class extends H{innerPattern(){return mze}innerExtract(e,t){let r=e.createParsingResult(t.index,t[0]),a=Qs[t[fze].toLowerCase()],i=yy(t[cne]);if(i>31)return t.index=t.index+t[cne].length,null;if(r.start.assign("month",a),r.start.assign("day",i),t[une]){let s=Ju(t[une]);r.start.assign("year",s)}else{let s=er(e.refDate,i,a);r.start.imply("year",s)}if(t[dne]){let s=yy(t[dne]);r.end=r.start.clone(),r.end.assign("day",s)}return r}}});var hze,gze,mne,wB,SB,Yb,fne=y(()=>{mn();Un();Un();Un();xt();we();hze=new RegExp(`(${ie(Qs)})(?:-|/|\\s*,?\\s*)(${gy})(?!\\s*(?:am|pm))\\s*(?:(?:to|\\-)\\s*(${gy})\\s*)?(?:(?:-|/|\\s*,\\s*|\\s+)(${Qu}))?(?=\\W|$)(?!\\:\\d)`,"i"),gze=1,mne=2,wB=3,SB=4,Yb=class extends H{constructor(t){super();z(this,"shouldSkipYearLikeDate");this.shouldSkipYearLikeDate=t}innerPattern(){return hze}innerExtract(t,r){let a=Qs[r[gze].toLowerCase()],i=yy(r[mne]);if(i>31||this.shouldSkipYearLikeDate&&!r[wB]&&!r[SB]&&r[mne].match(/^2[0-5]$/))return null;let s=t.createParsingComponents({day:i,month:a}).addTag("parser/ENMonthNameMiddleEndianParser");if(r[SB]){let c=Ju(r[SB]);s.assign("year",c)}else{let c=er(t.refDate,i,a);s.imply("year",c)}if(!r[wB])return s;let o=yy(r[wB]),l=t.createParsingResult(r.index,r[0]);return l.start=s,l.end=s.clone(),l.end.assign("day",o),l}}});var yze,vze,kze,hne,Kb,gne=y(()=>{Un();mn();xt();Un();we();yze=new RegExp(`((?:in)\\s*)?(${ie(Qs)})\\s*(?:(?:,|-|of)?\\s*(${Qu})?)?(?=[^\\s\\w]|\\s+[^0-9]|\\s+$|$)`,"i"),vze=1,kze=2,hne=3,Kb=class extends H{innerPattern(){return yze}innerExtract(e,t){let r=t[kze].toLowerCase();if(t[0].length<=3&&!bB[r])return null;let a=e.createParsingResult(t.index+(t[vze]||"").length,t.index+t[0].length);a.start.imply("day",1),a.start.addTag("parser/ENMonthNameParser");let i=Qs[r];if(a.start.assign("month",i),t[hne]){let s=Ju(t[hne]);a.start.assign("year",s)}else{let s=er(e.refDate,1,i);a.start.imply("year",s)}return a}}});var Tze,bze,wze,yne,Sze,Zb,vne=y(()=>{Un();xt();we();Tze=new RegExp(`([0-9]{4})[-\\.\\/\\s](?:(${ie(Qs)})|([0-9]{1,2}))[-\\.\\/\\s]([0-9]{1,2})(?=\\W|$)`,"i"),bze=1,wze=2,yne=3,Sze=4,Zb=class extends H{constructor(t){super();z(this,"strictMonthDateOrder");this.strictMonthDateOrder=t}innerPattern(){return Tze}innerExtract(t,r){let a=parseInt(r[bze]),i=parseInt(r[Sze]),s=r[yne]?parseInt(r[yne]):Qs[r[wze].toLowerCase()];if(s<1||s>12){if(this.strictMonthDateOrder)return null;i>=1&&i<=12&&([s,i]=[i,s])}return i<1||i>31?null:{day:i,month:s,year:a}}}});var Cze,xze,Eze,Qb,kne=y(()=>{we();Cze=new RegExp("([0-9]|0[1-9]|1[012])/([0-9]{4})","i"),xze=1,Eze=2,Qb=class extends H{innerPattern(){return Cze}innerExtract(e,t){let r=parseInt(t[Eze]),a=parseInt(t[xze]);return e.createParsingComponents().imply("day",1).assign("month",a).assign("year",r)}}});function Dze(n,e,t,r){return new RegExp(`${n}${e}(\\d{1,4})(?:(?:\\.|:|:)(\\d{1,2})(?:(?::|:)(\\d{2})(?:\\.(\\d{1,6}))?)?)?(?:\\s*(a\\.m\\.|p\\.m\\.|am?|pm?))?${t}`,r)}function Pze(n,e){return new RegExp(`^(${n})(\\d{1,4})(?:(?:\\.|\\:|\\:)(\\d{1,2})(?:(?:\\.|\\:|\\:)(\\d{1,2})(?:\\.(\\d{1,6}))?)?)?(?:\\s*(a\\.m\\.|p\\.m\\.|am?|pm?))?${e}`,"i")}var Tne,vy,J0,X0,Jb,na,Rd=y(()=>{Nt();Tne=2,vy=3,J0=4,X0=5,Jb=6,na=class{constructor(e=!1){z(this,"strictMode");z(this,"cachedPrimaryPrefix",null);z(this,"cachedPrimarySuffix",null);z(this,"cachedPrimaryTimePattern",null);z(this,"cachedFollowingPhase",null);z(this,"cachedFollowingSuffix",null);z(this,"cachedFollowingTimePatten",null);this.strictMode=e}patternFlags(){return"i"}primaryPatternLeftBoundary(){return"(^|\\s|T|\\b)"}primarySuffix(){return"(?!/)(?=\\W|$)"}followingSuffix(){return"(?!/)(?=\\W|$)"}pattern(e){return this.getPrimaryTimePatternThroughCache()}extract(e,t){let r=this.extractPrimaryTimeComponents(e,t);if(!r)return t[0].match(/^\d{4}/)?(t.index+=4,null):(t.index+=t[0].length,null);let a=t.index+t[1].length,i=t[0].substring(t[1].length),s=e.createParsingResult(a,i,r);t.index+=t[0].length;let o=e.text.substring(t.index),c=this.getFollowingTimePatternThroughCache().exec(o);return i.match(/^\d{3,4}/)&&c&&(c[0].match(/^\s*([+-])\s*\d{2,4}$/)||c[0].match(/^\s*([+-])\s*\d{2}\W\d{2}/))?null:!c||c[0].match(/^\s*([+-])\s*\d{3,4}$/)?this.checkAndReturnWithoutFollowingPattern(s):(s.end=this.extractFollowingTimeComponents(e,c,s),s.end&&(s.text+=c[0]),this.checkAndReturnWithFollowingPattern(s))}extractPrimaryTimeComponents(e,t,r=!1){let a=e.createParsingComponents(),i=0,s=null,o=parseInt(t[Tne]);if(o>100){if(this.strictMode||t[vy]!=null)return null;i=o%100,o=Math.floor(o/100)}if(o>24)return null;if(t[vy]!=null){if(t[vy].length==1&&!t[Jb])return null;i=parseInt(t[vy])}if(i>=60)return null;if(o>12&&(s=j.PM),t[Jb]!=null){if(o>12)return null;let l=t[Jb][0].toLowerCase();l=="a"&&(s=j.AM,o==12&&(o=0)),l=="p"&&(s=j.PM,o!=12&&(o+=12))}if(a.assign("hour",o),a.assign("minute",i),s!==null?a.assign("meridiem",s):o<12?a.imply("meridiem",j.AM):a.imply("meridiem",j.PM),t[X0]!=null){let l=parseInt(t[X0].substring(0,3));if(l>=1e3)return null;a.assign("millisecond",l)}if(t[J0]!=null){let l=parseInt(t[J0]);if(l>=60)return null;a.assign("second",l)}return a}extractFollowingTimeComponents(e,t,r){let a=e.createParsingComponents();if(t[X0]!=null){let l=parseInt(t[X0].substring(0,3));if(l>=1e3)return null;a.assign("millisecond",l)}if(t[J0]!=null){let l=parseInt(t[J0]);if(l>=60)return null;a.assign("second",l)}let i=parseInt(t[Tne]),s=0,o=-1;if(t[vy]!=null?s=parseInt(t[vy]):i>100&&(s=i%100,i=Math.floor(i/100)),s>=60||i>24)return null;if(i>=12&&(o=j.PM),t[Jb]!=null){if(i>12)return null;let l=t[Jb][0].toLowerCase();l=="a"&&(o=j.AM,i==12&&(i=0,a.isCertain("day")||a.imply("day",a.get("day")+1))),l=="p"&&(o=j.PM,i!=12&&(i+=12)),r.start.isCertain("meridiem")||(o==j.AM?(r.start.imply("meridiem",j.AM),r.start.get("hour")==12&&r.start.assign("hour",0)):(r.start.imply("meridiem",j.PM),r.start.get("hour")!=12&&r.start.assign("hour",r.start.get("hour")+12)))}return a.assign("hour",i),a.assign("minute",s),o>=0?a.assign("meridiem",o):r.start.isCertain("meridiem")&&r.start.get("hour")>12?r.start.get("hour")-12>i?a.imply("meridiem",j.AM):i<=12&&(a.assign("hour",i+12),a.assign("meridiem",j.PM)):i>12?a.imply("meridiem",j.PM):i<=12&&a.imply("meridiem",j.AM),a.date().getTime()24)return null}return e}checkAndReturnWithFollowingPattern(e){if(e.text.match(/^\d+-\d+$/))return null;let t=e.text.match(/[^\d:.](\d[\d.]+)\s*-\s*(\d[\d.]+)$/);if(t){if(this.strictMode)return null;let r=t[1],a=t[2];if(a.includes(".")&&!a.match(/\d(\.\d{2})+$/))return null;let i=parseInt(a),s=parseInt(r);if(i>24||s>24)return null}return e}getPrimaryTimePatternThroughCache(){let e=this.primaryPrefix(),t=this.primarySuffix();return this.cachedPrimaryPrefix===e&&this.cachedPrimarySuffix===t?this.cachedPrimaryTimePattern:(this.cachedPrimaryTimePattern=Dze(this.primaryPatternLeftBoundary(),e,t,this.patternFlags()),this.cachedPrimaryPrefix=e,this.cachedPrimarySuffix=t,this.cachedPrimaryTimePattern)}getFollowingTimePatternThroughCache(){let e=this.followingPhase(),t=this.followingSuffix();return this.cachedFollowingPhase===e&&this.cachedFollowingSuffix===t?this.cachedFollowingTimePatten:(this.cachedFollowingTimePatten=Pze(e,t),this.cachedFollowingPhase=e,this.cachedFollowingSuffix=t,this.cachedFollowingTimePatten)}}});var Xb,bne=y(()=>{Nt();Rd();Xb=class extends na{constructor(e){super(e)}followingPhase(){return"\\s*(?:\\-|\\–|\\~|\\〜|to|until|through|till|\\?)\\s*"}primaryPrefix(){return"(?:(?:at|from)\\s*)??"}primarySuffix(){return"(?:\\s*(?:o\\W*clock|at\\s*night|in\\s*the\\s*(?:morning|afternoon)))?(?!/)(?=\\W|$)"}extractPrimaryTimeComponents(e,t){let r=super.extractPrimaryTimeComponents(e,t);if(!r)return r;if(t[0].endsWith("night")){let a=r.get("hour");a>=6&&a<12?(r.assign("hour",r.get("hour")+12),r.assign("meridiem",j.PM)):a<6&&r.assign("meridiem",j.AM)}if(t[0].endsWith("afternoon")){r.assign("meridiem",j.PM);let a=r.get("hour");a>=0&&a<=6&&r.assign("hour",r.get("hour")+12)}return t[0].endsWith("morning")&&(r.assign("meridiem",j.AM),r.get("hour")<12&&r.assign("hour",r.get("hour"))),r.addTag("parser/ENTimeExpressionParser")}extractFollowingTimeComponents(e,t,r){let a=super.extractFollowingTimeComponents(e,t,r);return a&&a.addTag("parser/ENTimeExpressionParser"),a}}});var Aze,Mze,ew,wne=y(()=>{Un();ot();we();Vb();Aze=new RegExp(`(${Nd})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`,"i"),Mze=new RegExp(`(${Xu})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`,"i"),ew=class extends H{constructor(t){super();z(this,"strictMode");this.strictMode=t}innerPattern(){return this.strictMode?Mze:Aze}innerExtract(t,r){let a=Js(r[1]);return a?K.createRelativeFromReference(t.reference,hy(a)):null}}});var Ize,Nze,Rze,tw,Sne=y(()=>{Un();ot();we();Ize=new RegExp(`(${Nd})\\s{0,5}(?:later|after|from now|henceforth|forward|out)(?=(?:\\W|$))`,"i"),Nze=new RegExp(`(${Xu})\\s{0,5}(later|after|from now)(?=\\W|$)`,"i"),Rze=1,tw=class extends H{constructor(t){super();z(this,"strictMode");this.strictMode=t}innerPattern(){return this.strictMode?Nze:Ize}innerExtract(t,r){let a=Js(r[Rze]);return a?K.createRelativeFromReference(t.reference,a):null}}});var ky,Ii,_d=y(()=>{ky=class{refine(e,t){return t.filter(r=>this.isValid(e,r))}},Ii=class{refine(e,t){if(t.length<2)return t;let r=[],a=t[0],i=null;for(let s=1;s{console.log(`${this.constructor.name} merged ${l} and ${c} into ${d}`)}),a=d}}return a!=null&&r.push(a),r}}});var jr,Xs=y(()=>{_d();jr=class extends Ii{shouldMergeResults(e,t,r){return!t.end&&!r.end&&e.match(this.patternBetween())!=null}mergeResults(e,t,r){if(!t.start.isOnlyWeekdayComponent()&&!r.start.isOnlyWeekdayComponent()&&(r.start.getCertainComponents().forEach(i=>{t.start.isCertain(i)||t.start.imply(i,r.start.get(i))}),t.start.getCertainComponents().forEach(i=>{r.start.isCertain(i)||r.start.imply(i,t.start.get(i))})),t.start.date().getTime()>r.start.date().getTime()){let i=t.start.dayjs(),s=r.start.dayjs();r.start.isOnlyWeekdayComponent()&&s.add(7,"days").isAfter(i)?(s=s.add(7,"days"),r.start.imply("day",s.date()),r.start.imply("month",s.month()+1),r.start.imply("year",s.year())):t.start.isOnlyWeekdayComponent()&&i.add(-7,"days").isBefore(s)?(i=i.add(-7,"days"),t.start.imply("day",i.date()),t.start.imply("month",i.month()+1),t.start.imply("year",i.year())):r.start.isDateWithUnknownYear()&&s.add(1,"years").isAfter(i)?(s=s.add(1,"years"),r.start.imply("year",s.year())):t.start.isDateWithUnknownYear()&&i.add(-1,"years").isBefore(s)?(i=i.add(-1,"years"),t.start.imply("year",i.year())):[r,t]=[t,r]}let a=t.clone();return a.start=t.start,a.end=r.start,a.index=Math.min(t.index,r.index),t.index{Xs();rw=class extends jr{patternBetween(){return/^\s*(to|-|–|until|through|till)\s*$/i}}});function Xo(n,e){e=e.add(1,"day"),Mr(n,e),$l(n,e)}function xne(n,e){e=e.add(1,"day"),CB(n,e),$l(n,e)}function Mr(n,e){n.assign("day",e.date()),n.assign("month",e.month()+1),n.assign("year",e.year())}function Ene(n,e){n.assign("hour",e.hour()),n.assign("minute",e.minute()),n.assign("second",e.second()),n.assign("millisecond",e.millisecond()),n.get("hour")<12?n.assign("meridiem",j.AM):n.assign("meridiem",j.PM)}function CB(n,e){n.imply("day",e.date()),n.imply("month",e.month()+1),n.imply("year",e.year())}function $l(n,e){n.imply("hour",e.hour()),n.imply("minute",e.minute()),n.imply("second",e.second()),n.imply("millisecond",e.millisecond())}var hs=y(()=>{Nt()});function xB(n,e){let t=n.clone(),r=n.start,a=e.start;if(t.start=Dne(r,a),n.end!=null||e.end!=null){let i=n.end==null?n.start:n.end,s=e.end==null?e.start:e.end,o=Dne(i,s);if(n.end==null&&o.date().getTime(){Nt();hs()});var $r,eo=y(()=>{_d();Pne();$r=class extends Ii{shouldMergeResults(e,t,r){return(t.start.isOnlyDate()&&r.start.isOnlyTime()||r.start.isOnlyDate()&&t.start.isOnlyTime())&&e.match(this.patternBetween())!=null}mergeResults(e,t,r){let a=t.start.isOnlyDate()?xB(t,r):xB(r,t);return a.index=t.index,a.text=t.text+e+r.text,a}}});var Ty,Ane=y(()=>{eo();Ty=class extends $r{patternBetween(){return new RegExp("^\\s*(T|at|after|before|on|of|,|-|\\.|∙|:)?\\s*$")}}});var _ze,nw,Mne=y(()=>{yB();_ze=new RegExp("^\\s*,?\\s*\\(?([A-Z]{2,4})\\)?(?=\\W|$)","i"),nw=class{constructor(e){z(this,"timezoneOverrides");this.timezoneOverrides=e}refine(e,t){var a;let r=(a=e.option.timezones)!=null?a:{};return t.forEach(i=>{var m,f;let s=e.text.substring(i.index+i.text.length),o=_ze.exec(s);if(!o)return;let l=o[1].toUpperCase(),c=(f=(m=i.start.date())!=null?m:i.refDate)!=null?f:new Date,d={...this.timezoneOverrides,...r},u=Z0(l,c,d);if(u==null)return;e.debug(()=>{console.log(`Extracting timezone: '${l}' into: ${u} for: ${i.start}`)});let p=i.start.get("timezoneOffset");p!==null&&u!=p&&(i.start.isCertain("timezoneOffset")||l!=o[1])||i.start.isOnlyDate()&&l!=o[1]||(i.text+=o[0],i.start.isCertain("timezoneOffset")||i.start.assign("timezoneOffset",u),i.end!=null&&!i.end.isCertain("timezoneOffset")&&i.end.assign("timezoneOffset",u))}),t}}});var Fze,Lze,Oze,zze,el,aw=y(()=>{Fze=new RegExp("^\\s*(?:\\(?(?:GMT|UTC)\\s?)?([+-])(\\d{1,2})(?::?(\\d{2}))?\\)?","i"),Lze=1,Oze=2,zze=3,el=class{refine(e,t){return t.forEach(function(r){if(r.start.isCertain("timezoneOffset"))return;let a=e.text.substring(r.index+r.text.length),i=Fze.exec(a);if(!i)return;e.debug(()=>{console.log(`Extracting timezone: '${i[0]}' into : ${r}`)});let s=parseInt(i[Oze]),o=parseInt(i[zze]||"0"),l=s*60+o;l>840||(i[Lze]==="-"&&(l=-l),r.end!=null&&r.end.assign("timezoneOffset",l),r.start.assign("timezoneOffset",l),r.text+=i[0])}),t}}});var ep,EB=y(()=>{ep=class{refine(e,t){if(t.length<2)return t;let r=[],a=t[0];for(let i=1;i=a.index+a.text.length){r.push(a),a=s;continue}let o=null,l=null;s.text.length>a.text.length?(o=s,l=a):(o=a,l=s),e.debug(()=>{console.log(`${this.constructor.name} remove ${l} by ${o}`)}),a=o}return a!=null&&r.push(a),r}}});var Ine,iw,Nne=y(()=>{Ine=tt(Ht(),1);hB();iw=class{refine(e,t){return e.option.forwardDate&&t.forEach(r=>{let a=(0,Ine.default)(e.reference.getDateWithAdjustedTimezone());if(r.start.isOnlyTime()&&e.reference.instant>r.start.date()){let i=e.reference.getDateWithAdjustedTimezone(),s=new Date(i);s.setDate(s.getDate()+1),K0(r.start,s),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${r} time from the ref date (${i}) to the following day (${s})`)}),r.end&&r.end.isOnlyTime()&&(K0(r.end,s),r.start.date()>r.end.date()&&(s.setDate(s.getDate()+1),K0(r.end,s)))}if(r.start.isOnlyWeekdayComponent()&&a.isAfter(r.start.dayjs())&&(a.day()>=r.start.get("weekday")?a=a.day(r.start.get("weekday")+7):a=a.day(r.start.get("weekday")),r.start.imply("day",a.date()),r.start.imply("month",a.month()+1),r.start.imply("year",a.year()),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${r} weekday (${r.start})`)}),r.end&&r.end.isOnlyWeekdayComponent()&&(a.day()>r.end.get("weekday")?a=a.day(r.end.get("weekday")+7):a=a.day(r.end.get("weekday")),r.end.imply("day",a.date()),r.end.imply("month",a.month()+1),r.end.imply("year",a.year()),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${r} weekday (${r.end})`)}))),r.start.isDateWithUnknownYear()&&a.isAfter(r.start.dayjs()))for(let i=0;i<3&&a.isAfter(r.start.dayjs());i++)r.start.imply("year",r.start.get("year")+1),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${r} year (${r.start})`)}),r.end&&!r.end.isCertain("year")&&(r.end.imply("year",r.end.get("year")+1),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${r} month (${r.start})`)}))}),t}}});var sw,Rne=y(()=>{_d();sw=class extends ky{constructor(t){super();z(this,"strictMode");this.strictMode=t}isValid(t,r){return r.text.replace(" ","").match(/^\d*(\.\d*)?$/)?(t.debug(()=>{console.log(`Removing unlikely result '${r.text}'`)}),!1):r.start.isValidDate()?r.end&&!r.end.isValidDate()?(t.debug(()=>{console.log(`Removing invalid result: ${r} (${r.end})`)}),!1):this.strictMode?this.isStrictModeValid(t,r):!0:(t.debug(()=>{console.log(`Removing invalid result: ${r} (${r.start})`)}),!1)}isStrictModeValid(t,r){return r.start.isOnlyWeekdayComponent()?(t.debug(()=>{console.log(`(Strict) Removing weekday only component: ${r} (${r.end})`)}),!1):!0}}});var Bze,jze,$ze,Uze,_ne,Hze,Fne,Lne,Vze,One,zne,Fd,eA=y(()=>{we();Bze=new RegExp("([0-9]{4})\\-([0-9]{1,2})\\-([0-9]{1,2})(?:T([0-9]{1,2}):([0-9]{1,2})(?::([0-9]{1,2})(?:\\.(\\d{1,4}))?)?(Z|([+-]\\d{2}):?(\\d{2})?)?)?(?=\\W|$)","i"),jze=1,$ze=2,Uze=3,_ne=4,Hze=5,Fne=6,Lne=7,Vze=8,One=9,zne=10,Fd=class extends H{innerPattern(){return Bze}innerExtract(e,t){let r=e.createParsingComponents({year:parseInt(t[jze]),month:parseInt(t[$ze]),day:parseInt(t[Uze])});if(t[_ne]!=null&&(r.assign("hour",parseInt(t[_ne])),r.assign("minute",parseInt(t[Hze])),t[Fne]!=null&&r.assign("second",parseInt(t[Fne])),t[Lne]!=null&&r.assign("millisecond",parseInt(t[Lne])),t[Vze]!=null)){let a=0;if(t[One]){let i=parseInt(t[One]),s=0;t[zne]!=null&&(s=parseInt(t[zne])),a=i*60,a<0?a-=s:a+=s}r.assign("timezoneOffset",a)}return r.addTag("parser/ISOFormatParser")}}});var vf,DB=y(()=>{_d();vf=class extends Ii{mergeResults(e,t,r){let a=r.clone();return a.index=t.index,a.text=t.text+e+a.text,a.start.assign("weekday",t.start.get("weekday")),a.end&&a.end.assign("weekday",t.start.get("weekday")),a}shouldMergeResults(e,t,r){return t.start.isOnlyWeekdayComponent()&&!t.start.isCertain("hour")&&r.start.isCertain("day")&&e.match(/^,?\s*$/)!=null}}});function Gr(n,e=!1){return n.parsers.unshift(new Fd),n.refiners.unshift(new vf),n.refiners.unshift(new el),n.refiners.unshift(new ep),n.refiners.push(new nw),n.refiners.push(new ep),n.refiners.push(new iw),n.refiners.push(new sw(e)),n}var gs=y(()=>{Mne();aw();EB();Nne();Rne();eA();DB()});function Ba(n){let e=(0,tp.default)(n.getDateWithAdjustedTimezone()),t=new K(n,{});return Mr(t,e),Ene(t,e),t.assign("timezoneOffset",n.getTimezoneOffset()),t.addTag("casualReference/now"),t}function aa(n){let e=(0,tp.default)(n.getDateWithAdjustedTimezone()),t=new K(n,{});return Mr(t,e),$l(t,e),t.addTag("casualReference/today"),t}function ja(n){return kf(n,1).addTag("casualReference/yesterday")}function kf(n,e){return Ul(n,-e)}function $a(n){return Ul(n,1).addTag("casualReference/tomorrow")}function Ul(n,e){let t=(0,tp.default)(n.getDateWithAdjustedTimezone()),r=new K(n,{});return t=t.add(e,"day"),Mr(r,t),$l(r,t),r}function Bne(n,e=22){let t=(0,tp.default)(n.getDateWithAdjustedTimezone()),r=new K(n,{});return Mr(r,t),r.imply("hour",e),r.imply("meridiem",j.PM),r.addTag("casualReference/tonight"),r}function tA(n,e=0){let t=(0,tp.default)(n.getDateWithAdjustedTimezone()),r=new K(n,{});return t.hour()<6&&(t=t.add(-1,"day")),Mr(r,t),r.imply("hour",e),r}function by(n,e=20){let t=new K(n,{});return t.imply("meridiem",j.PM),t.imply("hour",e),t.addTag("casualReference/evening"),t}function rA(n,e=20){let t=(0,tp.default)(n.getDateWithAdjustedTimezone()),r=new K(n,{});return t=t.add(-1,"day"),Mr(r,t),r.imply("hour",e),r.imply("meridiem",j.PM),r.addTag("casualReference/yesterday"),r.addTag("casualReference/evening"),r}function Tf(n){let e=new K(n,{}),t=(0,tp.default)(n.getDateWithAdjustedTimezone());return t.hour()>2&&xne(e,t),e.assign("hour",0),e.imply("minute",0),e.imply("second",0),e.imply("millisecond",0),e.addTag("casualReference/midnight"),e}function wy(n,e=6){let t=new K(n,{});return t.imply("meridiem",j.AM),t.imply("hour",e),t.imply("minute",0),t.imply("second",0),t.imply("millisecond",0),t.addTag("casualReference/morning"),t}function jne(n,e=15){let t=new K(n,{});return t.imply("meridiem",j.PM),t.imply("hour",e),t.imply("minute",0),t.imply("second",0),t.imply("millisecond",0),t.addTag("casualReference/afternoon"),t}function Sy(n){let e=new K(n,{});return e.imply("meridiem",j.AM),e.assign("hour",12),e.imply("minute",0),e.imply("second",0),e.imply("millisecond",0),e.addTag("casualReference/noon"),e}var tp,ys=y(()=>{ot();tp=tt(Ht(),1);hs();Nt()});var $ne,Wze,ow,Une=y(()=>{$ne=tt(Ht(),1);we();hs();ys();Wze=/(now|today|tonight|tomorrow|overmorrow|tmr|tmrw|yesterday|last\s*night)(?=\W|$)/i,ow=class extends H{innerPattern(e){return Wze}innerExtract(e,t){let r=(0,$ne.default)(e.refDate),a=t[0].toLowerCase(),i=e.createParsingComponents();switch(a){case"now":i=Ba(e.reference);break;case"today":i=aa(e.reference);break;case"yesterday":i=ja(e.reference);break;case"tomorrow":case"tmr":case"tmrw":i=$a(e.reference);break;case"tonight":i=Bne(e.reference);break;case"overmorrow":i=Ul(e.reference,2);break;default:a.match(/last\s*night/)&&(r.hour()>6&&(r=r.add(-1,"day")),Mr(i,r),i.imply("hour",0));break}return i.addTag("parser/ENCasualDateParser"),i}}});var qze,lw,Hne=y(()=>{we();ys();qze=/(?:this)?\s{0,3}(morning|afternoon|evening|night|midnight|midday|noon)(?=\W|$)/i,lw=class extends H{innerPattern(){return qze}innerExtract(e,t){let r=null;switch(t[1].toLowerCase()){case"afternoon":r=jne(e.reference);break;case"evening":case"night":r=by(e.reference);break;case"midnight":r=Tf(e.reference);break;case"morning":r=wy(e.reference);break;case"noon":case"midday":r=Sy(e.reference);break}return r&&r.addTag("parser/ENCasualTimeParser"),r}}});function Mn(n){let e={};for(let t in n)e[t]=-n[t];return e}function nA(n,e){let t=n.clone(),r=n.dayjs();for(let a in e)r=r.add(e[a],a);return("day"in e||"d"in e||"week"in e||"month"in e||"year"in e)&&(t.imply("day",r.date()),t.imply("month",r.month()+1),t.imply("year",r.year())),("second"in e||"minute"in e||"hour"in e)&&(t.imply("second",r.second()),t.imply("minute",r.minute()),t.imply("hour",r.hour())),t}var vs=y(()=>{});function In(n,e,t){let r=n.getDateWithAdjustedTimezone(),a=Gze(r,e,t),i=new K(n);return i=nA(i,{day:a}),i.assign("weekday",e),i}function Gze(n,e,t){let r=n.getDay();switch(t){case"this":return aA(n,e);case"last":return Vne(n,e);case"next":return r==We.SUNDAY?e==We.SUNDAY?7:e:r==We.SATURDAY?e==We.SATURDAY?7:e==We.SUNDAY?8:1+e:e=0&&(r-=7),r}var tl=y(()=>{Nt();ot();vs()});var Kze,Zze,Qze,Jze,cw,Wne=y(()=>{Un();xt();we();tl();Nt();Kze=new RegExp(`(?:(?:\\,|\\(|\\()\\s*)?(?:on\\s*?)?(?:(this|last|past|next)\\s*)?(${ie(Q0)}|weekend|weekday)(?:\\s*(?:\\,|\\)|\\)))?(?:\\s*(this|last|past|next)\\s*week)?(?=\\W|$)`,"i"),Zze=1,Qze=2,Jze=3,cw=class extends H{innerPattern(){return Kze}innerExtract(e,t){let r=t[Zze],a=t[Jze],i=r||a;i=i||"",i=i.toLowerCase();let s=null;i=="last"||i=="past"?s="last":i=="next"?s="next":i=="this"&&(s="this");let o=t[Qze].toLowerCase(),l;if(Q0[o]!==void 0)l=Q0[o];else if(o=="weekend")l=s=="last"?We.SUNDAY:We.SATURDAY;else if(o=="weekday"){let c=e.reference.getDateWithAdjustedTimezone().getDay();c==We.SUNDAY||c==We.SATURDAY?l=s=="last"?We.FRIDAY:We.MONDAY:(l=c-1,l=s=="last"?l-1:l+1,l=l%5+1)}else return null;return In(e.reference,l,s)}}});var qne,Xze,eBe,tBe,dw,Gne=y(()=>{Un();ot();qne=tt(Ht(),1);we();xt();Xze=new RegExp(`(this|last|past|next|after\\s*this)\\s*(${ie(Wb)})(?=\\s*)(?=\\W|$)`,"i"),eBe=1,tBe=2,dw=class extends H{innerPattern(){return Xze}innerExtract(e,t){let r=t[eBe].toLowerCase(),a=t[tBe].toLowerCase(),i=Wb[a];if(r=="next"||r.startsWith("after")){let l={};return l[i]=1,K.createRelativeFromReference(e.reference,l)}if(r=="last"||r=="past"){let l={};return l[i]=-1,K.createRelativeFromReference(e.reference,l)}let s=e.createParsingComponents(),o=(0,qne.default)(e.reference.instant);return a.match(/week/i)?(o=o.add(-o.get("d"),"d"),s.imply("day",o.date()),s.imply("month",o.month()+1),s.imply("year",o.year())):a.match(/month/i)?(o=o.add(-o.date()+1,"d"),s.imply("day",o.date()),s.assign("year",o.year()),s.assign("month",o.month()+1)):a.match(/year/i)&&(o=o.add(-o.date()+1,"d"),o=o.add(-o.month(),"month"),s.imply("day",o.date()),s.imply("month",o.month()+1),s.assign("year",o.year())),s}}});var rBe,nBe,aBe,Yne,Kne,PB,Hn,Ld=y(()=>{mn();rBe=new RegExp("([^\\d]|^)([0-3]{0,1}[0-9]{1})[\\/\\.\\-]([0-3]{0,1}[0-9]{1})(?:[\\/\\.\\-]([0-9]{4}|[0-9]{2}))?(\\W|$)","i"),nBe=1,aBe=5,Yne=2,Kne=3,PB=4,Hn=class{constructor(e){z(this,"groupNumberMonth");z(this,"groupNumberDay");this.groupNumberMonth=e?Kne:Yne,this.groupNumberDay=e?Yne:Kne}pattern(){return rBe}extract(e,t){let r=t.index+t[nBe].length,a=t.index+t[0].length-t[aBe].length;if(r>0&&e.text.substring(0,r).match("\\d/?$")||a12)&&o>12)if(l>=1&&l<=12&&o<=31)[l,o]=[o,l];else return null;if(l<1||l>31)return null;if(s.start.assign("day",l),s.start.assign("month",o),t[PB]){let c=parseInt(t[PB]),d=Mi(c);s.start.assign("year",d)}else{let c=er(e.refDate,l,o);s.start.imply("year",c)}return s.addTag("parser/SlashDateFormatParser")}}});var iBe,sBe,uw,Zne=y(()=>{Un();ot();we();Vb();iBe=new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${Nd})(?=\\W|$)`,"i"),sBe=new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${Xu})(?=\\W|$)`,"i"),uw=class extends H{constructor(t=!0){super();z(this,"allowAbbreviations");this.allowAbbreviations=t}innerPattern(){return this.allowAbbreviations?iBe:sBe}innerExtract(t,r){let a=r[1].toLowerCase(),i=Js(r[2]);if(!i)return null;switch(a){case"last":case"past":case"-":i=hy(i);break}return K.createRelativeFromReference(t.reference,i)}}});function oBe(n){return n.text.match(/^[+-]/i)!=null}function Qne(n){return n.text.match(/^-/i)!=null}var pw,Jne=y(()=>{_d();ot();Un();vs();pw=class extends Ii{shouldMergeResults(e,t,r){return e.match(/^\s*$/i)?oBe(r)||Qne(r):!1}mergeResults(e,t,r,a){let i=Js(r.text);Qne(r)&&(i=Mn(i));let s=K.createRelativeFromReference(Vt.fromDate(t.start.date()),i);return new Lt(t.reference,t.index,`${t.text}${e}${r.text}`,s)}}});function Xne(n){return n.text.match(/\s+(before|from)$/i)!=null}function lBe(n){return n.text.match(/\s+(after|since)$/i)!=null}var mw,eae=y(()=>{_d();ot();Un();Vb();mw=class extends Ii{patternBetween(){return/^\s*$/i}shouldMergeResults(e,t,r){return!e.match(this.patternBetween())||!Xne(t)&&!lBe(t)?!1:!!r.start.get("day")&&!!r.start.get("month")&&!!r.start.get("year")}mergeResults(e,t,r){let a=Js(t.text);Xne(t)&&(a=hy(a));let i=K.createRelativeFromReference(Vt.fromDate(r.start.date()),a);return new Lt(r.reference,t.index,`${t.text}${e}${r.text}`,i)}}});var cBe,dBe,fw,tae=y(()=>{Un();cBe=new RegExp(`^\\s*(${Qu})`,"i"),dBe=1,fw=class{refine(e,t){return t.forEach(function(r){if(!r.start.isDateWithUnknownYear())return;let a=e.text.substring(r.index+r.text.length),i=cBe.exec(a);if(!i||i[0].trim().length<=3)return;e.debug(()=>{console.log(`Extracting year: '${i[0]}' into : ${r}`)});let s=Ju(i[dBe]);r.end!=null&&r.end.assign("year",s),r.start.assign("year",s),r.text+=i[0]}),t}}});var hw,rae=y(()=>{_d();hw=class extends ky{constructor(){super()}isValid(e,t){let r=t.text.trim();return r===e.text.trim()?!0:r.toLowerCase()==="may"&&!e.text.substring(0,t.index).trim().match(/\b(in)$/i)?(e.debug(()=>{console.log(`Removing unlikely result: ${t}`)}),!1):r.toLowerCase().endsWith("the second")?(e.text.substring(t.index+t.text.length).trim().length>0&&e.debug(()=>{console.log(`Removing unlikely result: ${t}`)}),!1):!0}}});var bf,AB=y(()=>{lne();pne();fne();gne();vne();kne();bne();wne();Sne();Cne();Ane();gs();Une();Hne();Wne();Gne();Ld();Zne();Jne();eae();EB();tae();rae();bf=class{createCasualConfiguration(e=!1){let t=this.createConfiguration(!1,e);return t.parsers.push(new ow),t.parsers.push(new lw),t.parsers.push(new Kb),t.parsers.push(new dw),t.parsers.push(new uw),t.refiners.push(new hw),t}createConfiguration(e=!0,t=!1){let r=Gr({parsers:[new Hn(t),new qb(e),new Gb,new Yb(t),new cw,new Qb,new Xb(e),new ew(e),new tw(e)],refiners:[new Ty]},e);return r.parsers.unshift(new Zb(e)),r.refiners.unshift(new mw),r.refiners.unshift(new pw),r.refiners.unshift(new ep),r.refiners.push(new Ty),r.refiners.push(new fw),r.refiners.push(new rw),r}}});var ze,gw,Ni=y(()=>{ot();AB();ze=class n{constructor(e){z(this,"parsers");z(this,"refiners");z(this,"defaultConfig",new bf);e=e||this.defaultConfig.createCasualConfiguration(),this.parsers=[...e.parsers],this.refiners=[...e.refiners]}clone(){return new n({parsers:[...this.parsers],refiners:[...this.refiners]})}parseDate(e,t,r){let a=this.parse(e,t,r);return a.length>0?a[0].start.date():null}parse(e,t,r){let a=new gw(e,t,r),i=[];return this.parsers.forEach(s=>{let o=n.executeParser(a,s);i=i.concat(o)}),i.sort((s,o)=>s.index-o.index),this.refiners.forEach(function(s){i=s.refine(a,i)}),i}static executeParser(e,t){let r=[],a=t.pattern(e),i=e.text,s=e.text,o=a.exec(s);for(;o;){let l=o.index+i.length-s.length;o.index=l;let c=t.extract(e,o);if(!c){s=i.substring(o.index+1),o=a.exec(s);continue}let d=null;c instanceof Lt?d=c:c instanceof K?(d=e.createParsingResult(o.index,o[0]),d.start=c):d=e.createParsingResult(o.index,o[0],c);let u=d.index,p=d.text;e.debug(()=>console.log(`${t.constructor.name} extracted (at index=${u}) '${p}'`)),r.push(d),s=i.substring(u+p.length),o=a.exec(s)}return r}},gw=class{constructor(e,t,r){z(this,"text");z(this,"option");z(this,"reference");z(this,"refDate");this.text=e,this.option=r!=null?r:{},this.reference=Vt.fromInput(t,this.option.timezones),this.refDate=this.reference.instant}createParsingComponents(e){return e instanceof K?e:new K(this.reference,e)}createParsingResult(e,t,r,a){let i=typeof t=="string"?t:this.text.substring(e,t),s=r?this.createParsingComponents(r):null,o=a?this.createParsingComponents(a):null;return new Lt(this.reference,e,i,s,o)}debug(e){this.option.debug&&(this.option.debug instanceof Function?this.option.debug(e):this.option.debug.debug(e))}}});var IB={};Xe(IB,{Chrono:()=>ze,GB:()=>uBe,Meridiem:()=>j,ParsingComponents:()=>K,ParsingResult:()=>Lt,ReferenceWithTimezone:()=>Vt,Weekday:()=>We,casual:()=>yw,configuration:()=>iA,parse:()=>pBe,parseDate:()=>mBe,strict:()=>MB});function pBe(n,e,t){return yw.parse(n,e,t)}function mBe(n,e,t){return yw.parseDate(n,e,t)}var iA,yw,MB,uBe,nae=y(()=>{Ni();ot();Nt();AB();iA=new bf,yw=new ze(iA.createCasualConfiguration(!1)),MB=new ze(iA.createConfiguration(!0,!1)),uBe=new ze(iA.createCasualConfiguration(!0))});var vw,aae=y(()=>{Rd();vw=class extends na{primaryPrefix(){return"(?:(?:um|von)\\s*)?"}followingPhase(){return"\\s*(?:\\-|\\–|\\~|\\〜|bis)\\s*"}extractPrimaryTimeComponents(e,t){return t[0].match(/^\s*\d{4}\s*$/)?null:super.extractPrimaryTimeComponents(e,t)}}});function LB(n){let e=n.toLowerCase();return NB[e]!==void 0?NB[e]:e==="ein"||e==="einer"||e==="einem"||e==="einen"||e==="eine"?1:e.match(/wenigen/)?2:e.match(/halb/)||e.match(/halben/)?.5:e.match(/einigen/)?3:e.match(/mehreren/)?7:parseFloat(e)}function oae(n){if(/v/i.test(n))return-parseInt(n.replace(/[^0-9]+/gi,""));if(/n/i.test(n))return parseInt(n.replace(/[^0-9]+/gi,""));if(/z/i.test(n))return parseInt(n.replace(/[^0-9]+/gi,""));let e=parseInt(n);return Mi(e)}function dae(n){let e={},t=n,r=iae.exec(t);for(;r;)fBe(e,r),t=t.substring(r[0].length),r=iae.exec(t);return e}function fBe(n,e){let t=LB(e[1]),r=kw[e[2].toLowerCase()];n[r]=t}var RB,_B,NB,kw,FB,sae,lae,iae,cae,Cy=y(()=>{xt();mn();RB={sonntag:0,so:0,montag:1,mo:1,dienstag:2,di:2,mittwoch:3,mi:3,donnerstag:4,do:4,freitag:5,fr:5,samstag:6,sa:6},_B={januar:1,jänner:1,janner:1,jan:1,"jan.":1,februar:2,feber:2,feb:2,"feb.":2,märz:3,maerz:3,mär:3,"mär.":3,mrz:3,"mrz.":3,april:4,apr:4,"apr.":4,mai:5,juni:6,jun:6,"jun.":6,juli:7,jul:7,"jul.":7,august:8,aug:8,"aug.":8,september:9,sep:9,"sep.":9,sept:9,"sept.":9,oktober:10,okt:10,"okt.":10,november:11,nov:11,"nov.":11,dezember:12,dez:12,"dez.":12},NB={eins:1,eine:1,einem:1,einen:1,einer:1,zwei:2,drei:3,vier:4,fünf:5,fuenf:5,sechs:6,sieben:7,acht:8,neun:9,zehn:10,elf:11,zwölf:12,zwoelf:12},kw={sek:"second",sekunde:"second",sekunden:"second",min:"minute",minute:"minute",minuten:"minute",h:"hour",std:"hour",stunde:"hour",stunden:"hour",tag:"d",tage:"d",tagen:"d",woche:"week",wochen:"week",monat:"month",monate:"month",monaten:"month",monats:"month",quartal:"quarter",quartals:"quarter",quartale:"quarter",quartalen:"quarter",a:"year",j:"year",jr:"year",jahr:"year",jahre:"year",jahren:"year",jahres:"year"},FB=`(?:${ie(NB)}|[0-9]+|[0-9]+\\.[0-9]+|halb?|halbe?|einigen?|wenigen?|mehreren?)`;sae="(?:[0-9]{1,4}(?:\\s*[vn]\\.?\\s*(?:C(?:hr)?|(?:u\\.?|d\\.?(?:\\s*g\\.?)?)?\\s*Z)\\.?|\\s*(?:u\\.?|d\\.?(?:\\s*g\\.)?)\\s*Z\\.?)?)";lae=`(${FB})\\s{0,5}(${ie(kw)})\\s{0,5}`,iae=new RegExp(lae,"i"),cae=li("",lae)});var hBe,gBe,yBe,vBe,Tw,uae=y(()=>{Cy();xt();we();tl();hBe=new RegExp(`(?:(?:\\,|\\(|\\()\\s*)?(?:a[mn]\\s*?)?(?:(diese[mn]|letzte[mn]|n(?:ä|ae)chste[mn])\\s*)?(${ie(RB)})(?:\\s*(?:\\,|\\)|\\)))?(?:\\s*(diese|letzte|n(?:ä|ae)chste)\\s*woche)?(?=\\W|$)`,"i"),gBe=1,yBe=3,vBe=2,Tw=class extends H{innerPattern(){return hBe}innerExtract(e,t){let r=t[vBe].toLowerCase(),a=RB[r],i=t[gBe],s=t[yBe],o=i||s;o=o||"",o=o.toLowerCase();let l=null;return o.match(/letzte/)?l="last":o.match(/chste/)?l="next":o.match(/diese/)&&(l="this"),In(e.reference,a,l)}}});var kBe,TBe,bBe,pae,mae,fae,bw,hae=y(()=>{Nt();kBe=new RegExp("(^|\\s|T)(?:(?:um|von)\\s*)?(\\d{1,2})(?:h|:)?(?:(\\d{1,2})(?:m|:)?)?(?:(\\d{1,2})(?:s)?)?(?:\\s*Uhr)?(?:\\s*(morgens|vormittags|nachmittags|abends|nachts|am\\s+(?:Morgen|Vormittag|Nachmittag|Abend)|in\\s+der\\s+Nacht))?(?=\\W|$)","i"),TBe=new RegExp("^\\s*(\\-|\\–|\\~|\\〜|bis(?:\\s+um)?|\\?)\\s*(\\d{1,2})(?:h|:)?(?:(\\d{1,2})(?:m|:)?)?(?:(\\d{1,2})(?:s)?)?(?:\\s*Uhr)?(?:\\s*(morgens|vormittags|nachmittags|abends|nachts|am\\s+(?:Morgen|Vormittag|Nachmittag|Abend)|in\\s+der\\s+Nacht))?(?=\\W|$)","i"),bBe=2,pae=3,mae=4,fae=5,bw=class n{pattern(e){return kBe}extract(e,t){let r=e.createParsingResult(t.index+t[1].length,t[0].substring(t[1].length));if(r.text.match(/^\d{4}$/)||(r.start=n.extractTimeComponent(r.start.clone(),t),!r.start))return t.index+=t[0].length,null;let a=e.text.substring(t.index+t[0].length),i=TBe.exec(a);return i&&(r.end=n.extractTimeComponent(r.start.clone(),i),r.end&&(r.text+=i[0])),r}static extractTimeComponent(e,t){let r=0,a=0,i=null;if(r=parseInt(t[bBe]),t[pae]!=null&&(a=parseInt(t[pae])),a>=60||r>24)return null;if(r>=12&&(i=j.PM),t[fae]!=null){if(r>12)return null;let s=t[fae].toLowerCase();s.match(/morgen|vormittag/)&&(i=j.AM,r==12&&(r=0)),s.match(/nachmittag|abend/)&&(i=j.PM,r!=12&&(r+=12)),s.match(/nacht/)&&(r==12?(i=j.AM,r=0):r<6?i=j.AM:(i=j.PM,r+=12))}if(e.assign("hour",r),e.assign("minute",a),i!==null?e.assign("meridiem",i):r<12?e.imply("meridiem",j.AM):e.imply("meridiem",j.PM),t[mae]!=null){let s=parseInt(t[mae]);if(s>=60)return null;e.assign("second",s)}return e}}});var ww,gae=y(()=>{Xs();ww=class extends jr{patternBetween(){return/^\s*(bis(?:\s*(?:am|zum))?|-)\s*$/i}}});var Sw,yae=y(()=>{eo();Sw=class extends $r{patternBetween(){return new RegExp("^\\s*(T|um|am|,|-)?\\s*$")}}});var vae,wf,OB=y(()=>{vae=tt(Ht(),1);Nt();we();hs();vs();wf=class n extends H{innerPattern(e){return/(diesen)?\s*(morgen|vormittag|mittags?|nachmittag|abend|nacht|mitternacht)(?=\W|$)/i}innerExtract(e,t){let r=(0,vae.default)(e.refDate),a=t[2].toLowerCase(),i=e.createParsingComponents();return $l(i,r),n.extractTimeComponents(i,a)}static extractTimeComponents(e,t){switch(t){case"morgen":e.imply("hour",6),e.imply("minute",0),e.imply("second",0),e.imply("meridiem",j.AM);break;case"vormittag":e.imply("hour",9),e.imply("minute",0),e.imply("second",0),e.imply("meridiem",j.AM);break;case"mittag":case"mittags":e.imply("hour",12),e.imply("minute",0),e.imply("second",0),e.imply("meridiem",j.AM);break;case"nachmittag":e.imply("hour",15),e.imply("minute",0),e.imply("second",0),e.imply("meridiem",j.PM);break;case"abend":e.imply("hour",18),e.imply("minute",0),e.imply("second",0),e.imply("meridiem",j.PM);break;case"nacht":e.imply("hour",22),e.imply("minute",0),e.imply("second",0),e.imply("meridiem",j.PM);break;case"mitternacht":e.get("hour")>1&&(e=nA(e,{day:1})),e.imply("hour",0),e.imply("minute",0),e.imply("second",0),e.imply("meridiem",j.AM);break}return e}}});var kae,wBe,SBe,CBe,Cw,Tae=y(()=>{kae=tt(Ht(),1);we();hs();OB();ys();wBe=new RegExp("(jetzt|heute|morgen|übermorgen|uebermorgen|gestern|vorgestern|letzte\\s*nacht)(?:\\s*(morgen|vormittag|mittags?|nachmittag|abend|nacht|mitternacht))?(?=\\W|$)","i"),SBe=1,CBe=2,Cw=class extends H{innerPattern(e){return wBe}innerExtract(e,t){let r=(0,kae.default)(e.refDate),a=(t[SBe]||"").toLowerCase(),i=(t[CBe]||"").toLowerCase(),s=e.createParsingComponents();switch(a){case"jetzt":s=Ba(e.reference);break;case"heute":s=aa(e.reference);break;case"morgen":Xo(s,r);break;case"übermorgen":case"uebermorgen":r=r.add(1,"day"),Xo(s,r);break;case"gestern":r=r.add(-1,"day"),Mr(s,r),$l(s,r);break;case"vorgestern":r=r.add(-2,"day"),Mr(s,r),$l(s,r);break;default:a.match(/letzte\s*nacht/)&&(r.hour()>6&&(r=r.add(-1,"day")),Mr(s,r),s.imply("hour",0));break}return i&&(s=wf.extractTimeComponents(s,i)),s}}});var xBe,bae,wae,EBe,Sae,xw,Cae=y(()=>{mn();Cy();Cy();xt();we();xBe=new RegExp(`(?:am\\s*?)?(?:den\\s*?)?([0-9]{1,2})\\.(?:\\s*(?:bis(?:\\s*(?:am|zum))?|\\-|\\–|\\s)\\s*([0-9]{1,2})\\.?)?\\s*(${ie(_B)})(?:(?:-|/|,?\\s*)(${sae}(?![^\\s]\\d)))?(?=\\W|$)`,"i"),bae=1,wae=2,EBe=3,Sae=4,xw=class extends H{innerPattern(){return xBe}innerExtract(e,t){let r=e.createParsingResult(t.index,t[0]),a=_B[t[EBe].toLowerCase()],i=parseInt(t[bae]);if(i>31)return t.index=t.index+t[bae].length,null;if(r.start.assign("month",a),r.start.assign("day",i),t[Sae]){let s=oae(t[Sae]);r.start.assign("year",s)}else{let s=er(e.refDate,i,a);r.start.imply("year",s)}if(t[wae]){let s=parseInt(t[wae]);r.end=r.start.clone(),r.end.assign("day",s)}return r}}});var Ew,xae=y(()=>{Cy();ot();we();vs();xt();Ew=class extends H{constructor(){super()}innerPattern(){return new RegExp(`(?:\\s*((?:nächste|kommende|folgende|letzte|vergangene|vorige|vor(?:her|an)gegangene)(?:s|n|m|r)?|vor|in)\\s*)?(${FB})?(?:\\s*(nächste|kommende|folgende|letzte|vergangene|vorige|vor(?:her|an)gegangene)(?:s|n|m|r)?)?\\s*(${ie(kw)})`,"i")}innerExtract(e,t){let r=t[2]?LB(t[2]):1,a=kw[t[4].toLowerCase()],i={};i[a]=r;let s=t[1]||t[3]||"";if(s=s.toLowerCase(),!!s)return(/vor/.test(s)||/letzte/.test(s)||/vergangen/.test(s))&&(i=Mn(i)),K.createRelativeFromReference(e.reference,i)}}});var Dw,Eae=y(()=>{Cy();ot();we();Dw=class extends H{innerPattern(){return new RegExp(`(?:in|für|während)\\s*(${cae})(?=\\W|$)`,"i")}innerExtract(e,t){let r=dae(t[1]);return K.createRelativeFromReference(e.reference,r)}}});var jB={};Xe(jB,{Chrono:()=>ze,Meridiem:()=>j,ParsingComponents:()=>K,ParsingResult:()=>Lt,ReferenceWithTimezone:()=>Vt,Weekday:()=>We,casual:()=>zB,createCasualConfiguration:()=>Dae,createConfiguration:()=>BB,parse:()=>PBe,parseDate:()=>ABe,strict:()=>DBe});function PBe(n,e,t){return zB.parse(n,e,t)}function ABe(n,e,t){return zB.parseDate(n,e,t)}function Dae(n=!0){let e=BB(!1,n);return e.parsers.unshift(new wf),e.parsers.unshift(new Cw),e.parsers.unshift(new Ew),e}function BB(n=!0,e=!0){return Gr({parsers:[new Fd,new Hn(e),new vw,new bw,new xw,new Tw,new Dw],refiners:[new ww,new Sw]},n)}var zB,DBe,Pae=y(()=>{gs();Ni();ot();Nt();Ld();eA();aae();uae();hae();gae();yae();Tae();OB();Cae();xae();Eae();zB=new ze(Dae()),DBe=new ze(BB(!0))});var Aae,Pw,Mae=y(()=>{Aae=tt(Ht(),1);Nt();we();hs();ys();Pw=class extends H{innerPattern(e){return/(maintenant|aujourd'hui|demain|hier|cette\s*nuit|la\s*veille)(?=\W|$)/i}innerExtract(e,t){let r=(0,Aae.default)(e.refDate),a=t[0].toLowerCase(),i=e.createParsingComponents();switch(a){case"maintenant":return Ba(e.reference);case"aujourd'hui":return aa(e.reference);case"hier":return ja(e.reference);case"demain":return $a(e.reference);default:a.match(/cette\s*nuit/)?(Mr(i,r),i.imply("hour",22),i.imply("meridiem",j.PM)):a.match(/la\s*veille/)&&(r=r.add(-1,"day"),Mr(i,r),i.imply("hour",0))}return i}}});var Aw,Iae=y(()=>{Nt();we();Aw=class extends H{innerPattern(e){return/(cet?)?\s*(matin|soir|après-midi|aprem|a midi|à minuit)(?=\W|$)/i}innerExtract(e,t){let r=t[2].toLowerCase(),a=e.createParsingComponents();switch(r){case"après-midi":case"aprem":a.imply("hour",14),a.imply("minute",0),a.imply("meridiem",j.PM);break;case"soir":a.imply("hour",18),a.imply("minute",0),a.imply("meridiem",j.PM);break;case"matin":a.imply("hour",8),a.imply("minute",0),a.imply("meridiem",j.AM);break;case"a midi":a.imply("hour",12),a.imply("minute",0),a.imply("meridiem",j.AM);break;case"à minuit":a.imply("hour",0),a.imply("meridiem",j.AM);break}return a}}});var Mw,Nae=y(()=>{Rd();Mw=class extends na{primaryPrefix(){return"(?:(?:[àa])\\s*)?"}followingPhase(){return"\\s*(?:\\-|\\–|\\~|\\〜|[àa]|\\?)\\s*"}extractPrimaryTimeComponents(e,t){return t[0].match(/^\s*\d{4}\s*$/)?null:super.extractPrimaryTimeComponents(e,t)}}});var Iw,Rae=y(()=>{eo();Iw=class extends $r{patternBetween(){return new RegExp("^\\s*(T|à|a|au|vers|de|,|-)?\\s*$")}}});var Nw,_ae=y(()=>{Xs();Nw=class extends jr{patternBetween(){return/^\s*(à|a|au|-)\s*$/i}}});function WB(n){let e=n.toLowerCase();return $B[e]!==void 0?$B[e]:e==="une"||e==="un"?1:e.match(/quelques?/)?3:e.match(/demi-?/)?.5:parseFloat(e)}function GB(n){let e=n.toLowerCase();return e=e.replace(/(?:er)$/i,""),parseInt(e)}function Oae(n){if(/AC/i.test(n))return n=n.replace(/BC/i,""),-parseInt(n);if(/AD/i.test(n)||/C/i.test(n))return n=n.replace(/[^\d]+/i,""),parseInt(n);let e=parseInt(n);return e<100&&(e>50?e=e+1900:e=e+2e3),e}function oA(n){let e={},t=n,r=Fae.exec(t);for(;r;)MBe(e,r),t=t.substring(r[0].length),r=Fae.exec(t);return e}function MBe(n,e){let t=WB(e[1]),r=Rw[e[2].toLowerCase()];n[r]=t}var UB,HB,$B,Rw,VB,qB,Lae,zae,Fae,sA,rp=y(()=>{xt();UB={dimanche:0,dim:0,lundi:1,lun:1,mardi:2,mar:2,mercredi:3,mer:3,jeudi:4,jeu:4,vendredi:5,ven:5,samedi:6,sam:6},HB={janvier:1,jan:1,"jan.":1,février:2,fév:2,"fév.":2,fevrier:2,fev:2,"fev.":2,mars:3,mar:3,"mar.":3,avril:4,avr:4,"avr.":4,mai:5,juin:6,jun:6,juillet:7,juil:7,jul:7,"jul.":7,août:8,aout:8,septembre:9,sep:9,"sep.":9,sept:9,"sept.":9,octobre:10,oct:10,"oct.":10,novembre:11,nov:11,"nov.":11,décembre:12,decembre:12,dec:12,"dec.":12},$B={un:1,deux:2,trois:3,quatre:4,cinq:5,six:6,sept:7,huit:8,neuf:9,dix:10,onze:11,douze:12,treize:13},Rw={sec:"second",seconde:"second",secondes:"second",min:"minute",mins:"minute",minute:"minute",minutes:"minute",h:"hour",hr:"hour",hrs:"hour",heure:"hour",heures:"hour",jour:"d",jours:"d",semaine:"week",semaines:"week",mois:"month",trimestre:"quarter",trimestres:"quarter",ans:"year",année:"year",années:"year"},VB=`(?:${ie($B)}|[0-9]+|[0-9]+\\.[0-9]+|une?\\b|quelques?|demi-?)`;qB="(?:[0-9]{1,2}(?:er)?)";Lae="(?:[1-9][0-9]{0,3}\\s*(?:AC|AD|p\\.\\s*C(?:hr?)?\\.\\s*n\\.)|[1-2][0-9]{3}|[5-9][0-9])";zae=`(${VB})\\s{0,5}(${ie(Rw)})\\s{0,5}`,Fae=new RegExp(zae,"i"),sA=li("",zae)});var IBe,NBe,RBe,_w,Bae=y(()=>{rp();xt();we();tl();IBe=new RegExp(`(?:(?:\\,|\\(|\\()\\s*)?(?:(?:ce)\\s*)?(${ie(UB)})(?:\\s*(?:\\,|\\)|\\)))?(?:\\s*(dernier|prochain)\\s*)?(?=\\W|\\d|$)`,"i"),NBe=1,RBe=2,_w=class extends H{innerPattern(){return IBe}innerExtract(e,t){let r=t[NBe].toLowerCase(),a=UB[r];if(a===void 0)return null;let i=t[RBe];i=i||"",i=i.toLowerCase();let s=null;return i=="dernier"?s="last":i=="prochain"&&(s="next"),In(e.reference,a,s)}}});var _Be,FBe,LBe,jae,$ae,Uae,Fw,Hae=y(()=>{Nt();_Be=new RegExp("(^|\\s|T)(?:(?:[àa])\\s*)?(\\d{1,2})(?:h|:)?(?:(\\d{1,2})(?:m|:)?)?(?:(\\d{1,2})(?:s|:)?)?(?:\\s*(A\\.M\\.|P\\.M\\.|AM?|PM?))?(?=\\W|$)","i"),FBe=new RegExp("^\\s*(\\-|\\–|\\~|\\〜|[àa]|\\?)\\s*(\\d{1,2})(?:h|:)?(?:(\\d{1,2})(?:m|:)?)?(?:(\\d{1,2})(?:s|:)?)?(?:\\s*(A\\.M\\.|P\\.M\\.|AM?|PM?))?(?=\\W|$)","i"),LBe=2,jae=3,$ae=4,Uae=5,Fw=class n{pattern(e){return _Be}extract(e,t){let r=e.createParsingResult(t.index+t[1].length,t[0].substring(t[1].length));if(r.text.match(/^\d{4}$/)||(r.start=n.extractTimeComponent(r.start.clone(),t),!r.start))return t.index+=t[0].length,null;let a=e.text.substring(t.index+t[0].length),i=FBe.exec(a);return i&&(r.end=n.extractTimeComponent(r.start.clone(),i),r.end&&(r.text+=i[0])),r}static extractTimeComponent(e,t){let r=0,a=0,i=null;if(r=parseInt(t[LBe]),t[jae]!=null&&(a=parseInt(t[jae])),a>=60||r>24)return null;if(r>=12&&(i=j.PM),t[Uae]!=null){if(r>12)return null;let s=t[Uae][0].toLowerCase();s=="a"&&(i=j.AM,r==12&&(r=0)),s=="p"&&(i=j.PM,r!=12&&(r+=12))}if(e.assign("hour",r),e.assign("minute",a),i!==null?e.assign("meridiem",i):r<12?e.imply("meridiem",j.AM):e.imply("meridiem",j.PM),t[$ae]!=null){let s=parseInt(t[$ae]);if(s>=60)return null;e.assign("second",s)}return e}}});var OBe,Vae,Wae,zBe,qae,Lw,Gae=y(()=>{mn();rp();rp();rp();xt();we();OBe=new RegExp(`(?:on\\s*?)?(${qB})(?:\\s*(?:au|\\-|\\–|jusqu'au?|\\s)\\s*(${qB}))?(?:-|/|\\s*(?:de)?\\s*)(${ie(HB)})(?:(?:-|/|,?\\s*)(${Lae}(?![^\\s]\\d)))?(?=\\W|$)`,"i"),Vae=1,Wae=2,zBe=3,qae=4,Lw=class extends H{innerPattern(){return OBe}innerExtract(e,t){let r=e.createParsingResult(t.index,t[0]),a=HB[t[zBe].toLowerCase()],i=GB(t[Vae]);if(i>31)return t.index=t.index+t[Vae].length,null;if(r.start.assign("month",a),r.start.assign("day",i),t[qae]){let s=Oae(t[qae]);r.start.assign("year",s)}else{let s=er(e.refDate,i,a);r.start.imply("year",s)}if(t[Wae]){let s=GB(t[Wae]);r.end=r.start.clone(),r.end.assign("day",s)}return r}}});var Ow,Yae=y(()=>{rp();ot();we();vs();Ow=class extends H{constructor(){super()}innerPattern(){return new RegExp(`il y a\\s*(${sA})(?=(?:\\W|$))`,"i")}innerExtract(e,t){let r=oA(t[1]),a=Mn(r);return K.createRelativeFromReference(e.reference,a)}}});var zw,Kae=y(()=>{rp();ot();we();zw=class extends H{innerPattern(){return new RegExp(`(?:dans|en|pour|pendant|de)\\s*(${sA})(?=\\W|$)`,"i")}innerExtract(e,t){let r=oA(t[1]);return K.createRelativeFromReference(e.reference,r)}}});var Bw,Zae=y(()=>{rp();ot();we();vs();xt();Bw=class extends H{constructor(){super()}innerPattern(){return new RegExp(`(?:les?|la|l'|du|des?)\\s*(${VB})?(?:\\s*(prochaine?s?|derni[eè]re?s?|pass[ée]e?s?|pr[ée]c[ée]dents?|suivante?s?))?\\s*(${ie(Rw)})(?:\\s*(prochaine?s?|derni[eè]re?s?|pass[ée]e?s?|pr[ée]c[ée]dents?|suivante?s?))?`,"i")}innerExtract(e,t){let r=t[1]?WB(t[1]):1,a=Rw[t[3].toLowerCase()],i={};i[a]=r;let s=t[2]||t[4]||"";if(s=s.toLowerCase(),!!s)return(/derni[eè]re?s?/.test(s)||/pass[ée]e?s?/.test(s)||/pr[ée]c[ée]dents?/.test(s))&&(i=Mn(i)),K.createRelativeFromReference(e.reference,i)}}});var ZB={};Xe(ZB,{Chrono:()=>ze,Meridiem:()=>j,ParsingComponents:()=>K,ParsingResult:()=>Lt,ReferenceWithTimezone:()=>Vt,Weekday:()=>We,casual:()=>YB,createCasualConfiguration:()=>Qae,createConfiguration:()=>KB,parse:()=>jBe,parseDate:()=>$Be,strict:()=>BBe});function jBe(n,e,t){return YB.parse(n,e,t)}function $Be(n,e,t){return YB.parseDate(n,e,t)}function Qae(n=!0){let e=KB(!1,n);return e.parsers.unshift(new Pw),e.parsers.unshift(new Aw),e.parsers.unshift(new Bw),e}function KB(n=!0,e=!0){return Gr({parsers:[new Hn(e),new Lw,new Mw,new Fw,new Ow,new zw,new _w],refiners:[new Iw,new Nw]},n)}var YB,BBe,Jae=y(()=>{gs();Ni();ot();Nt();Mae();Iae();Ld();Nae();Rae();_ae();Bae();Hae();Gae();Yae();Kae();Zae();YB=new ze(Qae()),BBe=new ze(KB(!0))});function ci(n){return String(n).replace(/\u2019/g,"'").replace(/\u201D/g,'"').replace(/\u3000/g," ").replace(/\uFFE5/g,"¥").replace(/[\uFF01\uFF03-\uFF06\uFF08\uFF09\uFF0C-\uFF19\uFF1C-\uFF1F\uFF21-\uFF3B\uFF3D\uFF3F\uFF41-\uFF5B\uFF5D\uFF5E]/g,UBe)}function UBe(n){return String.fromCharCode(n.charCodeAt(0)-65248)}function Sf(n){let e=0;for(let t=0;t{Hl={零:0,"〇":0,一:1,二:2,三:3,四:4,五:5,六:6,七:7,八:8,九:9,十:10},xy={日:0,月:1,火:2,水:3,木:4,金:5,土:6}});var eie,HBe,Xae,VBe,QB,WBe,qBe,GBe,jw,tie=y(()=>{Ey();mn();eie=tt(Ht(),1),HBe=/(?:(?:([同今本])|((昭和|平成|令和)?([0-90-9]{1,4}|元)))年\s*)?([0-90-9]{1,2})月\s*([0-90-9]{1,2})日/i,Xae=1,VBe=2,QB=3,WBe=4,qBe=5,GBe=6,jw=class{pattern(){return HBe}extract(e,t){let r=parseInt(ci(t[qBe])),a=parseInt(ci(t[GBe])),i=e.createParsingComponents({day:a,month:r});if(t[Xae]&&t[Xae].match("同|今|本")){let s=(0,eie.default)(e.refDate);i.assign("year",s.year())}if(t[VBe]){let s=t[WBe],o=s=="元"?1:parseInt(ci(s));t[QB]=="令和"?o+=2018:t[QB]=="平成"?o+=1988:t[QB]=="昭和"&&(o+=1925),i.assign("year",o)}else{let s=er(e.refDate,a,r);i.imply("year",s)}return i}}});var $w,rie=y(()=>{Xs();$w=class extends jr{patternBetween(){return/^\s*(から|-|ー|-|~|~)\s*$/i}}});function KBe(n){switch(n){case"きょう":return"今日";case"ほんじつ":return"本日";case"きのう":return"昨日";case"あした":return"明日";case"こんや":return"今夜";case"こんゆう":return"今夕";case"こんばん":return"今晩";case"けさ":return"今朝";default:return n}}var nie,YBe,Uw,aie=y(()=>{nie=tt(Ht(),1);Nt();ys();YBe=/今日|きょう|本日|ほんじつ|昨日|きのう|明日|あした|今夜|こんや|今夕|こんゆう|今晩|こんばん|今朝|けさ/i;Uw=class{pattern(){return YBe}extract(e,t){let r=KBe(t[0]),a=(0,nie.default)(e.refDate),i=e.createParsingComponents();switch(r){case"昨日":return ja(e.reference);case"明日":return $a(e.reference);case"本日":case"今日":return aa(e.reference)}return r=="今夜"||r=="今夕"||r=="今晩"?(i.imply("hour",22),i.assign("meridiem",j.PM)):r.match("今朝")&&(i.imply("hour",6),i.assign("meridiem",j.AM)),i.assign("day",a.date()),i.assign("month",a.month()+1),i.assign("year",a.year()),i}}});var ZBe,Hw,iie=y(()=>{Ey();tl();ZBe=new RegExp("((?前の|次の|今週))?(?"+Object.keys(xy).join("|")+")(?:曜日|曜)","i"),Hw=class{pattern(){return ZBe}extract(e,t){let r=t.groups.weekday,a=xy[r];if(a===void 0)return null;let i=t.groups.prefix||"",s=null;return i.match(/前の/)?s="last":i.match(/次の/)?s="next":i.match(/今週/)&&(s="this"),In(e.reference,a,s)}}});var QBe,sie,JBe,XBe,Vw,oie=y(()=>{mn();Ey();QBe=new RegExp("([0-90-9]{4}[\\/|\\/])?([0-10-1]{0,1}[0-90-9]{1})(?:[\\/|\\/]([0-30-3]{0,1}[0-90-9]{1}))","i"),sie=1,JBe=2,XBe=3,Vw=class{pattern(){return QBe}extract(e,t){let r=e.createParsingComponents(),a=parseInt(ci(t[JBe])),i=parseInt(ci(t[XBe]));if(a<1||a>12||i<1||i>31)return null;if(r.assign("day",i),r.assign("month",a),t[sie]){let s=parseInt(ci(t[sie])),o=Mi(s);r.assign("year",o)}else{let s=er(e.reference.instant,i,a);r.imply("year",s)}return r}}});var eje,tje,lA,cA,np,Dy,dA,Ww,lie=y(()=>{we();Nt();Ey();eje=new RegExp("(?:(午前|午後|A.M.|P.M.|AM|PM))?(?:[\\s,,、]*)(?:([0-90-9]+|["+Object.keys(Hl).join("")+"]+)(?:\\s*)(?:時|:|:)(?:\\s*)([0-90-9]+|半|["+Object.keys(Hl).join("")+"]+)?(?:\\s*)(?:分|:|:)?(?:\\s*)([0-90-9]+|["+Object.keys(Hl).join("")+"]+)?(?:\\s*)(?:秒)?)(?:\\s*(A.M.|P.M.|AM?|PM?))?","i"),tje=new RegExp("(?:^\\s*(?:から|\\-|\\–|\\-|\\~|\\〜)\\s*)(?:(午前|午後|A.M.|P.M.|AM|PM))?(?:[\\s,,、]*)(?:([0-90-9]+|["+Object.keys(Hl).join("")+"]+)(?:\\s*)(?:時|:|:)(?:\\s*)([0-90-9]+|半|["+Object.keys(Hl).join("")+"]+)?(?:\\s*)(?:分|:|:)?(?:\\s*)([0-90-9]+|["+Object.keys(Hl).join("")+"]+)?(?:\\s*)(?:秒)?)(?:\\s*(A.M.|P.M.|AM?|PM?))?","i"),lA=1,cA=2,np=3,Dy=4,dA=5,Ww=class extends H{innerPattern(){return eje}innerExtract(e,t){if(t.index>0&&e.text[t.index-1].match(/\w/))return null;let r=e.createParsingResult(t.index,t[0]),a=0,i=0,s=-1;if(t[Dy]){let o=parseInt(ci(t[Dy]));if(isNaN(o)&&(o=Sf(t[Dy])),o>=60)return null;r.start.assign("second",o)}if(a=parseInt(ci(t[cA])),isNaN(a)&&(a=Sf(t[cA])),t[np]?t[np]==="半"?i=30:(i=parseInt(ci(t[np])),isNaN(i)&&(i=Sf(t[np]))):a>100&&(i=a%100,a=Math.floor(a/100)),i>=60||a>24)return null;if(a>=12&&(s=j.PM),t[lA]){if(a>12)return null;let o=t[lA],l=o[0].toLowerCase();o==="午前"||l==="a"?(s=j.AM,a===12&&(a=0)):(o==="午後"||l==="p")&&(s=j.PM,a!=12&&(a+=12))}else if(t[dA]){if(a>12)return null;let o=t[dA][0].toLowerCase();o==="a"&&(s=j.AM,a===12&&(a=0)),o==="p"&&(s=j.PM,a!=12&&(a+=12))}if(r.start.assign("hour",a),r.start.assign("minute",i),s>=0?r.start.assign("meridiem",s):a<12?r.start.imply("meridiem",0):r.start.imply("meridiem",1),t=tje.exec(e.text.substring(r.index+r.text.length)),!t)return r.text.match(/^\d+$/)?null:r;if(r.end=e.createParsingComponents(),a=0,i=0,s=-1,t[Dy]){let o=parseInt(ci(t[Dy]));if(isNaN(o)&&(o=Sf(t[Dy])),o>=60)return null;r.end.assign("second",o)}if(a=parseInt(ci(t[cA])),isNaN(a)&&(a=Sf(t[cA])),t[np]?t[np]==="半"?i=30:(i=parseInt(ci(t[np])),isNaN(i)&&(i=Sf(t[np]))):a>100&&(i=a%100,a=Math.floor(a/100)),i>=60||a>24)return null;if(a>=12&&(s=j.PM),t[lA]){if(a>12)return null;let o=t[lA],l=o[0].toLowerCase();o==="午前"||l==="a"?(s=j.AM,a===12&&(a=0)):(o==="午後"||l==="p")&&(s=j.PM,a!=12&&(a+=12)),r.start.isCertain("meridiem")||(s===j.AM?(r.start.imply("meridiem",j.AM),r.start.get("hour")===12&&r.start.assign("hour",0)):(r.start.imply("meridiem",1),r.start.get("hour")!=12&&r.start.assign("hour",r.start.get("hour")+12)))}else if(t[dA]){if(a>12)return null;let o=t[dA][0].toLowerCase();o==="a"&&(s=j.AM,a===12&&(a=0)),o==="p"&&(s=j.PM,a!=12&&(a+=12))}return r.text=r.text+t[0],r.end.assign("hour",a),r.end.assign("minute",i),s>=0?r.end.assign("meridiem",s):r.start.isCertain("meridiem")&&r.start.get("hour")>12?r.start.get("hour")-12>a?r.end.imply("meridiem",j.AM):a<=12&&(r.end.assign("hour",a+12),r.end.assign("meridiem",j.PM)):a>12?r.end.imply("meridiem",j.PM):a<=12&&r.end.imply("meridiem",j.AM),r.end.date().getTime(){eo();qw=class extends $r{patternBetween(){return/^\s*(の)?\s*$/i}}});var Gw,die=y(()=>{_d();Gw=class extends Ii{mergeResults(e,t,r){let a=t.clone();return a.text=t.text+e+r.text,a.start.assign("weekday",r.start.get("weekday")),a.end&&a.end.assign("weekday",r.start.get("weekday")),a}shouldMergeResults(e,t,r){return t.start.isCertain("day")&&r.start.isOnlyWeekdayComponent()&&!r.start.isCertain("hour")&&e.match(/^[,、の]?\s*$/)!==null}}});var rje,Yw,uie=y(()=>{Ey();tl();rje=new RegExp("(?:\\(|\\()(?"+Object.keys(xy).join("|")+")(?:\\)|\\))","i"),Yw=class{pattern(){return rje}extract(e,t){let r=t.groups.weekday,a=xy[r];return a===void 0?null:In(e.reference,a)}}});var ej={};Xe(ej,{Chrono:()=>ze,Meridiem:()=>j,ParsingComponents:()=>K,ParsingResult:()=>Lt,ReferenceWithTimezone:()=>Vt,Weekday:()=>We,casual:()=>JB,createCasualConfiguration:()=>pie,createConfiguration:()=>XB,parse:()=>aje,parseDate:()=>ije,strict:()=>nje});function aje(n,e,t){return JB.parse(n,e,t)}function ije(n,e,t){return JB.parseDate(n,e,t)}function pie(){let n=XB(!1);return n.parsers.unshift(new Uw),n}function XB(n=!0){let e=Gr({parsers:[new jw,new Hw,new Yw,new Vw,new Ww],refiners:[new Gw,new qw,new $w]},n);return e.refiners=e.refiners.filter(t=>!(t instanceof vf)),e}var JB,nje,mie=y(()=>{tie();rie();aie();iie();oie();lie();cie();Ni();ot();Nt();die();uie();gs();DB();JB=new ze(pie()),nje=new ze(XB(!0))});function hie(n){if(n.match(/^[0-9]{1,4}$/)){let e=parseInt(n);return e<100&&(e>50?e=e+1900:e=e+2e3),e}return n.match(/a\.?\s*c\.?/i)?(n=n.replace(/a\.?\s*c\.?/i,""),-parseInt(n)):parseInt(n)}var tj,rj,fie,uA=y(()=>{tj={domingo:0,dom:0,segunda:1,"segunda-feira":1,seg:1,terça:2,"terça-feira":2,ter:2,quarta:3,"quarta-feira":3,qua:3,quinta:4,"quinta-feira":4,qui:4,sexta:5,"sexta-feira":5,sex:5,sábado:6,sabado:6,sab:6},rj={janeiro:1,jan:1,"jan.":1,fevereiro:2,fev:2,"fev.":2,março:3,mar:3,"mar.":3,abril:4,abr:4,"abr.":4,maio:5,mai:5,"mai.":5,junho:6,jun:6,"jun.":6,julho:7,jul:7,"jul.":7,agosto:8,ago:8,"ago.":8,setembro:9,set:9,"set.":9,outubro:10,out:10,"out.":10,novembro:11,nov:11,"nov.":11,dezembro:12,dez:12,"dez.":12},fie="[0-9]{1,4}(?![^\\s]\\d)(?:\\s*[a|d]\\.?\\s*c\\.?|\\s*a\\.?\\s*d\\.?)?"});var sje,oje,lje,cje,Kw,gie=y(()=>{uA();xt();we();tl();sje=new RegExp(`(?:(?:\\,|\\(|\\()\\s*)?(?:(este|esta|passado|pr[oó]ximo)\\s*)?(${ie(tj)})(?:\\s*(?:\\,|\\)|\\)))?(?:\\s*(este|esta|passado|pr[óo]ximo)\\s*semana)?(?=\\W|\\d|$)`,"i"),oje=1,lje=2,cje=3,Kw=class extends H{innerPattern(){return sje}innerExtract(e,t){let r=t[lje].toLowerCase(),a=tj[r];if(a===void 0)return null;let i=t[oje],s=t[cje],o=i||s||"";o=o.toLowerCase();let l=null;return o=="passado"?l="this":o=="próximo"||o=="proximo"?l="next":o=="este"&&(l="this"),In(e.reference,a,l)}}});var Zw,yie=y(()=>{Rd();Zw=class extends na{primaryPrefix(){return"(?:(?:ao?|às?|das|da|de|do)\\s*)?"}followingPhase(){return"\\s*(?:\\-|\\–|\\~|\\〜|a(?:o)?|\\?)\\s*"}}});var Qw,vie=y(()=>{eo();Qw=class extends $r{patternBetween(){return new RegExp("^\\s*(?:,|à)?\\s*$")}}});var Jw,kie=y(()=>{Xs();Jw=class extends jr{patternBetween(){return/^\s*(?:-)\s*$/i}}});var dje,Tie,bie,uje,wie,Xw,Sie=y(()=>{mn();uA();uA();xt();we();dje=new RegExp(`([0-9]{1,2})(?:º|ª|°)?(?:\\s*(?:desde|de|\\-|\\–|ao?|\\s)\\s*([0-9]{1,2})(?:º|ª|°)?)?\\s*(?:de)?\\s*(?:-|/|\\s*(?:de|,)?\\s*)(${ie(rj)})(?:\\s*(?:de|,)?\\s*(${fie}))?(?=\\W|$)`,"i"),Tie=1,bie=2,uje=3,wie=4,Xw=class extends H{innerPattern(){return dje}innerExtract(e,t){let r=e.createParsingResult(t.index,t[0]),a=rj[t[uje].toLowerCase()],i=parseInt(t[Tie]);if(i>31)return t.index=t.index+t[Tie].length,null;if(r.start.assign("month",a),r.start.assign("day",i),t[wie]){let s=hie(t[wie]);r.start.assign("year",s)}else{let s=er(e.refDate,i,a);r.start.imply("year",s)}if(t[bie]){let s=parseInt(t[bie]);r.end=r.start.clone(),r.end.assign("day",s)}return r}}});var eS,Cie=y(()=>{we();ys();eS=class extends H{innerPattern(e){return/(agora|hoje|amanha|amanhã|ontem)(?=\W|$)/i}innerExtract(e,t){let r=t[0].toLowerCase(),a=e.createParsingComponents();switch(r){case"agora":return Ba(e.reference);case"hoje":return aa(e.reference);case"amanha":case"amanhã":return $a(e.reference);case"ontem":return ja(e.reference)}return a}}});var xie,tS,Eie=y(()=>{Nt();we();hs();xie=tt(Ht(),1),tS=class extends H{innerPattern(){return/(?:esta\s*)?(manha|manhã|tarde|meia-noite|meio-dia|noite)(?=\W|$)/i}innerExtract(e,t){let r=(0,xie.default)(e.refDate),a=e.createParsingComponents();switch(t[1].toLowerCase()){case"tarde":a.imply("meridiem",j.PM),a.imply("hour",15);break;case"noite":a.imply("meridiem",j.PM),a.imply("hour",22);break;case"manha":case"manhã":a.imply("meridiem",j.AM),a.imply("hour",6);break;case"meia-noite":Xo(a,r),a.imply("hour",0),a.imply("minute",0),a.imply("second",0);break;case"meio-dia":a.imply("meridiem",j.AM),a.imply("hour",12);break}return a}}});var ij={};Xe(ij,{Chrono:()=>ze,Meridiem:()=>j,ParsingComponents:()=>K,ParsingResult:()=>Lt,ReferenceWithTimezone:()=>Vt,Weekday:()=>We,casual:()=>nj,createCasualConfiguration:()=>Die,createConfiguration:()=>aj,parse:()=>mje,parseDate:()=>fje,strict:()=>pje});function mje(n,e,t){return nj.parse(n,e,t)}function fje(n,e,t){return nj.parseDate(n,e,t)}function Die(n=!0){let e=aj(!1,n);return e.parsers.push(new eS),e.parsers.push(new tS),e}function aj(n=!0,e=!0){return Gr({parsers:[new Hn(e),new Kw,new Zw,new Xw],refiners:[new Qw,new Jw]},n)}var nj,pje,Pie=y(()=>{gs();Ni();ot();Nt();Ld();gie();yie();vie();kie();Sie();Cie();Eie();nj=new ze(Die()),pje=new ze(aj(!0))});var rS,Aie=y(()=>{Xs();rS=class extends jr{patternBetween(){return/^\s*(tot|-)\s*$/i}}});var nS,Mie=y(()=>{eo();nS=class extends $r{patternBetween(){return new RegExp("^\\s*(om|na|voor|in de|,|-)?\\s*$")}}});var aS,Iie=y(()=>{we();ys();aS=class extends H{innerPattern(e){return/(nu|vandaag|morgen|morgend|gisteren)(?=\W|$)/i}innerExtract(e,t){let r=t[0].toLowerCase(),a=e.createParsingComponents();switch(r){case"nu":return Ba(e.reference);case"vandaag":return aa(e.reference);case"morgen":case"morgend":return $a(e.reference);case"gisteren":return ja(e.reference)}return a}}});var Nie,hje,gje,iS,Rie=y(()=>{Nt();we();Nie=tt(Ht(),1);hs();hje=1,gje=2,iS=class extends H{innerPattern(){return/(deze)?\s*(namiddag|avond|middernacht|ochtend|middag|'s middags|'s avonds|'s ochtends)(?=\W|$)/i}innerExtract(e,t){let r=(0,Nie.default)(e.refDate),a=e.createParsingComponents();switch(t[hje]==="deze"&&(a.assign("day",e.refDate.getDate()),a.assign("month",e.refDate.getMonth()+1),a.assign("year",e.refDate.getFullYear())),t[gje].toLowerCase()){case"namiddag":case"'s namiddags":a.imply("meridiem",j.PM),a.imply("hour",15);break;case"avond":case"'s avonds'":a.imply("meridiem",j.PM),a.imply("hour",20);break;case"middernacht":Xo(a,r),a.imply("hour",0),a.imply("minute",0),a.imply("second",0);break;case"ochtend":case"'s ochtends":a.imply("meridiem",j.AM),a.imply("hour",6);break;case"middag":case"'s middags":a.imply("meridiem",j.AM),a.imply("hour",12);break}return a}}});function vje(n){let e=n.toLowerCase();return sj[e]!==void 0?sj[e]:e==="paar"?2:e==="half"||e.match(/halve?/)?.5:parseFloat(e.replace(",","."))}function dj(n){let e=n.toLowerCase();return oj[e]!==void 0?oj[e]:(e=e.replace(/(?:ste|de)$/i,""),parseInt(e))}function mA(n){if(/voor Christus/i.test(n))return n=n.replace(/voor Christus/i,""),-parseInt(n);if(/na Christus/i.test(n))return n=n.replace(/na Christus/i,""),parseInt(n);let e=parseInt(n);return Mi(e)}function ap(n){let e={},t=n,r=_ie.exec(t);for(;r;)kje(e,r),t=t.substring(r[0].length),r=_ie.exec(t);return e}function kje(n,e){let t=vje(e[1]),r=sS[e[2].toLowerCase()];n[r]=t}var lj,Od,sj,oj,sS,yje,cj,pA,Fie,_ie,Vl,ks=y(()=>{xt();mn();lj={zondag:0,zon:0,"zon.":0,zo:0,"zo.":0,maandag:1,ma:1,"ma.":1,dinsdag:2,din:2,"din.":2,di:2,"di.":2,woensdag:3,woe:3,"woe.":3,wo:3,"wo.":3,donderdag:4,dond:4,"dond.":4,do:4,"do.":4,vrijdag:5,vrij:5,"vrij.":5,vr:5,"vr.":5,zaterdag:6,zat:6,"zat.":6,za:6,"za.":6},Od={januari:1,jan:1,"jan.":1,februari:2,feb:2,"feb.":2,maart:3,mar:3,"mar.":3,mrt:3,"mrt.":3,april:4,apr:4,"apr.":4,mei:5,juni:6,jun:6,"jun.":6,juli:7,jul:7,"jul.":7,augustus:8,aug:8,"aug.":8,september:9,sep:9,"sep.":9,sept:9,"sept.":9,oktober:10,okt:10,"okt.":10,november:11,nov:11,"nov.":11,december:12,dec:12,"dec.":12},sj={een:1,twee:2,drie:3,vier:4,vijf:5,zes:6,zeven:7,acht:8,negen:9,tien:10,elf:11,twaalf:12},oj={eerste:1,tweede:2,derde:3,vierde:4,vijfde:5,zesde:6,zevende:7,achtste:8,negende:9,tiende:10,elfde:11,twaalfde:12,dertiende:13,veertiende:14,vijftiende:15,zestiende:16,zeventiende:17,achttiende:18,negentiende:19,twintigste:20,eenentwintigste:21,tweeëntwintigste:22,drieentwintigste:23,vierentwintigste:24,vijfentwintigste:25,zesentwintigste:26,zevenentwintigste:27,achtentwintig:28,negenentwintig:29,dertigste:30,eenendertigste:31},sS={sec:"second",second:"second",seconden:"second",min:"minute",mins:"minute",minute:"minute",minuut:"minute",minuten:"minute",minuutje:"minute",h:"hour",hr:"hour",hrs:"hour",uur:"hour",u:"hour",uren:"hour",dag:"d",dagen:"d",week:"week",weken:"week",maand:"month",maanden:"month",jaar:"year",jr:"year",jaren:"year"},yje=`(?:${ie(sj)}|[0-9]+|[0-9]+[\\.,][0-9]+|halve?|half|paar)`;cj=`(?:${ie(oj)}|[0-9]{1,2}(?:ste|de)?)`;pA="(?:[1-9][0-9]{0,3}\\s*(?:voor Christus|na Christus)|[1-2][0-9]{3}|[5-9][0-9])";Fie=`(${yje})\\s{0,5}(${ie(sS)})\\s{0,5}`,_ie=new RegExp(Fie,"i"),Vl=li("(?:(?:binnen|in)\\s*)?",Fie)});var oS,Lie=y(()=>{ks();ot();we();oS=class extends H{innerPattern(){return new RegExp("(?:binnen|in|binnen de|voor)\\s*("+Vl+")(?=\\W|$)","i")}innerExtract(e,t){let r=ap(t[1]);return K.createRelativeFromReference(e.reference,r)}}});var Tje,bje,wje,Sje,lS,Oie=y(()=>{ks();xt();we();tl();Tje=new RegExp(`(?:(?:\\,|\\(|\\()\\s*)?(?:op\\s*?)?(?:(deze|vorige|volgende)\\s*(?:week\\s*)?)?(${ie(lj)})(?=\\W|$)`,"i"),bje=1,wje=2,Sje=3,lS=class extends H{innerPattern(){return Tje}innerExtract(e,t){let r=t[wje].toLowerCase(),a=lj[r],i=t[bje],s=t[Sje],o=i||s;o=o||"",o=o.toLowerCase();let l=null;return o=="vorige"?l="last":o=="volgende"?l="next":o=="deze"&&(l="this"),In(e.reference,a,l)}}});var Cje,xje,zie,Bie,jie,cS,$ie=y(()=>{mn();ks();ks();ks();xt();we();Cje=new RegExp(`(?:on\\s*?)?(${cj})(?:\\s*(?:tot|\\-|\\–|until|through|till|\\s)\\s*(${cj}))?(?:-|/|\\s*(?:of)?\\s*)(`+ie(Od)+`)(?:(?:-|/|,?\\s*)(${pA}(?![^\\s]\\d)))?(?=\\W|$)`,"i"),xje=3,zie=1,Bie=2,jie=4,cS=class extends H{innerPattern(){return Cje}innerExtract(e,t){let r=Od[t[xje].toLowerCase()],a=dj(t[zie]);if(a>31)return t.index=t.index+t[zie].length,null;let i=e.createParsingComponents({day:a,month:r});if(t[jie]){let l=mA(t[jie]);i.assign("year",l)}else{let l=er(e.refDate,a,r);i.imply("year",l)}if(!t[Bie])return i;let s=dj(t[Bie]),o=e.createParsingResult(t.index,t[0]);return o.start=i,o.end=i.clone(),o.end.assign("day",s),o}}});var Eje,Dje,Uie,Py,Hie=y(()=>{ks();mn();xt();ks();we();Eje=new RegExp(`(${ie(Od)})\\s*(?:[,-]?\\s*(${pA})?)?(?=[^\\s\\w]|\\s+[^0-9]|\\s+$|$)`,"i"),Dje=1,Uie=2,Py=class extends H{innerPattern(){return Eje}innerExtract(e,t){let r=e.createParsingComponents();r.imply("day",1);let a=t[Dje],i=Od[a.toLowerCase()];if(r.assign("month",i),t[Uie]){let s=mA(t[Uie]);r.assign("year",s)}else{let s=er(e.refDate,1,i);r.imply("year",s)}return r}}});var Pje,Aje,Mje,dS,Vie=y(()=>{we();Pje=new RegExp("([0-9]|0[1-9]|1[012])/([0-9]{4})","i"),Aje=1,Mje=2,dS=class extends H{innerPattern(){return Pje}innerExtract(e,t){let r=parseInt(t[Mje]),a=parseInt(t[Aje]);return e.createParsingComponents().imply("day",1).assign("month",a).assign("year",r)}}});var uS,Wie=y(()=>{Rd();uS=class extends na{primaryPrefix(){return"(?:(?:om)\\s*)?"}followingPhase(){return"\\s*(?:\\-|\\–|\\~|\\〜|om|\\?)\\s*"}primarySuffix(){return"(?:\\s*(?:uur))?(?!/)(?=\\W|$)"}extractPrimaryTimeComponents(e,t){return t[0].match(/^\s*\d{4}\s*$/)?null:super.extractPrimaryTimeComponents(e,t)}}});var Ije,Nje,Rje,qie,_je,pS,Gie=y(()=>{ks();xt();we();Ije=new RegExp(`([0-9]{4})[\\.\\/\\s](?:(${ie(Od)})|([0-9]{1,2}))[\\.\\/\\s]([0-9]{1,2})(?=\\W|$)`,"i"),Nje=1,Rje=2,qie=3,_je=4,pS=class extends H{innerPattern(){return Ije}innerExtract(e,t){let r=t[qie]?parseInt(t[qie]):Od[t[Rje].toLowerCase()];if(r<1||r>12)return null;let a=parseInt(t[Nje]);return{day:parseInt(t[_je]),month:r,year:a}}}});var Yie,Fje,Lje,mS,Kie=y(()=>{we();Nt();hs();Yie=tt(Ht(),1),Fje=1,Lje=2,mS=class extends H{innerPattern(e){return/(gisteren|morgen|van)(ochtend|middag|namiddag|avond|nacht)(?=\W|$)/i}innerExtract(e,t){let r=t[Fje].toLowerCase(),a=t[Lje].toLowerCase(),i=e.createParsingComponents(),s=(0,Yie.default)(e.refDate);switch(r){case"gisteren":Mr(i,s.add(-1,"day"));break;case"van":Mr(i,s);break;case"morgen":Xo(i,s);break}switch(a){case"ochtend":i.imply("meridiem",j.AM),i.imply("hour",6);break;case"middag":i.imply("meridiem",j.AM),i.imply("hour",12);break;case"namiddag":i.imply("meridiem",j.PM),i.imply("hour",15);break;case"avond":i.imply("meridiem",j.PM),i.imply("hour",20);break}return i}}});var Oje,zje,Bje,fS,Zie=y(()=>{ks();ot();we();vs();Oje=new RegExp(`(dit|deze|vorig|afgelopen|(?:aan)?komend|over|\\+|-)e?\\s*(${Vl})(?=\\W|$)`,"i"),zje=1,Bje=2,fS=class extends H{innerPattern(){return Oje}innerExtract(e,t){let r=t[zje].toLowerCase(),a=ap(t[Bje]);switch(r){case"vorig":case"afgelopen":case"-":a=Mn(a);break}return K.createRelativeFromReference(e.reference,a)}}});var Qie,jje,$je,Uje,hS,Jie=y(()=>{ks();ot();Qie=tt(Ht(),1);we();xt();jje=new RegExp(`(dit|deze|(?:aan)?komend|volgend|afgelopen|vorig)e?\\s*(${ie(sS)})(?=\\s*)(?=\\W|$)`,"i"),$je=1,Uje=2,hS=class extends H{innerPattern(){return jje}innerExtract(e,t){let r=t[$je].toLowerCase(),a=t[Uje].toLowerCase(),i=sS[a];if(r=="volgend"||r=="komend"||r=="aankomend"){let l={};return l[i]=1,K.createRelativeFromReference(e.reference,l)}if(r=="afgelopen"||r=="vorig"){let l={};return l[i]=-1,K.createRelativeFromReference(e.reference,l)}let s=e.createParsingComponents(),o=(0,Qie.default)(e.reference.instant);return a.match(/week/i)?(o=o.add(-o.get("d"),"d"),s.imply("day",o.date()),s.imply("month",o.month()+1),s.imply("year",o.year())):a.match(/maand/i)?(o=o.add(-o.date()+1,"d"),s.imply("day",o.date()),s.assign("year",o.year()),s.assign("month",o.month()+1)):a.match(/jaar/i)&&(o=o.add(-o.date()+1,"d"),o=o.add(-o.month(),"month"),s.imply("day",o.date()),s.imply("month",o.month()+1),s.assign("year",o.year())),s}}});var Hje,Vje,gS,Xie=y(()=>{ks();ot();we();vs();Hje=new RegExp("("+Vl+")(?:geleden|voor|eerder)(?=(?:\\W|$))","i"),Vje=new RegExp("("+Vl+")geleden(?=(?:\\W|$))","i"),gS=class extends H{constructor(t){super();z(this,"strictMode");this.strictMode=t}innerPattern(){return this.strictMode?Vje:Hje}innerExtract(t,r){let a=ap(r[1]),i=Mn(a);return K.createRelativeFromReference(t.reference,i)}}});var Wje,qje,Gje,yS,ese=y(()=>{ks();ot();we();Wje=new RegExp("("+Vl+")(later|na|vanaf nu|voortaan|vooruit|uit)(?=(?:\\W|$))","i"),qje=new RegExp("("+Vl+")(later|vanaf nu)(?=(?:\\W|$))","i"),Gje=1,yS=class extends H{constructor(t){super();z(this,"strictMode");this.strictMode=t}innerPattern(){return this.strictMode?qje:Wje}innerExtract(t,r){let a=ap(r[Gje]);return K.createRelativeFromReference(t.reference,a)}}});var mj={};Xe(mj,{Chrono:()=>ze,Meridiem:()=>j,ParsingComponents:()=>K,ParsingResult:()=>Lt,ReferenceWithTimezone:()=>Vt,Weekday:()=>We,casual:()=>uj,createCasualConfiguration:()=>tse,createConfiguration:()=>pj,parse:()=>Kje,parseDate:()=>Zje,strict:()=>Yje});function Kje(n,e,t){return uj.parse(n,e,t)}function Zje(n,e,t){return uj.parseDate(n,e,t)}function tse(n=!0){let e=pj(!1,n);return e.parsers.unshift(new aS),e.parsers.unshift(new iS),e.parsers.unshift(new mS),e.parsers.unshift(new Py),e.parsers.unshift(new hS),e.parsers.unshift(new fS),e}function pj(n=!0,e=!0){return Gr({parsers:[new Hn(e),new oS,new cS,new Py,new lS,new pS,new dS,new uS(n),new gS(n),new yS(n)],refiners:[new nS,new rS]},n)}var uj,Yje,rse=y(()=>{gs();Ni();ot();Nt();Aie();Mie();Iie();Rie();Ld();Lie();Oie();$ie();Hie();Vie();Wie();Gie();Kie();Zie();Jie();Xie();ese();uj=new ze(tse()),Yje=new ze(pj(!0))});function ro(n){let e=0;for(let t=0;t{ia={零:0,"〇":0,一:1,二:2,两:2,三:3,四:4,五:5,六:6,七:7,八:8,九:9,十:10},Ay={天:0,日:0,一:1,二:2,三:3,四:4,五:5,六:6}});var ise,fj,ase,hj,Cf,gj=y(()=>{ise=tt(Ht(),1);we();My();fj=1,ase=2,hj=3,Cf=class extends H{innerPattern(){return new RegExp("(\\d{2,4}|["+Object.keys(ia).join("")+"]{4}|["+Object.keys(ia).join("")+"]{2})?(?:\\s*)(?:年)?(?:[\\s|,|,]*)(\\d{1,2}|["+Object.keys(ia).join("")+"]{1,3})(?:\\s*)(?:月)(?:\\s*)(\\d{1,2}|["+Object.keys(ia).join("")+"]{1,3})?(?:\\s*)(?:日|号)?")}innerExtract(e,t){let r=(0,ise.default)(e.refDate),a=e.createParsingResult(t.index,t[0]),i=parseInt(t[ase]);if(isNaN(i)&&(i=ro(t[ase])),a.start.assign("month",i),t[hj]){let s=parseInt(t[hj]);isNaN(s)&&(s=ro(t[hj])),a.start.assign("day",s)}else a.start.imply("day",r.date());if(t[fj]){let s=parseInt(t[fj]);isNaN(s)&&(s=nse(t[fj])),a.start.assign("year",s)}else a.start.imply("year",r.year());return a}}});var sse,Qje,yj,Jje,xf,vj=y(()=>{sse=tt(Ht(),1);we();My();Qje=new RegExp("(\\d+|["+Object.keys(ia).join("")+"]+|半|几)(?:\\s*)(?:个)?(秒(?:钟)?|分钟|小时|钟|日|天|星期|礼拜|月|年)(?:(?:之|过)?后|(?:之)?内)","i"),yj=1,Jje=2,xf=class extends H{innerPattern(){return Qje}innerExtract(e,t){let r=e.createParsingResult(t.index,t[0]),a=parseInt(t[yj]);if(isNaN(a)&&(a=ro(t[yj])),isNaN(a)){let l=t[yj];if(l==="几")a=3;else if(l==="半")a=.5;else return null}let i=(0,sse.default)(e.refDate),o=t[Jje][0];return o.match(/[日天星礼月年]/)?(o=="日"||o=="天"?i=i.add(a,"d"):o=="星"||o=="礼"?i=i.add(a*7,"d"):o=="月"?i=i.add(a,"month"):o=="年"&&(i=i.add(a,"year")),r.start.assign("year",i.year()),r.start.assign("month",i.month()+1),r.start.assign("day",i.date()),r):(o=="秒"?i=i.add(a,"second"):o=="分"?i=i.add(a,"minute"):(o=="小"||o=="钟")&&(i=i.add(a,"hour")),r.start.imply("year",i.year()),r.start.imply("month",i.month()+1),r.start.imply("day",i.date()),r.start.assign("hour",i.hour()),r.start.assign("minute",i.minute()),r.start.assign("second",i.second()),r)}}});var ose,Xje,Ef,kj=y(()=>{ose=tt(Ht(),1);we();My();Xje=new RegExp("(?上|下|这)(?:个)?(?:星期|礼拜|周)(?"+Object.keys(Ay).join("|")+")"),Ef=class extends H{innerPattern(){return Xje}innerExtract(e,t){let r=e.createParsingResult(t.index,t[0]),a=t.groups.weekday,i=Ay[a];if(i===void 0)return null;let s=null,o=t.groups.prefix;o=="上"?s="last":o=="下"?s="next":o=="这"&&(s="this");let l=(0,ose.default)(e.refDate),c=!1,d=l.day();return s=="last"||s=="past"?(l=l.day(i-7),c=!0):s=="next"?(l=l.day(i+7),c=!0):s=="this"?l=l.day(i):Math.abs(i-7-d){lse=tt(Ht(),1);we();My();e$e=new RegExp("(?:从|自)?(?:(今|明|前|大前|后|大后|昨)(早|朝|晚)|(上(?:午)|早(?:上)|下(?:午)|晚(?:上)|夜(?:晚)?|中(?:午)|凌(?:晨))|(今|明|前|大前|后|大后|昨)(?:日|天)(?:[\\s,,]*)(?:(上(?:午)|早(?:上)|下(?:午)|晚(?:上)|夜(?:晚)?|中(?:午)|凌(?:晨)))?)?(?:[\\s,,]*)(?:(\\d+|["+Object.keys(ia).join("")+"]+)(?:\\s*)(?:点|时|:|:)(?:\\s*)(\\d+|半|正|整|["+Object.keys(ia).join("")+"]+)?(?:\\s*)(?:分|:|:)?(?:\\s*)(\\d+|["+Object.keys(ia).join("")+"]+)?(?:\\s*)(?:秒)?)(?:\\s*(A.M.|P.M.|AM?|PM?))?","i"),t$e=new RegExp("(?:^\\s*(?:到|至|\\-|\\–|\\~|\\〜)\\s*)(?:(今|明|前|大前|后|大后|昨)(早|朝|晚)|(上(?:午)|早(?:上)|下(?:午)|晚(?:上)|夜(?:晚)?|中(?:午)|凌(?:晨))|(今|明|前|大前|后|大后|昨)(?:日|天)(?:[\\s,,]*)(?:(上(?:午)|早(?:上)|下(?:午)|晚(?:上)|夜(?:晚)?|中(?:午)|凌(?:晨)))?)?(?:[\\s,,]*)(?:(\\d+|["+Object.keys(ia).join("")+"]+)(?:\\s*)(?:点|时|:|:)(?:\\s*)(\\d+|半|正|整|["+Object.keys(ia).join("")+"]+)?(?:\\s*)(?:分|:|:)?(?:\\s*)(\\d+|["+Object.keys(ia).join("")+"]+)?(?:\\s*)(?:秒)?)(?:\\s*(A.M.|P.M.|AM?|PM?))?","i"),fA=1,hA=2,gA=3,yA=4,vA=5,kA=6,no=7,Iy=8,TA=9,Df=class extends H{innerPattern(){return e$e}innerExtract(e,t){if(t.index>0&&e.text[t.index-1].match(/\w/))return null;let r=(0,lse.default)(e.refDate),a=e.createParsingResult(t.index,t[0]),i=r.clone();if(t[fA]){let d=t[fA];d=="明"?r.hour()>1&&(i=i.add(1,"day")):d=="昨"?i=i.add(-1,"day"):d=="前"?i=i.add(-2,"day"):d=="大前"?i=i.add(-3,"day"):d=="后"?i=i.add(2,"day"):d=="大后"&&(i=i.add(3,"day")),a.start.assign("day",i.date()),a.start.assign("month",i.month()+1),a.start.assign("year",i.year())}else if(t[yA]){let d=t[yA];d=="明"?i=i.add(1,"day"):d=="昨"?i=i.add(-1,"day"):d=="前"?i=i.add(-2,"day"):d=="大前"?i=i.add(-3,"day"):d=="后"?i=i.add(2,"day"):d=="大后"&&(i=i.add(3,"day")),a.start.assign("day",i.date()),a.start.assign("month",i.month()+1),a.start.assign("year",i.year())}else a.start.imply("day",i.date()),a.start.imply("month",i.month()+1),a.start.imply("year",i.year());let s=0,o=0,l=-1;if(t[Iy]){let d=parseInt(t[Iy]);if(isNaN(d)&&(d=ro(t[Iy])),d>=60)return null;a.start.assign("second",d)}if(s=parseInt(t[kA]),isNaN(s)&&(s=ro(t[kA])),t[no]?t[no]=="半"?o=30:t[no]=="正"||t[no]=="整"?o=0:(o=parseInt(t[no]),isNaN(o)&&(o=ro(t[no]))):s>100&&(o=s%100,s=Math.floor(s/100)),o>=60||s>24)return null;if(s>=12&&(l=1),t[TA]){if(s>12)return null;let d=t[TA][0].toLowerCase();d=="a"&&(l=0,s==12&&(s=0)),d=="p"&&(l=1,s!=12&&(s+=12))}else if(t[hA]){let u=t[hA][0];u=="早"?(l=0,s==12&&(s=0)):u=="晚"&&(l=1,s!=12&&(s+=12))}else if(t[gA]){let u=t[gA][0];u=="上"||u=="早"||u=="凌"?(l=0,s==12&&(s=0)):(u=="下"||u=="晚")&&(l=1,s!=12&&(s+=12))}else if(t[vA]){let u=t[vA][0];u=="上"||u=="早"||u=="凌"?(l=0,s==12&&(s=0)):(u=="下"||u=="晚")&&(l=1,s!=12&&(s+=12))}if(a.start.assign("hour",s),a.start.assign("minute",o),l>=0?a.start.assign("meridiem",l):s<12?a.start.imply("meridiem",0):a.start.imply("meridiem",1),t=t$e.exec(e.text.substring(a.index+a.text.length)),!t)return a.text.match(/^\d+$/)?null:a;let c=i.clone();if(a.end=e.createParsingComponents(),t[fA]){let d=t[fA];d=="明"?r.hour()>1&&(c=c.add(1,"day")):d=="昨"?c=c.add(-1,"day"):d=="前"?c=c.add(-2,"day"):d=="大前"?c=c.add(-3,"day"):d=="后"?c=c.add(2,"day"):d=="大后"&&(c=c.add(3,"day")),a.end.assign("day",c.date()),a.end.assign("month",c.month()+1),a.end.assign("year",c.year())}else if(t[yA]){let d=t[yA];d=="明"?c=c.add(1,"day"):d=="昨"?c=c.add(-1,"day"):d=="前"?c=c.add(-2,"day"):d=="大前"?c=c.add(-3,"day"):d=="后"?c=c.add(2,"day"):d=="大后"&&(c=c.add(3,"day")),a.end.assign("day",c.date()),a.end.assign("month",c.month()+1),a.end.assign("year",c.year())}else a.end.imply("day",c.date()),a.end.imply("month",c.month()+1),a.end.imply("year",c.year());if(s=0,o=0,l=-1,t[Iy]){let d=parseInt(t[Iy]);if(isNaN(d)&&(d=ro(t[Iy])),d>=60)return null;a.end.assign("second",d)}if(s=parseInt(t[kA]),isNaN(s)&&(s=ro(t[kA])),t[no]?t[no]=="半"?o=30:t[no]=="正"||t[no]=="整"?o=0:(o=parseInt(t[no]),isNaN(o)&&(o=ro(t[no]))):s>100&&(o=s%100,s=Math.floor(s/100)),o>=60||s>24)return null;if(s>=12&&(l=1),t[TA]){if(s>12)return null;let d=t[TA][0].toLowerCase();d=="a"&&(l=0,s==12&&(s=0)),d=="p"&&(l=1,s!=12&&(s+=12)),a.start.isCertain("meridiem")||(l==0?(a.start.imply("meridiem",0),a.start.get("hour")==12&&a.start.assign("hour",0)):(a.start.imply("meridiem",1),a.start.get("hour")!=12&&a.start.assign("hour",a.start.get("hour")+12)))}else if(t[hA]){let u=t[hA][0];u=="早"?(l=0,s==12&&(s=0)):u=="晚"&&(l=1,s!=12&&(s+=12))}else if(t[gA]){let u=t[gA][0];u=="上"||u=="早"||u=="凌"?(l=0,s==12&&(s=0)):(u=="下"||u=="晚")&&(l=1,s!=12&&(s+=12))}else if(t[vA]){let u=t[vA][0];u=="上"||u=="早"||u=="凌"?(l=0,s==12&&(s=0)):(u=="下"||u=="晚")&&(l=1,s!=12&&(s+=12))}return a.text=a.text+t[0],a.end.assign("hour",s),a.end.assign("minute",o),l>=0?a.end.assign("meridiem",l):a.start.isCertain("meridiem")&&a.start.get("meridiem")==1&&a.start.get("hour")>s?a.end.imply("meridiem",0):s>12&&a.end.imply("meridiem",1),a.end.date().getTime(){cse=tt(Ht(),1);we();My();r$e=new RegExp("(?:星期|礼拜|周)(?"+Object.keys(Ay).join("|")+")"),Pf=class extends H{innerPattern(){return r$e}innerExtract(e,t){let r=e.createParsingResult(t.index,t[0]),a=t.groups.weekday,i=Ay[a];if(i===void 0)return null;let s=(0,cse.default)(e.refDate),o=!1,l=s.day();return Math.abs(i-7-l){mse=tt(Ht(),1);we();n$e=1,dse=2,a$e=3,use=4,pse=5,i$e=6,Af=class extends H{innerPattern(e){return new RegExp("(而家|立(?:刻|即)|即刻)|(今|明|前|大前|後|大後|聽|昨|尋|琴)(早|朝|晚)|(上(?:午|晝)|朝(?:早)|早(?:上)|下(?:午|晝)|晏(?:晝)|晚(?:上)|夜(?:晚)?|中(?:午)|凌(?:晨))|(今|明|前|大前|後|大後|聽|昨|尋|琴)(?:日|天)(?:[\\s|,|,]*)(?:(上(?:午|晝)|朝(?:早)|早(?:上)|下(?:午|晝)|晏(?:晝)|晚(?:上)|夜(?:晚)?|中(?:午)|凌(?:晨)))?","i")}innerExtract(e,t){let r=t.index,a=e.createParsingResult(r,t[0]),i=(0,mse.default)(e.refDate),s=i;if(t[n$e])a.start.imply("hour",i.hour()),a.start.imply("minute",i.minute()),a.start.imply("second",i.second()),a.start.imply("millisecond",i.millisecond());else if(t[dse]){let o=t[dse],l=t[a$e];o=="明"||o=="聽"?i.hour()>1&&(s=s.add(1,"day")):o=="昨"||o=="尋"||o=="琴"?s=s.add(-1,"day"):o=="前"?s=s.add(-2,"day"):o=="大前"?s=s.add(-3,"day"):o=="後"?s=s.add(2,"day"):o=="大後"&&(s=s.add(3,"day")),l=="早"||l=="朝"?a.start.imply("hour",6):l=="晚"&&(a.start.imply("hour",22),a.start.imply("meridiem",1))}else if(t[use]){let l=t[use][0];l=="早"||l=="朝"||l=="上"?a.start.imply("hour",6):l=="下"||l=="晏"?(a.start.imply("hour",15),a.start.imply("meridiem",1)):l=="中"?(a.start.imply("hour",12),a.start.imply("meridiem",1)):l=="夜"||l=="晚"?(a.start.imply("hour",22),a.start.imply("meridiem",1)):l=="凌"&&a.start.imply("hour",0)}else if(t[pse]){let o=t[pse];o=="明"||o=="聽"?i.hour()>1&&(s=s.add(1,"day")):o=="昨"||o=="尋"||o=="琴"?s=s.add(-1,"day"):o=="前"?s=s.add(-2,"day"):o=="大前"?s=s.add(-3,"day"):o=="後"?s=s.add(2,"day"):o=="大後"&&(s=s.add(3,"day"));let l=t[i$e];if(l){let c=l[0];c=="早"||c=="朝"||c=="上"?a.start.imply("hour",6):c=="下"||c=="晏"?(a.start.imply("hour",15),a.start.imply("meridiem",1)):c=="中"?(a.start.imply("hour",12),a.start.imply("meridiem",1)):c=="夜"||c=="晚"?(a.start.imply("hour",22),a.start.imply("meridiem",1)):c=="凌"&&a.start.imply("hour",0)}}return a.start.assign("day",s.date()),a.start.assign("month",s.month()+1),a.start.assign("year",s.year()),a}}});function ao(n){let e=0;for(let t=0;t{sa={零:0,一:1,二:2,兩:2,三:3,四:4,五:5,六:6,七:7,八:8,九:9,十:10,廿:20,卅:30},Ny={天:0,日:0,一:1,二:2,三:3,四:4,五:5,六:6}});var gse,Sj,hse,Cj,Mf,xj=y(()=>{gse=tt(Ht(),1);we();Ry();Sj=1,hse=2,Cj=3,Mf=class extends H{innerPattern(){return new RegExp("(\\d{2,4}|["+Object.keys(sa).join("")+"]{4}|["+Object.keys(sa).join("")+"]{2})?(?:\\s*)(?:年)?(?:[\\s|,|,]*)(\\d{1,2}|["+Object.keys(sa).join("")+"]{1,2})(?:\\s*)(?:月)(?:\\s*)(\\d{1,2}|["+Object.keys(sa).join("")+"]{1,2})?(?:\\s*)(?:日|號)?")}innerExtract(e,t){let r=(0,gse.default)(e.refDate),a=e.createParsingResult(t.index,t[0]),i=parseInt(t[hse]);if(isNaN(i)&&(i=ao(t[hse])),a.start.assign("month",i),t[Cj]){let s=parseInt(t[Cj]);isNaN(s)&&(s=ao(t[Cj])),a.start.assign("day",s)}else a.start.imply("day",r.date());if(t[Sj]){let s=parseInt(t[Sj]);isNaN(s)&&(s=fse(t[Sj])),a.start.assign("year",s)}else a.start.imply("year",r.year());return a}}});var yse,s$e,Ej,o$e,If,Dj=y(()=>{yse=tt(Ht(),1);we();Ry();s$e=new RegExp("(\\d+|["+Object.keys(sa).join("")+"]+|半|幾)(?:\\s*)(?:個)?(秒(?:鐘)?|分鐘|小時|鐘|日|天|星期|禮拜|月|年)(?:(?:之|過)?後|(?:之)?內)","i"),Ej=1,o$e=2,If=class extends H{innerPattern(){return s$e}innerExtract(e,t){let r=e.createParsingResult(t.index,t[0]),a=parseInt(t[Ej]);if(isNaN(a)&&(a=ao(t[Ej])),isNaN(a)){let l=t[Ej];if(l==="幾")a=3;else if(l==="半")a=.5;else return null}let i=(0,yse.default)(e.refDate),o=t[o$e][0];return o.match(/[日天星禮月年]/)?(o=="日"||o=="天"?i=i.add(a,"d"):o=="星"||o=="禮"?i=i.add(a*7,"d"):o=="月"?i=i.add(a,"month"):o=="年"&&(i=i.add(a,"year")),r.start.assign("year",i.year()),r.start.assign("month",i.month()+1),r.start.assign("day",i.date()),r):(o=="秒"?i=i.add(a,"second"):o=="分"?i=i.add(a,"minute"):(o=="小"||o=="鐘")&&(i=i.add(a,"hour")),r.start.imply("year",i.year()),r.start.imply("month",i.month()+1),r.start.imply("day",i.date()),r.start.assign("hour",i.hour()),r.start.assign("minute",i.minute()),r.start.assign("second",i.second()),r)}}});var vse,l$e,Nf,Pj=y(()=>{vse=tt(Ht(),1);we();Ry();l$e=new RegExp("(?上|今|下|這|呢)(?:個)?(?:星期|禮拜|週)(?"+Object.keys(Ny).join("|")+")"),Nf=class extends H{innerPattern(){return l$e}innerExtract(e,t){let r=e.createParsingResult(t.index,t[0]),a=t.groups.weekday,i=Ny[a];if(i===void 0)return null;let s=null,o=t.groups.prefix;o=="上"?s="last":o=="下"?s="next":(o=="今"||o=="這"||o=="呢")&&(s="this");let l=(0,vse.default)(e.refDate),c=!1,d=l.day();return s=="last"||s=="past"?(l=l.day(i-7),c=!0):s=="next"?(l=l.day(i+7),c=!0):s=="this"?l=l.day(i):Math.abs(i-7-d){kse=tt(Ht(),1);we();Ry();c$e=new RegExp("(?:由|從|自)?(?:(今|明|前|大前|後|大後|聽|昨|尋|琴)(早|朝|晚)|(上(?:午|晝)|朝(?:早)|早(?:上)|下(?:午|晝)|晏(?:晝)|晚(?:上)|夜(?:晚)?|中(?:午)|凌(?:晨))|(今|明|前|大前|後|大後|聽|昨|尋|琴)(?:日|天)(?:[\\s,,]*)(?:(上(?:午|晝)|朝(?:早)|早(?:上)|下(?:午|晝)|晏(?:晝)|晚(?:上)|夜(?:晚)?|中(?:午)|凌(?:晨)))?)?(?:[\\s,,]*)(?:(\\d+|["+Object.keys(sa).join("")+"]+)(?:\\s*)(?:點|時|:|:)(?:\\s*)(\\d+|半|正|整|["+Object.keys(sa).join("")+"]+)?(?:\\s*)(?:分|:|:)?(?:\\s*)(\\d+|["+Object.keys(sa).join("")+"]+)?(?:\\s*)(?:秒)?)(?:\\s*(A.M.|P.M.|AM?|PM?))?","i"),d$e=new RegExp("(?:^\\s*(?:到|至|\\-|\\–|\\~|\\〜)\\s*)(?:(今|明|前|大前|後|大後|聽|昨|尋|琴)(早|朝|晚)|(上(?:午|晝)|朝(?:早)|早(?:上)|下(?:午|晝)|晏(?:晝)|晚(?:上)|夜(?:晚)?|中(?:午)|凌(?:晨))|(今|明|前|大前|後|大後|聽|昨|尋|琴)(?:日|天)(?:[\\s,,]*)(?:(上(?:午|晝)|朝(?:早)|早(?:上)|下(?:午|晝)|晏(?:晝)|晚(?:上)|夜(?:晚)?|中(?:午)|凌(?:晨)))?)?(?:[\\s,,]*)(?:(\\d+|["+Object.keys(sa).join("")+"]+)(?:\\s*)(?:點|時|:|:)(?:\\s*)(\\d+|半|正|整|["+Object.keys(sa).join("")+"]+)?(?:\\s*)(?:分|:|:)?(?:\\s*)(\\d+|["+Object.keys(sa).join("")+"]+)?(?:\\s*)(?:秒)?)(?:\\s*(A.M.|P.M.|AM?|PM?))?","i"),bA=1,wA=2,SA=3,CA=4,xA=5,EA=6,io=7,_y=8,DA=9,Rf=class extends H{innerPattern(){return c$e}innerExtract(e,t){if(t.index>0&&e.text[t.index-1].match(/\w/))return null;let r=(0,kse.default)(e.refDate),a=e.createParsingResult(t.index,t[0]),i=r.clone();if(t[bA]){var s=t[bA];s=="明"||s=="聽"?r.hour()>1&&(i=i.add(1,"day")):s=="昨"||s=="尋"||s=="琴"?i=i.add(-1,"day"):s=="前"?i=i.add(-2,"day"):s=="大前"?i=i.add(-3,"day"):s=="後"?i=i.add(2,"day"):s=="大後"&&(i=i.add(3,"day")),a.start.assign("day",i.date()),a.start.assign("month",i.month()+1),a.start.assign("year",i.year())}else if(t[CA]){var o=t[CA];o=="明"||o=="聽"?i=i.add(1,"day"):o=="昨"||o=="尋"||o=="琴"?i=i.add(-1,"day"):o=="前"?i=i.add(-2,"day"):o=="大前"?i=i.add(-3,"day"):o=="後"?i=i.add(2,"day"):o=="大後"&&(i=i.add(3,"day")),a.start.assign("day",i.date()),a.start.assign("month",i.month()+1),a.start.assign("year",i.year())}else a.start.imply("day",i.date()),a.start.imply("month",i.month()+1),a.start.imply("year",i.year());let l=0,c=0,d=-1;if(t[_y]){var u=parseInt(t[_y]);if(isNaN(u)&&(u=ao(t[_y])),u>=60)return null;a.start.assign("second",u)}if(l=parseInt(t[EA]),isNaN(l)&&(l=ao(t[EA])),t[io]?t[io]=="半"?c=30:t[io]=="正"||t[io]=="整"?c=0:(c=parseInt(t[io]),isNaN(c)&&(c=ao(t[io]))):l>100&&(c=l%100,l=Math.floor(l/100)),c>=60||l>24)return null;if(l>=12&&(d=1),t[DA]){if(l>12)return null;var p=t[DA][0].toLowerCase();p=="a"&&(d=0,l==12&&(l=0)),p=="p"&&(d=1,l!=12&&(l+=12))}else if(t[wA]){var m=t[wA],f=m[0];f=="朝"||f=="早"?(d=0,l==12&&(l=0)):f=="晚"&&(d=1,l!=12&&(l+=12))}else if(t[SA]){var h=t[SA],g=h[0];g=="上"||g=="朝"||g=="早"||g=="凌"?(d=0,l==12&&(l=0)):(g=="下"||g=="晏"||g=="晚")&&(d=1,l!=12&&(l+=12))}else if(t[xA]){var v=t[xA],k=v[0];k=="上"||k=="朝"||k=="早"||k=="凌"?(d=0,l==12&&(l=0)):(k=="下"||k=="晏"||k=="晚")&&(d=1,l!=12&&(l+=12))}if(a.start.assign("hour",l),a.start.assign("minute",c),d>=0?a.start.assign("meridiem",d):l<12?a.start.imply("meridiem",0):a.start.imply("meridiem",1),t=d$e.exec(e.text.substring(a.index+a.text.length)),!t)return a.text.match(/^\d+$/)?null:a;let T=i.clone();if(a.end=e.createParsingComponents(),t[bA]){var s=t[bA];s=="明"||s=="聽"?r.hour()>1&&(T=T.add(1,"day")):s=="昨"||s=="尋"||s=="琴"?T=T.add(-1,"day"):s=="前"?T=T.add(-2,"day"):s=="大前"?T=T.add(-3,"day"):s=="後"?T=T.add(2,"day"):s=="大後"&&(T=T.add(3,"day")),a.end.assign("day",T.date()),a.end.assign("month",T.month()+1),a.end.assign("year",T.year())}else if(t[CA]){var o=t[CA];o=="明"||o=="聽"?T=T.add(1,"day"):o=="昨"||o=="尋"||o=="琴"?T=T.add(-1,"day"):o=="前"?T=T.add(-2,"day"):o=="大前"?T=T.add(-3,"day"):o=="後"?T=T.add(2,"day"):o=="大後"&&(T=T.add(3,"day")),a.end.assign("day",T.date()),a.end.assign("month",T.month()+1),a.end.assign("year",T.year())}else a.end.imply("day",T.date()),a.end.imply("month",T.month()+1),a.end.imply("year",T.year());if(l=0,c=0,d=-1,t[_y]){var u=parseInt(t[_y]);if(isNaN(u)&&(u=ao(t[_y])),u>=60)return null;a.end.assign("second",u)}if(l=parseInt(t[EA]),isNaN(l)&&(l=ao(t[EA])),t[io]?t[io]=="半"?c=30:t[io]=="正"||t[io]=="整"?c=0:(c=parseInt(t[io]),isNaN(c)&&(c=ao(t[io]))):l>100&&(c=l%100,l=Math.floor(l/100)),c>=60||l>24)return null;if(l>=12&&(d=1),t[DA]){if(l>12)return null;var p=t[DA][0].toLowerCase();p=="a"&&(d=0,l==12&&(l=0)),p=="p"&&(d=1,l!=12&&(l+=12)),a.start.isCertain("meridiem")||(d==0?(a.start.imply("meridiem",0),a.start.get("hour")==12&&a.start.assign("hour",0)):(a.start.imply("meridiem",1),a.start.get("hour")!=12&&a.start.assign("hour",a.start.get("hour")+12)))}else if(t[wA]){var m=t[wA],f=m[0];f=="朝"||f=="早"?(d=0,l==12&&(l=0)):f=="晚"&&(d=1,l!=12&&(l+=12))}else if(t[SA]){var h=t[SA],g=h[0];g=="上"||g=="朝"||g=="早"||g=="凌"?(d=0,l==12&&(l=0)):(g=="下"||g=="晏"||g=="晚")&&(d=1,l!=12&&(l+=12))}else if(t[xA]){var v=t[xA],k=v[0];k=="上"||k=="朝"||k=="早"||k=="凌"?(d=0,l==12&&(l=0)):(k=="下"||k=="晏"||k=="晚")&&(d=1,l!=12&&(l+=12))}return a.text=a.text+t[0],a.end.assign("hour",l),a.end.assign("minute",c),d>=0?a.end.assign("meridiem",d):a.start.isCertain("meridiem")&&a.start.get("meridiem")==1&&a.start.get("hour")>l?a.end.imply("meridiem",0):l>12&&a.end.imply("meridiem",1),a.end.date().getTime(){Tse=tt(Ht(),1);we();Ry();u$e=new RegExp("(?:星期|禮拜|週)(?"+Object.keys(Ny).join("|")+")"),_f=class extends H{innerPattern(){return u$e}innerExtract(e,t){let r=e.createParsingResult(t.index,t[0]),a=t.groups.weekday,i=Ny[a];if(i===void 0)return null;let s=(0,Tse.default)(e.refDate),o=!1,l=s.day();return Math.abs(i-7-l){Xs();Ff=class extends jr{patternBetween(){return/^\s*(至|到|\-|\~|~|-|ー)\s*$/i}}});var Lf,Nj=y(()=>{eo();Lf=class extends $r{patternBetween(){return/^\s*$/i}}});var PA={};Xe(PA,{Chrono:()=>ze,Meridiem:()=>j,ParsingComponents:()=>K,ParsingResult:()=>Lt,ReferenceWithTimezone:()=>Vt,Weekday:()=>We,casual:()=>Rj,createCasualConfiguration:()=>_j,createConfiguration:()=>Fj,hant:()=>p$e,parse:()=>f$e,parseDate:()=>h$e,strict:()=>m$e});function f$e(n,e,t){return Rj.parse(n,e,t)}function h$e(n,e,t){return Rj.parseDate(n,e,t)}function _j(){let n=Fj();return n.parsers.unshift(new Af),n}function Fj(){let n=Gr({parsers:[new Mf,new Nf,new _f,new Rf,new If],refiners:[new Ff,new Lf]});return n.refiners=n.refiners.filter(e=>!(e instanceof el)),n}var p$e,Rj,m$e,bse=y(()=>{aw();gs();Ni();ot();Nt();wj();xj();Dj();Pj();Aj();Mj();Ij();Nj();p$e=new ze(_j()),Rj=new ze(_j()),m$e=new ze(Fj())});var xse,g$e,wse,y$e,Sse,Cse,v$e,vS,Ese=y(()=>{xse=tt(Ht(),1);we();g$e=1,wse=2,y$e=3,Sse=4,Cse=5,v$e=6,vS=class extends H{innerPattern(e){return new RegExp("(现在|立(?:刻|即)|即刻)|(今|明|前|大前|后|大后|昨)(早|晚)|(上(?:午)|早(?:上)|下(?:午)|晚(?:上)|夜(?:晚)?|中(?:午)|凌(?:晨))|(今|明|前|大前|后|大后|昨)(?:日|天)(?:[\\s|,|,]*)(?:(上(?:午)|早(?:上)|下(?:午)|晚(?:上)|夜(?:晚)?|中(?:午)|凌(?:晨)))?","i")}innerExtract(e,t){let r=t.index,a=e.createParsingResult(r,t[0]),i=(0,xse.default)(e.refDate),s=i;if(t[g$e])a.start.imply("hour",i.hour()),a.start.imply("minute",i.minute()),a.start.imply("second",i.second()),a.start.imply("millisecond",i.millisecond());else if(t[wse]){let o=t[wse],l=t[y$e];o=="明"?i.hour()>1&&(s=s.add(1,"day")):o=="昨"?s=s.add(-1,"day"):o=="前"?s=s.add(-2,"day"):o=="大前"?s=s.add(-3,"day"):o=="后"?s=s.add(2,"day"):o=="大后"&&(s=s.add(3,"day")),l=="早"?a.start.imply("hour",6):l=="晚"&&(a.start.imply("hour",22),a.start.imply("meridiem",1))}else if(t[Sse]){let l=t[Sse][0];l=="早"||l=="上"?a.start.imply("hour",6):l=="下"?(a.start.imply("hour",15),a.start.imply("meridiem",1)):l=="中"?(a.start.imply("hour",12),a.start.imply("meridiem",1)):l=="夜"||l=="晚"?(a.start.imply("hour",22),a.start.imply("meridiem",1)):l=="凌"&&a.start.imply("hour",0)}else if(t[Cse]){let o=t[Cse];o=="明"?i.hour()>1&&(s=s.add(1,"day")):o=="昨"?s=s.add(-1,"day"):o=="前"?s=s.add(-2,"day"):o=="大前"?s=s.add(-3,"day"):o=="后"?s=s.add(2,"day"):o=="大后"&&(s=s.add(3,"day"));let l=t[v$e];if(l){let c=l[0];c=="早"||c=="上"?a.start.imply("hour",6):c=="下"?(a.start.imply("hour",15),a.start.imply("meridiem",1)):c=="中"?(a.start.imply("hour",12),a.start.imply("meridiem",1)):c=="夜"||c=="晚"?(a.start.imply("hour",22),a.start.imply("meridiem",1)):c=="凌"&&a.start.imply("hour",0)}}return a.start.assign("day",s.date()),a.start.assign("month",s.month()+1),a.start.assign("year",s.year()),a}}});var kS,Dse=y(()=>{Xs();kS=class extends jr{patternBetween(){return/^\s*(至|到|-|~|~|-|ー)\s*$/i}}});var TS,Pse=y(()=>{eo();TS=class extends $r{patternBetween(){return/^\s*$/i}}});var AA={};Xe(AA,{Chrono:()=>ze,Meridiem:()=>j,ParsingComponents:()=>K,ParsingResult:()=>Lt,ReferenceWithTimezone:()=>Vt,Weekday:()=>We,casual:()=>Lj,createCasualConfiguration:()=>Oj,createConfiguration:()=>zj,hans:()=>k$e,parse:()=>b$e,parseDate:()=>w$e,strict:()=>T$e});function b$e(n,e,t){return Lj.parse(n,e,t)}function w$e(n,e,t){return Lj.parseDate(n,e,t)}function Oj(){let n=zj();return n.parsers.unshift(new vS),n}function zj(){let n=Gr({parsers:[new Cf,new Ef,new Pf,new Df,new xf],refiners:[new kS,new TS]});return n.refiners=n.refiners.filter(e=>!(e instanceof el)),n}var k$e,Lj,T$e,Ase=y(()=>{aw();gs();Ni();ot();Nt();Ese();gj();vj();kj();Tj();bj();Dse();Pse();k$e=new ze(Oj()),Lj=new ze(Oj()),T$e=new ze(zj())});var $j={};Xe($j,{Chrono:()=>ze,Meridiem:()=>j,ParsingComponents:()=>K,ParsingResult:()=>Lt,ReferenceWithTimezone:()=>Vt,Weekday:()=>We,casual:()=>Bj,createCasualConfiguration:()=>Mse,createConfiguration:()=>jj,hans:()=>AA,hant:()=>PA,parse:()=>C$e,parseDate:()=>x$e,strict:()=>S$e});function C$e(n,e,t){return Bj.parse(n,e,t)}function x$e(n,e,t){return Bj.parseDate(n,e,t)}function Mse(){let n=jj();return n.parsers.unshift(new Af),n}function jj(){let n=Gr({parsers:[new Mf,new Cf,new Nf,new Ef,new _f,new Pf,new Rf,new Df,new If,new xf],refiners:[new Ff,new Lf]});return n.refiners=n.refiners.filter(e=>!(e instanceof el)),n}var Bj,S$e,Ise=y(()=>{gs();Ni();ot();Nt();aw();gj();vj();kj();Tj();bj();wj();xj();Dj();Pj();Aj();Mj();Ij();Nj();bse();Ase();Bj=new ze(Mse()),S$e=new ze(jj())});function D$e(n){let e=n.toLowerCase();return Hj[e]!==void 0?Hj[e]:e.match(/несколько/)?3:e.match(/пол/)?.5:e.match(/пар/)?2:e===""?1:parseFloat(e)}function Yj(n){let e=n.toLowerCase();return Vj[e]!==void 0?Vj[e]:parseInt(e)}function IA(n){if(/(год|года|г|г.)/i.test(n)&&(n=n.replace(/(год|года|г|г.)/i,"")),/(до н.э.|до н. э.)/i.test(n))return n=n.replace(/(до н.э.|до н. э.)/i,""),-parseInt(n);if(/(н. э.|н.э.)/i.test(n))return n=n.replace(/(н. э.|н.э.)/i,""),parseInt(n);let e=parseInt(n);return Mi(e)}function Oy(n){let e={},t=n,r=Nse.exec(t);for(;r;)P$e(e,r),t=t.substring(r[0].length).trim(),r=Nse.exec(t);return e}function P$e(n,e){let t=D$e(e[1]),r=bS[e[2].toLowerCase()];n[r]=t}var Ts,Wj,qj,Fy,Hj,Vj,bS,E$e,Gj,Uj,MA,Rse,Nse,Ly,bs=y(()=>{xt();mn();Ts={leftBoundary:"([^\\p{L}\\p{N}_]|^)",rightBoundary:"(?=[^\\p{L}\\p{N}_]|$)",flags:"iu"},Wj={воскресенье:0,воскресенья:0,вск:0,"вск.":0,понедельник:1,понедельника:1,пн:1,"пн.":1,вторник:2,вторника:2,вт:2,"вт.":2,среда:3,среды:3,среду:3,ср:3,"ср.":3,четверг:4,четверга:4,чт:4,"чт.":4,пятница:5,пятницу:5,пятницы:5,пт:5,"пт.":5,суббота:6,субботу:6,субботы:6,сб:6,"сб.":6},qj={январь:1,января:1,январе:1,февраль:2,февраля:2,феврале:2,март:3,марта:3,марте:3,апрель:4,апреля:4,апреле:4,май:5,мая:5,мае:5,июнь:6,июня:6,июне:6,июль:7,июля:7,июле:7,август:8,августа:8,августе:8,сентябрь:9,сентября:9,сентябре:9,октябрь:10,октября:10,октябре:10,ноябрь:11,ноября:11,ноябре:11,декабрь:12,декабря:12,декабре:12},Fy={...qj,янв:1,"янв.":1,фев:2,"фев.":2,мар:3,"мар.":3,апр:4,"апр.":4,авг:8,"авг.":8,сен:9,"сен.":9,окт:10,"окт.":10,ноя:11,"ноя.":11,дек:12,"дек.":12},Hj={один:1,одна:1,одной:1,одну:1,две:2,два:2,двух:2,три:3,трех:3,трёх:3,четыре:4,четырех:4,четырёх:4,пять:5,пяти:5,шесть:6,шести:6,семь:7,семи:7,восемь:8,восьми:8,девять:9,девяти:9,десять:10,десяти:10,одиннадцать:11,одиннадцати:11,двенадцать:12,двенадцати:12},Vj={первое:1,первого:1,второе:2,второго:2,третье:3,третьего:3,четвертое:4,четвертого:4,пятое:5,пятого:5,шестое:6,шестого:6,седьмое:7,седьмого:7,восьмое:8,восьмого:8,девятое:9,девятого:9,десятое:10,десятого:10,одиннадцатое:11,одиннадцатого:11,двенадцатое:12,двенадцатого:12,тринадцатое:13,тринадцатого:13,четырнадцатое:14,четырнадцатого:14,пятнадцатое:15,пятнадцатого:15,шестнадцатое:16,шестнадцатого:16,семнадцатое:17,семнадцатого:17,восемнадцатое:18,восемнадцатого:18,девятнадцатое:19,девятнадцатого:19,двадцатое:20,двадцатого:20,"двадцать первое":21,"двадцать первого":21,"двадцать второе":22,"двадцать второго":22,"двадцать третье":23,"двадцать третьего":23,"двадцать четвертое":24,"двадцать четвертого":24,"двадцать пятое":25,"двадцать пятого":25,"двадцать шестое":26,"двадцать шестого":26,"двадцать седьмое":27,"двадцать седьмого":27,"двадцать восьмое":28,"двадцать восьмого":28,"двадцать девятое":29,"двадцать девятого":29,тридцатое:30,тридцатого:30,"тридцать первое":31,"тридцать первого":31},bS={сек:"second",секунда:"second",секунд:"second",секунды:"second",секунду:"second",секундочка:"second",секундочки:"second",секундочек:"second",секундочку:"second",мин:"minute",минута:"minute",минут:"minute",минуты:"minute",минуту:"minute",минуток:"minute",минутки:"minute",минутку:"minute",минуточек:"minute",минуточки:"minute",минуточку:"minute",час:"hour",часов:"hour",часа:"hour",часу:"hour",часиков:"hour",часика:"hour",часике:"hour",часик:"hour",день:"d",дня:"d",дней:"d",суток:"d",сутки:"d",неделя:"week",неделе:"week",недели:"week",неделю:"week",недель:"week",недельке:"week",недельки:"week",неделек:"week",месяц:"month",месяце:"month",месяцев:"month",месяца:"month",квартал:"quarter",квартале:"quarter",кварталов:"quarter",год:"year",года:"year",году:"year",годов:"year",лет:"year",годик:"year",годика:"year",годиков:"year"},E$e=`(?:${ie(Hj)}|[0-9]+|[0-9]+\\.[0-9]+|пол|несколько|пар(?:ы|у)|\\s{0,3})`;Gj=`(?:${ie(Vj)}|[0-9]{1,2}(?:го|ого|е|ое)?)`;Uj="(?:\\s+(?:году|года|год|г|г.))?",MA=`(?:[1-9][0-9]{0,3}${Uj}\\s*(?:н.э.|до н.э.|н. э.|до н. э.)|[1-2][0-9]{3}${Uj}|[5-9][0-9]${Uj})`;Rse=`(${E$e})\\s{0,3}(${ie(bS)})`,Nse=new RegExp(Rse,"i"),Ly=li("(?:(?:около|примерно)\\s{0,3})?",Rse)});var _se,wS,Fse=y(()=>{bs();ot();we();_se=`(?:(?:около|примерно)\\s*(?:~\\s*)?)?(${Ly})${Ts.rightBoundary}`,wS=class extends H{patternLeftBoundary(){return Ts.leftBoundary}innerPattern(e){return e.option.forwardDate?new RegExp(_se,Ts.flags):new RegExp(`(?:в течение|в течении)\\s*${_se}`,Ts.flags)}innerExtract(e,t){let r=Oy(t[1]);return K.createRelativeFromReference(e.reference,r)}}});var Of,Ri,zd=y(()=>{we();bs();Of=class extends H{patternLeftBoundary(){return Ts.leftBoundary}innerPattern(e){return new RegExp(this.innerPatternString(e),Ts.flags)}innerPatternHasChange(e,t){return!1}},Ri=class extends Of{innerPattern(e){return new RegExp(`${this.innerPatternString(e)}${Ts.rightBoundary}`,Ts.flags)}}});var Lse,Ose,A$e,zse,SS,Bse=y(()=>{mn();bs();bs();bs();xt();zd();Lse=1,Ose=2,A$e=3,zse=4,SS=class extends Ri{innerPatternString(e){return`(?:с)?\\s*(${Gj})(?:\\s{0,3}(?:по|-|–|до)?\\s{0,3}(${Gj}))?(?:-|\\/|\\s{0,3}(?:of)?\\s{0,3})(${ie(Fy)})(?:(?:-|\\/|,?\\s{0,3})(${MA}(?![^\\s]\\d)))?`}innerExtract(e,t){let r=e.createParsingResult(t.index,t[0]),a=Fy[t[A$e].toLowerCase()],i=Yj(t[Lse]);if(i>31)return t.index=t.index+t[Lse].length,null;if(r.start.assign("month",a),r.start.assign("day",i),t[zse]){let s=IA(t[zse]);r.start.assign("year",s)}else{let s=er(e.refDate,i,a);r.start.imply("year",s)}if(t[Ose]){let s=Yj(t[Ose]);r.end=r.start.clone(),r.end.assign("day",s)}return r}}});var M$e,jse,CS,$se=y(()=>{bs();mn();xt();bs();zd();M$e=2,jse=3,CS=class extends Of{innerPatternString(e){return`((?:в)\\s*)?(${ie(Fy)})\\s*(?:[,-]?\\s*(${MA})?)?(?=[^\\s\\w]|\\s+[^0-9]|\\s+$|$)`}innerExtract(e,t){let r=t[M$e].toLowerCase();if(t[0].length<=3&&!qj[r])return null;let a=e.createParsingResult(t.index,t.index+t[0].length);a.start.imply("day",1);let i=Fy[r];if(a.start.assign("month",i),t[jse]){let s=IA(t[jse]);a.start.assign("year",s)}else{let s=er(e.refDate,1,i);a.start.imply("year",s)}return a}}});var xS,Use=y(()=>{Nt();Rd();bs();xS=class extends na{constructor(e){super(e)}patternFlags(){return Ts.flags}primaryPatternLeftBoundary(){return"(^|\\s|T|(?:[^\\p{L}\\p{N}_]))"}followingPhase(){return"\\s*(?:\\-|\\–|\\~|\\〜|до|и|по|\\?)\\s*"}primaryPrefix(){return"(?:(?:в|с)\\s*)??"}primarySuffix(){return`(?:\\s*(?:утра|вечера|после полудня))?(?!\\/)${Ts.rightBoundary}`}extractPrimaryTimeComponents(e,t){let r=super.extractPrimaryTimeComponents(e,t);if(r){if(t[0].endsWith("вечера")){let a=r.get("hour");a>=6&&a<12?(r.assign("hour",r.get("hour")+12),r.assign("meridiem",j.PM)):a<6&&r.assign("meridiem",j.AM)}if(t[0].endsWith("после полудня")){r.assign("meridiem",j.PM);let a=r.get("hour");a>=0&&a<=6&&r.assign("hour",r.get("hour")+12)}t[0].endsWith("утра")&&(r.assign("meridiem",j.AM),r.get("hour")<12&&r.assign("hour",r.get("hour")))}return r}}});var ES,Hse=y(()=>{bs();ot();vs();zd();ES=class extends Of{innerPatternString(e){return`(${Ly})\\s{0,5}назад(?=(?:\\W|$))`}innerExtract(e,t){let r=Oy(t[1]),a=Mn(r);return K.createRelativeFromReference(e.reference,a)}}});var DS,Vse=y(()=>{Xs();DS=class extends jr{patternBetween(){return/^\s*(и до|и по|до|по|-)\s*$/i}}});var PS,Wse=y(()=>{eo();PS=class extends $r{patternBetween(){return new RegExp("^\\s*(T|в|,|-)?\\s*$")}}});var AS,qse=y(()=>{ys();zd();AS=class extends Ri{innerPatternString(e){return"(?:с|со)?\\s*(сегодня|вчера|завтра|послезавтра|послепослезавтра|позапозавчера|позавчера)"}innerExtract(e,t){let r=t[1].toLowerCase(),a=e.createParsingComponents();switch(r){case"сегодня":return aa(e.reference);case"вчера":return ja(e.reference);case"завтра":return $a(e.reference);case"послезавтра":return Ul(e.reference,2);case"послепослезавтра":return Ul(e.reference,3);case"позавчера":return kf(e.reference,2);case"позапозавчера":return kf(e.reference,3)}return a}}});var Gse,MS,Yse=y(()=>{ys();hs();Gse=tt(Ht(),1);zd();MS=class extends Ri{innerPatternString(e){return"(сейчас|прошлым\\s*вечером|прошлой\\s*ночью|следующей\\s*ночью|сегодня\\s*ночью|этой\\s*ночью|ночью|этим утром|утром|утра|в\\s*полдень|вечером|вечера|в\\s*полночь)"}innerExtract(e,t){let r=(0,Gse.default)(e.refDate),a=t[0].toLowerCase(),i=e.createParsingComponents();if(a==="сейчас")return Ba(e.reference);if(a==="вечером"||a==="вечера")return by(e.reference);if(a.endsWith("утром")||a.endsWith("утра"))return wy(e.reference);if(a.match(/в\s*полдень/))return Sy(e.reference);if(a.match(/прошлой\s*ночью/))return tA(e.reference);if(a.match(/прошлым\s*вечером/))return rA(e.reference);if(a.match(/следующей\s*ночью/)){let s=r.hour()<22?1:2;r=r.add(s,"day"),Mr(i,r),i.imply("hour",0)}return a.match(/в\s*полночь/)||a.endsWith("ночью")?Tf(e.reference):i}}});var I$e,N$e,R$e,IS,Kse=y(()=>{bs();xt();tl();zd();I$e=1,N$e=2,R$e=3,IS=class extends Ri{innerPatternString(e){return`(?:(?:,|\\(|()\\s*)?(?:в\\s*?)?(?:(эту|этот|прошлый|прошлую|следующий|следующую|следующего)\\s*)?(${ie(Wj)})(?:\\s*(?:,|\\)|)))?(?:\\s*на\\s*(этой|прошлой|следующей)\\s*неделе)?`}innerExtract(e,t){let r=t[N$e].toLowerCase(),a=Wj[r],i=t[I$e],s=t[R$e],o=i||s;o=o||"",o=o.toLowerCase();let l=null;return o=="прошлый"||o=="прошлую"||o=="прошлой"?l="last":o=="следующий"||o=="следующую"||o=="следующей"||o=="следующего"?l="next":(o=="этот"||o=="эту"||o=="этой")&&(l="this"),In(e.reference,a,l)}}});var Zse,_$e,F$e,NS,Qse=y(()=>{bs();ot();Zse=tt(Ht(),1);xt();zd();_$e=1,F$e=2,NS=class extends Ri{innerPatternString(e){return`(в прошлом|на прошлой|на следующей|в следующем|на этой|в этом)\\s*(${ie(bS)})`}innerExtract(e,t){let r=t[_$e].toLowerCase(),a=t[F$e].toLowerCase(),i=bS[a];if(r=="на следующей"||r=="в следующем"){let l={};return l[i]=1,K.createRelativeFromReference(e.reference,l)}if(r=="в прошлом"||r=="на прошлой"){let l={};return l[i]=-1,K.createRelativeFromReference(e.reference,l)}let s=e.createParsingComponents(),o=(0,Zse.default)(e.reference.instant);return i.match(/week/i)?(o=o.add(-o.get("d"),"d"),s.imply("day",o.date()),s.imply("month",o.month()+1),s.imply("year",o.year())):i.match(/month/i)?(o=o.add(-o.date()+1,"d"),s.imply("day",o.date()),s.assign("year",o.year()),s.assign("month",o.month()+1)):i.match(/year/i)&&(o=o.add(-o.date()+1,"d"),o=o.add(-o.month(),"month"),s.imply("day",o.date()),s.imply("month",o.month()+1),s.assign("year",o.year())),s}}});var RS,Jse=y(()=>{bs();ot();vs();zd();RS=class extends Ri{innerPatternString(e){return`(эти|последние|прошлые|следующие|после|спустя|через|\\+|-)\\s*(${Ly})`}innerExtract(e,t){let r=t[1].toLowerCase(),a=Oy(t[2]);switch(r){case"последние":case"прошлые":case"-":a=Mn(a);break}return K.createRelativeFromReference(e.reference,a)}}});var Qj={};Xe(Qj,{Chrono:()=>ze,Meridiem:()=>j,ParsingComponents:()=>K,ParsingResult:()=>Lt,ReferenceWithTimezone:()=>Vt,Weekday:()=>We,casual:()=>Kj,createCasualConfiguration:()=>Xse,createConfiguration:()=>Zj,parse:()=>O$e,parseDate:()=>z$e,strict:()=>L$e});function O$e(n,e,t){return Kj.parse(n,e,t)}function z$e(n,e,t){return Kj.parseDate(n,e,t)}function Xse(){let n=Zj(!1);return n.parsers.unshift(new AS),n.parsers.unshift(new MS),n.parsers.unshift(new CS),n.parsers.unshift(new NS),n.parsers.unshift(new RS),n}function Zj(n=!0){return Gr({parsers:[new Hn(!0),new wS,new SS,new IS,new xS(n),new ES],refiners:[new PS,new DS]},n)}var Kj,L$e,eoe=y(()=>{Fse();Bse();$se();Use();Hse();Vse();Wse();gs();qse();Yse();Kse();Qse();Ni();ot();Nt();Ld();Jse();Kj=new ze(Xse()),L$e=new ze(Zj(!0))});function j$e(n){let e=n.toLowerCase();return Jj[e]!==void 0?Jj[e]:e==="un"||e==="una"||e==="uno"?1:e.match(/algunos?/)||e.match(/unos?/)?3:e.match(/media?/)?.5:parseFloat(e)}function aoe(n){if(n.match(/^[0-9]{1,4}$/)){let e=parseInt(n);return e<100&&(e>50?e=e+1900:e=e+2e3),e}return n.match(/a\.?\s*c\.?/i)?(n=n.replace(/a\.?\s*c\.?/i,""),-parseInt(n)):parseInt(n)}function ooe(n){let e={},t=n,r=toe.exec(t);for(;r;)$$e(e,r),t=t.substring(r[0].length),r=toe.exec(t);return e}function $$e(n,e){let t=j$e(e[1]),r=roe[e[2].toLowerCase()];n[r]=t}var Xj,e$,Jj,roe,B$e,noe,ioe,toe,soe,_S=y(()=>{xt();Xj={domingo:0,dom:0,lunes:1,lun:1,martes:2,mar:2,miércoles:3,miercoles:3,mié:3,mie:3,jueves:4,jue:4,viernes:5,vie:5,sábado:6,sabado:6,sáb:6,sab:6},e$={enero:1,ene:1,"ene.":1,febrero:2,feb:2,"feb.":2,marzo:3,mar:3,"mar.":3,abril:4,abr:4,"abr.":4,mayo:5,may:5,"may.":5,junio:6,jun:6,"jun.":6,julio:7,jul:7,"jul.":7,agosto:8,ago:8,"ago.":8,septiembre:9,setiembre:9,sep:9,"sep.":9,octubre:10,oct:10,"oct.":10,noviembre:11,nov:11,"nov.":11,diciembre:12,dic:12,"dic.":12},Jj={uno:1,dos:2,tres:3,cuatro:4,cinco:5,seis:6,siete:7,ocho:8,nueve:9,diez:10,once:11,doce:12,trece:13},roe={sec:"second",segundo:"second",segundos:"second",min:"minute",mins:"minute",minuto:"minute",minutos:"minute",h:"hour",hr:"hour",hrs:"hour",hora:"hour",horas:"hour",día:"d",días:"d",semana:"week",semanas:"week",mes:"month",meses:"month",cuarto:"quarter",cuartos:"quarter",año:"year",años:"year"},B$e=`(?:${ie(Jj)}|[0-9]+|[0-9]+\\.[0-9]+|un?|uno?|una?|algunos?|unos?|demi-?)`;noe="[0-9]{1,4}(?![^\\s]\\d)(?:\\s*[a|d]\\.?\\s*c\\.?|\\s*a\\.?\\s*d\\.?)?";ioe=`(${B$e})\\s{0,5}(${ie(roe)})\\s{0,5}`,toe=new RegExp(ioe,"i"),soe=li("",ioe)});var U$e,H$e,V$e,W$e,FS,loe=y(()=>{_S();xt();we();tl();U$e=new RegExp(`(?:(?:\\,|\\(|\\()\\s*)?(?:(este|esta|pasado|pr[oó]ximo)\\s*)?(${ie(Xj)})(?:\\s*(?:\\,|\\)|\\)))?(?:\\s*(este|esta|pasado|pr[óo]ximo)\\s*semana)?(?=\\W|\\d|$)`,"i"),H$e=1,V$e=2,W$e=3,FS=class extends H{innerPattern(){return U$e}innerExtract(e,t){let r=t[V$e].toLowerCase(),a=Xj[r];if(a===void 0)return null;let i=t[H$e],s=t[W$e],o=i||s||"";o=o.toLowerCase();let l=null;return o=="pasado"?l="this":o=="próximo"||o=="proximo"?l="next":o=="este"&&(l="this"),In(e.reference,a,l)}}});var LS,coe=y(()=>{Rd();LS=class extends na{primaryPrefix(){return"(?:(?:aslas|deslas|las?|al?|de|del)\\s*)?"}followingPhase(){return"\\s*(?:\\-|\\–|\\~|\\〜|a(?:l)?|\\?)\\s*"}}});var OS,doe=y(()=>{eo();OS=class extends $r{patternBetween(){return new RegExp("^\\s*(?:,|de|aslas|a)?\\s*$")}}});var zS,uoe=y(()=>{Xs();zS=class extends jr{patternBetween(){return/^\s*(?:-)\s*$/i}}});var q$e,poe,moe,G$e,foe,BS,hoe=y(()=>{mn();_S();_S();xt();we();q$e=new RegExp(`([0-9]{1,2})(?:º|ª|°)?(?:\\s*(?:desde|de|\\-|\\–|ao?|\\s)\\s*([0-9]{1,2})(?:º|ª|°)?)?\\s*(?:de)?\\s*(?:-|/|\\s*(?:de|,)?\\s*)(${ie(e$)})(?:\\s*(?:de|,)?\\s*(${noe}))?(?=\\W|$)`,"i"),poe=1,moe=2,G$e=3,foe=4,BS=class extends H{innerPattern(){return q$e}innerExtract(e,t){let r=e.createParsingResult(t.index,t[0]),a=e$[t[G$e].toLowerCase()],i=parseInt(t[poe]);if(i>31)return t.index=t.index+t[poe].length,null;if(r.start.assign("month",a),r.start.assign("day",i),t[foe]){let s=aoe(t[foe]);r.start.assign("year",s)}else{let s=er(e.refDate,i,a);r.start.imply("year",s)}if(t[moe]){let s=parseInt(t[moe]);r.end=r.start.clone(),r.end.assign("day",s)}return r}}});var jS,goe=y(()=>{we();ys();jS=class extends H{innerPattern(e){return/(ahora|hoy|mañana|ayer)(?=\W|$)/i}innerExtract(e,t){let r=t[0].toLowerCase(),a=e.createParsingComponents();switch(r){case"ahora":return Ba(e.reference);case"hoy":return aa(e.reference);case"mañana":return $a(e.reference);case"ayer":return ja(e.reference)}return a}}});var yoe,$S,voe=y(()=>{Nt();we();hs();yoe=tt(Ht(),1),$S=class extends H{innerPattern(){return/(?:esta\s*)?(mañana|tarde|medianoche|mediodia|mediodía|noche)(?=\W|$)/i}innerExtract(e,t){let r=(0,yoe.default)(e.refDate),a=e.createParsingComponents();switch(t[1].toLowerCase()){case"tarde":a.imply("meridiem",j.PM),a.imply("hour",15);break;case"noche":a.imply("meridiem",j.PM),a.imply("hour",22);break;case"mañana":a.imply("meridiem",j.AM),a.imply("hour",6);break;case"medianoche":Xo(a,r),a.imply("hour",0),a.imply("minute",0),a.imply("second",0);break;case"mediodia":case"mediodía":a.imply("meridiem",j.AM),a.imply("hour",12);break}return a}}});var US,koe=y(()=>{_S();ot();we();US=class extends H{innerPattern(){return new RegExp(`(?:en|por|durante|de|dentro de)\\s*(${soe})(?=\\W|$)`,"i")}innerExtract(e,t){let r=ooe(t[1]);return K.createRelativeFromReference(e.reference,r)}}});var n$={};Xe(n$,{Chrono:()=>ze,Meridiem:()=>j,ParsingComponents:()=>K,ParsingResult:()=>Lt,ReferenceWithTimezone:()=>Vt,Weekday:()=>We,casual:()=>t$,createCasualConfiguration:()=>Toe,createConfiguration:()=>r$,parse:()=>K$e,parseDate:()=>Z$e,strict:()=>Y$e});function K$e(n,e,t){return t$.parse(n,e,t)}function Z$e(n,e,t){return t$.parseDate(n,e,t)}function Toe(n=!0){let e=r$(!1,n);return e.parsers.push(new jS),e.parsers.push(new $S),e}function r$(n=!0,e=!0){return Gr({parsers:[new Hn(e),new FS,new LS,new BS,new US],refiners:[new OS,new zS]},n)}var t$,Y$e,boe=y(()=>{gs();Ni();ot();Nt();Ld();loe();coe();doe();uoe();hoe();goe();voe();koe();t$=new ze(Toe()),Y$e=new ze(r$(!0))});function J$e(n){let e=n.toLowerCase();return i$[e]!==void 0?i$[e]:e.match(/декілька/)?2:e.match(/пів/)?.5:e.match(/пар/)?2:e===""?1:parseFloat(e)}function d$(n){let e=n.toLowerCase();return s$[e]!==void 0?s$[e]:parseInt(e)}function RA(n){if(/(рік|року|р|р.)/i.test(n)&&(n=n.replace(/(рік|року|р|р.)/i,"")),/(до н.е.|до н. е.)/i.test(n))return n=n.replace(/(до н.е.|до н. е.)/i,""),-parseInt(n);if(/(н. е.|н.е.)/i.test(n))return n=n.replace(/(н. е.|н.е.)/i,""),parseInt(n);let e=parseInt(n);return Mi(e)}function jy(n){let e={},t=n,r=woe.exec(t);for(;r;)X$e(e,r),t=t.substring(r[0].length).trim(),r=woe.exec(t);return e}function X$e(n,e){let t=J$e(e[1]),r=HS[e[2].toLowerCase()];n[r]=t}var so,o$,l$,zy,i$,s$,HS,Q$e,c$,a$,NA,Soe,woe,By,ws=y(()=>{xt();mn();so={leftBoundary:"([^\\p{L}\\p{N}_]|^)",rightBoundary:"(?=[^\\p{L}\\p{N}_]|$)",flags:"iu"},o$={неділя:0,неділі:0,неділю:0,нд:0,"нд.":0,понеділок:1,понеділка:1,пн:1,"пн.":1,вівторок:2,вівторка:2,вт:2,"вт.":2,середа:3,середи:3,середу:3,ср:3,"ср.":3,четвер:4,четверга:4,четвергу:4,чт:4,"чт.":4,"п'ятниця":5,"п'ятниці":5,"п'ятницю":5,пт:5,"пт.":5,субота:6,суботи:6,суботу:6,сб:6,"сб.":6},l$={січень:1,січня:1,січні:1,лютий:2,лютого:2,лютому:2,березень:3,березня:3,березні:3,квітень:4,квітня:4,квітні:4,травень:5,травня:5,травні:5,червень:6,червня:6,червні:6,липень:7,липня:7,липні:7,серпень:8,серпня:8,серпні:8,вересень:9,вересня:9,вересні:9,жовтень:10,жовтня:10,жовтні:10,листопад:11,листопада:11,листопаду:11,грудень:12,грудня:12,грудні:12},zy={...l$,січ:1,"січ.":1,лют:2,"лют.":2,бер:3,"бер.":3,квіт:4,"квіт.":4,трав:5,"трав.":5,черв:6,"черв.":6,лип:7,"лип.":7,серп:8,"серп.":8,сер:8,"cер.":8,вер:9,"вер.":9,верес:9,"верес.":9,жовт:10,"жовт.":10,листоп:11,"листоп.":11,груд:12,"груд.":12},i$={один:1,одна:1,одної:1,одну:1,дві:2,два:2,двох:2,три:3,трьох:3,чотири:4,чотирьох:4,"п'ять":5,"п'яти":5,шість:6,шести:6,сім:7,семи:7,вісім:8,восьми:8,"дев'ять":9,"дев'яти":9,десять:10,десяти:10,одинадцять:11,одинадцяти:11,дванадцять:12,дванадцяти:12},s$={перше:1,першого:1,друге:2,другого:2,третє:3,третього:3,четверте:4,четвертого:4,"п'яте":5,"п'ятого":5,шосте:6,шостого:6,сьоме:7,сьомого:7,восьме:8,восьмого:8,"дев'яте":9,"дев'ятого":9,десяте:10,десятого:10,одинадцяте:11,одинадцятого:11,дванадцяте:12,дванадцятого:12,тринадцяте:13,тринадцятого:13,чотирнадцяте:14,чотинрнадцятого:14,"п'ятнадцяте":15,"п'ятнадцятого":15,шістнадцяте:16,шістнадцятого:16,сімнадцяте:17,сімнадцятого:17,вісімнадцяте:18,вісімнадцятого:18,"дев'ятнадцяте":19,"дев'ятнадцятого":19,двадцяте:20,двадцятого:20,"двадцять перше":21,"двадцять першого":21,"двадцять друге":22,"двадцять другого":22,"двадцять третє":23,"двадцять третього":23,"двадцять четверте":24,"двадцять четвертого":24,"двадцять п'яте":25,"двадцять п'ятого":25,"двадцять шосте":26,"двадцять шостого":26,"двадцять сьоме":27,"двадцять сьомого":27,"двадцять восьме":28,"двадцять восьмого":28,"двадцять дев'яте":29,"двадцять дев'ятого":29,тридцяте:30,тридцятого:30,"тридцять перше":31,"тридцять першого":31},HS={сек:"second",секунда:"second",секунд:"second",секунди:"second",секунду:"second",секундочок:"second",секундочки:"second",секундочку:"second",хв:"minute",хвилина:"minute",хвилин:"minute",хвилини:"minute",хвилину:"minute",хвилинок:"minute",хвилинки:"minute",хвилинку:"minute",хвилиночок:"minute",хвилиночки:"minute",хвилиночку:"minute",год:"hour",година:"hour",годин:"hour",години:"hour",годину:"hour",годинка:"hour",годинок:"hour",годинки:"hour",годинку:"hour",день:"d",дня:"d",днів:"d",дні:"d",доба:"d",добу:"d",тиждень:"week",тижню:"week",тижня:"week",тижні:"week",тижнів:"week",місяць:"month",місяців:"month",місяці:"month",місяця:"month",квартал:"quarter",кварталу:"quarter",квартала:"quarter",кварталів:"quarter",кварталі:"quarter",рік:"year",року:"year",році:"year",років:"year",роки:"year"},Q$e=`(?:${ie(i$)}|[0-9]+|[0-9]+\\.[0-9]+|пів|декілька|пар(?:у)|\\s{0,3})`;c$=`(?:${ie(s$)}|[0-9]{1,2}(?:го|ого|е)?)`;a$="(?:\\s+(?:року|рік|р|р.))?",NA=`(?:[1-9][0-9]{0,3}${a$}\\s*(?:н.е.|до н.е.|н. е.|до н. е.)|[1-2][0-9]{3}${a$}|[5-9][0-9]${a$})`;Soe=`(${Q$e})\\s{0,3}(${ie(HS)})`,woe=new RegExp(Soe,"i"),By=li("(?:(?:близько|приблизно)\\s{0,3})?",Soe)});var Coe,VS,xoe=y(()=>{ws();ot();we();Coe=`(?:(?:приблизно|орієнтовно)\\s*(?:~\\s*)?)?(${By})${so.rightBoundary}`,VS=class extends H{patternLeftBoundary(){return so.leftBoundary}innerPattern(e){return e.option.forwardDate?new RegExp(Coe,"i"):new RegExp(`(?:протягом|на протязі|протягом|упродовж|впродовж)\\s*${Coe}`,so.flags)}innerExtract(e,t){let r=jy(t[1]);return K.createRelativeFromReference(e.reference,r)}}});var zf,_i,Bd=y(()=>{we();ws();zf=class extends H{patternLeftBoundary(){return so.leftBoundary}innerPattern(e){return new RegExp(this.innerPatternString(e),so.flags)}innerPatternHasChange(e,t){return!1}},_i=class extends zf{innerPattern(e){return new RegExp(`${this.innerPatternString(e)}${so.rightBoundary}`,so.flags)}}});var Eoe,Doe,e2e,Poe,WS,Aoe=y(()=>{mn();ws();ws();ws();xt();Bd();Eoe=1,Doe=2,e2e=3,Poe=4,WS=class extends _i{innerPatternString(e){return`(?:з|із)?\\s*(${c$})(?:\\s{0,3}(?:по|-|–|до)?\\s{0,3}(${c$}))?(?:-|\\/|\\s{0,3}(?:of)?\\s{0,3})(${ie(zy)})(?:(?:-|\\/|,?\\s{0,3})(${NA}(?![^\\s]\\d)))?`}innerExtract(e,t){let r=e.createParsingResult(t.index,t[0]),a=zy[t[e2e].toLowerCase()],i=d$(t[Eoe]);if(i>31)return t.index=t.index+t[Eoe].length,null;if(r.start.assign("month",a),r.start.assign("day",i),t[Poe]){let s=RA(t[Poe]);r.start.assign("year",s)}else{let s=er(e.reference.instant,i,a);r.start.imply("year",s)}if(t[Doe]){let s=d$(t[Doe]);r.end=r.start.clone(),r.end.assign("day",s)}return r}}});var t2e,Moe,qS,Ioe=y(()=>{ws();mn();xt();ws();Bd();t2e=2,Moe=3,qS=class extends zf{innerPatternString(e){return`((?:в|у)\\s*)?(${ie(zy)})\\s*(?:[,-]?\\s*(${NA})?)?(?=[^\\s\\w]|\\s+[^0-9]|\\s+$|$)`}innerExtract(e,t){let r=t[t2e].toLowerCase();if(t[0].length<=3&&!l$[r])return null;let a=e.createParsingResult(t.index,t.index+t[0].length);a.start.imply("day",1);let i=zy[r];if(a.start.assign("month",i),t[Moe]){let s=RA(t[Moe]);a.start.assign("year",s)}else{let s=er(e.reference.instant,1,i);a.start.imply("year",s)}return a}}});var GS,Noe=y(()=>{Nt();Rd();ws();GS=class extends na{constructor(e){super(e)}patternFlags(){return so.flags}primaryPatternLeftBoundary(){return"(^|\\s|T|(?:[^\\p{L}\\p{N}_]))"}followingPhase(){return"\\s*(?:\\-|\\–|\\~|\\〜|до|і|по|\\?)\\s*"}primaryPrefix(){return"(?:(?:в|у|о|об|з|із|від)\\s*)??"}primarySuffix(){return`(?:\\s*(?:ранку|вечора|по обіді|після обіду))?(?!\\/)${so.rightBoundary}`}extractPrimaryTimeComponents(e,t){let r=super.extractPrimaryTimeComponents(e,t);if(r){if(t[0].endsWith("вечора")){let a=r.get("hour");a>=6&&a<12?(r.assign("hour",r.get("hour")+12),r.assign("meridiem",j.PM)):a<6&&r.assign("meridiem",j.AM)}if(t[0].endsWith("по обіді")||t[0].endsWith("після обіду")){r.assign("meridiem",j.PM);let a=r.get("hour");a>=0&&a<=6&&r.assign("hour",r.get("hour")+12)}t[0].endsWith("ранку")&&(r.assign("meridiem",j.AM),r.get("hour")<12&&r.assign("hour",r.get("hour")))}return r}}});var YS,Roe=y(()=>{ws();ot();vs();Bd();YS=class extends zf{innerPatternString(e){return`(${By})\\s{0,5}тому(?=(?:\\W|$))`}innerExtract(e,t){let r=jy(t[1]),a=Mn(r);return K.createRelativeFromReference(e.reference,a)}}});var KS,_oe=y(()=>{Xs();KS=class extends jr{patternBetween(){return/^\s*(і до|і по|до|по|-)\s*$/i}}});var ZS,Foe=y(()=>{eo();ZS=class extends $r{patternBetween(){return new RegExp("^\\s*(T|в|у|о|,|-)?\\s*$")}}});var QS,Loe=y(()=>{ys();Bd();QS=class extends _i{innerPatternString(e){return"(?:з|із|від)?\\s*(сьогодні|вчора|завтра|післязавтра|післяпіслязавтра|позапозавчора|позавчора)"}innerExtract(e,t){let r=t[1].toLowerCase(),a=e.createParsingComponents();switch(r){case"сьогодні":return aa(e.reference);case"вчора":return ja(e.reference);case"завтра":return $a(e.reference);case"післязавтра":return Ul(e.reference,2);case"післяпіслязавтра":return Ul(e.reference,3);case"позавчора":return kf(e.reference,2);case"позапозавчора":return kf(e.reference,3)}return a}}});var Ooe,JS,zoe=y(()=>{ys();hs();Ooe=tt(Ht(),1);Bd();JS=class extends _i{innerPatternString(e){return"(зараз|минулого\\s*вечора|минулої\\s*ночі|наступної\\s*ночі|сьогодні\\s*вночі|цієї\\s*ночі|цього ранку|вранці|ранку|зранку|опівдні|ввечері|вечора|опівночі|вночі)"}innerExtract(e,t){let r=(0,Ooe.default)(e.reference.instant),a=t[0].toLowerCase(),i=e.createParsingComponents();if(a==="зараз")return Ba(e.reference);if(a==="ввечері"||a==="вечора")return by(e.reference);if(a.endsWith("вранці")||a.endsWith("ранку")||a.endsWith("зранку"))return wy(e.reference);if(a.endsWith("опівдні"))return Sy(e.reference);if(a.match(/минулої\s*ночі/))return tA(e.reference);if(a.match(/минулого\s*вечора/))return rA(e.reference);if(a.match(/наступної\s*ночі/)){let s=r.hour()<22?1:2;r=r.add(s,"day"),Mr(i,r),i.imply("hour",1)}return a.match(/цієї\s*ночі/)?Tf(e.reference):a.endsWith("опівночі")||a.endsWith("вночі")?Tf(e.reference):i}}});var r2e,n2e,a2e,XS,Boe=y(()=>{ws();xt();tl();Bd();r2e=1,n2e=2,a2e=3,XS=class extends _i{innerPatternString(e){return`(?:(?:,|\\(|()\\s*)?(?:в\\s*?)?(?:у\\s*?)?(?:(цей|минулого|минулий|попередній|попереднього|наступного|наступний|наступному)\\s*)?(${ie(o$)})(?:\\s*(?:,|\\)|)))?(?:\\s*(на|у|в)\\s*(цьому|минулому|наступному)\\s*тижні)?`}innerExtract(e,t){let r=t[n2e].toLocaleLowerCase(),a=o$[r],i=t[r2e],s=t[a2e],o=i||s;o=o||"",o=o.toLocaleLowerCase();let l=null;return o=="минулого"||o=="минулий"||o=="попередній"||o=="попереднього"?l="last":o=="наступного"||o=="наступний"?l="next":(o=="цей"||o=="цього"||o=="цьому")&&(l="this"),In(e.reference,a,l)}}});var joe,i2e,s2e,eC,$oe=y(()=>{ws();ot();joe=tt(Ht(),1);xt();Bd();i2e=1,s2e=2,eC=class extends _i{innerPatternString(e){return`(в минулому|у минулому|на минулому|минулого|на наступному|в наступному|у наступному|наступного|на цьому|в цьому|у цьому|цього)\\s*(${ie(HS)})(?=\\s*)`}innerExtract(e,t){let r=t[i2e].toLowerCase(),a=t[s2e].toLowerCase(),i=HS[a];if(r=="на наступному"||r=="в наступному"||r=="у наступному"||r=="наступного"){let l={};return l[i]=1,K.createRelativeFromReference(e.reference,l)}if(r=="на минулому"||r=="в минулому"||r=="у минулому"||r=="минулого"){let l={};return l[i]=-1,K.createRelativeFromReference(e.reference,l)}let s=e.createParsingComponents(),o=(0,joe.default)(e.reference.instant);return i.match(/week/i)?(o=o.add(-o.get("d"),"d"),s.imply("day",o.date()),s.imply("month",o.month()+1),s.imply("year",o.year())):i.match(/month/i)?(o=o.add(-o.date()+1,"d"),s.imply("day",o.date()),s.assign("year",o.year()),s.assign("month",o.month()+1)):i.match(/year/i)&&(o=o.add(-o.date()+1,"d"),o=o.add(-o.month(),"month"),s.imply("day",o.date()),s.imply("month",o.month()+1),s.assign("year",o.year())),s}}});var tC,Uoe=y(()=>{ws();ot();vs();Bd();tC=class extends _i{innerPatternString(e){return`(ці|останні|минулі|майбутні|наступні|після|через|\\+|-)\\s*(${By})`}innerExtract(e,t){let r=t[1].toLowerCase(),a=jy(t[3]);switch(r){case"останні":case"минулі":case"-":a=Mn(a);break}return K.createRelativeFromReference(e.reference,a)}}});var m$={};Xe(m$,{Chrono:()=>ze,Meridiem:()=>j,ParsingComponents:()=>K,ParsingResult:()=>Lt,ReferenceWithTimezone:()=>Vt,Weekday:()=>We,casual:()=>u$,createCasualConfiguration:()=>Hoe,createConfiguration:()=>p$,parse:()=>l2e,parseDate:()=>c2e,strict:()=>o2e});function Hoe(){let n=p$(!1);return n.parsers.unshift(new QS),n.parsers.unshift(new JS),n.parsers.unshift(new qS),n.parsers.unshift(new eC),n.parsers.unshift(new tC),n}function p$(n){return Gr({parsers:[new Fd,new Hn(!0),new VS,new WS,new XS,new GS(n),new YS],refiners:[new ZS,new KS]},n)}function l2e(n,e,t){return u$.parse(n,e,t)}function c2e(n,e,t){return u$.parseDate(n,e,t)}var u$,o2e,Voe=y(()=>{xoe();Aoe();Ioe();Noe();Roe();_oe();Foe();gs();Loe();zoe();Boe();$oe();Ni();ot();Nt();Ld();Uoe();eA();u$=new ze(Hoe()),o2e=new ze(p$(!0))});var _A={};Xe(_A,{Chrono:()=>ze,Meridiem:()=>j,ParsingComponents:()=>K,ParsingContext:()=>gw,ParsingResult:()=>Lt,ReferenceWithTimezone:()=>Vt,Weekday:()=>We,casual:()=>f$,de:()=>jB,en:()=>IB,es:()=>n$,fr:()=>ZB,ja:()=>ej,nl:()=>mj,parse:()=>u2e,parseDate:()=>p2e,pt:()=>ij,ru:()=>Qj,strict:()=>d2e,uk:()=>m$,zh:()=>$j});function u2e(n,e,t){return f$.parse(n,e,t)}function p2e(n,e,t){return f$.parseDate(n,e,t)}var d2e,f$,Woe=y(()=>{nae();Ni();ot();Nt();Pae();Jae();mie();Pie();rse();Ise();eoe();boe();Voe();d2e=MB,f$=yw});var m2e,FA,qoe=y(()=>{Cr();Woe();ny();cB();dB();lB();m2e=ye,FA=class{constructor(e=[],t=[],r=!0,a="en",i,s,o={}){this.isValidDateString=c=>/^\d{4}-\d{2}-\d{2}$/.test(c),this.isValidTimeString=c=>/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(c),this.escapeRegex=c=>c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),this.cleanupWhitespace=c=>c.replace(/\s+/g," ").replace(/^\s+|\s+$/g,"").trim(),this.defaultToScheduled=r,this.languageConfig=Yre(a),this.options=o,this.statusConfigs=e,this.priorityConfigs=t;let l=i||bre;this.triggerConfig=new Y0(l,s||[]),this.boundaries=this.createBoundaryConfig(),this.recurrencePatterns=this.buildRecurrencePatterns(),this.processingPipeline=this.buildProcessingPipeline()}createBoundaryConfig(){let e=["ru","zh","ja","uk","fr"].includes(this.languageConfig.code);return{boundary:e?"(?:^|\\s)":"\\b",endBoundary:e?"(?=\\s|$)":"\\b",isNonAscii:e}}getChronoParser(){let e=this.languageConfig.chronoLocale;return _A[e]||_A}buildProcessingPipeline(){return[{name:"extractTags",process:(e,t)=>this.extractTags(e,t)},{name:"extractContexts",process:(e,t)=>this.extractContexts(e,t)},{name:"extractProjects",process:(e,t)=>this.extractProjects(e,t)},{name:"extractPriority",process:(e,t)=>this.extractPriority(e,t)},{name:"extractStatus",process:(e,t)=>this.extractStatus(e,t)},{name:"extractRecurrence",process:(e,t)=>this.extractRecurrence(e,t)},{name:"extractTimeEstimate",process:(e,t)=>this.extractTimeEstimate(e,t)},{name:"extractUserFields",process:(e,t)=>this.extractUserFields(e,t)},{name:"parseUnifiedDatesAndTimes",process:(e,t)=>this.parseUnifiedDatesAndTimes(e,t)}]}parseInput(e){let t={title:"",tags:[],contexts:[],projects:[]},r=this.protectNlpLiterals(e),a=this.normalizeNumericDateLiterals(r.text),[i,s]=this.extractTitleAndDetails(a);s&&(t.details=s);let o=i;for(let c of this.processingPipeline)try{o=c.process(o,t)}catch(d){console.debug(`Error in processor ${c.name}:`,d)}t.title=o.trim();let l=this.validateAndCleanupResult(t);return this.restoreProtectedLiterals(l,r.literals),l}protectNlpLiterals(e){let t=this.protectQuotedLiterals(e);return this.protectEscapedLiterals(t.text,t.literals)}protectQuotedLiterals(e){let t=[],r="",a=0;for(;a=e.length||!this.shouldProtectEscapedLiteral(e,a,i)){r+=e[a],a+=1;continue}let s=i;for(;sthis.restoreProtectedLiteralsInText(i,t))}restoreProtectedLiteralsInText(e,t){let r=e;return t.forEach((a,i)=>{r=r.replace(`__TASKNOTES_NLP_LITERAL_${i}__`,a)}),r}isQuoteDelimiter(e){return e==='"'||e==="'"||e==="`"}isEligibleQuoteStart(e,t){if(e[t]!=="'")return!0;let a=t>0?e[t-1]:"";return!this.isWordCharacter(a)}isEligibleQuoteEnd(e,t){if(e[t]!=="'")return!0;let a=t+10?e[a-1]:"")==="\\"))return a;return-1}shouldProtectEscapedLiteral(e,t,r){if(this.startsWithEscapableTrigger(e,r))return!0;let a=t>0?e[t-1]:"";return a&&!/\s/u.test(a)?!1:/[\p{L}\p{N}]/u.test(e[r])}startsWithEscapableTrigger(e,t){return this.getEscapableTriggers().some(r=>e.startsWith(r,t))}getEscapableTriggers(){let e=this.triggerConfig.getTriggersOrderedByLength().map(t=>t.trigger).filter(t=>t.length>0);return e.length>0?e:["#","@","+","*","!"]}normalizeNumericDateLiterals(e){let t=e.replace(/(^|[^\p{L}\p{N}_])(\d{4})[/.](\d{1,2})[/.](\d{1,2})(?=$|[^\p{L}\p{N}_])/gu,(r,a,i,s,o)=>{let l=this.toValidatedISODate(Number(i),Number(s),Number(o));return l?`${a}${l}`:r});return this.getNumericDateOrder()!=="day-first"?t:t.replace(/(^|[^\p{L}\p{N}_])(\d{1,2})[/.](\d{1,2})[/.](\d{4})(?=$|[^\p{L}\p{N}_])/gu,(r,a,i,s,o)=>{let l=this.toValidatedISODate(Number(o),Number(s),Number(i));return l?`${a}${l}`:r})}getNumericDateOrder(){if(this.options.dateOrder)return this.options.dateOrder;let e=this.options.dateLocale||this.languageConfig.code;try{let r=new Intl.DateTimeFormat(e).formatToParts(new Date(2006,10,22)).find(a=>a.type==="day"||a.type==="month"||a.type==="year");if((r==null?void 0:r.type)==="day")return"day-first"}catch(t){}return"month-first"}toValidatedISODate(e,t,r){let a=new Date(Date.UTC(e,t-1,r));return a.getUTCFullYear()!==e||a.getUTCMonth()!==t-1||a.getUTCDate()!==r?null:`${e}-${this.padDatePart(t)}-${this.padDatePart(r)}`}padDatePart(e){return String(e).padStart(2,"0")}extractTitleAndDetails(e){let t=e.trim(),r=t.indexOf(` +`);if(r!==-1){let a=t.substring(0,r).trim(),i=t.substring(r+1).trim();return[a,i]}return[t,void 0]}extractTags(e,t){let r=this.triggerConfig.getTagTrigger();if(!r)return e;let a=this.escapeRegex(r),i=new RegExp(`${a}[\\p{L}\\p{N}\\p{M}_/-]+`,"gu"),s=e.match(i);return s?(t.tags.push(...s.map(o=>o.substring(r.length))),this.cleanupWhitespace(e.replace(i,""))):e}extractContexts(e,t){let r=this.triggerConfig.getContextTrigger();if(!r)return e;let a=this.escapeRegex(r),i=new RegExp(`${a}[\\p{L}\\p{N}\\p{M}_/-]+`,"gu"),s=e.match(i);return s?(t.contexts.push(...s.map(o=>o.substring(r.length))),this.cleanupWhitespace(e.replace(i,""))):e}extractProjects(e,t){let r=this.triggerConfig.getProjectTrigger();if(!r)return e;let a=e,i=this.escapeRegex(r),s=new RegExp(`${i}\\[\\[.*?\\]\\]`,"g"),o=a.match(s);o&&(t.projects.push(...o.map(d=>d.slice(r.length))),a=this.cleanupWhitespace(a.replace(s,"")));let l=new RegExp(`${i}[\\p{L}\\p{N}\\p{M}_/-]+`,"gu"),c=a.match(l);return c&&(t.projects.push(...c.map(d=>d.substring(r.length))),a=this.cleanupWhitespace(a.replace(l,""))),a}extractUserFields(e,t){let r=e,a=this.triggerConfig.getAllEnabledTriggers().filter(i=>this.triggerConfig.isUserField(i.propertyId));for(let i of a){let s=this.triggerConfig.getUserField(i.propertyId);if(!s)continue;let o=this.escapeRegex(i.trigger);if(s.type==="list"){let l=new RegExp(`${o}(?:"([^"]+)"|([\\p{L}\\p{N}\\p{M}_/-]+))`,"gu"),c=[],d;for(;(d=l.exec(r))!==null;){let u=d[1]||d[2];c.push(u)}c.length>0&&(t.userFields||(t.userFields={}),t.userFields[s.id]=c,r=this.cleanupWhitespace(r.replace(l,"")))}else if(s.type==="text"||s.type==="boolean"||s.type==="number"){let l=new RegExp(`${o}(?:"([^"]+)"|([\\p{L}\\p{N}\\p{M}_/-]+))`,"u"),c=r.match(l);if(c){let d=c[1]||c[2];t.userFields||(t.userFields={}),s.type==="boolean"?t.userFields[s.id]=d.toLowerCase()==="true"?"true":"false":t.userFields[s.id]=d,r=this.cleanupWhitespace(r.replace(l,""))}}else if(s.type==="date"){let l=new RegExp(`${o}(?:"([^"]+)"|([\\p{L}\\p{N}\\p{M}_/-]+))`,"u"),c=r.match(l);if(c){let d=c[1]||c[2];t.userFields||(t.userFields={}),t.userFields[s.id]=d,r=this.cleanupWhitespace(r.replace(l,""))}}}return r}extractPriority(e,t){if(this.priorityConfigs.length>0){let i=[...this.priorityConfigs].sort((l,c)=>c.label.length-l.label.length),s=this.triggerConfig.getTriggerForProperty("priority"),o=s!=null&&s.enabled?s.trigger:"";for(let l of i){let c=[l.label,l.value];for(let d of c){if(!d||d.trim()==="")continue;if(o){let p=o+d,m=this.findTextMatch(e,p);if(m)return t.priority=l.value,this.cleanupWhitespace(e.replace(m.fullMatch,""))}let u=this.findTextMatch(e,d);if(u)return t.priority=l.value,this.cleanupWhitespace(e.replace(u.fullMatch,""))}}return e}let r=this.languageConfig.fallbackPriority,a=this.findPhraseValueMatch(e,[{value:"urgent",phrases:r.urgent},{value:"high",phrases:r.high},{value:"normal",phrases:r.normal},{value:"low",phrases:r.low}]);return a?(t.priority=a.value,this.removePhraseMatch(e,a.match)):e}extractStatus(e,t){if(this.statusConfigs.length>0){let i=[...this.statusConfigs].sort((l,c)=>c.label.length-l.label.length),s=this.triggerConfig.getTriggerForProperty("status"),o=s!=null&&s.enabled?s.trigger:"";for(let l of i){let c=[l.label,l.value];for(let d of c){if(!d||d.trim()==="")continue;if(o){let p=o+d,m=this.findTextMatch(e,p);if(m)return t.status=l.value,this.cleanupWhitespace(e.replace(m.fullMatch,""))}let u=this.findTextMatch(e,d);if(u)return t.status=l.value,this.cleanupWhitespace(e.replace(u.fullMatch,""))}}return e}let r=this.languageConfig.fallbackStatus,a=this.findPhraseValueMatch(e,[{value:"open",phrases:r.open},{value:"in-progress",phrases:r.inProgress},{value:"done",phrases:r.done},{value:"cancelled",phrases:r.cancelled},{value:"waiting",phrases:r.waiting}]);return a?(t.status=a.value,this.removePhraseMatch(e,a.match)):e}findTextMatch(e,t){let r=this.findPhraseMatch(e,[t]);if(!r)return null;let a=this.includeTrailingPhraseSeparator(e,r.endIndex);return{fullMatch:e.substring(r.startIndex,a),startIndex:r.startIndex}}findPhraseMatch(e,t){let r=t.filter(s=>s&&s.trim()!=="").sort((s,o)=>o.length-s.length);if(r.length===0)return null;let a=e.toLowerCase(),i=null;for(let s of r){let o=s.toLowerCase(),l=0;for(;l<=a.length;){let c=a.indexOf(o,l);if(c===-1)break;let d=c+s.length;if(this.hasPhraseBoundaries(e,c,d)){let u={fullMatch:e.substring(c,d),phrase:s,startIndex:c,endIndex:d};(!i||u.startIndexi.phrase.length)&&(i=u)}l=c+1}}return i}findPhraseValueMatch(e,t){let r=null;for(let a of t){let i=this.findPhraseMatch(e,a.phrases);i&&(!r||i.startIndexr.match.phrase.length)&&(r={value:a.value,match:i})}return r}removePhraseMatch(e,t){let r=this.includeTrailingPhraseSeparator(e,t.endIndex);return this.cleanupWhitespace(e.substring(0,t.startIndex)+e.substring(r))}hasPhraseBoundaries(e,t,r){if(["zh","ja"].includes(this.languageConfig.code))return!0;let a=this.getCodePointBefore(e,t),i=this.getCodePointAt(e,r);return!this.isWordCharacter(a)&&!this.isWordCharacter(i)}getCodePointBefore(e,t){return t<=0?"":Array.from(e.slice(0,t)).pop()||""}getCodePointAt(e,t){return t>=e.length?"":Array.from(e.slice(t))[0]||""}isWordCharacter(e){return e!==""&&/[\p{L}\p{N}\p{M}_]/u.test(e)}includeTrailingPhraseSeparator(e,t){return/[:,;]/.test(e[t]||"")?t+1:t}parseUnifiedDatesAndTimes(e,t){var a,i;let r=e;try{let s=this.getChronoParser(),o=this.languageConfig.dateTriggers,l=[{type:"due",phrases:o.due},{type:"scheduled",phrases:o.scheduled}],c=!1;for(let v of l){let k=this.findPhraseMatch(r,v.phrases);if(k){let T=r.substring(k.endIndex),b=this.parseChronoFromPosition(T);if(b.success){c=!0,v.type==="due"?(t.dueDate=b.date,b.time&&(t.dueTime=b.time)):(t.scheduledDate=b.date,b.time&&(t.scheduledTime=b.time));let w=this.getChronoMatchOffset(T,b),S=b.matchedText?k.endIndex+w+b.matchedText.length:k.endIndex;r=r.substring(0,k.startIndex)+r.substring(S),r=this.cleanupWhitespace(r)}}}if(c)return r;let d=s.parse(e,new Date,{forwardDate:!0});if(d.length===0)return e;let u=d[0],p=u.text,m=u.start.date(),f=(a=u.end)==null?void 0:a.date(),h=this.findPhraseMatch(u.text,o.due)!==null,g=this.findPhraseMatch(u.text,o.scheduled)!==null;if(f&&ta(f)&&f.getTime()!==m.getTime())t.scheduledDate=D(m,"yyyy-MM-dd"),u.start.isCertain("hour")&&(t.scheduledTime=D(m,"HH:mm")),t.dueDate=D(f,"yyyy-MM-dd"),(i=u.end)!=null&&i.isCertain("hour")&&(t.dueTime=D(f,"HH:mm"));else if(ta(m)){let v=D(m,"yyyy-MM-dd"),k=u.start.isCertain("hour")?D(m,"HH:mm"):void 0;h&&!g?(t.dueDate=v,t.dueTime=k):g&&!h||this.defaultToScheduled?(t.scheduledDate=v,t.scheduledTime=k):(t.dueDate=v,t.dueTime=k)}r=r.replace(p,"").trim(),r=this.cleanupWhitespace(r)}catch(s){console.debug("Error in unified date parsing:",s)}return r}parseChronoFromPosition(e){try{let r=this.getChronoParser().parse(e,new Date,{forwardDate:!0});if(r.length>0){let a=r[0];if(a.index<=3){let i=a.start.date();if(ta(i)){let s={success:!0,date:D(i,"yyyy-MM-dd"),matchedText:a.text,startIndex:a.index};return a.start.isCertain("hour")&&(s.time=D(i,"HH:mm")),s}}}}catch(t){console.debug("Error parsing date with chrono:",t)}return{success:!1}}getChronoMatchOffset(e,t){var i;let r=(i=t.startIndex)!=null?i:0;if(!t.matchedText)return r;let a=e.indexOf(t.matchedText);return a!==-1?a:r}buildRecurrencePatterns(){let e=this.languageConfig.recurrence,t=[],{boundary:r,endBoundary:a}=this.boundaries,i=s=>s.map(o=>this.escapeRegex(o)).join("|");return t.push(...this.buildOrdinalWeekdayPatterns(e,r,a,i)),t.push(...this.buildIntervalPatterns(e,r,a,i)),t.push(...this.buildEveryOtherPatterns(e,r,a,i)),t.push(...this.buildWeekdayPatterns(e,r,a,i)),t.push(...this.buildFrequencyPatterns(e,r,a,i)),t}buildOrdinalWeekdayPatterns(e,t,r,a){let i=a(e.every),s=a([...e.ordinals.first,...e.ordinals.second,...e.ordinals.third,...e.ordinals.fourth,...e.ordinals.last]),o=a([...e.weekdays.monday,...e.weekdays.tuesday,...e.weekdays.wednesday,...e.weekdays.thursday,...e.weekdays.friday,...e.weekdays.saturday,...e.weekdays.sunday]);return[{regex:new RegExp(`${t}(${i})\\s+(${s})\\s+(${o})${r}`,"i"),handler:l=>{let c=l[2].toLowerCase(),d=l[3].toLowerCase(),u=1;return e.ordinals.second.some(m=>m.toLowerCase()===c)?u=2:e.ordinals.third.some(m=>m.toLowerCase()===c)?u=3:e.ordinals.fourth.some(m=>m.toLowerCase()===c)?u=4:e.ordinals.last.some(m=>m.toLowerCase()===c)&&(u=-1),`FREQ=MONTHLY;BYDAY=${this.getWeekdayRRuleCode(d,e)};BYSETPOS=${u}`}}]}buildIntervalPatterns(e,t,r,a){let i=a(e.every),s=a([...e.periods.day,...e.periods.week,...e.periods.month,...e.periods.year]);return[{regex:new RegExp(`${t}(${i})\\s+(\\d+)\\s+(${s})${r}`,"i"),handler:o=>{let l=parseInt(o[2]),c=o[3].toLowerCase();return`FREQ=${this.getPeriodFrequency(c,e)};INTERVAL=${l}`}}]}buildEveryOtherPatterns(e,t,r,a){let i=a(e.every),s=a(e.other),o=a([...e.periods.day,...e.periods.week,...e.periods.month,...e.periods.year]);return[{regex:new RegExp(`${t}(${i})\\s+(${s})\\s+(${o})${r}`,"i"),handler:l=>{let c=l[3].toLowerCase();return`FREQ=${this.getPeriodFrequency(c,e)};INTERVAL=2`}}]}buildWeekdayPatterns(e,t,r,a){let i=a(e.every),s=a([...e.weekdays.monday,...e.weekdays.tuesday,...e.weekdays.wednesday,...e.weekdays.thursday,...e.weekdays.friday,...e.weekdays.saturday,...e.weekdays.sunday]),o=a([...e.pluralWeekdays.monday,...e.pluralWeekdays.tuesday,...e.pluralWeekdays.wednesday,...e.pluralWeekdays.thursday,...e.pluralWeekdays.friday,...e.pluralWeekdays.saturday,...e.pluralWeekdays.sunday]);return[{regex:new RegExp(`${t}(${i})\\s+(${s})${r}`,"i"),handler:l=>{let c=l[2].toLowerCase();return`FREQ=WEEKLY;BYDAY=${this.getWeekdayRRuleCode(c,e)}`}},{regex:new RegExp(`${t}(${o})${r}`,"i"),handler:l=>{let c=l[1].toLowerCase();return`FREQ=WEEKLY;BYDAY=${this.getPluralWeekdayRRuleCode(c,e)}`}}]}buildFrequencyPatterns(e,t,r,a){return[{regex:new RegExp(`${t}(${a(e.frequencies.daily)})${r}`,"i"),handler:()=>"FREQ=DAILY"},{regex:new RegExp(`${t}(${a(e.frequencies.weekly)})${r}`,"i"),handler:()=>"FREQ=WEEKLY"},{regex:new RegExp(`${t}(${a(e.frequencies.monthly)})${r}`,"i"),handler:()=>"FREQ=MONTHLY"},{regex:new RegExp(`${t}(${a(e.frequencies.yearly)})${r}`,"i"),handler:()=>"FREQ=YEARLY"}]}getPeriodFrequency(e,t){return t.periods.week.some(r=>r.toLowerCase()===e)?"WEEKLY":t.periods.month.some(r=>r.toLowerCase()===e)?"MONTHLY":t.periods.year.some(r=>r.toLowerCase()===e)?"YEARLY":"DAILY"}getWeekdayRRuleCode(e,t){return t.weekdays.tuesday.some(r=>r.toLowerCase()===e)?"TU":t.weekdays.wednesday.some(r=>r.toLowerCase()===e)?"WE":t.weekdays.thursday.some(r=>r.toLowerCase()===e)?"TH":t.weekdays.friday.some(r=>r.toLowerCase()===e)?"FR":t.weekdays.saturday.some(r=>r.toLowerCase()===e)?"SA":t.weekdays.sunday.some(r=>r.toLowerCase()===e)?"SU":"MO"}getPluralWeekdayRRuleCode(e,t){return t.pluralWeekdays.tuesday.some(r=>r.toLowerCase()===e)?"TU":t.pluralWeekdays.wednesday.some(r=>r.toLowerCase()===e)?"WE":t.pluralWeekdays.thursday.some(r=>r.toLowerCase()===e)?"TH":t.pluralWeekdays.friday.some(r=>r.toLowerCase()===e)?"FR":t.pluralWeekdays.saturday.some(r=>r.toLowerCase()===e)?"SA":t.pluralWeekdays.sunday.some(r=>r.toLowerCase()===e)?"SU":"MO"}extractRecurrence(e,t){for(let r of this.recurrencePatterns){let a=e.match(r.regex);if(a){let i=r.handler(a);if(this.isValidRRuleString(i))return t.recurrence=i,this.cleanupWhitespace(e.replace(r.regex,""))}}return e}isValidRRuleString(e){if(e.includes("BYDAY=undefined")||e.includes("BYDAY=;")||e.includes("BYDAY=")){let t=e.match(/BYDAY=([^;]*)/);if(t&&(!t[1]||t[1]==="undefined"||t[1].trim()===""))return!1}return!!e.includes("FREQ=")}extractTimeEstimate(e,t){let r=this.languageConfig.timeEstimate,{boundary:a,endBoundary:i}=this.boundaries,s=[{regex:new RegExp(`${a}(\\d+)(${r.hours.map(c=>this.escapeRegex(c)).join("|")})\\s*(\\d+)(${r.minutes.map(c=>this.escapeRegex(c)).join("|")})${i}`,"i"),handler:c=>parseInt(c[1])*60+parseInt(c[3])},{regex:new RegExp(`${a}(\\d+)\\s*(${r.hours.map(c=>this.escapeRegex(c)).join("|")})${i}`,"i"),handler:c=>parseInt(c[1])*60},{regex:new RegExp(`${a}(\\d+)\\s*(${r.minutes.map(c=>this.escapeRegex(c)).join("|")})${i}`,"i"),handler:c=>parseInt(c[1])}],o=e,l=0;for(let c of s){let d=o.match(c.regex);d&&(l+=c.handler(d),o=this.cleanupWhitespace(o.replace(c.regex,"")))}return l>0&&(t.estimate=l),o}validateAndCleanupResult(e){return e.title.trim()||(e.title="Untitled Task"),e.tags=[...new Set(e.tags.filter(Boolean))],e.contexts=[...new Set(e.contexts.filter(Boolean))],e.projects=[...new Set(e.projects.filter(Boolean))],e.dueDate&&!this.isValidDateString(e.dueDate)&&delete e.dueDate,e.scheduledDate&&!this.isValidDateString(e.scheduledDate)&&delete e.scheduledDate,e.dueTime&&!this.isValidTimeString(e.dueTime)&&delete e.dueTime,e.scheduledTime&&!this.isValidTimeString(e.scheduledTime)&&delete e.scheduledTime,e}getPreviewData(e){let t=[];if(e.title&&t.push({icon:"edit-3",text:`"${e.title}"`}),e.details&&t.push({icon:"file-text",text:`Details: "${e.details.substring(0,50)}${e.details.length>50?"...":""}"`}),e.dueDate){let r=e.dueTime?`${e.dueDate} at ${e.dueTime}`:e.dueDate;t.push({icon:"calendar",text:`Due: ${r}`})}if(e.scheduledDate){let r=e.scheduledTime?`${e.scheduledDate} at ${e.scheduledTime}`:e.scheduledDate;t.push({icon:"calendar-clock",text:`Scheduled: ${r}`})}if(e.priority&&t.push({icon:"alert-triangle",text:`Priority: ${e.priority}`}),e.status&&t.push({icon:"activity",text:`Status: ${e.status}`}),e.contexts&&e.contexts.length>0&&t.push({icon:"map-pin",text:`Contexts: ${e.contexts.map(r=>"@"+r).join(", ")}`}),e.projects&&e.projects.length>0){let r=e.projects.map(a=>`+${a}`).join(", ");t.push({icon:"folder",text:`Projects: ${r}`})}if(e.tags&&e.tags.length>0&&t.push({icon:"tag",text:`Tags: ${e.tags.map(r=>"#"+r).join(", ")}`}),e.recurrence){let r="Invalid recurrence";try{e.recurrence.includes("FREQ=")&&this.isValidRRuleString(e.recurrence)&&(r=m2e.fromString(e.recurrence).toText())}catch(a){console.debug("Error parsing rrule for preview:",a)}t.push({icon:"repeat",text:`Recurrence: ${r}`})}if(e.estimate&&t.push({icon:"clock",text:`Estimate: ${e.estimate} min`}),e.userFields&&Object.keys(e.userFields).length>0)for(let[r,a]of Object.entries(e.userFields)){let i=this.triggerConfig.getUserField(r),s=(i==null?void 0:i.displayName)||r,o;Array.isArray(a)?o=a.join(", "):o=a,t.push({icon:"box",text:`${s}: ${o}`})}return t}getPreviewText(e){return this.getPreviewData(e).map(t=>t.text).join(" • ")}getStatusSuggestions(e,t=10){let r=e.toLowerCase();return this.statusConfigs.filter(a=>a&&typeof a.value=="string"&&typeof a.label=="string").filter(a=>a.value.trim()!==""&&a.label.trim()!=="").filter(a=>a.value.toLowerCase().includes(r)||a.label.toLowerCase().includes(r)).slice(0,t).map(a=>({value:a.value,label:a.label,display:a.label}))}}});var Goe=y(()=>{Tre();lB();cB();dB();qoe()});function f2e(){return typeof navigator!="undefined"&&navigator.language?navigator.language:void 0}function h2e(n){var t,r;let e=(r=(t=n.settings.calendarViewSettings)==null?void 0:t.locale)==null?void 0:r.trim();return e||f2e()||n.settings.nlpLanguage||"en"}var Nn,Wl=y(()=>{Goe();Nn=class n extends FA{static fromPlugin(e){let t=e.settings;return new n(t.customStatuses,t.customPriorities,t.nlpDefaultToScheduled,t.nlpLanguage,t.nlpTriggers,t.userFields,{dateLocale:h2e(e)})}constructor(e=[],t=[],r=!0,a="en",i,s,o){super(e,t,r,a,i,s,o),this.taskNotesNlpTriggers=i,this.taskNotesStatusConfigs=e,this.taskNotesUserFields=s||[],this.taskNotesPriorityConfigs=t}parseInput(e){let t=super.parseInput(e),r=this.applyTriggeredStatusMatch(e,t),a=this.removePriorityShortcutResidue(e,r),i=this.extractLinkedUserFields(e,a);return this.normalizeUserFieldValues(i)}applyTriggeredStatusMatch(e,t){let r=this.findTriggeredStatusMatch(e);if(!r)return t;t.status=r.config.value;let a=t.title;for(let i of this.getStatusShortcutResidues(r.token))a=this.removeTokenFragment(a,i);return t.title=a||"Untitled Task",t}findTriggeredStatusMatch(e){var a;let t=this.getStatusTrigger();if(!t||this.taskNotesStatusConfigs.length===0)return null;let r=[];for(let i of this.taskNotesStatusConfigs)for(let s of this.getStatusPhrases(i))r.push({config:i,token:`${t}${s}${t}`}),r.push({config:i,token:`${t}${s}`});return r.sort((i,s)=>s.token.length-i.token.length),(a=r.find(i=>this.containsToken(e,i.token)))!=null?a:null}getStatusShortcutResidues(e){let t=new Set([e]);for(let r of this.taskNotesStatusConfigs)for(let a of this.getStatusPhrases(r)){let i=this.removeFirstCaseInsensitive(e,a);i&&i!==e&&this.addStatusShortcutResidue(t,i)}return Array.from(t).filter(r=>r.trim().length>0).sort((r,a)=>a.length-r.length)}addStatusShortcutResidue(e,t){e.add(t),e.add(t.replace(/\s+/g," ").trim())}getStatusPhrases(e){return[e.value,e.label].filter(t=>typeof t=="string"&&t.trim().length>0).map(t=>t.trim())}removePriorityShortcutResidue(e,t){if(!t.priority||this.taskNotesPriorityConfigs.length===0)return t;let r=this.taskNotesPriorityConfigs.find(c=>c.value===t.priority);if(!r)return t;let a=this.getPriorityTrigger(),i=[r.value,r.label].filter(c=>typeof c=="string"&&c.trim().length>0).flatMap(c=>a?[`${a}${c}`,c]:[c]),s=[r.label,r.value].filter(c=>typeof c=="string"&&c.trim().length>0),o=new Set;for(let c of i)if(this.containsToken(e,c))for(let d of s){let u=this.removeFirstCaseInsensitive(c,d);!u||u===c||o.add(u)}let l=t.title;for(let c of Array.from(o).sort((d,u)=>u.length-d.length))l=this.removeTokenFragment(l,c);return t.title=l||"Untitled Task",t}getPriorityTrigger(){var t;let e=(t=this.taskNotesNlpTriggers)==null?void 0:t.triggers.find(r=>r.propertyId==="priority");return(e==null?void 0:e.trigger)||""}getStatusTrigger(){var t;let e=(t=this.taskNotesNlpTriggers)==null?void 0:t.triggers.find(r=>r.propertyId==="status");return(e==null?void 0:e.enabled)===!1?"":(e==null?void 0:e.trigger)||"*"}containsToken(e,t){let r=this.escapeRegexLiteral(t);return new RegExp(`(^|\\s)${r}(?=\\s|$)`,"iu").test(e)}removeTokenFragment(e,t){let r=this.escapeRegexLiteral(t);return e.replace(new RegExp(`(^|\\s)${r}(?=\\s|$)`,"giu"),"$1").replace(/\s+/g," ").trim()}removeFirstCaseInsensitive(e,t){let r=e.toLowerCase().indexOf(t.toLowerCase());return r===-1?null:`${e.slice(0,r)}${e.slice(r+t.length)}`}normalizeUserFieldValues(e){var r;if(!e.userFields)return e;let t=e.userFields;for(let a of this.taskNotesUserFields){let i=t[a.id];if(typeof i=="string")if(a.type==="boolean"){let s=i.trim().toLowerCase();s==="true"?t[a.id]=!0:s==="false"&&(t[a.id]=!1)}else a.type==="date"&&(t[a.id]=(r=this.normalizeDateUserFieldValue(i))!=null?r:i)}return e}normalizeDateUserFieldValue(e){let t=e.trim();if(!t)return null;let r=super.parseInput(t);return r.scheduledDate||r.dueDate||null}extractLinkedUserFields(e,t){var i;let r=((i=this.taskNotesNlpTriggers)==null?void 0:i.triggers)||[];if(r.length===0||this.taskNotesUserFields.length===0)return t;let a=t.title;for(let s of r){if(!s.enabled)continue;let o=this.taskNotesUserFields.find(p=>p.id===s.propertyId);if(!o)continue;let l=this.escapeRegexLiteral(s.trigger),c=new RegExp(`${l}(\\[\\[[^\\]]+\\]\\]|\\[[^\\]]+\\]\\([^\\)]+\\))`,"gu"),d=Array.from(e.matchAll(c));if(d.length===0)continue;let u=d.map(p=>p[1]).filter(p=>typeof p=="string"&&p.length>0);if(u.length!==0){if(t.userFields||(t.userFields={}),o.type==="list"){let p=t.userFields[o.id],m=Array.isArray(p)?p:typeof p=="string"?[p]:[];t.userFields[o.id]=[...m,...u]}else t.userFields[o.id]=u[u.length-1];a=a.replace(c,"").replace(/\s+/g," ").trim()}}return t.title=a,t}escapeRegexLiteral(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}}});function Yoe(n){return n.padStart(2,"0")}function Koe(n,e,t){let r=Number(n),a=Number(e),i=Number(t),s=new Date(r,a-1,i);return s.getFullYear()!==r||s.getMonth()!==a-1||s.getDate()!==i?null:`${n}-${Yoe(e)}-${Yoe(t)}`}function h$(n){let e=n.trim();if(!e)return null;let t=g2e.exec(e);if(t)return Koe(t[1],t[2],t[3]);let r=y2e.exec(e);return r?Koe(r[1],r[2],r[3]):null}function g$(n,e,t){var r;n.value=e,(r=t.onCommit)==null||r.call(t,e),n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0}))}function v2e(n){return n.key.length===1&&/\d/.test(n.key)&&!n.altKey&&!n.ctrlKey&&!n.metaKey}function ql(n,e={}){var c,d;let t="",r=0,a=(c=e.now)!=null?c:(()=>Date.now()),i=(d=e.typeBufferResetMs)!=null?d:1500,s=u=>{if(!v2e(u))return;let p=a();p-r>i&&(t=""),r=p,t=`${t}${u.key}`.slice(-8);let m=h$(t);m&&(u.preventDefault(),t="",g$(n,m,e))},o=u=>{var f,h;let p=(h=(f=u.clipboardData)==null?void 0:f.getData("text"))!=null?h:"",m=h$(p);m&&(u.preventDefault(),t="",g$(n,m,e))},l=()=>{let u=h$(n.value);!u||u===n.value||(t="",g$(n,u,e))};return n.addEventListener("keydown",s),n.addEventListener("paste",o),n.addEventListener("input",l),()=>{n.removeEventListener("keydown",s),n.removeEventListener("paste",o),n.removeEventListener("input",l)}}var g2e,y2e,rC=y(()=>{g2e=/^(\d{4})(\d{2})(\d{2})$/,y2e=/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})$/});var ele={};Xe(ele,{DateTimePickerModal:()=>oo,formatCalendarDate:()=>Qoe,getParsedDateTimeSelection:()=>Joe,parseNaturalLanguageDateTime:()=>Xoe});function Zoe(n){return String(n).padStart(2,"0")}function Qoe(n,e,t){return`${n}-${Zoe(e+1)}-${Zoe(t)}`}function Joe(n,e){let t=n.scheduledDate||n.dueDate,r=n.scheduledDate?n.scheduledTime:n.dueTime;if(e==="due"?(t=n.dueDate,r=n.dueTime):e==="scheduled"&&(t=n.scheduledDate,r=n.scheduledTime),t)return{date:t,time:r||null};let a=e==="due"?n.scheduledDate:n.dueDate,i=e==="due"?n.scheduledTime:n.dueTime;return a?{date:a,time:i||null}:null}function Xoe(n,e,t){let r=n.trim();return r?Joe(e.parseInput(r),t):null}function k2e(n,e){let t=new Date(n);return t.setDate(t.getDate()+e),t}function T2e(n){let e=new Date(n),t=(1-e.getDay()+7)%7||7;return e.setDate(e.getDate()+t),e}var Bf,oo,$y=y(()=>{Bf=require("obsidian");Wl();rC();oo=class extends Bf.Modal{constructor(t,r){var a;super(t);this.naturalLanguageInput=null;this.dateInput=null;this.timeInput=null;this.selectButtonEl=null;this.detachDateInputBehavior=null;this.options=r,this.selectedDate=(a=r.currentDate)!=null?a:null}onOpen(){let{contentEl:t}=this;t.empty(),t.addClass("tasknotes-plugin","date-time-picker-modal"),this.options.title&&t.createEl("h3",{text:this.options.title,cls:"date-time-picker-modal__title"}),this.renderQuickActions(t),this.renderNaturalLanguageInput(t),this.renderDateInput(t),this.shouldShowTime()&&this.renderTimeInput(t),this.renderActions(t),this.updateSelectButtonState(),window.setTimeout(()=>{var r;this.canUseNaturalLanguageInput()&&this.naturalLanguageInput?this.naturalLanguageInput.focus():(r=this.dateInput)==null||r.focus()},100)}onClose(){var t;(t=this.detachDateInputBehavior)==null||t.call(this),this.detachDateInputBehavior=null,this.contentEl.empty()}renderQuickActions(t){let r=new Date,a=[{label:"Today",date:r},{label:"Tomorrow",date:k2e(r,1)},{label:"Next week",date:T2e(r)}],i=t.createDiv({cls:"date-time-picker-modal__quick-actions"});for(let s of a)i.createEl("button",{text:s.label,cls:"date-time-picker-modal__quick-button",attr:{type:"button"}}).addEventListener("click",()=>{this.selectDate(Qoe(s.date.getFullYear(),s.date.getMonth(),s.date.getDate()))})}renderNaturalLanguageInput(t){if(!this.canUseNaturalLanguageInput())return;let r=t.createDiv({cls:"date-time-picker-modal__nlp-row"});this.naturalLanguageInput=r.createEl("input",{cls:"date-time-picker-modal__nlp-input",attr:{type:"text",placeholder:"Tomorrow at 3pm","aria-label":"Natural language date"}}),this.naturalLanguageInput.addEventListener("keydown",i=>{i.key==="Enter"&&(i.preventDefault(),this.applyNaturalLanguageInput())});let a=r.createEl("button",{cls:"clickable-icon date-time-picker-modal__nlp-button",attr:{type:"button","aria-label":"Apply natural language date",title:"Apply natural language date"}});(0,Bf.setIcon)(a,"wand"),a.addEventListener("click",()=>this.applyNaturalLanguageInput())}renderDateInput(t){var o;let r=t.createDiv({cls:"date-time-picker-modal__date-field"});r.createEl("label",{text:"Date",cls:"date-time-picker-modal__field-label",attr:{for:"tasknotes-date-time-picker-date"}});let a=r.createDiv({cls:"date-time-picker-modal__native-date-control"});this.dateInput=a.createEl("input",{cls:"date-time-picker-modal__date-input",attr:{id:"tasknotes-date-time-picker-date",type:"date",value:(o=this.selectedDate)!=null?o:"","aria-label":"Date"}});let i=()=>{var l;this.updateSelectedDate(((l=this.dateInput)==null?void 0:l.value)||null)};this.dateInput.addEventListener("input",i),this.dateInput.addEventListener("change",i),this.detachDateInputBehavior=ql(this.dateInput,{onCommit:l=>this.updateSelectedDate(l)}),this.dateInput.addEventListener("keydown",l=>{var c;l.key==="Enter"&&((c=this.dateInput)!=null&&c.value)&&(l.preventDefault(),this.updateSelectedDate(this.dateInput.value),this.confirmSelectedDate())});let s=a.createEl("button",{cls:"clickable-icon date-time-picker-modal__native-date-button",attr:{type:"button","aria-label":"Open native date picker",title:"Open native date picker"}});(0,Bf.setIcon)(s,"calendar-days"),s.addEventListener("click",()=>{var l,c,d;(c=(l=this.dateInput)==null?void 0:l.showPicker)==null||c.call(l),(d=this.dateInput)==null||d.focus()})}renderTimeInput(t){var a;let r=t.createDiv({cls:"date-time-picker-modal__time-field"});r.createEl("label",{text:"Time (optional)",cls:"date-time-picker-modal__field-label",attr:{for:"tasknotes-date-time-picker-time"}}),this.timeInput=r.createEl("input",{cls:"date-time-picker-modal__time-input",attr:{id:"tasknotes-date-time-picker-time",type:"time",value:(a=this.options.currentTime)!=null?a:""}}),this.timeInput.addEventListener("keydown",i=>{i.key==="Enter"&&this.selectedDate&&(i.preventDefault(),this.confirmSelectedDate())})}renderActions(t){let r=t.createDiv({cls:"date-time-picker-modal__actions"});this.options.currentDate&&r.createEl("button",{text:"Clear date",cls:"date-time-picker-modal__action-button",attr:{type:"button"}}).addEventListener("click",()=>{this.options.onSelect(null,null),this.close()}),r.createEl("button",{text:"Cancel",cls:"date-time-picker-modal__action-button",attr:{type:"button"}}).addEventListener("click",()=>this.close()),this.selectButtonEl=r.createEl("button",{text:"Select",cls:"mod-cta date-time-picker-modal__action-button",attr:{type:"button"}}),this.selectButtonEl.addEventListener("click",()=>this.confirmSelectedDate())}selectDate(t){this.updateSelectedDate(t),this.confirmSelectedDate()}updateSelectedDate(t){this.selectedDate=t,this.dateInput&&this.dateInput.value!==(t!=null?t:"")&&(this.dateInput.value=t!=null?t:""),this.updateSelectButtonState()}confirmSelectedDate(){var t;this.selectedDate&&(this.options.onSelect(this.selectedDate,this.shouldShowTime()&&((t=this.timeInput)==null?void 0:t.value)||null),this.close())}updateSelectButtonState(){this.selectButtonEl&&(this.selectButtonEl.disabled=!this.selectedDate)}canUseNaturalLanguageInput(){var t;return this.options.naturalLanguageParser?!0:!!((t=this.options.plugin)!=null&&t.settings.enableNaturalLanguageInput)}shouldShowTime(){return this.options.showTime!==!1}getNaturalLanguageParser(){var t;return this.options.naturalLanguageParser?this.options.naturalLanguageParser:(t=this.options.plugin)!=null&&t.settings.enableNaturalLanguageInput?Nn.fromPlugin(this.options.plugin):null}applyNaturalLanguageInput(){var i,s;let t=this.getNaturalLanguageParser(),r=(s=(i=this.naturalLanguageInput)==null?void 0:i.value)!=null?s:"",a=t?Xoe(r,t,this.options.dateRole):null;if(!a){new Bf.Notice("Could not find a date in that text.");return}this.options.onSelect(a.date,this.shouldShowTime()?a.time:null),this.close()}}});var rle={};Xe(rle,{DateContextMenu:()=>rl});function w2e(){return(0,tle.moment)()}function S2e(n){return n.setSubmenu()}var tle,b2e,rl,Uy=y(()=>{tle=require("obsidian");Md();Id();$y();xe();q();b2e=M({tag:"Components/DateContextMenu"});rl=class{constructor(e){this.menu=new ra,this.options=e,this.buildMenu()}t(e,t,r){var a;return((a=this.options.plugin)==null?void 0:a.i18n.translate(e,r))||t||e}getFirstDayOfWeek(){var t,r,a;let e=(a=(r=(t=this.options.plugin)==null?void 0:t.settings)==null?void 0:r.calendarViewSettings)==null?void 0:a.firstDay;return typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=6?e:0}buildMenu(){this.options.title&&(this.menu.addItem(i=>{i.setTitle(this.options.title||""),i.setIcon("calendar"),i.setDisabled(!0)}),this.menu.addSeparator());let e=this.getDateOptions(),t=e.filter(i=>i.category==="increment");t.length>0&&(t.forEach(i=>{this.menu.addItem(s=>{i.icon&&s.setIcon(i.icon),s.setTitle(i.label),s.onClick(async()=>{this.options.onSelect(i.value,null)})})}),this.menu.addSeparator()),e.filter(i=>i.category==="basic").forEach(i=>{this.menu.addItem(s=>{i.icon&&s.setIcon(i.icon);let l=i.value&&i.value===this.options.currentValue?this.t("contextMenus.date.selected","✓ {label}",{label:i.label}):i.label;s.setTitle(l),s.onClick(async()=>{this.options.onSelect(i.value,null)})})});let a=e.filter(i=>i.category==="weekday");a.length>0&&(this.menu.addSeparator(),this.menu.addItem(i=>{i.setTitle(this.t("contextMenus.date.weekdaysLabel","Weekdays")),i.setIcon("calendar");let s=S2e(i);a.forEach(o=>{s.addItem(l=>{let d=o.value&&o.value===this.options.currentValue?this.t("contextMenus.date.selected","✓ {label}",{label:o.label}):o.label;l.setTitle(d),l.setIcon("calendar"),l.onClick(async()=>{this.options.onSelect(o.value,null)})})})})),this.menu.addSeparator(),this.menu.addItem(i=>{i.setTitle(this.t("contextMenus.date.pickDateTime","Pick date & time…")),i.setIcon("calendar"),i.onClick(async()=>{this.showDateTimePicker()})}),this.options.currentValue&&this.menu.addItem(i=>{i.setTitle(this.t("contextMenus.date.clearDate","Clear date")),i.setIcon("x"),i.onClick(async()=>{this.options.onSelect(null,null)})})}show(e){za(this.menu,e)}showAtElement(e){jl(this.menu,e)}getDateOptions(){let e=w2e(),t=[];this.options.currentValue&&(t.push({label:this.t("contextMenus.date.increment.plusOneDay","+1 day"),value:ay(this.options.currentValue,1),icon:"plus",category:"increment"}),t.push({label:this.t("contextMenus.date.increment.minusOneDay","-1 day"),value:ay(this.options.currentValue,-1),icon:"minus",category:"increment"}),t.push({label:this.t("contextMenus.date.increment.plusOneWeek","+1 week"),value:ay(this.options.currentValue,7),icon:"plus-circle",category:"increment"}),t.push({label:this.t("contextMenus.date.increment.minusOneWeek","-1 week"),value:ay(this.options.currentValue,-7),icon:"minus-circle",category:"increment"})),t.push({label:this.t("contextMenus.date.basic.today","Today"),value:e.format("YYYY-MM-DD"),icon:"calendar-check",isToday:!0,category:"basic"}),t.push({label:this.t("contextMenus.date.basic.tomorrow","Tomorrow"),value:e.clone().add(1,"day").format("YYYY-MM-DD"),icon:"calendar-plus",category:"basic"});let r=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],a=this.getFirstDayOfWeek();[...r.slice(a),...r.slice(0,a)].forEach(c=>{let d=r.indexOf(c),u=e.clone().day(d);u.isSameOrBefore(e,"day")&&(u=u.add(1,"week"));let p=this.t(`common.weekdays.${c.toLowerCase()}`,c);t.push({label:p,value:u.format("YYYY-MM-DD"),icon:"calendar",category:"weekday"})});let s=e.clone().day(6);(s.isBefore(e)||s.isSame(e,"day"))&&s.add(1,"week"),t.push({label:this.t("contextMenus.date.basic.thisWeekend","This weekend"),value:s.format("YYYY-MM-DD"),icon:"calendar-days",category:"basic"});let o=e.clone().day(1).add(1,"week");t.push({label:this.t("contextMenus.date.basic.nextWeek","Next week"),value:o.format("YYYY-MM-DD"),icon:"calendar-plus",category:"basic"});let l=e.clone().add(1,"month").startOf("month");return t.push({label:this.t("contextMenus.date.basic.nextMonth","Next month"),value:l.format("YYYY-MM-DD"),icon:"calendar-range",category:"basic"}),t}showDateTimePicker(){var r;let e=this.options.app||((r=this.options.plugin)==null?void 0:r.app);if(!e){b2e.error("DateContextMenu: No app instance available for modal",{category:"validation",operation:"datecontextmenu-no-app-instance-modal"});return}new oo(e,{currentDate:this.options.currentValue||null,currentTime:this.options.currentTime||null,title:this.t("contextMenus.date.modal.title","Set date & time"),dateRole:this.options.dateRole,plugin:this.options.plugin,onSelect:(a,i)=>{this.options.onSelect(a,i)}}).open()}}});var nle={};Xe(nle,{ConfirmationModal:()=>Hy,showConfirmationModal:()=>ur});async function ur(n,e){return new Hy(n,e).show()}var LA,Hy,Fi=y(()=>{LA=require("obsidian"),Hy=class extends LA.Modal{constructor(e,t){super(e),this.options={confirmText:"Confirm",cancelText:"Cancel",isDestructive:!1,...t}}show(){return new Promise(e=>{this.resolve=e,this.open()})}onOpen(){let{contentEl:e}=this;e.empty(),new LA.Setting(e).setName(this.options.title).setHeading(),e.createEl("p",{text:this.options.message});let t=e.createDiv({cls:"modal-button-container"});t.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),t.classList.add("tn-static-display-flex-75816cae"),t.classList.remove("tn-static-display-flex-8bb39979","tn-static-gap-0-5rem-ce2fca4d","tn-static-gap-12px-ed7b3d87","tn-static-gap-6px-f0abc1db","tn-static-gap-8px-33fcd4c3"),t.classList.add("tn-static-gap-10px-f3d7ce77"),t.classList.remove("tn-static-justify-content-center-03c4bb6f","tn-static-justify-content-space-between-a562f4fd"),t.classList.add("tn-static-justify-content-flex-end-455f8cca"),t.classList.remove("tn-static-font-size-12px-b0cc7e05","tn-static-margin-top-0-5rem-3dc98b5e","tn-static-margin-top-0-d462248a","tn-static-margin-top-12px-91e0f558","tn-static-margin-top-16px-1b0f4999","tn-static-margin-top-1rem-2239d6d5","tn-static-margin-top-30px-2fbbbcd4","tn-static-margin-top-4px-96ad6099","tn-static-margin-top-8px-8a77e5a3","tn-static-margin-top-8px-f4f01e68"),t.classList.add("tn-static-margin-top-20px-a26bda7d");let r=null;this.options.thirdButtonText&&(r=t.createEl("button",{text:this.options.thirdButtonText}),r.addEventListener("click",()=>{this.options.onThirdButton&&this.options.onThirdButton(),this.close()}));let a=t.createEl("button",{text:this.options.cancelText});a.addEventListener("click",()=>{this.resolve(!1),this.close()});let i=t.createEl("button",{text:this.options.confirmText,cls:this.options.isDestructive?"mod-warning":"mod-cta"});this.options.isDestructive&&(i.classList.remove("tn-static-background-color-var-background-mo-94b219f0","tn-static-background-color-var-background-se-9087a23e","tn-static-background-color-var-color-base-40-ef5f175e","tn-static-background-color-var-text-accent-a954c70f"),i.classList.add("tn-static-background-color-var-color-red-134bc721"),i.classList.remove("tn-static-color-var-color-accent-d2cad743","tn-static-color-var-text-accent-65b47ee3","tn-static-color-var-text-muted-5872de20","tn-static-color-var-text-on-accent-f3e1679d","tn-static-color-var-text-warning-783d5f03","tn-static-color-var-tn-text-muted-a90fb6f3","tn-static-cursor-pointer-2723efcc","tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-2px-0-edce9b14","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c"),i.classList.add("tn-static-color-white-0a43e56a")),i.addEventListener("click",()=>{this.resolve(!0),this.close()}),window.setTimeout(()=>{this.options.defaultToConfirm?i.focus():a.focus()},0)}onClose(){let{contentEl:e}=this;e.empty(),this.resolve&&this.resolve(!1)}}});async function Vy(n,e){return new y$(n,e).show()}var nC,y$,v$=y(()=>{nC=require("obsidian"),y$=class extends nC.Modal{constructor(e,t){super(e),this.options={confirmText:"Confirm",cancelText:"Cancel",...t}}show(){return new Promise(e=>{this.resolve=e,this.open()})}onOpen(){let{contentEl:e}=this;e.empty(),new nC.Setting(e).setName(this.options.title).setHeading(),new nC.Setting(e).addText(i=>{var s,o;this.inputEl=i.inputEl,i.setPlaceholder(this.options.placeholder||"").setValue(this.options.initialValue||"").onChange(()=>{}),window.setTimeout(()=>{this.inputEl.focus(),this.inputEl.select()},100),(o=(s=this.options).onInputReady)==null||o.call(s,this.inputEl)});let t=e.createDiv({cls:"modal-button-container"});t.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),t.classList.add("tn-static-display-flex-75816cae"),t.classList.remove("tn-static-display-flex-8bb39979","tn-static-gap-0-5rem-ce2fca4d","tn-static-gap-12px-ed7b3d87","tn-static-gap-6px-f0abc1db","tn-static-gap-8px-33fcd4c3"),t.classList.add("tn-static-gap-10px-f3d7ce77"),t.classList.remove("tn-static-justify-content-center-03c4bb6f","tn-static-justify-content-space-between-a562f4fd"),t.classList.add("tn-static-justify-content-flex-end-455f8cca"),t.classList.remove("tn-static-font-size-12px-b0cc7e05","tn-static-margin-top-0-5rem-3dc98b5e","tn-static-margin-top-0-d462248a","tn-static-margin-top-12px-91e0f558","tn-static-margin-top-16px-1b0f4999","tn-static-margin-top-1rem-2239d6d5","tn-static-margin-top-30px-2fbbbcd4","tn-static-margin-top-4px-96ad6099","tn-static-margin-top-8px-8a77e5a3","tn-static-margin-top-8px-f4f01e68"),t.classList.add("tn-static-margin-top-20px-a26bda7d");let r=t.createEl("button",{text:this.options.cancelText});r.addEventListener("click",()=>{this.resolve(null),this.close()});let a=t.createEl("button",{text:this.options.confirmText,cls:"mod-cta"});a.addEventListener("click",()=>{let i=this.inputEl.value.trim();this.resolve(i||null),this.close()}),this.inputEl.addEventListener("keydown",i=>{i.key==="Enter"?(i.preventDefault(),a.click()):i.key==="Escape"&&(i.preventDefault(),r.click())})}onClose(){let{contentEl:e}=this;e.empty(),this.resolve&&this.resolve(null)}}});function Gl(n){let e=n.trim();return e.startsWith("#")?e.slice(1):e}function C2e(n,e){let t=Gl(n),r=Gl(e);return!t||!r?!1:t.toLowerCase()===r.toLowerCase()}function OA(n,e,t="all"){let r=Gl(n),a=Gl(e);return t==="exact-only"?C2e(r,a):ir.matchesHierarchicalTagExact(r,a)}function jd(n,e,t="all"){return n.filter(r=>!OA(r,e,t))}function k$(n){return n.taskIdentificationMethod==="tag"&&!!n.hideIdentifyingTagsInCards&&!!n.taskTag}function zA(n,e){return k$(e)?jd(n,e.taskTag,e.hideIdentifyingTagsMode):[...n]}function ale(n,e,t,r="all"){let a=[...n],i=e.filter(o=>OA(o,t,r)).map(Gl),s=i.length>0?i:[Gl(t)];for(let o of s)o&&(a.some(l=>Gl(l)===o)||a.push(o));return a}var ip=y(()=>{Ad()});function ile(n,e){n.addEventListener("focus",e),n.addEventListener("click",e)}var $A,x2e,BA,sp,jA,aC=y(()=>{$A=require("obsidian");ip();q();x2e=M({tag:"Modals/TaskModalSuggests"});BA=class extends $A.AbstractInputSuggest{constructor(e,t,r){super(e,t),this.plugin=r,this.input=t,ile(this.input,()=>this.open())}async getSuggestions(e){let t=this.input.value.split(",").map(s=>s.trim()),r=t[t.length-1],a=this.plugin.cacheManager.getAllContexts(),i=t.slice(0,-1);return a.filter(s=>s&&typeof s=="string").filter(s=>!i.includes(s)&&(!r||s.toLowerCase().includes(r.toLowerCase()))).slice(0,10).map(s=>({value:s,display:s,type:"context",toString(){return this.value}}))}renderSuggestion(e,t){t.textContent=e.display}selectSuggestion(e){let t=this.input.value.split(",").map(r=>r.trim());t[t.length-1]=e.value,this.input.value=t.join(", ")+", ",this.input.dispatchEvent(new Event("input",{bubbles:!0})),this.input.focus()}},sp=class extends $A.AbstractInputSuggest{constructor(e,t,r){super(e,t),this.plugin=r,this.input=t,ile(this.input,()=>this.open())}async getSuggestions(e){let t=this.input.value.split(",").map(s=>s.trim()),r=t[t.length-1],a=zA(this.plugin.cacheManager.getAllTags(),this.plugin.settings),i=t.slice(0,-1);return a.filter(s=>s&&typeof s=="string").filter(s=>!i.includes(s)&&(!r||s.toLowerCase().includes(r.toLowerCase()))).slice(0,10).map(s=>({value:s,display:s,type:"tag",toString(){return this.value}}))}renderSuggestion(e,t){t.textContent=e.display}selectSuggestion(e){let t=this.input.value.split(",").map(r=>r.trim());t[t.length-1]=e.value,this.input.value=t.join(", ")+", ",this.input.dispatchEvent(new Event("input",{bubbles:!0})),this.input.focus()}},jA=class extends $A.AbstractInputSuggest{constructor(e,t,r,a){super(e,t),this.plugin=r,this.input=t,this.fieldConfig=a}async getSuggestions(e){let t=this.fieldConfig.type==="list",r="",a=[];if(t?(a=this.input.value.split(",").map(o=>o.trim()),r=a[a.length-1]||""):r=this.input.value.trim(),!r)return[];let i=r.match(/\[\[([^\]]*)$/);if(i){let o=i[1]||"",{FileSuggestHelper:l}=await Promise.resolve().then(()=>(Hb(),aB));return(await l.suggest(this.plugin,o,20,this.fieldConfig.autosuggestFilter)).map(d=>({value:d.insertText,display:d.displayText,type:"user-field",fieldKey:this.fieldConfig.key,toString(){return this.value}}))}return(await this.getExistingUserFieldValues(this.fieldConfig.key)).filter(o=>o&&typeof o=="string").filter(o=>o.toLowerCase().includes(r.toLowerCase())&&(!t||!a.slice(0,-1).includes(o))).slice(0,10).map(o=>({value:o,display:o,type:"user-field",fieldKey:this.fieldConfig.key,toString(){return this.value}}))}async getExistingUserFieldValues(e){var a,i;let t=async()=>{try{let s=this.plugin.app.vault.getMarkdownFiles(),o=new Set;for(let l of s)try{let c=this.plugin.app.metadataCache.getFileCache(l),d=c==null?void 0:c.frontmatter;if(d&&d[e]!==void 0){let u=d[e];Array.isArray(u)?u.forEach(p=>{typeof p=="string"&&p.trim()&&o.add(p.trim())}):typeof u=="string"&&u.trim()?o.add(u.trim()):(typeof u=="number"||typeof u=="boolean")&&o.add(u.toString())}if(o.size>=200)break}catch(c){continue}return Array.from(o).sort()}catch(s){return x2e.error("Error getting user field values:",{category:"persistence",operation:"getting-user-field-values",error:s}),[]}},r=(i=(a=this.plugin.settings)==null?void 0:a.suggestionDebounceMs)!=null?i:0;return r?new Promise(s=>{let o=this.plugin;o.__userFieldSuggestTimer&&window.clearTimeout(o.__userFieldSuggestTimer),o.__userFieldSuggestTimer=window.setTimeout(()=>{(async()=>s(await t()))()},r)}):t()}renderSuggestion(e,t){t.textContent=e.display}selectSuggestion(e){var r;if(this.fieldConfig.type==="list"){let a=this.input.value.split(","),i=(r=a.pop())!=null?r:"",s=a.join(","),o=i.trim(),l=/\[\[/.test(o)?o.replace(/\[\[[^\]]*$/,`[[${e.value}]]`):e.value,c=(s?s+", ":"")+l;this.input.value=c.endsWith(",")?c+" ":c+", "}else{let a=this.input.value,i=a.replace(/\[\[[^\]]*$/,`[[${e.value}]]`);this.input.value=i===a?e.value:i}this.input.dispatchEvent(new Event("input",{bubbles:!0})),this.input.focus()}}});function UA(n,e,t=r=>r.path){return n.map(r=>{switch(e){case"filenames":return sle(r.path);case"markdown-links":return`[[${t(r)}]]`;case"titles":return r.title||sle(r.path);case"paths":return r.path}}).join(` +`)}function sle(n){return(n.split("/").pop()||n).replace(/\.md$/i,"")}var T$=y(()=>{});function Wy(n){let e=new Set,t=[];for(let r of n!=null?n:[]){if(typeof r!="string")continue;let a=Gl(r);!a||e.has(a)||(e.add(a),t.push(a))}return t}function iC(n){return!n||typeof n!="string"?[]:Wy(n.split(","))}function ole(n,e){let t=Wy(n.tags);return e.taskIdentificationMethod!=="tag"?t:jd(t,e.taskTag,e.hideIdentifyingTagsMode)}function HA(n,e){let t=Wy(n),r=new Set(t);for(let a of e){let i=Gl(a);!i||r.has(i)||(r.add(i),t.push(i))}return t.length>0?t:void 0}function sC(n,e){let t=new Set(iC(e.join(",")));if(t.size===0){let a=Wy(n);return a.length>0?a:void 0}let r=Wy(n).filter(a=>!t.has(a));return r.length>0?r:void 0}function VA(n,e){let t=Wy(n);if(e.taskIdentificationMethod!=="tag")return;let r=t.filter(a=>OA(a,e.taskTag,e.hideIdentifyingTagsMode));return r.length>0?r:void 0}var b$=y(()=>{ip()});function qy(n){return n.setSubmenu()}function lle(n){var t,r;let e=n;return(r=(t=e.dom)!=null?t:e.domEl)!=null?r:null}var Rn,op,Gy,w$=y(()=>{Rn=require("obsidian");Uy();Md();Id();Fi();v$();aC();T$();b$();q();op=M({tag:"Components/BatchContextMenu"});Gy=class{constructor(e){this.menu=new ra,this.options=e,this.buildMenu()}t(e,t){return this.options.plugin.i18n.translate(e,t)}buildMenu(){let{selectedPaths:e}=this.options,t=e.length;this.menu.addItem(r=>{r.setTitle(`${t} tasks selected`),r.setIcon("check-square"),r.setDisabled(!0)}),this.menu.addSeparator(),this.menu.addItem(r=>{r.setTitle(this.t("contextMenus.task.status")),r.setIcon("circle");let a=qy(r);this.addStatusOptions(a)}),this.menu.addItem(r=>{r.setTitle(this.t("contextMenus.task.priority")),r.setIcon("star");let a=qy(r);this.addPriorityOptions(a)}),this.menu.addItem(r=>{r.setTitle(this.t("contextMenus.task.tags")),r.setIcon("tags");let a=qy(r);this.addTagOptions(a)}),this.menu.addSeparator(),this.menu.addItem(r=>{r.setTitle(this.t("contextMenus.task.dueDate")),r.setIcon("calendar");let a=qy(r);this.addDateOptions(a,"due")}),this.menu.addItem(r=>{r.setTitle(this.t("contextMenus.task.scheduledDate")),r.setIcon("calendar-clock");let a=qy(r);this.addDateOptions(a,"scheduled")}),this.menu.addSeparator(),this.menu.addItem(r=>{r.setTitle(this.t("contextMenus.task.archive")),r.setIcon("archive"),r.onClick(async()=>{await this.batchArchive(!0)})}),this.menu.addItem(r=>{r.setTitle(this.t("contextMenus.task.unarchive")),r.setIcon("archive-restore"),r.onClick(async()=>{await this.batchArchive(!1)})}),this.menu.addSeparator(),this.menu.addItem(r=>{r.setTitle("Copy selected tasks"),r.setIcon("copy");let a=qy(r);this.addCopyOptions(a)}),this.menu.addSeparator(),this.menu.addItem(r=>{r.setTitle("Clear selection"),r.setIcon("x"),r.onClick(()=>{var a,i;(a=this.options.plugin.taskSelectionService)==null||a.clearSelection(),(i=this.options.plugin.taskSelectionService)==null||i.exitSelectionMode()})}),this.menu.addSeparator(),this.menu.addItem(r=>{r.setTitle(`Delete ${t} tasks`),r.setIcon("trash"),r.onClick(async()=>{await this.batchDelete()})})}addTagOptions(e){e.addItem(t=>{t.setTitle(this.t("contextMenus.task.addTag")),t.setIcon("plus"),t.onClick(()=>{this.openBatchTagInput("add")})}),e.addItem(t=>{t.setTitle(this.t("contextMenus.task.removeTagInput")),t.setIcon("x"),t.onClick(()=>{this.openBatchTagInput("remove")})}),e.addSeparator(),e.addItem(t=>{t.setTitle(this.t("contextMenus.task.clearTags")),t.setIcon("eraser"),t.onClick(async()=>{await this.batchUpdateTags(r=>VA(r.tags,this.options.plugin.settings))})})}addCopyOptions(e){let t=[{title:"Copy filenames",icon:"file-text",format:"filenames"},{title:"Copy Markdown links",icon:"link",format:"markdown-links"},{title:"Copy titles",icon:"text",format:"titles"},{title:"Copy paths",icon:"copy",format:"paths"}];for(let r of t)e.addItem(a=>{a.setTitle(r.title),a.setIcon(r.icon),a.onClick(async()=>{await this.copySelectedTasks(r.format)})})}addStatusOptions(e){let r=[...this.options.plugin.settings.customStatuses].sort((a,i)=>a.order-i.order);for(let a of r)e.addItem(i=>{i.setTitle(a.label),i.setIcon(a.icon||"circle"),i.onClick(async()=>{await this.batchUpdateProperty("status",a.value)}),a.color&&window.setTimeout(()=>{let s=lle(i);if(s){let o=s.querySelector(".menu-item-icon");o&&(o.style.color=a.color)}},10)})}addPriorityOptions(e){let t=this.options.plugin.priorityManager.getPrioritiesByWeight();for(let r of t)e.addItem(a=>{a.setTitle(r.label),a.setIcon("star"),a.onClick(async()=>{await this.batchUpdateProperty("priority",r.value)}),r.color&&window.setTimeout(()=>{let i=lle(a);if(i){let s=i.querySelector(".menu-item-icon");s&&(s.style.color=r.color)}},10)});e.addSeparator(),e.addItem(r=>{r.setTitle(this.t("contextMenus.priority.clearPriority")),r.setIcon("x"),r.onClick(async()=>{await this.batchUpdateProperty("priority",void 0)})})}addDateOptions(e,t){let i=new rl({currentValue:void 0,onSelect:()=>{},plugin:this.options.plugin,app:this.options.plugin.app}).getDateOptions().filter(s=>s.category==="basic");for(let s of i)e.addItem(o=>{s.icon&&o.setIcon(s.icon),o.setTitle(s.label),o.onClick(async()=>{await this.batchUpdateProperty(t,s.value)})});e.addSeparator(),e.addItem(s=>{s.setTitle(this.t("contextMenus.date.clearDate")),s.setIcon("x"),s.onClick(async()=>{await this.batchUpdateProperty(t,void 0)})})}async openBatchTagInput(e){let{plugin:t}=this.options,r=await Vy(t.app,{title:e==="add"?this.t("contextMenus.task.addTag"):this.t("contextMenus.task.removeTagInput"),placeholder:this.t("contextMenus.task.tagPlaceholder"),confirmText:this.t("common.confirm"),cancelText:this.t("common.cancel"),onInputReady:i=>{new sp(t.app,i,t)}}),a=iC(r);a.length!==0&&await this.batchUpdateTags(i=>e==="add"?HA(i.tags,a):sC(i.tags,a))}async copySelectedTasks(e){let{plugin:t,selectedPaths:r}=this.options,a=[];for(let s of r){let o=await t.cacheManager.getTaskInfo(s);a.push({path:s,title:o==null?void 0:o.title})}let i=UA(a,e,s=>this.getMarkdownLinkText(s.path));await navigator.clipboard.writeText(i),new Rn.Notice(`Copied ${a.length} tasks`)}getMarkdownLinkText(e){let t=this.options.plugin.app.vault.getAbstractFileByPath(e);return t instanceof Rn.TFile?this.options.plugin.app.metadataCache.fileToLinktext(t,""):e}async batchUpdateTags(e){var s,o;let{plugin:t,selectedPaths:r,onUpdate:a}=this.options,i=r.length;try{new Rn.Notice(`Updating tags on ${i} tasks...`);let l=0,c=0;for(let d of r)try{let u=await t.cacheManager.getTaskInfo(d);u?(await t.taskService.updateProperty(u,"tags",e(u)),l++):c++}catch(u){op.error(`[BatchContextMenu] Failed to update tags for ${d}:`,{category:"validation",operation:"update-tags",error:u}),c++}c===0?new Rn.Notice(`Updated tags on ${l} tasks`):new Rn.Notice(`Updated tags on ${l} tasks, ${c} failed`),(s=t.taskSelectionService)==null||s.clearSelection(),(o=t.taskSelectionService)==null||o.exitSelectionMode(),a==null||a()}catch(l){op.error("[BatchContextMenu] Batch tag update failed:",{category:"validation",operation:"batch-tag-update",error:l}),new Rn.Notice(this.t("contextMenus.task.notices.updateTagsFailed"))}}async batchUpdateProperty(e,t){var o,l;let{plugin:r,selectedPaths:a,onUpdate:i}=this.options,s=a.length;try{new Rn.Notice(`Updating ${s} tasks...`);let c=0,d=0;for(let u of a)try{let p=await r.cacheManager.getTaskInfo(u);p?(await r.taskService.updateProperty(p,e,t),c++):d++}catch(p){op.error(`[BatchContextMenu] Failed to update task ${u}:`,{category:"validation",operation:"update-task",error:p}),d++}d===0?new Rn.Notice(`Updated ${c} tasks`):new Rn.Notice(`Updated ${c} tasks, ${d} failed`),(o=r.taskSelectionService)==null||o.clearSelection(),(l=r.taskSelectionService)==null||l.exitSelectionMode(),i==null||i()}catch(c){op.error("[BatchContextMenu] Batch update failed:",{category:"validation",operation:"batch-update",error:c}),new Rn.Notice("Failed to update tasks")}}async batchArchive(e){var s,o;let{plugin:t,selectedPaths:r,onUpdate:a}=this.options,i=r.length;try{new Rn.Notice(`${e?"Archiving":"Unarchiving"} ${i} tasks...`);let l=0,c=0;for(let d of r)try{let u=await t.cacheManager.getTaskInfo(d);u&&u.archived!==e?(await t.toggleTaskArchive(u),l++):u?l++:c++}catch(u){op.error(`[BatchContextMenu] Failed to archive task ${d}:`,{category:"persistence",operation:"archive-task",error:u}),c++}c===0?new Rn.Notice(`${e?"Archived":"Unarchived"} ${l} tasks`):new Rn.Notice(`${e?"Archived":"Unarchived"} ${l} tasks, ${c} failed`),(s=t.taskSelectionService)==null||s.clearSelection(),(o=t.taskSelectionService)==null||o.exitSelectionMode(),a==null||a()}catch(l){op.error("[BatchContextMenu] Batch archive failed:",{category:"persistence",operation:"batch-archive",error:l}),new Rn.Notice("Failed to archive tasks")}}async batchDelete(){var s,o;let{plugin:e,selectedPaths:t,onUpdate:r}=this.options,a=t.length;if(await ur(e.app,{title:"Delete tasks",message:`Are you sure you want to delete ${a} tasks? This action cannot be undone.`,confirmText:"Delete",cancelText:this.t("common.cancel"),isDestructive:!0}))try{new Rn.Notice(`Deleting ${a} tasks...`);let l=0,c=0;for(let d of t)try{let u=await e.cacheManager.getTaskInfo(d);u?(await e.taskService.deleteTask(u),l++):c++}catch(u){op.error(`[BatchContextMenu] Failed to delete task ${d}:`,{category:"persistence",operation:"delete-task",error:u}),c++}c===0?new Rn.Notice(`Deleted ${l} tasks`):new Rn.Notice(`Deleted ${l} tasks, ${c} failed`),(s=e.taskSelectionService)==null||s.clearSelection(),(o=e.taskSelectionService)==null||o.exitSelectionMode(),r==null||r()}catch(l){op.error("[BatchContextMenu] Batch delete failed:",{category:"persistence",operation:"batch-delete",error:l}),new Rn.Notice("Failed to delete tasks")}}show(e){za(this.menu,e)}showAtPosition(e,t){G0(),this.menu.showAtPosition({x:e,y:t})}}});function D2e(n){return E2e.includes(n)}function di(n,e){return n.map(t=>D2e(t)?t:t in e.fieldMapper.getMapping()?e.fieldMapper.toUserField(t):t)}function Yy(n,e,t){return t.fieldMapper.isPropertyForField(n,e)}var E2e,Yl=y(()=>{E2e=["tags","blocked","blocking"]});var oC,P2e,A2e,M2e,I2e,N2e,R2e,_2e,S$,Vn,jf=y(()=>{s0();s0();oC=["status","priority","due","scheduled","projects","contexts"],P2e=[{id:"none",value:"none",label:"None",color:"#cccccc",isCompleted:!1,excludeFromCycle:!1,order:0,autoArchive:!1,autoArchiveDelay:5},{id:"open",value:"open",label:"Open",color:"#808080",isCompleted:!1,excludeFromCycle:!1,order:1,autoArchive:!1,autoArchiveDelay:5},{id:"in-progress",value:"in-progress",label:"In progress",color:"#0066cc",isCompleted:!1,excludeFromCycle:!1,order:2,autoArchive:!1,autoArchiveDelay:5},{id:"done",value:"done",label:"Done",color:"#00aa00",isCompleted:!0,excludeFromCycle:!1,order:3,autoArchive:!1,autoArchiveDelay:5}],A2e=[{id:"none",value:"none",label:"None",color:"#cccccc",weight:0},{id:"low",value:"low",label:"Low",color:"#00aa00",weight:1},{id:"normal",value:"normal",label:"Normal",color:"#ffaa00",weight:2},{id:"high",value:"high",label:"High",color:"#ff0000",weight:3}],M2e={defaultContexts:"",defaultTags:"",defaultProjects:"",useParentNoteForTaskCreation:!1,useParentNoteAsProject:!1,useParentHeaderAsProject:!1,inheritParentTaskProperties:!1,defaultTimeEstimate:0,defaultRecurrence:"none",defaultDueDate:"none",defaultDueTime:"none",defaultScheduledDate:"today",defaultScheduledTime:"none",bodyTemplate:"",useBodyTemplate:!1,occurrenceBodyTemplate:"",useOccurrenceBodyTemplate:!1,defaultReminders:[]},I2e={defaultView:"dayGridMonth",customDayCount:3,slotDuration:"00:30:00",slotMinTime:"00:00:00",slotMaxTime:"24:00:00",scrollTime:"08:00:00",firstDay:1,timeFormat:"24",showWeekends:!0,locale:"",defaultShowScheduled:!0,defaultShowDue:!0,defaultShowDueWhenScheduled:!0,defaultShowScheduledToDueSpan:!1,defaultShowTimeEntries:!1,defaultShowRecurring:!0,defaultShowICSEvents:!0,enableTimeblocking:!1,defaultShowTimeblocks:!0,defaultTimeblockColor:"#6366f1",timeblockAttachmentSearchOrder:"name-asc",nowIndicator:!0,selectMirror:!0,weekNumbers:!1,showTodayHighlight:!0,eventMinHeight:15,slotEventOverlap:!0,eventMaxStack:null,dayMaxEvents:!0,dayMaxEventRows:!1},N2e={defaultNoteTemplate:"",defaultNoteFolder:"",icsNoteFilenameFormat:"title",customICSNoteFilenameTemplate:"{title}",enableAutoExport:!1,autoExportPath:"tasknotes-calendar.ics",autoExportInterval:60,useDurationForExport:!1,excludeArchivedFromExport:!1,excludeCompletedFromExport:!1,requireDueDateForExport:!1,requireScheduledDateForExport:!1,useICSEndAsDue:!1,recurringEventRelatedNotesMode:"series"},R2e={enabled:!1,targetCalendarId:"",syncOnTaskCreate:!0,syncOnTaskUpdate:!0,syncOnTaskComplete:!0,syncOnTaskDelete:!0,eventTitleTemplate:"{{title}}",includeDescription:!0,eventColorId:null,syncTrigger:"scheduled",createAsAllDay:!0,defaultEventDuration:60,includeObsidianLink:!0,defaultReminderMinutes:null},_2e={enableFuzzy:!1,rows:["{title|n(Title)}","{aliases|n(Aliases)}","{file.path|n(Path)}"],showAdvanced:!1,requiredTags:[],includeFolders:[],propertyKey:"",propertyValue:""},S$={triggers:[{propertyId:"tags",trigger:"#",enabled:!0},{propertyId:"contexts",trigger:"@",enabled:!0},{propertyId:"projects",trigger:"+",enabled:!0},{propertyId:"status",trigger:"*",enabled:!0},{propertyId:"priority",trigger:"!",enabled:!1}]},Vn={tasksFolder:"TaskNotes/Tasks",moveArchivedTasks:!1,archiveFolder:"TaskNotes/Archive",taskTag:"task",taskIdentificationMethod:"tag",hideIdentifyingTagsInCards:!1,hideIdentifyingTagsMode:"all",taskPropertyName:"",taskPropertyValue:"",excludedFolders:"",defaultTaskPriority:"normal",defaultTaskStatus:"open",taskOrgFiltersCollapsed:!1,taskFilenameFormat:"zettel",storeTitleInFilename:!0,customFilenameTemplate:"{{title}}",occurrenceFilenameTemplate:"",occurrenceFilenameTemplateProperty:"occurrenceFilenameTemplate",taskCreationDefaults:M2e,openTaskAfterCreation:"none",calendarViewSettings:I2e,pomodoroWorkDuration:25,pomodoroShortBreakDuration:5,pomodoroLongBreakDuration:15,pomodoroLongBreakInterval:4,pomodoroAutoStartBreaks:!0,pomodoroAutoStartWork:!1,pomodoroNotifications:!0,pomodoroSoundEnabled:!0,pomodoroSoundVolume:50,pomodoroStorageLocation:"plugin",pomodoroMobileSidebar:"tab",showPomodoroInStatusBar:!0,enableTaskLinkOverlay:!0,disableOverlayOnAlias:!1,enableInstantTaskConvert:!0,useDefaultsOnInstantConvert:!0,preserveCheckboxOnConvert:!1,taskModalTabMovesFocus:!0,enableNaturalLanguageInput:!0,nlpDefaultToScheduled:!0,nlpLanguage:"en",uiLanguage:"system",statusSuggestionTrigger:"*",nlpTriggers:S$,singleClickAction:"edit",doubleClickAction:"openNote",projectAutosuggest:_2e,inlineTaskConvertFolder:"{{currentNotePath}}",disableNoteIndexing:!1,suggestionDebounceMs:0,fieldMapping:Sb,customStatuses:P2e,customPriorities:A2e,recurrenceMigrated:!1,lastSeenVersion:void 0,showReleaseNotesOnUpdate:!0,checkForUpdatesOnStartup:!0,lastNotifiedReleaseVersion:void 0,starterNoteCreated:!1,showTrackedTasksInStatusBar:!1,autoStopTimeTrackingOnComplete:!0,autoStopTimeTrackingNotification:!1,showRelationships:!0,relationshipsPosition:"bottom",showTaskCardInNote:!0,showCompletedTaskStrikethrough:!0,completionMenuAsSubmenu:!0,showExpandableSubtasks:!0,expandSubtasksByDefault:!1,subtaskChevronPosition:"right",viewsButtonAlignment:"right",hideCompletedFromOverdue:!0,icsIntegration:N2e,savedViews:[],enableNotifications:!0,notificationType:"system",notificationSoundEnabled:!1,notificationSoundVolume:50,enableAPI:!1,apiPort:8080,apiAuthToken:"",enableMCP:!1,webhooks:[],userFields:[],modalFieldsConfig:void 0,enableModalSplitLayout:!0,defaultVisibleProperties:["status","priority","due","scheduled","projects","contexts","tags","blocked","blocking"],inlineVisibleProperties:["status","priority","due","scheduled","recurrence"],enableBases:!0,enableMdbaseSpec:!1,autoCreateDefaultBasesFiles:!0,commandFileMapping:{"open-calendar-view":"TaskNotes/Views/mini-calendar-default.base","open-kanban-view":"TaskNotes/Views/kanban-default.base","open-tasks-view":"TaskNotes/Views/tasks-default.base","open-advanced-calendar-view":"TaskNotes/Views/calendar-default.base","open-agenda-view":"TaskNotes/Views/agenda-default.base","pomodoro-stats-base":"TaskNotes/Views/pomodoro-stats.base",relationships:"TaskNotes/Views/relationships.base"},maintainDueDateOffsetInRecurring:!1,resetCheckboxesOnRecurrence:!1,useFrontmatterMarkdownLinks:!1,enableGoogleCalendar:!1,enableMicrosoftCalendar:!1,disableCalendarOnMobile:!1,enabledGoogleCalendars:[],googleCalendarSyncTokens:{},enabledMicrosoftCalendars:[],microsoftCalendarSyncTokens:{},googleCalendarExport:R2e,enableDebugLogging:!1}});function cle(n){return L2e.has(n.trim().toLowerCase())}function qA(n){return typeof n=="object"&&n!==null&&typeof n.renderTo=="function"&&typeof n.toString=="function"}function WA(n){let e=n.toString();return e==="[object Object]"?"":e}function C$(n){var t;return n==null||((t=n.constructor)==null?void 0:t.name)==="NullValue"?!0:qA(n)&&cle(WA(n))}function lC(n){return C$(n)?!0:Array.isArray(n)?n.every(lC):typeof n=="string"?n.trim()===""||cle(n):qA(n)?WA(n).trim()==="":!1}function GA(n,e,t){if(!qA(e)||C$(e))return!1;try{e.renderTo(n,t),!n.hasChildNodes()&&!n.textContent&&(n.textContent=WA(e))}catch(r){F2e.debug("[TaskNotes] Error rendering Bases value:",{category:"persistence",operation:"rendering-bases-value",error:r}),n.textContent=WA(e)}return!0}function $d(n){if(C$(n))return"";if(qA(n))return n;if(n&&typeof n=="object"&&"icon"in n){let e=n;if(e.icon==="lucide-link"&&"data"in e&&e.data!==null&&e.data!==void 0){let t=Y(e.data);if(!t.match(/^[a-z]+:\/\//i)){let a="display"in e&&e.display?Y(e.display):null;return a&&a!==t?`[[${t}|${a}]]`:`[[${t}]]`}let r="display"in e&&e.display?Y(e.display):null;return r?`[${r}](${t})`:t}return"display"in e&&e.display!==null&&e.display!==void 0?e.display:"date"in e&&e.date!==null&&e.date!==void 0?e.date:"data"in e&&e.data!==null&&e.data!==void 0?e.data:e.icon==="lucide-file-question"||e.icon==="lucide-help-circle"?"":e.icon?Y(e.icon).replace("lucide-",""):""}return n}function YA(n,e={},t){var a;let r=(a=e.propertyLabels)==null?void 0:a[n];return r&&r.trim()!==""?r:t&&t.trim()!==""?t:n.startsWith("formula.")?n.substring(8):n.charAt(0).toUpperCase()+n.slice(1)}var F2e,L2e,cC=y(()=>{dr();q();F2e=M({tag:"Ui/TaskCardPresentation"}),L2e=new Set(["null","undefined"])});function x$(n){return n!==null&&typeof n=="object"&&typeof n.getValue=="function"?n:null}function dle(n){return Object.prototype.hasOwnProperty.call(ple,n)}function ule(n,e){return ple[e](n)}function dC(n,e,t){try{let r=t.fieldMapper.lookupMappingKey(e);if(r&&dle(r))return ule(n,r);if(dle(e))return ule(n,e);if(e.startsWith("user:"))return O2e(n,e,t);if(n.customProperties&&e in n.customProperties)return $d(n.customProperties[e]);if(n.customProperties){let i=`file.${e}`;if(i in n.customProperties)return $d(n.customProperties[i])}if(e.startsWith("file.")){let i=x$(n.basesData);if(i)try{let s=i.getValue(e);if(s!=null)return $d(s)}catch(s){}}if(e.startsWith("formula."))try{let i=x$(n.basesData);if(!i)return"";let s=i.getValue(e);if(s==null)return"";let o=$d(s);return o!==""?o:""}catch(i){return E$.debug(`[TaskNotes] Error computing formula ${e}:`,{category:"validation",operation:"computing-formula",error:i}),"[Formula Error]"}let a=x$(n.basesData);if(a)try{let i=`note.${e}`,s=a.getValue(i);if(s!=null)return $d(s)}catch(i){}if(n.path){let i=mle(n.path,e,t);if(i!==void 0)return i}return null}catch(r){return E$.warn(`TaskCard: Error getting property ${e}:`,{category:"persistence",operation:"taskcard-getting-property",error:r}),null}}function O2e(n,e,t){var s;let r=e.slice(5),a=(s=t.settings.userFields)==null?void 0:s.find(o=>o.id===r);if(!(a!=null&&a.key))return null;let i=n[a.key];return i===void 0&&(i=mle(n.path,a.key,t)),i}function mle(n,e,t){try{let r=t.app.metadataCache.getCache(n);return r!=null&&r.frontmatter?r.frontmatter[e]:void 0}catch(r){E$.warn(`TaskCard: Error accessing frontmatter for ${n}:`,{category:"validation",operation:"taskcard-accessing-frontmatter",error:r});return}}var E$,ple,D$=y(()=>{cC();q();E$=M({tag:"Ui/TaskCardPropertyAccess"});ple={due:n=>n.due,scheduled:n=>n.scheduled,projects:n=>n.projects,contexts:n=>n.contexts,tags:n=>n.tags,blocked:n=>n.isBlocked,blocking:n=>n.isBlocking,blockedBy:n=>n.blockedBy,blockingTasks:n=>n.blocking,timeEstimate:n=>n.timeEstimate,timeEntries:n=>n.timeEntries,totalTrackedTime:n=>n.totalTrackedTime,recurrence:n=>n.recurrence,recurrenceParent:n=>n.recurrence_parent,occurrenceDate:n=>n.occurrence_date,occurrenceMaterialization:n=>n.occurrence_materialization,occurrenceNextTrigger:n=>n.occurrence_next_trigger,occurrenceTemplate:n=>n.occurrence_template,occurrencePastHorizon:n=>n.occurrence_past_horizon,occurrenceFutureHorizon:n=>n.occurrence_future_horizon,completedDate:n=>n.completedDate,reminders:n=>n.reminders,icsEventId:n=>n.icsEventId,completeInstances:n=>n.complete_instances,skippedInstances:n=>n.skipped_instances,dateCreated:n=>n.dateCreated,dateModified:n=>n.dateModified,sortOrder:n=>n.sortOrder,googleCalendarSync:n=>n.path,checklistProgress:n=>n.path}});function Ss(n,e,t){return n.i18n.translate(`ui.taskCard.${e}`,t)}function Kl(n,e,t){let r=t==null?void 0:t[n];if(r&&r.trim()!=="")return r;let a=z2e(n,e,t),i={due:Ss(e,"labels.due"),scheduled:Ss(e,"labels.scheduled"),recurrence:Ss(e,"labels.recurrence"),completedDate:Ss(e,"labels.completed"),dateCreated:Ss(e,"labels.created"),dateModified:Ss(e,"labels.modified"),blocked:Ss(e,"labels.blocked"),blocking:Ss(e,"labels.blocking")};return YA(n,{propertyLabels:a?{[n]:a}:t},i[n])}function z2e(n,e,t){var r,a;if(t){for(let[i,s]of Object.entries(t))if(!(i===n||s.trim()==="")&&((a=(r=e.fieldMapper)==null?void 0:r.lookupMappingKey)==null?void 0:a.call(r,i))===n)return s}}function uC(n,e,t){return Ss(n,"recurrenceTooltip",{label:Kl("recurrence",n,t),value:Gte(e)})}function P$(n,e){return e===1?Ss(n,"reminderTooltipOne"):Ss(n,"reminderTooltipMany",{count:e})}function KA(n,e){return e?Ss(n,"collapseSubtasks"):Ss(n,"expandSubtasks")}var A$=y(()=>{yt();cC();D$()});function hle(n,e,t){n.createEl("a",{text:t,attr:{href:e,target:"_blank",rel:"noopener"}}).classList.add("external-link")}function $2e(n){return j2e.test(n)}function nl(n,e,t,r,a={}){var p;let{cssClass:i="internal-link",hoverSource:s="tasknotes-property-link",showErrorNotices:o=!1,onPrimaryNavigate:l}=a,c=(p=r.sourcePath)!=null?p:"",d=vt(e),u=n.createEl("a",{cls:i,text:t,attr:{"data-href":d,role:"link",tabindex:"0"}});u.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),(async()=>{try{if(m.ctrlKey||m.metaKey){r.workspace.openLinkText(d,c,!0);return}if(l&&await l(d,m)!==!1)return;let f=r.metadataCache.getFirstLinkpathDest(d,c)||r.metadataCache.getFirstLinkpathDest(d,"");f instanceof lp.TFile?await r.workspace.getLeaf(!1).openFile(f):o&&new lp.Notice(`Note "${t}" not found`)}catch(f){fle.error("[TaskNotes] Error opening internal link:",{category:"internal",operation:"opening-internal-link",details:{filePath:e},error:f}),o&&new lp.Notice(`Failed to open note "${t}"`)}})()}),u.addEventListener("auxclick",m=>{m.button===1&&(m.preventDefault(),m.stopPropagation(),(async()=>{try{(r.metadataCache.getFirstLinkpathDest(d,c)||r.metadataCache.getFirstLinkpathDest(d,""))instanceof lp.TFile&&r.workspace.openLinkText(d,c,!0)}catch(f){fle.error("[TaskNotes] Error opening internal link:",{category:"internal",operation:"opening-internal-link",details:{filePath:e},error:f})}})())}),u.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),u.click())}),u.addEventListener("mouseover",m=>{let f=r.metadataCache.getFirstLinkpathDest(d,c)||r.metadataCache.getFirstLinkpathDest(d,"");if(f instanceof lp.TFile){let h={event:m,source:s,hoverParent:n,targetEl:u,linktext:d,sourcePath:c||f.path};r.workspace.trigger("hover-link",h)}})}function Zl(n,e,t,r){let a=0,i;for(;(i=B2e.exec(e))!==null;){let[o,l,c,d,u,p]=i,m=i.index;if(m>a&&n.appendChild(activeDocument.createTextNode(e.slice(a,m))),l){let f=l,h=f,g=f;if(f.includes("|")){let[v,k]=f.split("|");h=v,g=k}nl(n,h,g,t)}else if(c&&d){let f=String(d).trim(),h=String(c).trim();$2e(f)?hle(n,f,h):nl(n,f,h,t)}else if(u||p){let f=String(u||p);hle(n,f,f)}else n.appendChild(activeDocument.createTextNode(o));a=m+o.length}let s=e.slice(a);if(s&&(r!=null&&r.onTagClick)){let o=/(^|\s)(#[\p{L}\p{N}\p{M}_/-]+)/gu,l=0,c;for(;(c=o.exec(s))!==null;){let[,d,u]=c,p=c.index;p>l&&n.appendChild(activeDocument.createTextNode(s.slice(l,p))),d&&n.appendChild(activeDocument.createTextNode(d));let m=n.createEl("a",{cls:"tag",text:u,attr:{href:u,role:"button",tabindex:"0","data-tn-click-exclude":"true"}});m.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),r.onTagClick(u,f)}),m.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),f.stopPropagation(),r.onTagClick(u,f))}),l=p+d.length+u.length}l0}function H2e(n){return!n||typeof n!="string"?!1:/^\[([^\]]*)\]\(([^)]+)\)$/.test(n)}function V2e(n){let e=n.match(/^\[([^\]]*)\]\(([^)]+)\)$/);if(!e)return null;let t=e[1].trim(),r=e[2].trim(),a=vt(r);return{displayText:t,filePath:a}}function gle(n,e,t){var u,p;let r=(u=t.sourcePath)!=null?u:"",a=vt(n),i=t.metadataCache.getFirstLinkpathDest(a,r)||t.metadataCache.getFirstLinkpathDest(a,"");if(!(i instanceof lp.TFile))return e;let s=t.metadataCache.getCache(i.path),o=(p=s==null?void 0:s.frontmatter)==null?void 0:p.title;if(typeof o!="string"||o.trim().length===0)return e;let l=(e==null?void 0:e.trim())||"",c=i.name,d=i.basename;return l===""||l===c||l===d||l===i.path||l===a?o:e}function Ky(n,e,t,r={}){n.innerHTML="",e.flat(2).filter(i=>i!=null&&typeof i=="string").forEach((i,s)=>{if(s>0&&n.appendChild(activeDocument.createTextNode(", ")),n.appendChild(activeDocument.createTextNode("+")),U2e(i)){let o=i.slice(2,-2),l=o,c=o;if(o.includes("|")){let u=o.split("|");l=u[0].trim(),c=u[1].trim()}let d=gle(l,c,t);nl(n,l,d,t,{cssClass:"task-card__project-link internal-link",hoverSource:"tasknotes-project-link",showErrorNotices:!0,onPrimaryNavigate:r.onPrimaryNavigate})}else if(H2e(i)){let o=V2e(i);if(o){let l=gle(o.filePath,o.displayText,t);nl(n,o.filePath,l,t,{cssClass:"task-card__project-link internal-link",hoverSource:"tasknotes-project-link",showErrorNotices:!0,onPrimaryNavigate:r.onPrimaryNavigate})}else n.appendChild(activeDocument.createTextNode(i))}else n.appendChild(activeDocument.createTextNode(i))})}var lp,fle,B2e,j2e,cp=y(()=>{lp=require("obsidian");Cn();q();fle=M({tag:"Ui/Renderers/LinkRenderer"}),B2e=/\[\[([^[\]]+)\]\]|\[([^\]]+)\]\(([^)]+)\)|<(https?:\/\/[^\s>]+)>|(https?:\/\/[^\s<>()]+[^\s<>().,;:!?])|\[([^\]]+)\]\s*\[([^\]]*)\]/g,j2e=/^[a-z][a-z0-9+.-]*:/i});function yle(n,e,t){if(!e||typeof e!="string")return;let r=G2e(e);if(!r)return;let a=n.createEl("a",{cls:"tag",text:r,attr:{href:r,role:"button",tabindex:"0","data-tn-click-exclude":"true"}});t!=null&&t.onTagClick&&(a.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),t.onTagClick(r,i)}),a.addEventListener("keydown",i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),i.stopPropagation(),t.onTagClick(r,i))}))}function Tle(n,e,t){if(typeof e=="string"){yle(n,e,t);return}if(Array.isArray(e)){e.flat(2).filter(a=>a!=null&&typeof a=="string").forEach((a,i)=>{i>0&&n.appendChild(activeDocument.createTextNode(" ")),yle(n,String(a),t)});return}e!=null&&n.appendChild(activeDocument.createTextNode(Y(e)))}function ble(n,e,t){if(typeof e=="string"){vle(n,e,t);return}if(Array.isArray(e)){e.flat(2).filter(a=>a!=null&&typeof a=="string").forEach((a,i)=>{i>0&&n.appendChild(activeDocument.createTextNode(", ")),vle(n,a,t)||n.appendChild(activeDocument.createTextNode(String(a)))});return}e!=null&&n.appendChild(activeDocument.createTextNode(Y(e)))}function vle(n,e,t){let r=W2e(e);if(t!=null&&t.linkServices&&q2e(r)){let o=kle(r),l=n.createSpan({cls:`context-tag context-tag--link ${o}`,attr:{"data-tn-click-exclude":"true"}});return l.appendChild(activeDocument.createTextNode("@")),Zl(l,r,t.linkServices),!0}let a=K2e(e);if(!a)return!1;let i=kle(a),s=n.createSpan({cls:`context-tag ${i}`,text:a,attr:{role:"button",tabindex:"0","data-tn-click-exclude":"true"}});return t!=null&&t.onTagClick&&(s.addEventListener("click",o=>{var l;o.preventDefault(),o.stopPropagation(),(l=t.onTagClick)==null||l.call(t,a,o)}),s.addEventListener("keydown",o=>{var l;(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),o.stopPropagation(),(l=t.onTagClick)==null||l.call(t,a,o))})),!0}function W2e(n){let e=n.trim();return e.startsWith("@")?e.slice(1).trim():e}function q2e(n){return/\[\[[^[\]]+\]\]/.test(n)||/\[[^\]]+\]\([^)]+\)/.test(n)||/]+>/i.test(n)||/https?:\/\/[^\s<>()]+[^\s<>().,;:!?]/i.test(n)}function G2e(n){if(!n||typeof n!="string")return null;let e=n.trim();if(!e)return null;let t=e.startsWith("#"),r=e.replace(/[^\p{L}\p{N}_#/-]/gu,"");return t?r.length>1?r:null:r?`#${r}`:null}function Y2e(n){let e=5381;for(let t=0;t>>0}function kle(n){if(!n||typeof n!="string")return"context-tag--color-0";let e=n.replace(/^@/,"").toLowerCase();return e?`context-tag--color-${Y2e(e)%20}`:"context-tag--color-0"}function K2e(n){if(!n||typeof n!="string")return null;let e=n.trim();if(!e)return null;let t=e.startsWith("@"),r=e.replace(/[^\p{L}\p{N}_@/-]/gu,"");return t?r.length>1?r:null:r?`@${r}`:null}var wle=y(()=>{dr();cp()});function dp(n,e,t){return n.i18n.translate(`ui.taskCard.${e}`,t)}function Z2e(n){if(n.setAttribute("role","button"),n.tabIndex=0,n.dataset.tnNoDrag==="true"){n.setAttribute("draggable","false");return}n.dataset.tnNoDrag="true",n.setAttribute("draggable","false"),n.addEventListener("mousedown",e=>{e.preventDefault(),e.stopPropagation()}),n.addEventListener("keydown",e=>{e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),e.stopPropagation(),n.click())})}function Q2e(n){return(Array.isArray(n)?n:n?[n]:[]).filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean)}function J2e(n,e){let t=n.start?Sn(n.start,{userTimeFormat:e.settings.calendarViewSettings.timeFormat}):"";return t?`${n.title} (${t})`:n.title}function Sle(n){var e;return((e=n.split("/").pop())==null?void 0:e.replace(/\.md$/i,""))||n}function X2e(n,e,t){let r=Ai(n);if(r){let a=Jo(t.app,e.path,r),i=(a==null?void 0:a.path)||r.uid;return i?{path:i,displayText:(a==null?void 0:a.file.basename)||Sle(i)}:null}if(typeof n=="object"&&n!==null){let a=n.path;if(typeof a=="string"&&a.trim()!=="")return{path:a.trim(),displayText:Sle(a)}}return null}function Dle(n,e,t,r){Z2e(n),n.addEventListener("click",a=>{a.stopPropagation();let i=r==="due"?e.due:e.scheduled;new rl({currentValue:re(i||""),currentTime:si(i||""),onSelect:(o,l)=>{(async()=>{try{let c;o?l?c=`${o}T${l}`:c=o:c=void 0,await t.updateTaskProperty(e,r,c)}catch(c){let d=c instanceof Error?c.message:String(c);I$.error(`Error updating ${r} date:`,{category:"persistence",operation:"updating",details:{value:d}});let u=r==="due"?"contextMenus.task.notices.updateDueDateFailure":"contextMenus.task.notices.updateScheduledFailure";new Zy.Notice(t.i18n.translate(u,{message:d}))}})()},dateRole:r,plugin:t,app:t.app}).show(a)})}function Ple(n){let e=[...oC,"tags","blocked","blocking","googleCalendarSync"];return di(e,n)}function eUe(n){return n.trim().toLowerCase()}function tUe(n,e){let t=e.app.vault.getAbstractFileByPath(n);if(!(t instanceof Zy.TFile))return null;let r=e.app.metadataCache.getFileCache(t);return rUe(r)}function rUe(n){if(n==null)return null;let e=n.listItems;if(!Array.isArray(e)||e.length===0)return null;let t=0,r=0;for(let a of e){if(!a||typeof a.task!="string"||typeof a.parent=="number"&&a.parent>=0)continue;let s=eUe(a.task);s!=="-"&&(t+=1,s==="x"&&(r+=1))}return t===0?null:{completed:r,total:t,percent:Math.round(r/t*100)}}function Ale(n,e,t,r,a={}){let i=dC(t,e,r);if(!QA(i))return null;let s=n.createSpan({cls:`task-card__metadata-property task-card__metadata-property--${e.replace(":","-")}`});try{let l=r.fieldMapper.lookupMappingKey(e)||e;return l in Cle?Cle[l](s,i,t,r,a):e.startsWith("user:")?nUe(s,e,i,r):aUe(s,e,i,r,Kl(e,r,a.propertyLabels)),!s.textContent&&!s.hasChildNodes()?(s.remove(),null):s}catch(o){return I$.warn(`TaskCard: Error rendering property ${e}:`,{category:"persistence",operation:"taskcard-rendering-property",error:o}),s.textContent=`${e}: (error)`,s}}function QA(n){return!lC(n)}function nUe(n,e,t,r){var c;let a=e.slice(5),i=(c=r.settings.userFields)==null?void 0:c.find(d=>d.id===a);if(!i){n.textContent=`${a}: (not found)`;return}let s=i.displayName||a;n.createSpan({text:`${s}: `});let o=n.createSpan({cls:"task-card__metadata-value"}),l={metadataCache:r.app.metadataCache,workspace:r.app.workspace};if(typeof t=="string"&&t.trim()!==""){let d=t.trim();M$(d)?Zl(o,d,l):o.textContent=Ele(t,i)}else if(i.type==="list"&&Array.isArray(t))t.map(u=>$d(u)).filter(QA).forEach((u,p)=>{if(p>0&&o.appendChild(activeDocument.createTextNode(", ")),typeof u=="string"&&u.trim()!==""){let m=u.trim();if(M$(m)){let f=o.createSpan();Zl(f,m,l)}else o.appendChild(activeDocument.createTextNode(String(u)))}else o.appendChild(activeDocument.createTextNode(String(u)))});else{let d=Ele(t,i);o.textContent=d.trim()!==""?d:"(empty)"}}function aUe(n,e,t,r,a){let i=YA(e,{},a);n.createSpan({text:`${i}: `});let s=n.createSpan({cls:"task-card__metadata-value"});Array.isArray(t)?t.map(l=>$d(l)).filter(QA).forEach((l,c)=>{c>0&&s.appendChild(activeDocument.createTextNode(", ")),xle(s,l,r)}):xle(s,t,r)}function xle(n,e,t){if(!QA(e)||t&&GA(n,e,t.app.renderContext))return;if(typeof e=="string"&&t){let a={metadataCache:t.app.metadataCache,workspace:t.app.workspace};if(M$(e)){Zl(n,e,a,{onTagClick:async i=>{let s=i.startsWith("#")?i.slice(1):i;await t.openTagsPane(`#${s}`)}});return}n.appendChild(activeDocument.createTextNode(e));return}let r;if(typeof e=="object"&&e!==null)if(e instanceof Date)r=Sn(e.toISOString(),{dateFormat:"MMM d, yyyy",timeFormat:"",showTime:!1});else{let a=Object.entries(e);r=a.length<=3?a.map(([i,s])=>`${i}: ${Y(s)}`).join(", "):Y(e)}else typeof e=="boolean"?r=e?"✓":"✗":typeof e=="number"?r=Number.isInteger(e)?String(e):e.toFixed(2):r=Y(e);r.length>100&&(r=r.substring(0,97)+"..."),n.appendChild(activeDocument.createTextNode(r))}function M$(n){return n.includes("[[")||n.includes("](")||/]+>/i.test(n)||/(^|\s)https?:\/\/[^\s<>()]+/i.test(n)||n.includes("[")&&n.includes("](")||n.includes("#")&&/\s#\w+|#\w+/.test(n)}function Ele(n,e){if(n==null)return"";try{switch(e.type){case"text":case"number":return Y(n);case"date":return Sn(Y(n),{dateFormat:"MMM d, yyyy",timeFormat:"",showTime:!1});case"boolean":return n?"✓":"✗";case"list":return Array.isArray(n)?n.flat(2).map(Y).join(", "):Y(n);default:return Y(n)}}catch(t){return I$.warn("TaskCard: Error formatting user property value:",{category:"validation",operation:"taskcard-formatting-user-property-value",error:t}),Y(n)}}function ZA(n){let e=Number(re(n).slice(0,4));return Number.isInteger(e)&&e!==new Date().getFullYear()?"MMM d, yyyy":"MMM d"}function iUe(n,e,t,r,a){var p,m;let i=C0(e),s=r.statusManager.isCompletedStatus(t.status),o=(m=(p=r.settings)==null?void 0:p.hideCompletedFromOverdue)!=null?m:!0,l=ps(e,s,o),c=r.settings.calendarViewSettings.timeFormat,d=Kl("due",r,a),u="";if(i){let f=Sn(e,{dateFormat:"",showTime:!0,userTimeFormat:c});u=f.trim()===""?dp(r,"dueToday",{label:d}):dp(r,"dueTodayAt",{label:d,time:f})}else if(l){let f=Sn(e,{dateFormat:ZA(e),showTime:!0,userTimeFormat:c});u=dp(r,"dueOverdue",{label:d,display:f})}else{let f=Sn(e,{dateFormat:ZA(e),showTime:!0,userTimeFormat:c});u=dp(r,"dueLabel",{label:d,display:f})}n.textContent=u,n.classList.add("task-card__metadata-date","task-card__metadata-date--due"),l&&n.classList.add("task-card__metadata-date--overdue"),i&&n.classList.add("task-card__metadata-date--today"),!i&&!ps(e,!1,!1)&&n.classList.add("task-card__metadata-date--future"),n.dataset.tnAction="edit-date",n.dataset.tnDateType="due",Dle(n,t,r,"due")}function sUe(n,e,t,r,a){var p,m;let i=C0(e),s=r.statusManager.isCompletedStatus(t.status),o=(m=(p=r.settings)==null?void 0:p.hideCompletedFromOverdue)!=null?m:!0,l=ps(e,s,o),c=r.settings.calendarViewSettings.timeFormat,d=Kl("scheduled",r,a),u="";if(i){let f=Sn(e,{dateFormat:"",showTime:!0,userTimeFormat:c});u=f.trim()===""?dp(r,"scheduledToday",{label:d}):dp(r,"scheduledTodayAt",{label:d,time:f})}else if(l){let f=Sn(e,{dateFormat:ZA(e),showTime:!0,userTimeFormat:c});u=dp(r,"scheduledPast",{label:d,display:f})}else{let f=Sn(e,{dateFormat:ZA(e),showTime:!0,userTimeFormat:c});u=dp(r,"scheduledLabel",{label:d,display:f})}n.textContent=u,n.classList.add("task-card__metadata-date","task-card__metadata-date--scheduled"),l&&n.classList.add("task-card__metadata-date--past"),i&&n.classList.add("task-card__metadata-date--today"),!i&&!ps(e,!1,!1)&&n.classList.add("task-card__metadata-date--future"),n.dataset.tnAction="edit-date",n.dataset.tnDateType="scheduled",Dle(n,t,r,"scheduled")}function Mle(n,e){n.style.display=e.length>0?"":"none"}var Zy,I$,Cle,Ile=y(()=>{Zy=require("obsidian");Uy();jf();yt();ip();xe();dr();Yl();cC();A$();cp();wle();Zs();q();I$=M({tag:"Ui/TaskCardProperties"});Cle={due:(n,e,t,r,a)=>{typeof e=="string"&&iUe(n,e,t,r,a==null?void 0:a.propertyLabels)},scheduled:(n,e,t,r,a)=>{typeof e=="string"&&sUe(n,e,t,r,a==null?void 0:a.propertyLabels)},projects:(n,e,t,r)=>{if(Array.isArray(e)){let a={metadataCache:r.app.metadataCache,workspace:r.app.workspace,sourcePath:t.path};Ky(n,e,a)}},contexts:(n,e,t,r)=>{if(Array.isArray(e)){let a={onTagClick:async i=>{let s=i.startsWith("@")?i.slice(1):i;await r.openTagsPane(`#${s}`)},linkServices:{metadataCache:r.app.metadataCache,workspace:r.app.workspace,sourcePath:t.path}};ble(n,e,a)}},tags:(n,e,t,r)=>{if(Array.isArray(e)){let a=e;r.settings.taskIdentificationMethod==="tag"&&r.settings.hideIdentifyingTagsInCards&&(a=jd(e,r.settings.taskTag,r.settings.hideIdentifyingTagsMode)),a.length>0&&Tle(n,a,{onTagClick:async s=>{let o=s.startsWith("#")?s.slice(1):s;await r.openTagsPane(`#${o}`)}})}},timeEstimate:(n,e,t,r)=>{typeof e=="number"&&(n.textContent=`${r.formatTime(e)} estimated`)},totalTrackedTime:(n,e,t,r)=>{typeof e=="number"&&e>0&&(n.textContent=`${r.formatTime(e)} tracked`)},recurrence:(n,e,t,r,a)=>{typeof e=="string"&&(n.textContent=uC(r,e,a==null?void 0:a.propertyLabels))},recurrenceParent:(n,e,t,r)=>{if(typeof e=="string"&&e.trim()!==""){n.createSpan({text:"Parent: "});let a={metadataCache:r.app.metadataCache,workspace:r.app.workspace,sourcePath:t.path};Zl(n,e,a)}},occurrenceDate:(n,e,t,r)=>{var a;typeof e=="string"&&(n.textContent=`Occurrence: ${Sn(e,{dateFormat:"MMM d",showTime:!1,userTimeFormat:(a=r.settings.calendarViewSettings)==null?void 0:a.timeFormat})}`,n.classList.add("task-card__metadata-pill--occurrence"))},occurrenceMaterialization:(n,e)=>{e==="manual"?n.textContent="Occurrence notes: manual":e==="on_completion"?n.textContent="Occurrence notes: after completion":e==="rolling"&&(n.textContent="Occurrence notes: rolling")},occurrenceNextTrigger:(n,e)=>{e==="completion"?n.textContent="Next note: completion":e==="completion_or_skip"&&(n.textContent="Next note: completion or skip")},occurrenceTemplate:(n,e,t,r)=>{if(typeof e=="string"&&e.trim()!==""){n.createSpan({text:"Template: "});let a={metadataCache:r.app.metadataCache,workspace:r.app.workspace,sourcePath:t.path};Zl(n,e,a)}},completeInstances:(n,e,t)=>{var r;if(Array.isArray(e)&&e.length>0){let a=e.length,i=((r=t.skipped_instances)==null?void 0:r.length)||0,s=Wte(t);if(s){let o=Math.max(s,a+i),l=Math.round(a/o*100);n.textContent=`✓ ${a}/${o} completed (${l}%)`}else n.textContent=`✓ ${a} completed`;n.classList.add("task-card__metadata-pill--completed-instances")}},skippedInstances:(n,e)=>{Array.isArray(e)&&e.length>0&&(n.textContent=`⊘ ${e.length} skipped`,n.classList.add("task-card__metadata-pill--skipped-instances"))},completedDate:(n,e,t,r,a)=>{if(typeof e=="string"){let i=Kl("completedDate",r,a==null?void 0:a.propertyLabels);n.textContent=`${i}: ${Sn(e,{dateFormat:"MMM d",showTime:!1,userTimeFormat:r.settings.calendarViewSettings.timeFormat})}`}},dateCreated:(n,e,t,r,a)=>{if(typeof e=="string"){let i=Kl("dateCreated",r,a==null?void 0:a.propertyLabels);n.textContent=`${i}: ${Sn(e,{dateFormat:"MMM d",showTime:!1,userTimeFormat:r.settings.calendarViewSettings.timeFormat})}`}},dateModified:(n,e,t,r,a)=>{if(typeof e=="string"){let i=Kl("dateModified",r,a==null?void 0:a.propertyLabels);n.textContent=`${i}: ${Sn(e,{dateFormat:"MMM d",showTime:!1,userTimeFormat:r.settings.calendarViewSettings.timeFormat})}`}},blocked:(n,e,t,r,a)=>{var i,s;if(e===!0){let o=(s=(i=t.blockedBy)==null?void 0:i.length)!=null?s:0,l=Kl("blocked",r,a==null?void 0:a.propertyLabels);n.textContent=o>0?`${l} (${o})`:l,n.classList.add("task-card__metadata-pill--blocked")}},blocking:(n,e,t,r,a)=>{var i,s;if(e===!0){let o=(s=(i=t.blocking)==null?void 0:i.length)!=null?s:0,l=Kl("blocking",r,a==null?void 0:a.propertyLabels);n.textContent=o>0?`${l} (${o})`:l,n.classList.add("task-card__metadata-pill--blocking")}},blockedBy:(n,e,t,r)=>{if(Array.isArray(e)&&e.length>0){n.createSpan({text:"Blocked by: "});let a=n.createSpan(),i={metadataCache:r.app.metadataCache,workspace:r.app.workspace,sourcePath:t.path};e.forEach((s,o)=>{o>0&&a.appendChild(activeDocument.createTextNode(", "));let l=X2e(s,t,r);l&&nl(a,l.path,l.displayText,i)})}},blockingTasks:(n,e,t,r)=>{if(Array.isArray(e)&&e.length>0){n.createSpan({text:"Blocking: "});let a=n.createSpan();e.forEach((i,s)=>{var l;s>0&&a.appendChild(activeDocument.createTextNode(", "));let o=a.createEl("a",{cls:"internal-link",attr:{href:i}});o.textContent=((l=i.split("/").pop())==null?void 0:l.replace(".md",""))||i,o.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),r.app.workspace.openLinkText(i,"",!1)})})}},timeEntries:(n,e,t,r)=>{if(Array.isArray(e)&&e.length>0){let a=oi(e);a>0&&(n.textContent=`${r.formatTime(a)} tracked (${e.length} ${e.length===1?"entry":"entries"})`)}},reminders:(n,e)=>{Array.isArray(e)&&e.length>0&&(n.textContent=`${e.length} ${e.length===1?"reminder":"reminders"}`)},icsEventId:(n,e,t,r)=>{let a=Q2e(e);if(a.length===0)return;let i=a.map(s=>{var o;return(o=r.icsNoteService.findEventById(s))==null?void 0:o.event}).filter(s=>!!s).map(s=>J2e(s,r));i.length>0?n.textContent=`Calendar: ${i.join(", ")}`:n.textContent=`Linked to ${a.length} calendar ${a.length===1?"event":"events"}`},checklistProgress:(n,e,t,r)=>{let a=tUe(t.path,r);if(!a)return;let i=n.createSpan({cls:"task-card__progress"}),o=i.createSpan({cls:"task-card__progress-bar"}).createSpan({cls:"task-card__progress-fill"});o.style.width=`${a.percent}%`,a.percent>0&&a.percent<5&&(o.classList.remove("tn-static-min-width-0-3922d326"),o.classList.add("tn-static-min-width-2px-709d7da0")),i.createSpan({cls:"task-card__progress-label",text:`${a.completed}/${a.total}`}),(0,Zy.setTooltip)(i,`${a.percent}% complete (${a.completed}/${a.total})`,{placement:"top"})}}});function oUe(n){if(typeof n=="number")return n===1?"show-all":"inherit";let e=Y(n).trim().toLowerCase().replace(/^['"]|['"]$/g,"").replace(/[_\s]+/g,"-");return e==="show-all"||e==="1"?"show-all":"inherit"}function JA(n,e={}){var a,i;if(oUe((i=(a=e.resolveExpandedRelationshipFilterMode)==null?void 0:a.call(e))!=null?i:e.expandedRelationshipFilterMode)!=="inherit")return n;let r=e.expandedRelationshipTaskPaths;return r?n.filter(s=>r.has(s.path)):n}function Nle(n,e={},t){let r=e.expandedRelationshipTaskOrder;if(!r||r.size===0)return t([...n]);let a=[],i=[];for(let s of n)r.has(s.path)?a.push(s):i.push(s);return a.sort((s,o)=>{let l=r.get(s.path),c=r.get(o.path);return l===void 0||c===void 0?0:l-c}),[...a,...t([...i])]}function $f(n,e){let t=Array.isArray(n.blockedBy)?n.blockedBy:[],r=new Set;for(let a of t){let i=Ai(a);if(!i)continue;let s=Jo(e,n.path,i),o=(s==null?void 0:s.path)||i.uid;o&&r.add(o)}return Array.from(r)}var XA=y(()=>{Zs();dr()});function al(n){if(n.setAttribute("role","button"),n.tabIndex=0,n.dataset.tnNoDrag==="true"){n.setAttribute("draggable","false");return}n.dataset.tnNoDrag="true",n.setAttribute("draggable","false"),n.addEventListener("mousedown",e=>{e.preventDefault(),e.stopPropagation()}),n.addEventListener("keydown",e=>{e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),e.stopPropagation(),n.click())})}function Ql(n){let{container:e,className:t,icon:r,tooltip:a,ariaLabel:i,onClick:s,visible:o=!0}=n;if(!o)return null;let l=e.createDiv({cls:t,attr:{"aria-label":i||a}});return(0,pC.setIcon)(l,r),(0,pC.setTooltip)(l,a,{placement:"top"}),s&&(al(l),l.addEventListener("click",c=>{c.stopPropagation(),s(c)})),l}function Uf(n,e,t){let r=n.querySelector(e);if(!t.shouldExist)return r==null||r.remove(),null;if(r)return r.setAttribute("aria-label",t.ariaLabel||t.tooltip),(0,pC.setTooltip)(r,t.tooltip,{placement:"top"}),t.onClick&&al(r),r;let i=n.querySelector(".task-card__badges")||n.querySelector(".task-card__main-row");return i?Ql({container:i,...t}):null}var pC,mC=y(()=>{pC=require("obsidian")});var Rle={};Xe(Rle,{PriorityContextMenu:()=>Ud});var Ud,fC=y(()=>{Md();Id();Ud=class{constructor(e){this.sortedPriorities=[];this.targetDoc=activeDocument;this.menu=new ra,this.options=e,this.buildMenu()}buildMenu(){this.sortedPriorities=this.options.plugin.priorityManager.getPrioritiesByWeightAsc(),this.sortedPriorities.forEach(e=>{this.menu.addItem(t=>{let r=e.label;t.setIcon("star"),e.value===this.options.currentValue&&(r=`✓ ${e.label}`),t.setTitle(r),t.onClick(async()=>{this.options.onSelect(e.value)})})})}show(e){var t,r;(r=(t=e.target)==null?void 0:t.instanceOf)!=null&&r.call(t,HTMLElement)&&(this.targetDoc=e.target.ownerDocument),za(this.menu,e),window.setTimeout(()=>{this.applyColorStyling()},10)}showAtElement(e){this.targetDoc=e.ownerDocument,jl(this.menu,e),window.setTimeout(()=>{this.applyColorStyling()},10)}applyColorStyling(){let e=this.targetDoc.querySelector(".menu");if(!e)return;let t=e.querySelectorAll(".menu-item");this.sortedPriorities.forEach((r,a)=>{let i=t[a];if(i&&r.color){let s=i.querySelector(".menu-item-icon");s&&(s.style.color=r.color)}})}}});var jle={};Xe(jle,{RecurrenceContextMenu:()=>il,buildCustomRecurrenceRule:()=>Ble,buildRecurrenceOptions:()=>zle,buildWeekdaysOnlyRecurrenceRule:()=>tM,formatDateForDTSTART:()=>Ole,formatDateForInput:()=>R$,getMonthDayOptions:()=>_$,getOrderedRecurrenceWeekdays:()=>Fle,getPluginCalendarLocale:()=>gC,getRecurrenceStartDate:()=>hC,getWeekdayOnlyRRuleCodes:()=>Lle});function _le(n){if(n)try{let e=Intl.Locale;return e?new e(n).weekInfo:void 0}catch(e){return}}function lUe(n,e){var r;if(typeof n=="number"&&Number.isInteger(n)&&n>=0&&n<=6)return n;let t=(r=_le(e))==null?void 0:r.firstDay;return typeof t=="number"?t%7:1}function gC(n){var r,a,i;let e=(i=(a=(r=n.settings)==null?void 0:r.calendarViewSettings)==null?void 0:a.locale)==null?void 0:i.trim();if(e)return e;let t=typeof navigator!="undefined"?navigator.language:"";if(t)return t;try{return Intl.DateTimeFormat().resolvedOptions().locale}catch(s){return}}function Fle(n,e){let t=lUe(n,e),r=eM.findIndex(i=>i.dateIndex===t),a=r>=0?r:1;return[...eM.slice(a),...eM.slice(0,a)]}function Lle(n){var a,i;let e=(i=(a=_le(n))==null?void 0:a.weekend)==null?void 0:i.map(s=>s%7).filter(s=>s>=0&&s<=6);if(!e||e.length===0)return["MO","TU","WE","TH","FR"];let t=new Set(e),r=eM.filter(s=>!t.has(s.dateIndex)).map(s=>s.code);return r.length>0&&r.length<7?r:["MO","TU","WE","TH","FR"]}function tM(n,e){return`DTSTART:${n};FREQ=WEEKLY;BYDAY=${Lle(e).join(",")}`}function hC(n,e=new Date){let t=n==null?void 0:n.match(/^(\d{4})-(\d{2})-(\d{2})/);if(!t)return e;let r=parseInt(t[1],10),a=parseInt(t[2],10),i=parseInt(t[3],10),s=new Date(r,a-1,i);return s.getFullYear()!==r||s.getMonth()!==a-1||s.getDate()!==i?e:s}function Ole(n){let e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),r=String(n.getDate()).padStart(2,"0");return`${e}${t}${r}`}function R$(n){let e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),r=String(n.getDate()).padStart(2,"0");return`${e}-${t}-${r}`}function cUe(n){var t;if(!(n!=null&&n.includes("T")))return;let e=n.match(/T(\d{2}):(\d{2})(?::(\d{2}))?/);if(e)return`${e[1]}${e[2]}${(t=e[3])!=null?t:"00"}Z`}function N$(n){let e=["th","st","nd","rd"],t=n%100;return n+(e[(t-20)%10]||e[t]||e[0])}function zle(n){let e=[],t=hC(n.scheduledDate),r=["SU","MO","TU","WE","TH","FR","SA"],a=["January","February","March","April","May","June","July","August","September","October","November","December"],i=r[t.getDay()],s=t.getDate(),o=t.getMonth()+1,l=a[t.getMonth()],c=t.toLocaleDateString(n.calendarLocale||void 0,{weekday:"long"}),d=Ole(t);if(n.currentValue){let u=n.currentValue.match(/DTSTART:(\d{8}(?:T\d{6}Z?)?)/);if(u&&u[1].includes("T")){let p=u[1].split("T")[1].replace(/Z$/,"")+"Z";d=`${d}T${p}`}}else{let u=cUe(n.scheduledDate);u&&(d=`${d}T${u}`)}return e.push({label:n.translate("components.recurrenceContextMenu.daily"),value:`DTSTART:${d};FREQ=DAILY;INTERVAL=1`,icon:"calendar-days"}),e.push({label:n.translate("components.recurrenceContextMenu.weeklyOn",{day:c}),value:`DTSTART:${d};FREQ=WEEKLY;INTERVAL=1;BYDAY=${i}`,icon:"calendar"}),e.push({label:n.translate("components.recurrenceContextMenu.everyTwoWeeksOn",{day:c}),value:`DTSTART:${d};FREQ=WEEKLY;INTERVAL=2;BYDAY=${i}`,icon:"calendar"}),e.push({label:n.translate("components.recurrenceContextMenu.monthlyOnThe",{ordinal:N$(s)}),value:`DTSTART:${d};FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=${s}`,icon:"calendar-range"}),e.push({label:n.translate("components.recurrenceContextMenu.everyThreeMonthsOnThe",{ordinal:N$(s)}),value:`DTSTART:${d};FREQ=MONTHLY;INTERVAL=3;BYMONTHDAY=${s}`,icon:"calendar-range"}),e.push({label:n.translate("components.recurrenceContextMenu.yearlyOn",{month:l,ordinal:N$(s)}),value:`DTSTART:${d};FREQ=YEARLY;INTERVAL=1;BYMONTH=${o};BYMONTHDAY=${s}`,icon:"calendar-clock"}),e.push({label:n.translate("components.recurrenceContextMenu.weekdaysOnly"),value:tM(d,n.calendarLocale),icon:"briefcase"}),e.push({label:"─────────",value:"",icon:void 0}),e.push({label:n.translate("components.recurrenceContextMenu.dailyAfterCompletion"),value:`DTSTART:${d};FREQ=DAILY;INTERVAL=1`,icon:"calendar-days",anchor:"completion"}),e.push({label:n.translate("components.recurrenceContextMenu.every3DaysAfterCompletion"),value:`DTSTART:${d};FREQ=DAILY;INTERVAL=3`,icon:"calendar-days",anchor:"completion"}),e.push({label:n.translate("components.recurrenceContextMenu.weeklyAfterCompletion"),value:`DTSTART:${d};FREQ=WEEKLY;INTERVAL=1`,icon:"calendar",anchor:"completion"}),e.push({label:n.translate("components.recurrenceContextMenu.monthlyAfterCompletion"),value:`DTSTART:${d};FREQ=MONTHLY;INTERVAL=1`,icon:"calendar-range",anchor:"completion"}),e}function Ble(n){var r;let e=[],t=n.recurrenceAnchor==="completion";if(n.dtstart){let a=n.dtstart.replace(/-/g,"");if(n.dtstartTime){let i=n.dtstartTime.split(":"),s=`${i[0]}${i[1]}${(r=i[2])!=null?r:"00"}`;a=`${a}T${s}Z`}e.push(`DTSTART:${a}`)}switch(e.push(`FREQ=${n.frequency}`),n.interval>1&&e.push(`INTERVAL=${n.interval}`),n.frequency){case"DAILY":!t&&n.byDay.length>0&&e.push(`BYDAY=${n.byDay.join(",")}`);break;case"WEEKLY":!t&&n.byDay.length>0&&e.push(`BYDAY=${n.byDay.join(",")}`);break;case"MONTHLY":if(t)break;if(n.monthlyType==="bydate"){let a=n.byMonthDay.length>0?n.byMonthDay[0]:new Date().getDate();e.push(`BYMONTHDAY=${a}`)}else if(n.monthlyType==="byday"&&n.byDay.length>0){let a=n.bySetPos||1;e.push(`BYDAY=${a}${n.byDay[0]}`)}break;case"YEARLY":if(t)break;if(n.yearlyType==="bydate"){let a=n.byMonth.length>0?n.byMonth[0]:new Date().getMonth()+1,i=n.byMonthDay.length>0?n.byMonthDay[0]:new Date().getDate();e.push(`BYMONTH=${a}`),e.push(`BYMONTHDAY=${i}`)}else if(n.yearlyType==="byday"){let a=n.byMonth.length>0?n.byMonth[0]:new Date().getMonth()+1;if(e.push(`BYMONTH=${a}`),n.byDay.length>0){let i=n.bySetPos||1;e.push(`BYDAY=${i}${n.byDay[0]}`)}}break}switch(n.endType){case"count":n.count&&n.count>0&&e.push(`COUNT=${n.count}`);break;case"until":n.until&&e.push(`UNTIL=${n.until.replace(/-/g,"")}`);break}return e.join(";")}function _$(){return[...Array.from({length:31},(n,e)=>{let t=e+1;return{value:t.toString(),text:t.toString()}}),{value:"-1",text:"Last day"}]}var lo,eM,il,F$,Qy=y(()=>{lo=require("obsidian");Md();Id();rC();eM=[{dateIndex:0,code:"SU",nameKey:"sunday",shortKey:"sun"},{dateIndex:1,code:"MO",nameKey:"monday",shortKey:"mon"},{dateIndex:2,code:"TU",nameKey:"tuesday",shortKey:"tue"},{dateIndex:3,code:"WE",nameKey:"wednesday",shortKey:"wed"},{dateIndex:4,code:"TH",nameKey:"thursday",shortKey:"thu"},{dateIndex:5,code:"FR",nameKey:"friday",shortKey:"fri"},{dateIndex:6,code:"SA",nameKey:"saturday",shortKey:"sat"}];il=class{constructor(e){this.menu=new ra,this.options=e,this.translate=e.plugin.i18n.translate.bind(e.plugin.i18n),this.buildMenu()}buildMenu(){this.getRecurrenceOptions().forEach(t=>{if(t.label.startsWith("─")){this.menu.addSeparator();return}this.menu.addItem(r=>{let a=t.label;t.icon&&r.setIcon(t.icon),t.value===this.options.currentValue&&(a=`✓ ${t.label}`),r.setTitle(a),r.onClick(async()=>{let i=t.anchor||"scheduled";this.options.onSelect(t.value,i)})})}),this.menu.addSeparator(),this.menu.addItem(t=>{t.setTitle(this.translate("components.recurrenceContextMenu.customRecurrence")),t.setIcon("settings"),t.onClick(async()=>{this.showCustomRecurrenceModal()})}),this.options.currentValue&&this.menu.addItem(t=>{t.setTitle(this.translate("components.recurrenceContextMenu.clearRecurrence")),t.setIcon("x"),t.onClick(async()=>{this.options.onSelect(null)})})}getRecurrenceOptions(){return zle({currentValue:this.options.currentValue,scheduledDate:this.options.scheduledDate,calendarLocale:gC(this.options.plugin),translate:this.translate})}showCustomRecurrenceModal(){new F$(this.options.app,this.options.currentValue||"",this.options.currentAnchor||"scheduled",this.options.scheduledDate,this.options.plugin,(e,t)=>{e&&this.options.onSelect(e,t)}).open()}show(e){za(this.menu,e)}},F$=class extends lo.Modal{constructor(t,r,a,i,s,o){super(t);this.frequency="DAILY";this.interval=1;this.byDay=[];this.byMonthDay=[];this.byMonth=[];this.until="";this.endType="never";this.dtstart="";this.dtstartTime="";this.recurrenceAnchor="scheduled";this.currentValue=r,this.recurrenceAnchor=a,this.scheduledDate=i,this.plugin=s,this.translate=s.i18n.translate.bind(s.i18n),this.onSubmit=o,this.parseCurrentValue()}parseCurrentValue(){var r;if(!this.currentValue){if(this.dtstart=R$(hC(this.scheduledDate)),this.scheduledDate&&this.scheduledDate.includes("T")){let a=this.scheduledDate.match(/T(\d{2}):(\d{2})(?::(\d{2}))?/);a&&(this.dtstartTime=`${a[1]}:${a[2]}:${(r=a[3])!=null?r:"00"}`)}return}let t=this.currentValue.split(";");for(let a of t){let i=a.includes(":")&&a.startsWith("DTSTART")?":":"=",[s,o]=a.split(i);switch(s){case"DTSTART":if(o.length>=8){if(this.dtstart=`${o.slice(0,4)}-${o.slice(4,6)}-${o.slice(6,8)}`,o.length>8&&o.includes("T")){let l=o.slice(9);l.length>=4&&(this.dtstartTime=`${l.slice(0,2)}:${l.slice(2,4)}:${l.slice(4,6)||"00"}`)}}else{let l=new Date(o);isNaN(l.getTime())?this.dtstart=R$(hC(this.scheduledDate)):this.dtstart=o}break;case"FREQ":this.frequency=o;break;case"INTERVAL":this.interval=parseInt(o)||1;break;case"BYDAY":{let l=o.split(","),c=[];for(let d of l){let u=d.match(/^(-?\d+)([A-Z]{2})$/);u?(this.bySetPos=parseInt(u[1]),c.push(u[2])):c.push(d)}this.byDay=c;break}case"BYMONTHDAY":this.byMonthDay=o.split(",").map(l=>parseInt(l));break;case"BYMONTH":this.byMonth=o.split(",").map(l=>parseInt(l));break;case"BYSETPOS":this.bySetPos=parseInt(o);break;case"COUNT":this.count=parseInt(o),this.endType="count";break;case"UNTIL":o.length===8?this.until=`${o.slice(0,4)}-${o.slice(4,6)}-${o.slice(6,8)}`:this.until=o,this.endType="until";break}}}onOpen(){var Dr,cs;let{contentEl:t}=this;t.empty();let r=gC(this.plugin),a=(cs=(Dr=this.plugin.settings)==null?void 0:Dr.calendarViewSettings)==null?void 0:cs.firstDay,i=Fle(a,r),s=hC(this.scheduledDate);t.createEl("h2",{text:this.translate("components.recurrenceContextMenu.customRecurrenceModal.title")}),new lo.Setting(t).setName("Start date").setDesc("The date when the recurrence pattern begins").addText(ne=>{ne.inputEl.type="date",ne.setValue(this.dtstart).onChange(Ce=>{this.dtstart=Ce}),ql(ne.inputEl,{onCommit:Ce=>{this.dtstart=Ce}})}),new lo.Setting(t).setName("Start time").setDesc("The time when recurring instances should appear (optional)").addText(ne=>{ne.inputEl.type="time",ne.inputEl.step="1",ne.setValue(this.dtstartTime).onChange(Ce=>{this.dtstartTime=Ce})}),new lo.Setting(t).setName("Recur from").setDesc("When should the next occurrence be calculated from?").addDropdown(ne=>{ne.addOption("scheduled","Scheduled date (fixed schedule)").addOption("completion","Completion date (flexible schedule)").setValue(this.recurrenceAnchor).onChange(Ce=>{this.recurrenceAnchor=Ce,this.updateFrequencySpecificVisibility()})}),new lo.Setting(t).setName("Frequency").addDropdown(ne=>{ne.addOption("DAILY","Daily").addOption("WEEKLY","Weekly").addOption("MONTHLY","Monthly").addOption("YEARLY","Yearly").setValue(this.frequency).onChange(Ce=>{this.frequency=Ce,this.updateFrequencySpecificVisibility()})}),new lo.Setting(t).setName("Interval").setDesc("Every X days/weeks/months/years").addText(ne=>{ne.setValue(this.interval.toString()).onChange(Ce=>{this.interval=parseInt(Ce)||1})});let o=new lo.Setting(t).setName("Days of week").setDesc("Select specific days (for daily or weekly recurrence)"),l=o.controlEl.createDiv("days-container");i.map(ne=>({key:ne.code,label:this.translate(`components.recurrenceContextMenu.customRecurrenceModal.weekdaysShort.${ne.shortKey}`)})).forEach(ne=>{let Ce=l.createEl("label",{cls:"day-checkbox"});Ce.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),Ce.classList.add("tn-static-display-inline-block-60e32dcb"),Ce.classList.remove("tn-static-margin-right-4px-c6b76b85"),Ce.classList.add("tn-static-margin-right-8px-539fa9a0");let en=Ce.createEl("input",{type:"checkbox"});en.checked=this.byDay.includes(ne.key),en.addEventListener("change",()=>{en.checked?this.byDay.includes(ne.key)||this.byDay.push(ne.key):this.byDay=this.byDay.filter(Qm=>Qm!==ne.key)}),Ce.createSpan({text:` ${ne.label}`})});let d=new lo.Setting(t).setName("Monthly recurrence").setDesc("Choose how to repeat monthly"),u=d.controlEl.createDiv("monthly-options"),p=u.createEl("label",{cls:"radio-option"});p.classList.remove("tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),p.classList.add("tn-static-display-block-2a1b75c9"),p.classList.remove("tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-bottom-0-75rem-c05a3c6e","tn-static-margin-bottom-20px-49f14f8f"),p.classList.add("tn-static-margin-bottom-8px-fdf33f23");let m=p.createEl("input",{type:"radio",value:"bydate"});m.name="monthly-type",m.checked=this.byMonthDay.length>0||this.byDay.length===0&&this.bySetPos===void 0,p.createSpan({text:" On "});let f=p.createEl("select");f.classList.add("tn-static-margin-left-4px-46cec891"),f.classList.remove("tn-static-margin-right-8px-539fa9a0"),f.classList.add("tn-static-margin-right-4px-c6b76b85");for(let ne of _$()){let Ce=f.createEl("option",{value:ne.value,text:ne.text}),en=parseInt(ne.value,10);(this.byMonthDay.length>0&&this.byMonthDay[0]===en||this.byMonthDay.length===0&&en===s.getDate())&&(Ce.selected=!0)}p.createSpan({text:" of each month"});let h=u.createEl("label",{cls:"radio-option"});h.classList.remove("tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),h.classList.add("tn-static-display-block-2a1b75c9"),h.classList.remove("tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-bottom-0-75rem-c05a3c6e","tn-static-margin-bottom-20px-49f14f8f"),h.classList.add("tn-static-margin-bottom-8px-fdf33f23");let g=h.createEl("input",{type:"radio",value:"byday"});g.name="monthly-type",g.checked=this.byDay.length>0&&this.bySetPos!==void 0,h.createSpan({text:" On the "});let v=h.createEl("select");v.classList.add("tn-static-margin-left-4px-46cec891"),v.classList.remove("tn-static-margin-right-8px-539fa9a0"),v.classList.add("tn-static-margin-right-4px-c6b76b85");let k=[{value:"1",text:"first"},{value:"2",text:"second"},{value:"3",text:"third"},{value:"4",text:"fourth"},{value:"-1",text:"last"}];k.forEach(ne=>{let Ce=v.createEl("option",{value:ne.value,text:ne.text});(this.bySetPos===parseInt(ne.value)||!this.bySetPos&&ne.value==="1")&&(Ce.selected=!0)});let T=h.createEl("select");T.classList.add("tn-static-margin-left-4px-46cec891"),T.classList.remove("tn-static-margin-right-8px-539fa9a0"),T.classList.add("tn-static-margin-right-4px-c6b76b85");let b=i.map(ne=>({value:ne.code,text:this.translate(`components.recurrenceContextMenu.customRecurrenceModal.weekdays.${ne.nameKey}`)})),w=["SU","MO","TU","WE","TH","FR","SA"][s.getDay()];b.forEach(ne=>{let Ce=T.createEl("option",{value:ne.value,text:ne.text});(this.byDay.length>0&&this.byDay[0]===ne.value||this.byDay.length===0&&ne.value===w)&&(Ce.selected=!0)}),h.createSpan({text:" of each month"});let S=new lo.Setting(t).setName("Yearly recurrence").setDesc("Choose how to repeat yearly"),C=S.controlEl.createDiv("yearly-options"),x=C.createEl("label",{cls:"radio-option"});x.classList.remove("tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),x.classList.add("tn-static-display-block-2a1b75c9"),x.classList.remove("tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-bottom-0-75rem-c05a3c6e","tn-static-margin-bottom-20px-49f14f8f"),x.classList.add("tn-static-margin-bottom-8px-fdf33f23");let E=x.createEl("input",{type:"radio",value:"bydate"});E.name="yearly-type",E.checked=this.byMonthDay.length>0||this.byDay.length===0&&this.bySetPos===void 0,x.createSpan({text:" On "});let _=x.createEl("select");_.classList.add("tn-static-margin-left-4px-46cec891"),_.classList.remove("tn-static-margin-right-8px-539fa9a0"),_.classList.add("tn-static-margin-right-4px-c6b76b85");let F=["January","February","March","April","May","June","July","August","September","October","November","December"];F.forEach((ne,Ce)=>{let en=_.createEl("option",{value:(Ce+1).toString(),text:ne});(this.byMonth.length>0&&this.byMonth[0]===Ce+1||this.byMonth.length===0&&Ce+1===s.getMonth()+1)&&(en.selected=!0)});let I=x.createEl("select");I.classList.add("tn-static-margin-left-4px-46cec891"),I.classList.remove("tn-static-margin-right-8px-539fa9a0"),I.classList.add("tn-static-margin-right-4px-c6b76b85");for(let ne of _$()){let Ce=I.createEl("option",{value:ne.value,text:ne.text}),en=parseInt(ne.value,10);(this.byMonthDay.length>0&&this.byMonthDay[0]===en||this.byMonthDay.length===0&&en===s.getDate())&&(Ce.selected=!0)}x.createSpan({text:" each year"});let A=C.createEl("label",{cls:"radio-option"});A.classList.remove("tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),A.classList.add("tn-static-display-block-2a1b75c9"),A.classList.remove("tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-bottom-0-75rem-c05a3c6e","tn-static-margin-bottom-20px-49f14f8f"),A.classList.add("tn-static-margin-bottom-8px-fdf33f23");let R=A.createEl("input",{type:"radio",value:"byday"});R.name="yearly-type",R.checked=this.byDay.length>0&&this.bySetPos!==void 0,A.createSpan({text:" On the "});let O=A.createEl("select");O.classList.add("tn-static-margin-left-4px-46cec891"),O.classList.remove("tn-static-margin-right-8px-539fa9a0"),O.classList.add("tn-static-margin-right-4px-c6b76b85"),k.forEach(ne=>{let Ce=O.createEl("option",{value:ne.value,text:ne.text});(this.bySetPos===parseInt(ne.value)||!this.bySetPos&&ne.value==="1")&&(Ce.selected=!0)});let U=A.createEl("select");U.classList.add("tn-static-margin-left-4px-46cec891"),U.classList.remove("tn-static-margin-right-8px-539fa9a0"),U.classList.add("tn-static-margin-right-4px-c6b76b85"),b.forEach(ne=>{let Ce=U.createEl("option",{value:ne.value,text:ne.text});(this.byDay.length>0&&this.byDay[0]===ne.value||this.byDay.length===0&&ne.value===w)&&(Ce.selected=!0)});let pe=A.createEl("select");pe.classList.add("tn-static-margin-left-4px-46cec891"),pe.classList.remove("tn-static-margin-right-8px-539fa9a0"),pe.classList.add("tn-static-margin-right-4px-c6b76b85"),F.forEach((ne,Ce)=>{let en=pe.createEl("option",{value:(Ce+1).toString(),text:ne});(this.byMonth.length>0&&this.byMonth[0]===Ce+1||this.byMonth.length===0&&Ce+1===s.getMonth()+1)&&(en.selected=!0)}),A.createSpan({text:" each year"}),new lo.Setting(t).setName("End condition").setDesc("Choose when the recurrence should end");let oe=t.createDiv("end-condition-container"),X=oe.createEl("label",{cls:"radio-option"});X.classList.remove("tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),X.classList.add("tn-static-display-block-2a1b75c9"),X.classList.remove("tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-bottom-0-75rem-c05a3c6e","tn-static-margin-bottom-20px-49f14f8f"),X.classList.add("tn-static-margin-bottom-8px-fdf33f23");let de=X.createEl("input",{type:"radio",value:"never"});de.name="end-type",de.checked=this.endType==="never",X.createSpan({text:" Never ends"});let Oe=oe.createEl("label",{cls:"radio-option"});Oe.classList.remove("tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),Oe.classList.add("tn-static-display-block-2a1b75c9"),Oe.classList.remove("tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-bottom-0-75rem-c05a3c6e","tn-static-margin-bottom-20px-49f14f8f"),Oe.classList.add("tn-static-margin-bottom-8px-fdf33f23");let Q=Oe.createEl("input",{type:"radio",value:"count"});Q.name="end-type",Q.checked=this.endType==="count",Oe.createSpan({text:" End after "});let Z=Oe.createEl("input",{type:"number",placeholder:"10"});Z.classList.remove("tn-static-width-100-0466783d","tn-static-width-12px-fbf353fb","tn-static-width-16px-7375d50b","tn-static-width-1px-aa77e27e","tn-static-width-200px-2acaf3b5","tn-static-width-80px-8573bae3"),Z.classList.add("tn-static-width-60px-bd09c419"),Z.classList.add("tn-static-margin-left-4px-46cec891"),Z.classList.remove("tn-static-margin-right-8px-539fa9a0"),Z.classList.add("tn-static-margin-right-4px-c6b76b85"),Z.value=this.count?this.count.toString():"",Oe.createSpan({text:" occurrences"});let Ue=oe.createEl("label",{cls:"radio-option"});Ue.classList.remove("tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),Ue.classList.add("tn-static-display-block-2a1b75c9"),Ue.classList.remove("tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-bottom-0-75rem-c05a3c6e","tn-static-margin-bottom-20px-49f14f8f"),Ue.classList.add("tn-static-margin-bottom-8px-fdf33f23");let le=Ue.createEl("input",{type:"radio",value:"until"});le.name="end-type",le.checked=this.endType==="until",Ue.createSpan({text:" End on "});let at=Ue.createEl("input",{type:"date"});at.classList.add("tn-static-margin-left-4px-46cec891"),at.value=this.until?this.until.replace(/(\d{4})(\d{2})(\d{2})/,"$1-$2-$3"):"",ql(at,{onCommit:ne=>{this.until=ne.replace(/-/g,""),le.checked=!0,this.endType="until"}}),de.addEventListener("change",()=>{de.checked&&(this.endType="never")}),Q.addEventListener("change",()=>{Q.checked&&(this.endType="count")}),le.addEventListener("change",()=>{le.checked&&(this.endType="until")}),Z.addEventListener("input",()=>{this.count=parseInt(Z.value)||void 0,Z.value&&(Q.checked=!0,this.endType="count")}),at.addEventListener("input",()=>{this.until=at.value?at.value.replace(/-/g,""):"",at.value&&(le.checked=!0,this.endType="until")}),this.updateFrequencySpecificVisibility=()=>{let ne=this.recurrenceAnchor==="completion";o.settingEl.style.display=(this.frequency==="DAILY"||this.frequency==="WEEKLY")&&!ne?"flex":"none",d.settingEl.style.display=this.frequency==="MONTHLY"&&!ne?"flex":"none",S.settingEl.style.display=this.frequency==="YEARLY"&&!ne?"flex":"none"},this.updateFrequencySpecificVisibility();let He=t.createDiv("button-container");He.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),He.classList.add("tn-static-display-flex-75816cae"),He.classList.remove("tn-static-justify-content-center-03c4bb6f","tn-static-justify-content-space-between-a562f4fd"),He.classList.add("tn-static-justify-content-flex-end-455f8cca"),He.classList.remove("tn-static-display-flex-8bb39979","tn-static-gap-0-5rem-ce2fca4d","tn-static-gap-10px-f3d7ce77","tn-static-gap-12px-ed7b3d87","tn-static-gap-6px-f0abc1db"),He.classList.add("tn-static-gap-8px-33fcd4c3"),He.classList.remove("tn-static-font-size-12px-b0cc7e05","tn-static-margin-top-0-5rem-3dc98b5e","tn-static-margin-top-0-d462248a","tn-static-margin-top-12px-91e0f558","tn-static-margin-top-1rem-2239d6d5","tn-static-margin-top-20px-a26bda7d","tn-static-margin-top-30px-2fbbbcd4","tn-static-margin-top-4px-96ad6099","tn-static-margin-top-8px-8a77e5a3","tn-static-margin-top-8px-f4f01e68"),He.classList.add("tn-static-margin-top-16px-1b0f4999"),He.createEl("button",{text:"Cancel"}).addEventListener("click",()=>{this.close()}),He.createEl("button",{text:"Save",cls:"mod-cta"}).addEventListener("click",()=>{let ne=m.checked?"bydate":"byday",Ce=E.checked?"bydate":"byday";this.frequency==="MONTHLY"?ne==="bydate"?(this.byMonthDay=[parseInt(f.value)],this.byDay=[],this.bySetPos=void 0):(this.byMonthDay=[],this.byDay=[T.value],this.bySetPos=parseInt(v.value)):this.frequency==="YEARLY"&&(Ce==="bydate"?(this.byMonth=[parseInt(_.value)],this.byMonthDay=[parseInt(I.value)],this.byDay=[],this.bySetPos=void 0):(this.byMonth=[parseInt(pe.value)],this.byMonthDay=[],this.byDay=[U.value],this.bySetPos=parseInt(O.value)));let en=this.buildRRule(ne,Ce);this.onSubmit(en,this.recurrenceAnchor),this.close()})}updateFrequencySpecificVisibility(){}buildRRule(t,r){return Ble({frequency:this.frequency,interval:this.interval,dtstart:this.dtstart,dtstartTime:this.dtstartTime,recurrenceAnchor:this.recurrenceAnchor,byDay:this.byDay,byMonthDay:this.byMonthDay,byMonth:this.byMonth,bySetPos:this.bySetPos,endType:this.endType,count:this.count,until:this.until,monthlyType:t,yearlyType:r})}onClose(){let{contentEl:t}=this;t.empty()}}});var $le={};Xe($le,{ReminderModal:()=>sl});var Yr,L$,O$,sl,Jy=y(()=>{Yr=require("obsidian");xe();rC();q();L$=M({tag:"Modals/ReminderModal"}),O$="reminder-modal__fields--hidden",sl=class extends Yr.Modal{constructor(t,r,a,i){super(t);this.selectedType="relative";this.relativeAnchor="due";this.relativeOffset=15;this.relativeUnit="minutes";this.relativeDirection="before";this.absoluteDate="";this.absoluteTime="";this.description="";this.plugin=r,this.task=a,this.reminders=a.reminders?[...a.reminders]:[],this.originalReminders=a.reminders?[...a.reminders]:[],this.onSave=i}onOpen(){let{contentEl:t}=this;t.empty(),t.addClass("tasknotes-plugin"),t.addClass("tasknotes-reminder-modal"),t.createDiv({cls:"reminder-modal__loading"}).createDiv({text:"Loading reminders..."}),this.initializeWithFreshData().catch(a=>{L$.error("Failed to initialize reminder modal:",{category:"internal",operation:"initialize-reminder-modal",error:a}),t.empty(),t.addClass("tasknotes-plugin"),t.addClass("tasknotes-reminder-modal"),t.createDiv({cls:"reminder-modal__error",text:"Failed to load task data. Please try again."})})}async initializeWithFreshData(){let{contentEl:t}=this;if(this.task.path&&this.task.path.trim()!==""){let s=await this.plugin.cacheManager.getTaskInfo(this.task.path);s?(this.task=s,this.reminders=s.reminders?[...s.reminders]:[],this.originalReminders=s.reminders?[...s.reminders]:[]):(this.reminders=this.task.reminders?[...this.task.reminders]:[],this.originalReminders=this.task.reminders?[...this.task.reminders]:[])}else this.reminders=this.task.reminders?[...this.task.reminders]:[],this.originalReminders=this.task.reminders?[...this.task.reminders]:[];t.empty(),t.addClass("tasknotes-plugin"),t.addClass("tasknotes-reminder-modal");let r=t.createDiv({cls:"reminder-modal__header"});r.createEl("h2",{text:"Task reminders"}),r.createDiv({cls:"reminder-modal__task-title",text:this.task.title});let a=this.getTaskContextInfo();if(a){let s=r.createDiv({cls:"reminder-modal__task-dates"});s.textContent=a}let i=t.createDiv({cls:"reminder-modal__content"});this.renderExistingReminders(i),this.renderAddReminderForm(i),this.renderActionButtons(t),this.setupKeyboardHandlers(),this.updateSaveButtonState()}renderActionButtons(t){let r=t.createDiv({cls:"reminder-modal__actions"});this.saveBtn=r.createEl("button",{text:"Save changes",cls:"mod-cta reminder-modal__save-btn"}),this.saveBtn.disabled=!0,this.saveBtn.onclick=async()=>{await this.save()};let a=r.createEl("button",{text:"Cancel",cls:"reminder-modal__cancel-btn"});a.onclick=()=>{this.cancel()}}getTaskContextInfo(){let t=[];return this.task.due&&t.push(`Due: ${wd(this.task.due)}`),this.task.scheduled&&t.push(`Scheduled: ${wd(this.task.scheduled)}`),t.length>0?t.join(" • "):null}setupKeyboardHandlers(){let t=r=>{r.key==="Enter"&&(r.ctrlKey||r.metaKey)&&!this.saveBtn.disabled?(r.preventDefault(),this.save()):r.key==="Escape"&&(r.preventDefault(),this.cancel())};this.contentEl.addEventListener("keydown",t),this.onClose=()=>{this.contentEl.removeEventListener("keydown",t);let{contentEl:r}=this;r.empty()}}updateSaveButtonState(){if(!this.saveBtn)return;let t=this.remindersHaveChanged();this.saveBtn.disabled=!t,this.saveBtn.textContent=t?"Save Changes":"No Changes"}renderExistingReminders(t){let r=t.createDiv({cls:"reminder-modal__section"}),a=r.createDiv({cls:"reminder-modal__section-header"});if(a.createEl("h3",{text:"Current reminders"}),this.reminders.length>0&&a.createSpan({cls:"reminder-modal__reminder-count",text:`(${this.reminders.length})`}),this.reminders.length===0){let s=r.createDiv({cls:"reminder-modal__empty-state"});(0,Yr.setIcon)(s.createDiv({cls:"reminder-modal__empty-icon"}),"bell-off"),s.createDiv({cls:"reminder-modal__empty-text",text:"No reminders set"});return}let i=r.createDiv({cls:"reminder-modal__reminder-list"});this.reminders.forEach((s,o)=>{let l=i.createDiv({cls:"reminder-modal__reminder-card"}),c=l.createDiv({cls:"reminder-modal__reminder-icon"}),d=s.type==="absolute"?"calendar-clock":"timer";(0,Yr.setIcon)(c,d);let u=l.createDiv({cls:"reminder-modal__reminder-content"}),p=u.createDiv({cls:"reminder-modal__reminder-primary"});if(p.textContent=this.formatReminderDisplayText(s),s.description){let h=u.createDiv({cls:"reminder-modal__reminder-description"});h.textContent=`"${s.description}"`}let f=l.createDiv({cls:"reminder-modal__reminder-actions"}).createEl("button",{cls:"reminder-modal__action-btn reminder-modal__remove-btn"});(0,Yr.setIcon)(f,"trash-2"),(0,Yr.setTooltip)(f,"Delete this reminder"),f.onclick=async h=>{h.stopPropagation(),await this.removeReminder(o)}})}formatReminderDisplayText(t){if(t.type==="absolute"){if(t.absoluteTime)try{let r=new Date(t.absoluteTime);return`${r.toLocaleDateString()} at ${r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`}catch(r){return`At ${t.absoluteTime}`}return"Absolute reminder"}else{let r=t.relatedTo==="due"?"due date":"scheduled date";return`${this.formatOffset(t.offset||"")} ${r}`}}renderQuickActions(t){if(!(this.task.due||this.task.scheduled))return;let i=t.createDiv({cls:"reminder-modal__quick-actions"}).createDiv({cls:"reminder-modal__quick-buttons"});[{label:"5m",fullLabel:"5 minutes before",offset:"-PT5M",icon:"clock"},{label:"15m",fullLabel:"15 minutes before",offset:"-PT15M",icon:"clock"},{label:"1h",fullLabel:"1 hour before",offset:"-PT1H",icon:"clock"},{label:"1d",fullLabel:"1 day before",offset:"-P1D",icon:"calendar"}].forEach(({label:o,fullLabel:l,offset:c,icon:d})=>{let u=this.task.due?"due":"scheduled",p=i.createEl("button",{cls:"reminder-modal__quick-btn"}),m=p.createSpan({cls:"reminder-modal__quick-btn-icon"});(0,Yr.setIcon)(m,d),p.createSpan({cls:"reminder-modal__quick-btn-label",text:o}),(0,Yr.setTooltip)(p,`Add reminder ${l} ${u} date`),p.onclick=async()=>{await this.addQuickReminder(u,c,l)}})}async addQuickReminder(t,r,a){let i={id:`rem_${Date.now()}`,type:"relative",relatedTo:t,offset:r,description:a};await this.addReminder(i),new Yr.Notice(`Added reminder: ${a}`)}renderAddReminderForm(t){let r=t.createDiv({cls:"reminder-modal__section"});r.createDiv({cls:"reminder-modal__section-header"}).createEl("h3",{text:"Add new reminder"}),this.renderQuickActions(r);let i=r.createDiv({cls:"reminder-modal__form"}),s=i.createDiv({cls:"reminder-modal__type-selector"}),o=s.createEl("button",{cls:"reminder-modal__type-tab reminder-modal__type-tab--active",text:"Relative",attr:{"data-type":"relative"}}),l=s.createEl("button",{cls:"reminder-modal__type-tab",text:"Absolute",attr:{"data-type":"absolute"}});o.classList.toggle("reminder-modal__type-tab--active",this.selectedType==="relative"),l.classList.toggle("reminder-modal__type-tab--active",this.selectedType==="absolute");let c=f=>{this.selectedType=f,o.classList.toggle("reminder-modal__type-tab--active",f==="relative"),l.classList.toggle("reminder-modal__type-tab--active",f==="absolute"),this.updateFormVisibility(i,this.selectedType)};o.onclick=()=>c("relative"),l.onclick=()=>c("absolute");let d=i.createDiv({cls:"relative-fields"});new Yr.Setting(d).setName("Time").addText(f=>{f.setPlaceholder("15").setValue(String(this.relativeOffset)).onChange(h=>{this.relativeOffset=parseInt(h)||0})}).addDropdown(f=>{f.addOption("minutes","Minutes").addOption("hours","Hours").addOption("days","Days").setValue(this.relativeUnit).onChange(h=>{this.relativeUnit=h})}),new Yr.Setting(d).setName("Direction").addDropdown(f=>{f.addOption("before","Before").addOption("after","After").setValue(this.relativeDirection).onChange(h=>{this.relativeDirection=h})}),new Yr.Setting(d).setName("Relative to").addDropdown(f=>{let h={};this.task.due&&(h.due=`Due date (${wd(this.task.due)})`),this.task.scheduled&&(h.scheduled=`Scheduled date (${wd(this.task.scheduled)})`),Object.keys(h).length===0?(h.none="No dates available",f.setDisabled(!0)):(Object.entries(h).forEach(([g,v])=>{f.addOption(g,v)}),f.setValue(this.relativeAnchor)),f.onChange(g=>{this.relativeAnchor=g})});let u=i.createDiv({cls:`absolute-fields ${O$}`});new Yr.Setting(u).setName("Date").addText(f=>{f.setPlaceholder("Yyyy-mm-dd").setValue(this.absoluteDate).onChange(h=>{this.absoluteDate=h}),f.inputEl.type="date",ql(f.inputEl,{onCommit:h=>{this.absoluteDate=h}})}),new Yr.Setting(u).setName("Time").addText(f=>{f.setPlaceholder("Hh:mm").setValue(this.absoluteTime).onChange(h=>{this.absoluteTime=h}),f.inputEl.type="time"}),new Yr.Setting(i).setName("Description (optional)").addText(f=>{f.setPlaceholder("Custom reminder message").setValue(this.description).onChange(h=>{this.description=h})});let p=i.createEl("button",{cls:"reminder-add-btn"}),m=p.createSpan({cls:"reminder-add-btn-icon"});(0,Yr.setIcon)(m,"plus"),p.createSpan({cls:"reminder-add-btn-text",text:"Add Reminder"}),p.onclick=async()=>{p.disabled=!0,p.classList.add("reminder-add-btn--loading");try{let f=this.createReminder(this.selectedType,this.relativeAnchor,this.relativeOffset,this.relativeUnit,this.relativeDirection,this.absoluteDate,this.absoluteTime,this.description);f&&(await this.addReminder(f),this.selectedType==="relative"?(this.relativeOffset=15,this.relativeUnit="minutes",this.description=""):(this.absoluteDate="",this.absoluteTime="",this.description=""),this.resetFormInputs(i))}catch(f){L$.error("Error adding reminder:",{category:"internal",operation:"adding-reminder",error:f}),new Yr.Notice("Failed to add reminder. Please check your inputs.")}finally{p.disabled=!1,p.classList.remove("reminder-add-btn--loading")}},this.updateFormVisibility(i,this.selectedType)}updateFormVisibility(t,r){let a=t.querySelector(".relative-fields"),i=t.querySelector(".absolute-fields");a.classList.toggle(O$,r!=="relative"),i.classList.toggle(O$,r!=="absolute")}createReminder(t,r,a,i,s,o,l,c){let d=`rem_${Date.now()}`;if(t==="relative"){if(!(r==="due"?this.task.due:this.task.scheduled))return new Yr.Notice(`Cannot create reminder: Task has no ${r} date`),null;let p="PT";return i==="days"?p=`P${a}D`:i==="hours"?p=`PT${a}H`:p=`PT${a}M`,s==="before"&&(p="-"+p),{id:d,type:"relative",relatedTo:r,offset:p,description:c||void 0}}else{if(!o||!l)return new Yr.Notice("Please specify both date and time for absolute reminder"),null;let u=`${o}T${l}:00`;return{id:d,type:"absolute",absoluteTime:u,description:c||void 0}}}formatReminderTiming(t){if(t.type==="absolute")return"Absolute reminder";{let r=t.relatedTo==="due"?"due date":"scheduled date";return`${this.formatOffset(t.offset||"")} ${r}`}}formatReminderDetails(t){if(t.type==="absolute")return`At ${wd(t.absoluteTime||"")}`;{let r=t.relatedTo==="due"?this.task.due:this.task.scheduled;return r?`When ${t.relatedTo} date is ${wd(r)}`:`Relative to ${t.relatedTo} date (not set)`}}formatReminderDescription(t){if(t.description)return t.description;if(t.type==="absolute")return`At ${wd(t.absoluteTime||"")}`;{let r=t.relatedTo==="due"?"due date":"scheduled date";return`${this.formatOffset(t.offset||"")} ${r}`}}formatOffset(t){let r=t.startsWith("-"),i=(r?t.substring(1):t).match(/P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?)?/);if(!i)return t;let[,s,o,l]=i,c=[];if(s&&c.push(`${s} day${s!=="1"?"s":""}`),o&&c.push(`${o} hour${o!=="1"?"s":""}`),l&&c.push(`${l} minute${l!=="1"?"s":""}`),c.length===0)return"At time of";let d=c.join(" ");return r?`${d} before`:`${d} after`}async addReminder(t){this.reminders.push(t),this.refreshRemindersListOnly(),this.task.path&&this.plugin.emitter.trigger("reminder-preview-changed",{taskPath:this.task.path,currentReminders:[...this.reminders],action:"added",reminder:t})}async removeReminder(t){let r=this.reminders[t];this.reminders.splice(t,1),this.refreshRemindersListOnly(),this.task.path&&r&&this.plugin.emitter.trigger("reminder-preview-changed",{taskPath:this.task.path,currentReminders:[...this.reminders],action:"removed",reminder:r})}async refresh(){await this.initializeWithFreshData()}refreshRemindersListOnly(){let t=this.contentEl.querySelector(".reminder-modal__content");if(t){let r=t.querySelector(".reminder-modal__section");r&&r.remove();let a=activeWindow.createDiv();this.renderExistingReminders(a);let i=a.firstChild;i&&t.insertBefore(i,t.firstChild)}this.updateSaveButtonState()}resetFormInputs(t){let r=t.querySelector('input[placeholder="15"]');r&&(r.value=String(this.relativeOffset));let a=t.querySelector('input[placeholder="Custom reminder message"]');a&&(a.value=this.description);let i=t.querySelector('input[type="date"]');i&&(i.value=this.absoluteDate);let s=t.querySelector('input[type="time"]');s&&(s.value=this.absoluteTime);let o=t.querySelector('.setting-item:has(input[placeholder="15"]) select');o&&(o.value=this.relativeUnit);let l=t.querySelector(".setting-item:nth-child(2) select");l&&(l.value=this.relativeDirection);let c=t.querySelector(".setting-item:nth-child(3) select");c&&(c.value=this.relativeAnchor)}async save(){var t;this.saveBtn.disabled=!0,this.saveBtn.textContent="Saving...";try{this.task.path&&this.task.path.trim()!==""&&((t=this.plugin.notificationService)==null||t.clearProcessedRemindersForTask(this.task.path));let r=this.remindersHaveChanged();this.onSave(this.reminders),r&&this.task.path&&this.plugin.emitter.trigger("reminder-changed",{taskPath:this.task.path,oldReminders:this.originalReminders,newReminders:[...this.reminders]}),this.close()}catch(r){L$.error("Failed to save reminders:",{category:"persistence",operation:"save-reminders",error:r}),new Yr.Notice("Failed to save reminders. Please try again."),this.saveBtn.disabled=!1,this.saveBtn.textContent="Save changes"}}cancel(){this.remindersHaveChanged()&&this.task.path&&this.plugin.emitter.trigger("reminder-preview-changed",{taskPath:this.task.path,currentReminders:[...this.originalReminders],action:"cancelled"}),this.close()}remindersHaveChanged(){return this.reminders.length!==this.originalReminders.length?!0:!this.reminders.every((t,r)=>{let a=this.originalReminders[r];return a?t.id===a.id&&t.type===a.type&&t.relatedTo===a.relatedTo&&t.offset===a.offset&&t.absoluteTime===a.absoluteTime&&t.description===a.description:!1})}onClose(){let{contentEl:t}=this;t.empty()}}});function rM(n){return M({tag:"TaskCard/Actions",isDebugEnabled:()=>n.settings.enableDebugLogging})}function z$(n){let{task:e,plugin:t,targetDate:r,updateStatusVisuals:a}=n;return i=>{i.stopPropagation(),(async()=>{let s=rM(t);try{if(e.recurrence){let p=await t.toggleRecurringTaskComplete(e,r),m=oy(p,r,t.statusManager.getCompletedStatuses()[0]),f=t.statusManager.isCompletedStatus(m);a(p,m,f);return}let o=await t.cacheManager.getTaskInfo(e.path);if(!o){new Xy.Notice("Task not found");return}let l=o.status||t.settings.defaultTaskStatus,c=i.shiftKey?t.statusManager.getPreviousStatus(l):t.statusManager.getNextStatus(l),d=await t.updateTaskProperty(o,"status",c),u=t.statusManager.isCompletedStatus(c);a(d,c,u)}catch(o){let l=o instanceof Error?o.message:String(o);s.error("Error cycling task status",{category:"persistence",operation:"cycle-status",details:{taskPath:e.path,errorMessage:l},error:o}),new Xy.Notice(`Failed to update task status: ${l}`)}})()}}function B$(n,e){return t=>{t.stopPropagation(),new Ud({currentValue:n.priority,onSelect:a=>{(async()=>{let i=rM(e);try{await e.updateTaskProperty(n,"priority",a)}catch(s){i.error("Error updating priority",{category:"persistence",operation:"update-priority",details:{taskPath:n.path,newPriority:a},error:s}),new Xy.Notice("Failed to update priority")}})()},plugin:e}).show(t)}}function j$(n,e){return t=>{t.stopPropagation(),new il({currentValue:typeof n.recurrence=="string"?n.recurrence:void 0,currentAnchor:n.recurrence_anchor||"scheduled",scheduledDate:n.scheduled,onSelect:(a,i)=>{(async()=>{let s=rM(e);try{await e.updateTaskProperty(n,"recurrence",a||void 0),i!==void 0&&await e.updateTaskProperty(n,"recurrence_anchor",i)}catch(o){s.error("Error updating recurrence",{category:"persistence",operation:"update-recurrence",details:{taskPath:n.path,newRecurrence:a,anchor:i},error:o}),new Xy.Notice("Failed to update recurrence")}})()},app:e.app,plugin:e}).show(t)}}function $$(n,e){return()=>{new sl(e.app,e,n,r=>{(async()=>{let a=rM(e);try{await e.updateTaskProperty(n,"reminders",r.length>0?r:void 0)}catch(i){a.error("Error updating reminders",{category:"persistence",operation:"update-reminders",details:{taskPath:n.path,reminderCount:r.length},error:i}),new Xy.Notice("Failed to update reminders")}})()}).open()}}var Xy,U$=y(()=>{Xy=require("obsidian");fC();Qy();Jy();yt();q()});function Ie(n,e){return n.createElement(e,{})}var Li=y(()=>{});function nM(n){return M({tag:"TaskCard/Relationships",isDebugEnabled:()=>{var e;return((e=n.settings)==null?void 0:e.enableDebugLogging)===!0}})}function H$(n,e){var t,r;return(r=(t=n.getRelationshipOptions)==null?void 0:t.call(n,e))!=null?r:{}}function dUe(n,e){let t=()=>e.classList.add("task-card--nested-interactive-hover"),r=()=>e.classList.remove("task-card--nested-interactive-hover");n.addEventListener("mouseenter",t),n.addEventListener("mouseleave",r)}function uUe(n){let e=n,t=e._clickHandler;t&&(n.removeEventListener("click",t),delete e._clickHandler)}function Cs(n,e){let t=n.querySelector(e);t&&(n.classList.remove("task-card--nested-interactive-hover"),uUe(t),t.remove())}function Ule(n){Cs(n,".task-card__subtasks"),Cs(n,".task-card__blocking"),Cs(n,".task-card__blocked-by")}function V$(n,e,t,r={}){let a=n.querySelector(e);if(a)return a;let i=Ie(n.ownerDocument,"div");i.className=t;let s=o=>{o.stopPropagation()};return i.addEventListener("click",s),i._clickHandler=s,r.stopExtraPointerEvents&&(i.addEventListener("dblclick",o=>o.stopPropagation()),i.addEventListener("contextmenu",o=>o.stopPropagation())),dUe(i,n),n.appendChild(i),i}function pUe(n){var r;let e=[],t=n.closest(".task-card");for(;t;){let a=t._taskPath;typeof a=="string"&&e.unshift(a),t=(r=t.parentElement)==null?void 0:r.closest(".task-card")}return e}function W$(n){for(;n.firstChild;)n.removeChild(n.firstChild)}function Hle(n,e,t,r,a){for(let i of e){let s=t.renderTaskCard(i,r);s.classList.add(a),n.appendChild(s)}}async function q$(n,e,t,r){let{plugin:a}=n,i=nM(a);try{if(!r){Cs(e,".task-card__subtasks");return}let s=V$(e,".task-card__subtasks","task-card__subtasks");W$(s);let o=s.createDiv({cls:"task-card__subtasks-loading",text:a.i18n.translate("contextMenus.task.subtasks.loading")});try{let l=a.app.vault.getAbstractFileByPath(t.path);if(!(l instanceof yC.TFile))throw new Error("Task file not found");if(!a.projectSubtasksService)throw new Error("projectSubtasksService not initialized");let c=H$(n,e),d=JA(await a.projectSubtasksService.getTasksLinkedToProject(l),c);if(o.remove(),d.length===0){s.createDiv({cls:"task-card__subtasks-loading",text:a.i18n.translate("contextMenus.task.subtasks.noSubtasks")});return}let u=Nle(d,c,m=>a.projectSubtasksService.sortTasks(m)),p=pUe(e);for(let m of u){if(p.includes(m.path)){i.warn("Skipped circular task relationship",{category:"validation",operation:"render-subtasks",details:{taskPath:t.path,subtaskPath:m.path,parentChain:p}});continue}let f=n.renderTaskCard(m,c);f.classList.add("task-card--subtask"),s.appendChild(f)}}catch(l){i.error("Error loading subtasks",{category:"provider",operation:"load-subtasks",details:{taskPath:t.path},error:l}),o.textContent=a.i18n.translate("contextMenus.task.subtasks.loadFailed")}}catch(s){throw i.error("Error toggling subtasks",{category:"internal",operation:"toggle-subtasks",details:{taskPath:t.path,expanded:r},error:s}),s}}async function Vle(n,e,t,r){let{plugin:a}=n,i=nM(a);if(!r){Cs(e,".task-card__blocking");return}let s=V$(e,".task-card__blocking","task-card__blocking",{stopExtraPointerEvents:!0});W$(s);let o=s.createDiv({cls:"task-card__blocking-loading",text:a.i18n.translate("ui.taskCard.loadingDependencies")});try{let l=t.blocking?await Promise.all(t.blocking.map(u=>a.cacheManager.getTaskInfo(u))):[],c=H$(n,e),d=JA(l.filter(u=>!!u),c);if(o.remove(),d.length===0){s.createDiv({cls:"task-card__blocking-empty",text:a.i18n.translate("ui.taskCard.blockingEmpty")});return}Hle(s,d,n,c,"task-card--dependency")}catch(l){i.error("Error loading blocking tasks",{category:"provider",operation:"load-blocking-tasks",details:{taskPath:t.path},error:l}),o.textContent=a.i18n.translate("ui.taskCard.blockingLoadError")}}async function Wle(n,e,t,r){let{plugin:a}=n,i=nM(a);if(!r){Cs(e,".task-card__blocked-by");return}let s=V$(e,".task-card__blocked-by","task-card__blocked-by",{stopExtraPointerEvents:!0});W$(s);let o=s.createDiv({cls:"task-card__blocked-by-loading",text:a.i18n.translate("ui.taskCard.loadingDependencies")});try{let l=$f(t,a.app),c=await Promise.all(l.map(p=>a.cacheManager.getTaskInfo(p))),d=H$(n,e),u=JA(c.filter(p=>!!p),d);if(o.remove(),u.length===0){s.createDiv({cls:"task-card__blocked-by-empty",text:a.i18n.translate("ui.taskCard.blockedBadge")});return}Hle(s,u,n,d,"task-card--dependency")}catch(l){i.error("Error loading blocked-by tasks",{category:"provider",operation:"load-blocked-by-tasks",details:{taskPath:t.path},error:l}),o.textContent=a.i18n.translate("ui.taskCard.blockingLoadError")}}async function qle(n,e,t){let{plugin:r}=n,a=nM(r);if(!e.projects||e.projects.length===0)return;let i=0,s=10;for(;iwindow.setTimeout(l,10)),i++}let o=t.querySelectorAll(".task-card__chevron--expanded");for(let l of o){let c=l.closest(".task-card");if(!c)continue;let d=c.dataset.taskPath;if(!d)continue;let u=r.app.vault.getAbstractFileByPath(d);if(!(u instanceof yC.TFile))continue;let p=u.basename;if(!(!e.projects.flat(2).some(h=>{if(h&&typeof h=="string"&&h.startsWith("[[")&&h.endsWith("]]")){let g=h.slice(2,-2).trim(),v=(0,yC.parseLinktext)(g).path,k=r.app.metadataCache.getFirstLinkpathDest(v,"");return v===p||k&&k.path===d}return h===p||h===d})||!c.querySelector(".task-card__subtasks")))try{let h=await r.cacheManager.getTaskInfo(d);h&&await q$(n,c,h,!0)}catch(h){a.error("Error refreshing parent task subtasks",{category:"provider",operation:"refresh-parent-subtasks",details:{taskPath:e.path,projectTaskPath:d},error:h})}}}var yC,G$=y(()=>{yC=require("obsidian");q();Li();XA()});function ev(n){return M({tag:"TaskCard/Badges",isDebugEnabled:()=>n.settings.enableDebugLogging})}function tv(n,e,t){return n.i18n.translate(`ui.taskCard.${e}`,t)}function aM(n){var e;return((e=n.settings)==null?void 0:e.showExpandableSubtasks)===!0}function Y$(n){var e;return((e=n.settings)==null?void 0:e.expandSubtasksByDefault)===!0&&aM(n)}function Gle(n,e){var t;return aM(e)&&((t=e.expandedProjectsService)==null?void 0:t.isExpanded(n.path,Y$(e)))||!1}function fUe(n){for(let e of mUe)for(let t of n.querySelectorAll(e))t.remove();Cs(n,".task-card__subtasks"),Cs(n,".task-card__blocking"),Cs(n,".task-card__blocked-by")}function K$(n,e,t){n.classList.toggle("task-card__chevron--expanded",t);let r=KA(e,t);n.setAttribute("aria-label",r),(0,Hf.setTooltip)(n,r,{placement:"top"})}function Yle(n,e,t,r){return()=>{(async()=>{let a=ev(e);try{if(!e.expandedProjectsService){new Hf.Notice("Service not available. Please try reloading the plugin.");return}let i=t.querySelector(".task-card__chevron");if(!i)return;let s=e.expandedProjectsService.toggle(n.path,Y$(e));K$(i,e,s),await r.toggleSubtasks(t,n,s)}catch(i){a.error("Error toggling subtasks",{category:"internal",operation:"toggle-subtasks",details:{taskPath:n.path},error:i}),new Hf.Notice("Failed to toggle subtasks")}})()}}function Kle(n,e,t,r){return()=>{(async()=>{let a=ev(e);try{if(!e.expandedProjectsService){new Hf.Notice("Service not available. Please try reloading the plugin.");return}let i=e.expandedProjectsService.toggle(n.path,Y$(e)),s=t.querySelector(".task-card__chevron");s&&K$(s,e,i),await r.toggleSubtasks(t,n,i)}catch(i){a.error("Error toggling project subtasks",{category:"internal",operation:"toggle-project-subtasks",details:{taskPath:n.path},error:i}),new Hf.Notice("Failed to toggle subtasks")}})()}}function Zle(n,e,t){return()=>{(async()=>{let r=e.querySelector(".task-card__blocking-toggle");if(!r)return;let a=r.classList.toggle("task-card__blocking-toggle--expanded");await t.toggleBlockingTasks(e,n,a)})()}}function Qle(n,e,t,r){return()=>{Z$({card:t,task:n,plugin:e,handlers:r})}}function hUe(n,e){let t=n.querySelector(".task-card__blocked-toggle");t&&(t.classList.toggle("task-card__blocked-toggle--expanded",e),t.setAttribute("aria-expanded",String(e)));for(let r of n.querySelectorAll(".task-card__metadata-pill--blocked"))r.getAttribute("role")==="button"&&r.setAttribute("aria-expanded",String(e))}async function Z$(n){let{card:e,task:t,handlers:r}=n,a=!e.querySelector(".task-card__blocked-by");hUe(e,a),await r.toggleBlockedByTasks(e,t,a)}function gUe(n,e){let{card:t,task:r,plugin:a,handlers:i}=n;if(!a.projectSubtasksService.isTaskUsedAsProjectSync(r.path))return;let o=Gle(r,a),l=aM(a);Ql({container:e,className:"task-card__project-indicator",icon:"folder",tooltip:tv(a,l?"projectTooltip":"projectIndicatorTooltip"),onClick:l?Kle(r,a,t,i):void 0}),l&&Ql({container:e,className:`task-card__chevron${o?" task-card__chevron--expanded":""}`,icon:"chevron-right",tooltip:KA(a,o),onClick:Yle(r,a,t,i)}),o&&i.toggleSubtasks(t,r,!0).catch(c=>{ev(a).error("Error showing initial subtasks",{category:"internal",operation:"show-initial-subtasks",details:{taskPath:r.path},error:c})})}function yUe(n,e){let{card:t,task:r,plugin:a,handlers:i}=n;if(r.blocking&&r.blocking.length>0){let o=r.blocking.length,l=a.i18n.translate("ui.taskCard.blockingToggle",{count:o}),c=Ql({container:e,className:"task-card__blocking-toggle is-visible",icon:"git-branch",tooltip:l,onClick:Zle(r,t,i)});c&&(c.dataset.count=String(o))}let s=$f(r,a.app);if(s.length>0){let o=`${tv(a,"blockedBadge")} (${s.length})`,l=Ql({container:e,className:"task-card__blocked-toggle is-visible",icon:"git-merge",tooltip:o,onClick:Qle(r,a,t,i)});l&&(l.dataset.count=String(s.length))}}function Jle(n){let{badgesContainer:e,task:t,plugin:r,hasDetails:a,propertyOptions:i}=n;if(!(!e||i.showSecondaryBadges===!1)){if(t.recurrence&&Ql({container:e,className:"task-card__recurring-indicator",icon:"rotate-ccw",tooltip:uC(r,t.recurrence,i.propertyLabels),onClick:j$(t,r)}),t.reminders&&t.reminders.length>0){let s=t.reminders.length;Ql({container:e,className:"task-card__reminder-indicator",icon:"bell",tooltip:P$(r,s),onClick:$$(t,r)})}a&&Ql({container:e,className:"task-card__details-indicator",icon:"file-text",tooltip:tv(r,"detailsTooltip")}),gUe(n,e),yUe(n,e)}}function vUe(n){let{card:e,mainRow:t,task:r,plugin:a,handlers:i}=n,s=ev(a);a.projectSubtasksService.isTaskUsedAsProject(r.path).then(o=>{var f,h,g,v;(f=e.querySelector(".task-card__project-indicator-placeholder"))==null||f.remove(),(h=e.querySelector(".task-card__chevron-placeholder"))==null||h.remove();let l=aM(a),c=e.querySelector(".task-card__project-indicator"),d=(c==null?void 0:c.getAttribute("role"))==="button";o&&c&&d!==l&&c.remove(),Uf(e,".task-card__project-indicator",{shouldExist:o,className:"task-card__project-indicator",icon:"folder",tooltip:tv(a,l?"projectTooltip":"projectIndicatorTooltip"),onClick:l?Kle(r,a,e,i):void 0});let u=o&&l,p=e.querySelector(".task-card__chevron"),m=o&&Gle(r,a);u&&!p?Ql({container:(v=(g=e.querySelector(".task-card__badges"))!=null?g:t)!=null?v:e,className:`task-card__chevron${m?" task-card__chevron--expanded":""}`,icon:"chevron-right",tooltip:KA(a,m),onClick:Yle(r,a,e,i)}):u&&p?K$(p,a,m):!u&&p&&p.remove(),m?i.toggleSubtasks(e,r,!0).catch(k=>{s.error("Error showing subtasks in update",{category:"internal",operation:"show-subtasks-update",details:{taskPath:r.path},error:k})}):Cs(e,".task-card__subtasks")}).catch(o=>{s.error("Error checking if task is used as project in update",{category:"internal",operation:"check-project-task",details:{taskPath:r.path},error:o})})}function kUe(n){var c,d;let{card:e,task:t,plugin:r,handlers:a}=n,i=(d=(c=t.blocking)==null?void 0:c.length)!=null?d:0,s=i>0,o=r.i18n.translate("ui.taskCard.blockingToggle",{count:i}),l=Uf(e,".task-card__blocking-toggle",{shouldExist:s,className:"task-card__blocking-toggle is-visible",icon:"git-branch",tooltip:o,onClick:Zle(t,e,a)});if(!s){Cs(e,".task-card__blocking");return}l&&(l.classList.add("is-visible"),l.classList.remove("is-hidden"),l.dataset.count=String(i),l.classList.contains("task-card__blocking-toggle--expanded")&&a.toggleBlockingTasks(e,t,!0).catch(u=>{ev(r).error("Error refreshing blocking tasks",{category:"internal",operation:"refresh-blocking-tasks",details:{taskPath:t.path,blockingCount:i},error:u})}))}function TUe(n){let{card:e,task:t,plugin:r,handlers:a}=n,i=$f(t,r.app),s=i.length>0,o=`${tv(r,"blockedBadge")} (${i.length})`,l=Uf(e,".task-card__blocked-toggle",{shouldExist:s,className:"task-card__blocked-toggle is-visible",icon:"git-merge",tooltip:o,onClick:Qle(t,r,e,a)});if(!s){Cs(e,".task-card__blocked-by");return}l&&(l.classList.add("is-visible"),l.classList.remove("is-hidden"),l.dataset.count=String(i.length),l.classList.contains("task-card__blocked-toggle--expanded")&&a.toggleBlockedByTasks(e,t,!0).catch(c=>{ev(r).error("Error refreshing blocked-by tasks",{category:"internal",operation:"refresh-blocked-by-tasks",details:{taskPath:t.path,blockedByCount:i.length},error:c})}))}function Xle(n){var c,d;let{card:e,mainRow:t,task:r,plugin:a,hasDetails:i,propertyOptions:s}=n,o=e.querySelector(".task-card__badges");if(!o||s.showSecondaryBadges===!1){fUe(e);return}Uf(e,".task-card__recurring-indicator",{shouldExist:!!r.recurrence,className:"task-card__recurring-indicator",icon:"rotate-ccw",tooltip:r.recurrence?uC(a,r.recurrence,s.propertyLabels):"",onClick:j$(r,a)});let l=(d=(c=r.reminders)==null?void 0:c.length)!=null?d:0;Uf(e,".task-card__reminder-indicator",{shouldExist:l>0,className:"task-card__reminder-indicator",icon:"bell",tooltip:P$(a,l),onClick:$$(r,a)}),Uf(e,".task-card__details-indicator",{shouldExist:i,className:"task-card__details-indicator",icon:"file-text",tooltip:tv(a,"detailsTooltip")}),vUe({...n,mainRow:t!=null?t:o}),kUe(n),TUe(n)}var Hf,mUe,Q$=y(()=>{Hf=require("obsidian");q();U$();A$();mC();G$();XA();mUe=[".task-card__recurring-indicator",".task-card__reminder-indicator",".task-card__details-indicator",".task-card__project-indicator",".task-card__chevron",".task-card__blocking-toggle",".task-card__blocked-toggle"]});function bUe(n,e){return n||(e.settings.defaultVisibleProperties?di(e.settings.defaultVisibleProperties,e):Ple(e))}function wUe(n){var u,p;let{metadataLine:e,card:t,task:r,plugin:a,onBlockedByToggle:i}=n;if(!r.isBlocked)return null;let s=a.i18n.translate("ui.taskCard.blockedBadge"),o=$f(r,a.app),l=(p=(u=r.blockedBy)==null?void 0:u.length)!=null?p:0,c=l>0?`${s} (${l})`:s,d=e.createSpan({cls:"task-card__metadata-pill task-card__metadata-pill--blocked",text:c});if(o.length>0){let m=`${s} (${o.length})`;al(d),d.setAttribute("aria-label",m),d.setAttribute("aria-expanded",String(!!t.querySelector(".task-card__blocked-by"))),(0,Hd.setTooltip)(d,m,{placement:"top"}),d.addEventListener("click",f=>{f.stopPropagation(),i()})}else(0,Hd.setTooltip)(d,a.i18n.translate("ui.taskCard.blockedBadgeTooltip"),{placement:"top"});return d}function SUe(n){var l,c;let{metadataLine:e,task:t,plugin:r}=n;if(!t.isBlocking)return null;let a=r.i18n.translate("ui.taskCard.blockingBadge"),i=(c=(l=t.blocking)==null?void 0:l.length)!=null?c:0,s=i>0?`${a} (${i})`:a,o=e.createSpan({cls:"task-card__metadata-pill task-card__metadata-pill--blocking",text:s});return(0,Hd.setTooltip)(o,r.i18n.translate("ui.taskCard.blockingBadgeTooltip"),{placement:"top"}),o}function CUe(n){let{metadataLine:e,task:t,plugin:r}=n;if(!t.googleCalendarEventId)return null;let a=e.createSpan({cls:"task-card__metadata-pill task-card__metadata-pill--google-calendar"});return(0,Hd.setIcon)(a,"calendar"),(0,Hd.setTooltip)(a,r.i18n.translate("ui.taskCard.googleCalendarSyncTooltip"),{placement:"top"}),a}function xUe(n){var s;let{metadataLine:e,task:t,plugin:r}=n;if(!t.recurrence_parent||!t.occurrence_date)return null;let a=Sn(t.occurrence_date,{dateFormat:"MMM d",showTime:!1,userTimeFormat:(s=r.settings.calendarViewSettings)==null?void 0:s.timeFormat}),i=e.createSpan({cls:"task-card__metadata-pill task-card__metadata-pill--occurrence"});return(0,Hd.setIcon)(i,"refresh-ccw"),i.createSpan({text:`Occurrence: ${a}`}),al(i),i.setAttribute("aria-label",`Open recurring parent for occurrence on ${t.occurrence_date}`),(0,Hd.setTooltip)(i,`Occurrence of ${t.recurrence_parent} on ${t.occurrence_date}`,{placement:"top"}),i.addEventListener("click",o=>{o.stopPropagation();let l=vt(t.recurrence_parent||"");r.app.workspace.openLinkText(l,t.path,!1)}),i}function EUe(n){let{metadataLine:e,task:t,plugin:r,visibleProperties:a,propertyOptions:i={}}=n;e.empty();let s=[],o=bUe(a,r),l=xUe(n);l&&s.push(l);for(let c of o){if(Yy(c,"status",r)||Yy(c,"priority",r))continue;if(c==="blocked"){let u=wUe(n);u&&s.push(u);continue}if(c==="blocking"){let u=SUe(n);u&&s.push(u);continue}if(c==="googleCalendarSync"){let u=CUe(n);u&&s.push(u);continue}let d=Ale(e,c,t,r,i);d&&s.push(d)}return Mle(e,s),s}function J$(n){let{metadataLine:e,card:t,task:r,plugin:a,visibleProperties:i,propertyOptions:s,handlers:o}=n;return EUe({metadataLine:e,card:t,task:r,plugin:a,visibleProperties:i,propertyOptions:s,onBlockedByToggle:()=>void Z$({card:t,task:r,plugin:a,handlers:o})})}var Hd,ece=y(()=>{Hd=require("obsidian");xe();Cn();Yl();Ile();XA();mC();Q$()});function tce(n,e,t=!1){return!t&&(!n||n.some(r=>Yy(r,"status",e)))}function rce(n,e){return!n||n.some(t=>Yy(t,"priority",e))}function iM(n,e,t){let r=t.statusManager.getStatusConfig(e);r!=null&&r.color?n.style.setProperty("--current-status-color",r.color):n.style.removeProperty("--current-status-color");let a=t.statusManager.getNextStatus(e),i=t.statusManager.getStatusConfig(a);i!=null&&i.color?n.style.setProperty("--next-status-color",i.color):n.style.removeProperty("--next-status-color")}function e2(n,e,t){let r=t.priorityManager.getPriorityConfig(e.priority);return r!=null&&r.color?(n.style.setProperty("--priority-color",r.color),n.style.setProperty("--current-priority-color",r.color)):(n.style.removeProperty("--priority-color"),n.style.removeProperty("--current-priority-color")),r}function sM(n,e){e!=null&&e.color?n.style.borderColor=e.color:n.style.removeProperty("border-color"),e!=null&&e.icon?(n.addClass("task-card__status-dot--icon"),n.empty(),(0,X$.setIcon)(n,e.icon)):(n.removeClass("task-card__status-dot--icon"),n.empty(),n.removeAttribute("data-icon"),n.classList.remove("has-icon"))}function t2(n){let{mainRow:e,card:t,task:r,plugin:a,effectiveStatus:i,visibleProperties:s,hideStatusIndicator:o,onClick:l}=n;if(!tce(s,a,o)||!e)return null;let c=e.createSpan({cls:"task-card__status-dot"});return sM(c,a.statusManager.getStatusConfig(i)),al(c),c.addEventListener("click",l),c.dataset.taskPath=r.path,iM(t,i,a),c}function nce(n,e,t){let r=n.querySelector(t);if(r){r.insertAdjacentElement("afterend",e);return}let a=n.querySelector(".task-card__checkbox");if(a){a.insertAdjacentElement("afterend",e);return}n.insertBefore(e,n.firstChild)}function ace(n){let{mainRow:e,card:t,plugin:r,effectiveStatus:a,visibleProperties:i,hideStatusIndicator:s}=n,o=t.querySelector(".task-card__status-dot");if(iM(t,a,r),!tce(i,r,s))return o==null||o.remove(),null;if(o)return sM(o,r.statusManager.getStatusConfig(a)),o;if(!e)return null;let l=t2(n);return l&&nce(e,l,".task-card__checkbox"),l}function ice(n,e,t){n.style.borderColor=e.color,n.setAttribute("aria-label",t.i18n.translate("ui.taskCard.priorityAriaLabel",{label:e.label})),n.replaceChildren(),n.classList.toggle("task-card__priority-dot--icon",!!e.icon),e.icon?(0,X$.setIcon)(n,e.icon):(n.removeAttribute("data-icon"),n.classList.remove("has-icon"))}function r2(n){let{mainRow:e,task:t,plugin:r,visibleProperties:a,onClick:i}=n,s=r.priorityManager.getPriorityConfig(t.priority);if(!t.priority||!s||!rce(a,r)||!e)return null;let o=e.createSpan({cls:"task-card__priority-dot"});return ice(o,s,r),al(o),o.addEventListener("click",i),o}function sce(n){var c,d;let{mainRow:e,card:t,task:r,plugin:a,visibleProperties:i}={...n,card:(d=(c=n.mainRow)==null?void 0:c.closest(".task-card"))!=null?d:n.mainRow};if(!t)return null;let s=t.querySelector(".task-card__priority-dot"),o=a.priorityManager.getPriorityConfig(r.priority);if(!r.priority||!o||!rce(i,a))return s==null||s.remove(),null;if(!s){if(!e)return null;let u=r2(n);return u&&nce(e,u,".task-card__status-dot"),u}ice(s,o,a);let l=s.cloneNode(!0);return al(l),l.addEventListener("click",n.onClick),s.replaceWith(l),l}var X$,n2=y(()=>{X$=require("obsidian");Yl();mC()});function DUe(n){let e=/^(\d{4})-(\d{2})-(\d{2})$/.exec(n);if(!e)return null;let[,t,r,a]=e;return new Date(Date.UTC(Number(t),Number(r)-1,Number(a)))}function PUe(){let n=new Date;return new Date(Date.UTC(n.getFullYear(),n.getMonth(),n.getDate()))}function AUe(n){if(n.recurrence&&n.recurrence_anchor!=="completion"&&n.scheduled){let e=DUe(re(n.scheduled));if(e)return e}return PUe()}function a2(n,e){var r,a,i;if(typeof n.details=="string")return n.details.trim().length>0;if(!e||!n.path)return!1;let t=(i=(a=(r=e.app.metadataCache).getCache)==null?void 0:a.call(r,n.path))==null?void 0:i.sections;return t?t.some(s=>s.type!=="yaml"):!1}function i2(n){var e;return((e=n.settings)==null?void 0:e.showCompletedTaskStrikethrough)!==!1}function s2(n){let e=new Set;for(let t of Ko(n.projects||[])){let r=Dd(t);r&&e.add(`task-card--project-${r}`)}return Array.from(e)}function MUe(n,e,t){var i;let r=["task-card"];t.layout!=="default"&&r.push(`task-card--layout-${t.layout}`),t.isCompleted&&r.push("task-card--completed"),t.isCompleted&&i2(e)&&r.push("task-card--completed-strikethrough"),t.isSkipped&&r.push("task-card--skipped"),n.archived&&r.push("task-card--archived"),t.isActivelyTracked&&r.push("task-card--actively-tracked"),t.isRecurring&&r.push("task-card--recurring"),t.isMaterializedOccurrence&&r.push("task-card--materialized-occurrence"),t.hasDetails&&r.push("task-card--has-details"),n.priority&&r.push(`task-card--priority-${Dd(n.priority)}`),t.effectiveStatus&&r.push(`task-card--status-${Dd(t.effectiveStatus)}`),((i=e.settings)==null?void 0:i.subtaskChevronPosition)==="left"&&r.push("task-card--chevron-left");let a=s2(n);return a.length>0&&r.push("task-card--has-projects",...a),r}function o2(n,e,t={}){var c,d;let r=t.targetDate||AUe(n),a=n.recurrence?oy(n,r,e.statusManager.getCompletedStatuses()[0]):n.status,i=t.layout||"default",s=n.recurrence?((c=n.complete_instances)==null?void 0:c.includes(ae(r)))||!1:e.statusManager.isCompletedStatus(a),o=n.recurrence&&((d=n.skipped_instances)==null?void 0:d.includes(ae(r)))||!1,l={targetDate:r,effectiveStatus:a,layout:i,isCompleted:s,isSkipped:o,isRecurring:!!n.recurrence,isMaterializedOccurrence:!!(n.recurrence_parent&&n.occurrence_date),isActivelyTracked:e.getActiveTimeSession(n)!==null,hasDetails:a2(n,e)};return{...l,cardClasses:MUe(n,e,l)}}var l2=y(()=>{xe();yt()});function oce(n){if(!n)return null;let e=re(n);return e?st(e):null}function c2(n,e,t={}){var r;switch(e){case"today":return{available:!0,date:Br(Xt())};case"asScheduled":{let a=(r=t.occurrenceDate)!=null?r:oce(n.scheduled);return a?{available:!0,date:a}:{available:!1,reasonKey:"contextMenus.task.completion.noScheduledDate"}}case"onDue":{let a=oce(n.due);return a?{available:!0,date:a}:{available:!1,reasonKey:"contextMenus.task.completion.noDueDate"}}case"onPicked":return t.pickedDate?{available:!0,date:t.pickedDate}:{available:!1,reasonKey:"contextMenus.task.completion.noPickedDate"}}}var lce=y(()=>{xe()});function ve(n,e,t){n==null||n.trigger(d2,{message:e,timeout:t})}var d2,Oi=y(()=>{d2="user-notice"});function oM(n,e,t){return n.i18n.translate(e,t)}function IUe(n){let e=new Set,t=[];for(let r of n){let a=r.trim();!a||e.has(a)||(e.add(a),t.push(a))}return t}function dce(n,e,t){return Qo(n.app,e,t,"","",n.settings.useFrontmatterMarkdownLinks)}function NUe(n,e,t){var s,o;let r=e.trim();if(!r)return"";let a=vt(r),i=(o=(s=n.app.metadataCache).getFirstLinkpathDest)==null?void 0:o.call(s,a,t);return i instanceof cce.TFile?dce(n,i,t):r}async function rv(n,e,t){let r=Qo(n.app,t,e.path,"","",n.settings.useFrontmatterMarkdownLinks),a=`[[${t.basename}]]`,i=Array.isArray(e.projects)?e.projects:[];if(i.includes(r)||i.includes(a))return ve(n.emitter,oM(n,"contextMenus.task.organization.notices.alreadyInProject")),null;let o=[...i.filter(c=>c!==a),r],l=await n.updateTaskProperty(e,"projects",o);return ve(n.emitter,oM(n,"contextMenus.task.organization.notices.addedToProject",{project:t.basename})),l}async function lM(n,e,t){let r=Qo(n.app,e,t.path,"","",n.settings.useFrontmatterMarkdownLinks),a=`[[${e.basename}]]`,i=Array.isArray(t.projects)?t.projects:[];if(i.includes(r)||i.includes(a))return ve(n.emitter,oM(n,"contextMenus.task.organization.notices.alreadySubtask")),null;let o=[...i.filter(c=>c!==a),r],l=await n.updateTaskProperty(t,"projects",o);return ve(n.emitter,oM(n,"contextMenus.task.organization.notices.addedAsSubtask",{subtask:t.title,parent:e.basename})),l}function cM(n,e,t){var c;let r=!!((c=n.settings.taskCreationDefaults)!=null&&c.inheritParentTaskProperties),a=dce(n,t,e.path),i=Array.isArray(e.tags)?e.tags:[],s=r?Array.isArray(e.projects)?e.projects.map(d=>NUe(n,d,e.path)):[]:[],o=r?n.settings.taskIdentificationMethod==="tag"?jd(i,n.settings.taskTag,n.settings.hideIdentifyingTagsMode):[...i]:[],l={projects:IUe([...s,a])};return o.length>0&&(l.tags=o),r&&Array.isArray(e.contexts)&&e.contexts.length>0&&(l.contexts=[...e.contexts]),r&&e.priority&&(l.priority=e.priority),l}var cce,vC=y(()=>{cce=require("obsidian");Cn();ip();Oi()});var ya=y(()=>{Zz()});function u2(n){return!!(n.googleCalendarEventId||n.googleCalendarExceptionEventId||n.googleCalendarExceptionOriginalScheduled||n.googleCalendarMovedOriginalDates&&n.googleCalendarMovedOriginalDates.length>0)&&!!n.recurrence&&(n.recurrence_anchor||"scheduled")==="scheduled"}function RUe(n){let e=n.googleCalendarExceptionOriginalScheduled||n.scheduled||n.due;return re(e||"")||void 0}function dM(n,e,t){if(!u2(n)||e===n.scheduled)return;let r=RUe(n);if(!r)return;let a=typeof e=="string"?re(e):"";t.googleCalendarExceptionOriginalScheduled=a&&a!==r?r:void 0}function Vf(n){u2(n)||(n.googleCalendarExceptionOriginalScheduled=void 0,n.googleCalendarMovedOriginalDates=void 0)}function kC(n,e,t){if(!u2(n))return;let r=re(n.googleCalendarExceptionOriginalScheduled||"");if(!r)return;let a=re(n.scheduled||"");!a||e!==a||(t.googleCalendarMovedOriginalDates=Array.from(new Set([...n.googleCalendarMovedOriginalDates||[],r])).sort(),t.googleCalendarExceptionOriginalScheduled=void 0)}var uM=y(()=>{xe()});function up(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}function _Ue(n){let e=n.match(/(?:^|;)INTERVAL=(\d+)(?:;|$)/),t=e?Number.parseInt(e[1],10):1;return n.includes("FREQ=DAILY")?Math.max(30,t*2):n.includes("FREQ=WEEKLY")?Math.max(90,t*7*2):n.includes("FREQ=MONTHLY")?Math.max(400,t*31*2):n.includes("FREQ=YEARLY")?Math.max(800,t*366*2):365}function FUe(n,e){if(!n.recurrence)return null;let t=Hu(n,e,e),r=ae(e);if(t.some(l=>ae(l)===r))return e;let a=new Set([...n.complete_instances||[],...n.skipped_instances||[]]),i=_Ue(n.recurrence),s=new Date(e.getTime()-i*24*60*60*1e3),o=Hu(n,s,e);for(let l=o.length-1;l>=0;l--)if(!a.has(ae(o[l])))return o[l];return Fb(n,{minOccurrenceDate:r})}function uce(n,e){return(n.recurrence_anchor||"scheduled")==="completion"||n.googleCalendarExceptionOriginalScheduled?null:FUe(n,e)}function pce(n,e){let t=ae(e);if(!n)return t;let r=re(n);return`${t}${n.slice(r.length)}`}function mce(n,e,t){if((e.recurrence_anchor||"scheduled")!=="scheduled")return n;let r=new Set;for(let d of e.googleCalendarMovedOriginalDates||[]){let u=re(d);u&&r.add(u)}let a=re(e.googleCalendarExceptionOriginalScheduled||""),i=re(e.scheduled||"");a&&a!==t&&i===t&&r.add(a);let s=new Set(up(n.complete_instances)),o=up(n.skipped_instances),l=new Set(o),c=Array.from(r).filter(d=>!s.has(d)&&!l.has(d)).sort();return c.length===0?n:{...n,skipped_instances:[...o,...c]}}function mM(n,e){if(e)return e;if(n.recurrence_anchor!=="completion"&&n.scheduled)return st(re(n.scheduled));let t=Xt();return Br(t)}function fce({freshTask:n,targetDate:e,currentTimestamp:t,maintainDueDateOffsetInRecurring:r}){var v;if(!n.recurrence)throw new Error("Task is not recurring");let a=n.recurrence_anchor||"scheduled",i=uce(n,e),s=i!=null?i:e,o=ae(s),l=up(n.complete_instances),d=!l.includes(o),u={...n,dateModified:t};if(d){l.includes(o)||(u.complete_instances=[...l,o]);let k=up(n.skipped_instances);u.skipped_instances=k.filter(T=>T!==o)}else{u.complete_instances=l.filter(T=>T!==o);let k=up(n.skipped_instances);u.skipped_instances=k.filter(T=>T!==o)}if(d&&typeof u.recurrence=="string"){if(a==="completion"){let k=b0(u.recurrence,o);if(k){let T=(v=n.recurrence.match(/DTSTART:\d{8}T(\d{6})Z?(?=;|$)/))==null?void 0:v[1];u.recurrence=T?k.replace(/DTSTART:(\d{8})(?=;|$)/,`DTSTART:$1T${T}Z`):k}}else if(!u.recurrence.includes("DTSTART:")){let k=uf(u);k&&(u.recurrence=k)}}let p=i?{...u,scheduled:pce(u.scheduled,i)}:u,m=mce(p,n,o),f=zr(),h=o>f?o:f,g=Cd(m,r,{minOccurrenceDate:h});return g.scheduled&&(u.scheduled=g.scheduled),g.due&&(u.due=g.due),kC(n,o,u),Vf(u),{updatedTask:u,targetDate:e,dateStr:o,newComplete:d,dateModified:t,originalRecurrence:n.recurrence}}function hce({frontmatter:n,completeInstancesField:e,skippedInstancesField:t,dateModifiedField:r,scheduledField:a,dueField:i,recurrenceField:s,googleCalendarExceptionOriginalScheduledField:o,googleCalendarMovedOriginalDatesField:l,plan:c}){n[e]||(n[e]=[]),n[t]||(n[t]=[]);let d=up(n[e]);c.newComplete?d.includes(c.dateStr)||(n[e]=[...d,c.dateStr]):n[e]=d.filter(u=>u!==c.dateStr),n[t]=c.updatedTask.skipped_instances||[],c.updatedTask.recurrence!==c.originalRecurrence&&(n[s]=c.updatedTask.recurrence),c.updatedTask.scheduled&&(n[a]=c.updatedTask.scheduled),c.updatedTask.due&&(n[i]=c.updatedTask.due),pM(n,o,c.updatedTask.googleCalendarExceptionOriginalScheduled),pM(n,l,c.updatedTask.googleCalendarMovedOriginalDates),n[r]=c.dateModified}function gce({freshTask:n,targetDate:e,currentTimestamp:t,maintainDueDateOffsetInRecurring:r}){if(!n.recurrence)throw new Error("Task is not recurring");let a=uce(n,e),i=a!=null?a:e,s=ae(i),o=up(n.skipped_instances),c=!o.includes(s),d={...n,dateModified:t};if(c){o.includes(s)||(d.skipped_instances=[...o,s]);let g=up(n.complete_instances);d.complete_instances=g.filter(v=>v!==s)}else d.skipped_instances=o.filter(g=>g!==s);let u=a?{...d,scheduled:pce(d.scheduled,a)}:d,p=mce(u,n,s),m=zr(),f=s>m?s:m,h=Cd(p,r,{minOccurrenceDate:f});return h.scheduled&&(d.scheduled=h.scheduled),h.due&&(d.due=h.due),kC(n,s,d),Vf(d),{updatedTask:d,targetDate:e,dateStr:s,newSkipped:c,dateModified:t}}function yce({frontmatter:n,skippedField:e,completeField:t,dateModifiedField:r,scheduledField:a,dueField:i,googleCalendarExceptionOriginalScheduledField:s,googleCalendarMovedOriginalDatesField:o,plan:l}){n[e]||(n[e]=[]),n[e]=l.updatedTask.skipped_instances||[],n[t]||(n[t]=[]),n[t]=l.updatedTask.complete_instances||[],l.updatedTask.scheduled&&(n[a]=l.updatedTask.scheduled),l.updatedTask.due&&(n[i]=l.updatedTask.due),pM(n,s,l.updatedTask.googleCalendarExceptionOriginalScheduled),pM(n,o,l.updatedTask.googleCalendarMovedOriginalDates),n[r]=l.dateModified}function pM(n,e,t){if(t==null||Array.isArray(t)&&t.length===0){delete n[e];return}n[e]=t}var p2=y(()=>{pf();xe();uM()});function Vd(n,e,t={}){let r=qe(),a={title:e.title.trim(),status:e.status||n.settings.defaultTaskStatus,priority:e.priority||n.settings.defaultTaskPriority,dateCreated:r,dateModified:r};if(t.creationContext&&(a.creationContext=t.creationContext),e.dueDate&&(a.due=e.dueTime?fa(e.dueDate,e.dueTime):e.dueDate),e.scheduledDate&&(a.scheduled=e.scheduledTime?fa(e.scheduledDate,e.scheduledTime):e.scheduledDate),e.contexts&&e.contexts.length>0&&(a.contexts=e.contexts),e.projects&&e.projects.length>0&&(a.projects=e.projects),e.tags&&e.tags.length>0&&(a.tags=e.tags.map(i=>ha(i))),e.details&&(a.details=e.details),e.recurrence&&(a.recurrence=e.recurrence),e.estimate&&e.estimate>0&&(a.timeEstimate=e.estimate),e.userFields){let i=n.settings.userFields||[],s={};for(let[o,l]of Object.entries(e.userFields)){let c=i.find(d=>d.id===o);c&&(s[c.key]=Array.isArray(l)?l.join(", "):l)}Object.keys(s).length>0&&(a.customFrontmatter=s)}return a}var TC=y(()=>{xe();yt()});function LUe(n,e){if(!n.recurrence)return!1;let t=ae(e);return(Array.isArray(n.complete_instances)?n.complete_instances:[]).includes(t)}function vce(n,e,t,r="open"){let a=t.getCompletedStatuses()[0]||"done",i=T0(n,e,a)||r;return!n.recurrence||LUe(n,e)?i:t.isCompletedStatus(i)?r:i}function Wf(n,e,t,r="open"){return t.isCompletedStatus(vce(n,e,t,r))}function fM(n,e,t,r="open"){let a=vce(n,e,t,r);return a===n.status?n:{...n,status:a}}var hM=y(()=>{pf();xe()});var av,OUe,nv,m2=y(()=>{av=require("obsidian");Wl();O0();$b();ip();q();OUe=M({tag:"Modals/TaskCreationSuggest"}),nv=class extends av.AbstractInputSuggest{constructor(t,r,a){super(t,r);this.currentTrigger=null;this.projectMetadataResolver=null;this.plugin=a,this.textarea=r,this.obsidianApp=t}getCursorPosition(){var t;return(t=this.textarea.selectionStart)!=null?t:this.textarea.value.length}isBoundary(t,r){if(r===-1)return!1;if(r===0)return!0;let a=t[r-1];return!/\w/.test(a)}findActiveTrigger(t){let r=t.lastIndexOf("@"),a=t.lastIndexOf("#"),i=t.lastIndexOf("+"),s=(this.plugin.settings.statusSuggestionTrigger||"").trim(),o=s?t.lastIndexOf(s):-1,l=[{type:"@",index:r},{type:"#",index:a},{type:"+",index:i},{type:"status",index:o}].filter(m=>this.isBoundary(t,m.index));if(l.length===0)return{trigger:null,triggerIndex:-1,queryAfterTrigger:""};l.sort((m,f)=>f.index-m.index);let c=l[0].index,d=l[0].type,u=d==="status"?(s==null?void 0:s.length)||0:1,p=t.slice(c+u);return{trigger:d,triggerIndex:c,queryAfterTrigger:p}}shouldEndSuggestionContext(t,r){return!!(t==="+"&&/^\[\[[^\]]*\]\]/.test(r)||(t==="@"||t==="#"||t==="status")&&(r.includes(" ")||r.includes(` +`)))}getContextSuggestions(t){return this.plugin.cacheManager.getAllContexts().filter(a=>a&&typeof a=="string").filter(a=>a.toLowerCase().includes(t.toLowerCase())).slice(0,10).map(a=>({value:a,display:a,type:"context",toString(){return this.value}}))}getStatusSuggestions(t){return Nn.fromPlugin(this.plugin).getStatusSuggestions(t,10).map(a=>({...a,type:"status",toString(){return this.value}}))}getTagSuggestions(t){return zA(this.plugin.cacheManager.getAllTags(),this.plugin.settings).filter(a=>a&&typeof a=="string").filter(a=>a.toLowerCase().includes(t.toLowerCase())).slice(0,10).map(a=>({value:a,display:a,type:"tag",toString(){return this.value}}))}getProjectMetadataResolver(){var t;if(!this.projectMetadataResolver){let r=(t=this.obsidianApp)!=null?t:this.plugin.app;this.projectMetadataResolver=new Yu({getFrontmatter:a=>{let i=r==null?void 0:r.vault.getAbstractFileByPath(a.path),s=i instanceof av.TFile?r==null?void 0:r.metadataCache.getFileCache(i):void 0;return(s==null?void 0:s.frontmatter)||{}}})}return this.projectMetadataResolver}async getProjectSuggestions(t){var s,o,l,c;let{FileSuggestHelper:r}=await Promise.resolve().then(()=>(Hb(),aB)),a=await r.suggest(this.plugin,t,20,this.plugin.settings.projectAutosuggest),i=(s=this.obsidianApp)!=null?s:this.plugin.app;try{let d=this.getProjectMetadataResolver(),u=((c=(l=(o=this.plugin.settings)==null?void 0:o.projectAutosuggest)==null?void 0:l.rows)!=null?c:[]).slice(0,3);return a.map(p=>{var S;let m=i==null?void 0:i.vault.getMarkdownFiles().find(C=>C.path===p.path);if(!m)return{basename:p.insertText,displayName:p.displayText,linkText:p.insertText,type:"project",toString(){return this.basename}};let f=i==null?void 0:i.metadataCache.getFileCache(m),h=(f==null?void 0:f.frontmatter)||{},g=this.plugin.fieldMapper.mapFromFrontmatter(h,m.path,this.plugin.settings.storeTitleInFilename),v=typeof g.title=="string"?g.title:"",k=(0,av.parseFrontMatterAliases)(h)||[],T=Array.isArray(k)?k.filter(C=>typeof C=="string"):[],b={basename:m.basename,name:m.name,path:m.path,parent:((S=m.parent)==null?void 0:S.path)||"",title:v,aliases:T,frontmatter:h},w=this.generateProjectDisplayName(u,b,d,m.basename);return{basename:m.basename,displayName:w,linkText:p.insertText,type:"project",entry:{basename:b.basename,name:b.name,path:b.path,parent:b.parent,title:b.title,aliases:b.aliases,frontmatter:b.frontmatter},toString(){return this.basename}}})}catch(d){return OUe.error("Enhanced project autosuggest failed, falling back to basic suggestions",{category:"persistence",operation:"enhanced-project-autosuggest-falling-back-basic-suggestions",error:d}),a.map(u=>({basename:u.insertText,displayName:u.displayText,linkText:u.insertText,type:"project",toString(){return this.basename}}))}}generateProjectDisplayName(t,r,a,i){var o;let s=[];for(let l of t)try{let c=zl(l),d=[];for(let p of c){if(p.property.startsWith("literal:")){d.push(p.property.slice(8));continue}let m=a.resolve(p.property,r)||"";if(m)if(p.showName){let f=(o=p.displayName)!=null?o:p.property;d.push(`${f}: ${m}`)}else d.push(m)}let u=d.join(" ");u.trim()&&s.push(u)}catch(c){}return s.join(" | ")||i}async getSuggestions(t){let r=this.getCursorPosition(),a=this.textarea.value.slice(0,r),{trigger:i,triggerIndex:s,queryAfterTrigger:o}=this.findActiveTrigger(a);if(!i||s===-1)return this.currentTrigger=null,[];if(this.shouldEndSuggestionContext(i,o))return this.currentTrigger=null,[];switch(this.currentTrigger=i,i){case"@":return this.getContextSuggestions(o);case"status":return this.getStatusSuggestions(o);case"#":return this.getTagSuggestions(o);case"+":return await this.getProjectSuggestions(o);default:return[]}}renderSuggestion(t,r){var c,d,u,p,m;r.setAttribute("role","option");let a=t.type==="project"?t.displayName:t.display;r.setAttribute("aria-label",`${t.type}: ${a}`);let i=r.createSpan("nlp-suggest-icon");i.textContent=this.currentTrigger==="status"?this.plugin.settings.statusSuggestionTrigger||"":this.currentTrigger||"",i.setAttribute("aria-hidden","true");let s=r.createSpan("nlp-suggest-text"),o=(f,h)=>{if(!h)return;let g=h.toLowerCase().split(/\s+/).filter(Boolean);if(!g.length)return;let v=k=>{var T;if(k.nodeType===Node.TEXT_NODE){let b=k.nodeValue||"",w=b.toLowerCase(),S=[];for(let _ of g){let F=w.indexOf(_);for(;F!==-1;)S.push({start:F,end:F+_.length}),F=w.indexOf(_,F+1)}S.sort((_,F)=>_.start-F.start);let C=[];for(let _ of S)(!C.length||_.start>=C[C.length-1].end)&&C.push(_);if(!C.length)return;let x=activeWindow.createFragment(),E=0;for(let _ of C){_.start>E&&x.appendChild(activeDocument.createTextNode(b.slice(E,_.start)));let F=activeWindow.createEl("mark");F.textContent=b.slice(_.start,_.end),x.appendChild(F),E=_.end}E0&&t.entry){let g=this.getProjectMetadataResolver();for(let v=0;vwC,getTaskSelectorQueryRank:()=>f2,openTaskSelector:()=>fn,openTaskSelectorWithCreate:()=>BUe,taskMatchesSelectorQuery:()=>Tce});function bC(n,e){return n==null||typeof n!="string"&&typeof n!="number"&&typeof n!="boolean"?!1:String(n).toLowerCase().includes(e)}function gM(n,e){if(n==null||typeof n!="string"&&typeof n!="number"&&typeof n!="boolean")return null;let t=String(n).toLowerCase();return t.includes(e)?t===e?0:t.startsWith(e)?1:t.split(/[^a-z0-9]+/).some(a=>a.startsWith(e))?2:3:null}function kce(n,e){let t=null;for(let r of n){let a=gM(r,e);a!==null&&(t=t===null?a:Math.min(t,a))}return t}function Tce(n,e){var r;return!!(bC(n.title,e)||bC(n.due,e)||n.priority!=="normal"&&bC(n.priority,e)||(r=n.contexts)!=null&&r.some(a=>bC(a,e))||Ko(n.projects||[]).some(a=>bC(a,e)))}function f2(n,e){let t=gM(n.title,e);if(t!==null)return t;let r=kce(n.contexts||[],e);if(r!==null)return 10+r;let a=Ko(n.projects||[]),i=kce(a,e);if(i!==null)return 20+i;if(n.priority!=="normal"){let o=gM(n.priority,e);if(o!==null)return 30+o}let s=gM(n.due,e);return s!==null?40+s:Number.MAX_SAFE_INTEGER}async function BUe(n,e){let t=await n.cacheManager.getAllTasks();return new Promise(r=>{new wC(n.app,n,t,{onResult:r,...e}).open()})}function fn(n,e,t,r){new wC(n.app,n,e,{placeholder:r==null?void 0:r.placeholder,title:r==null?void 0:r.title,targetDate:r==null?void 0:r.targetDate,creationDefaults:r==null?void 0:r.creationDefaults,onResult:i=>{i.type==="selected"||i.type==="created"?t(i.task):t(null)}}).open()}var Jl,zUe,wC,co=y(()=>{Jl=require("obsidian");yt();Wl();Ua();TC();hM();m2();q();zUe=M({tag:"Modals/TaskSelectorWithCreateModal"});wC=class extends Jl.SuggestModal{constructor(t,r,a,i){super(t);this.nlpSuggest=null;this.createFooterEl=null;this.currentQuery="";this.resultHandled=!1;this.isCreatingTask=!1;this.handleCreateFooterActivation=t=>{!this.createFooterEl||this.createFooterEl.classList.contains("tn-static-display-none-6b99de8b")||(t.preventDefault(),t.stopPropagation(),this.createNewTask())};this.handleCreateFooterKeydown=t=>{t.key!=="Enter"&&t.key!==" "||this.handleCreateFooterActivation(t)};this.handleInputChange=()=>{let t=this.inputEl.value.trim();this.currentQuery=t,this.updateCreateFooter(t)};this.plugin=r,this.tasks=a,this.options=i,this.targetDate=i.targetDate||new Date,this.translate=r.i18n.translate.bind(r.i18n),this.nlParser=Nn.fromPlugin(r),this.setPlaceholder(i.placeholder||this.translate("modals.taskSelectorWithCreate.placeholder")),this.setInstructions([{command:"↑↓",purpose:this.translate("modals.taskSelector.instructions.navigate")},{command:"↵",purpose:this.translate("modals.taskSelector.instructions.select")},{command:"⇧↵",purpose:this.translate("modals.taskSelectorWithCreate.instructions.create")},{command:"esc",purpose:this.translate("modals.taskSelector.instructions.dismiss")}]),this.titleEl.setText(i.title||this.translate("modals.taskSelectorWithCreate.title")),this.titleEl.setAttribute("id","task-selector-with-create-title"),this.containerEl.setAttribute("aria-labelledby","task-selector-with-create-title"),this.containerEl.setAttribute("role","dialog"),this.containerEl.setAttribute("aria-modal","true"),this.containerEl.addClass("task-selector-with-create-modal"),this.containerEl.addClass("tasknotes-plugin")}onOpen(){super.onOpen(),this.scope.register(["Shift"],"Enter",t=>(t.preventDefault(),t.stopPropagation(),this.createNewTask(),!1)),this.inputEl.addEventListener("input",this.handleInputChange),this.nlpSuggest=new nv(this.app,this.inputEl,this.plugin),window.setTimeout(()=>this.createFooter(),0)}createFooter(){var r;let t=((r=this.modalEl.querySelector(".prompt"))==null?void 0:r.parentElement)||this.modalEl;this.createFooterEl=t.createDiv({cls:"task-selector-create-footer"}),this.createFooterEl.setAttribute("role","button"),this.createFooterEl.setAttribute("aria-hidden","true"),this.createFooterEl.tabIndex=-1,this.createFooterEl.addEventListener("click",this.handleCreateFooterActivation),this.createFooterEl.addEventListener("keydown",this.handleCreateFooterKeydown),this.createFooterEl.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-min-height-800px-997b4c8c"),this.createFooterEl.classList.add("tn-static-display-none-6b99de8b"),this.currentQuery&&this.updateCreateFooter(this.currentQuery)}updateCreateFooter(t){if(!this.createFooterEl)return;if(!t){this.createFooterEl.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-min-height-800px-997b4c8c"),this.createFooterEl.classList.add("tn-static-display-none-6b99de8b"),this.createFooterEl.setAttribute("aria-hidden","true"),this.createFooterEl.removeAttribute("aria-label"),this.createFooterEl.tabIndex=-1,this.createFooterEl.empty();return}let r=this.nlParser.parseInput(t);if(r.title&&r.title!=="Untitled Task"){this.createFooterEl.empty(),this.createFooterEl.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),this.createFooterEl.classList.add("tn-static-display-flex-75816cae"),this.createFooterEl.setAttribute("aria-hidden","false"),this.createFooterEl.setAttribute("aria-label",`${this.translate("modals.taskSelectorWithCreate.footer.createLabel").trim()} ${r.title}`.trim()),this.createFooterEl.tabIndex=0;let a=this.createFooterEl.createDiv({cls:"task-selector-create-footer__icon"});(0,Jl.setIcon)(a,"plus-circle");let i=this.createFooterEl.createDiv({cls:"task-selector-create-footer__content"});i.createDiv({cls:"task-selector-create-footer__title-line"}).createSpan({cls:"task-selector-create-footer__title",text:r.title});let o=this.buildMetadataParts(r);if(o.length>0){let c=i.createDiv({cls:"task-selector-create-footer__meta"});o.forEach(d=>{let u=c.createSpan({cls:`task-selector-create-footer__chip task-selector-create-footer__chip--${d.type}`}),p=u.createSpan({cls:"task-selector-create-footer__chip-icon"});(0,Jl.setIcon)(p,d.icon),u.createSpan({cls:"task-selector-create-footer__chip-text",text:d.text})})}let l=i.createDiv({cls:"task-selector-create-footer__hint"});l.createSpan({cls:"task-selector-create-footer__shortcut",text:"⇧↵"}),l.createSpan({cls:"task-selector-create-footer__hint-text",text:this.translate("modals.taskSelectorWithCreate.footer.createLabel")})}else this.createFooterEl.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-min-height-800px-997b4c8c"),this.createFooterEl.classList.add("tn-static-display-none-6b99de8b"),this.createFooterEl.setAttribute("aria-hidden","true"),this.createFooterEl.removeAttribute("aria-label"),this.createFooterEl.tabIndex=-1,this.createFooterEl.empty()}buildMetadataParts(t){let r=[];if(t.dueDate){let a=t.dueTime?`${t.dueDate} ${t.dueTime}`:t.dueDate;r.push({icon:"calendar",text:a,type:"due"})}if(t.scheduledDate){let a=t.scheduledTime?`${t.scheduledDate} ${t.scheduledTime}`:t.scheduledDate;r.push({icon:"calendar-clock",text:a,type:"scheduled"})}if(t.priority&&t.priority!=="normal"&&r.push({icon:"flag",text:t.priority,type:"priority"}),t.status){let a=this.plugin.statusManager.getStatusConfig(t.status);r.push({icon:"circle-dot",text:(a==null?void 0:a.label)||t.status,type:"status"})}if(t.contexts&&t.contexts.length>0&&t.contexts.forEach(a=>{r.push({icon:"at-sign",text:a,type:"context"})}),t.projects&&t.projects.length>0&&t.projects.forEach(a=>{r.push({icon:"folder",text:a.replace(/^\[\[|\]\]$/g,""),type:"project"})}),t.tags&&t.tags.length>0&&t.tags.forEach(a=>{r.push({icon:"hash",text:a,type:"tag"})}),t.recurrence&&r.push({icon:"repeat",text:t.recurrence,type:"recurrence"}),t.estimate&&t.estimate>0){let a=Math.floor(t.estimate/60),i=t.estimate%60,s=a>0?`${a}h ${i}m`:`${i}m`;r.push({icon:"timer",text:s,type:"estimate"})}if(t.details){let a=t.details.length>30?t.details.substring(0,30)+"...":t.details;r.push({icon:"file-text",text:a,type:"details"})}if(t.userFields){let a=this.plugin.settings.userFields||[];for(let[i,s]of Object.entries(t.userFields)){let o=a.find(d=>d.id===i),l=(o==null?void 0:o.displayName)||i,c=Array.isArray(s)?s.join(", "):s;r.push({icon:"sliders-horizontal",text:`${l}: ${c}`,type:"userfield"})}}return r}async createNewTask(){if(this.isCreatingTask)return;let t=this.inputEl.value.trim();if(!t){new Jl.Notice(this.translate("modals.taskSelectorWithCreate.notices.emptyQuery"));return}this.isCreatingTask=!0;try{let r=this.nlParser.parseInput(t);if(!r.title||r.title==="Untitled Task"){new Jl.Notice(this.translate("modals.taskSelectorWithCreate.notices.invalidTitle"));return}let a=this.buildTaskDataFromParsed(r),i=await this.plugin.taskService.createTask(a);new Jl.Notice(this.translate("modals.taskCreation.notices.success",{title:i.taskInfo.title})),this.resultHandled=!0,this.close(),this.options.onResult({type:"created",task:i.taskInfo})}catch(r){zUe.error("Failed to create task:",{category:"persistence",operation:"create-task",error:r});let a=r instanceof Error?r.message:String(r);new Jl.Notice(this.translate("modals.taskCreation.notices.failure",{message:a}))}finally{this.isCreatingTask=!1}}buildTaskDataFromParsed(t){let r=Vd(this.plugin,t),a=this.options.creationDefaults;return a?{...a,...r,priority:t.priority||a.priority||r.priority,projects:[...new Set([...a.projects||[],...r.projects||[]])],tags:[...new Set([...a.tags||[],...r.tags||[]])],contexts:[...new Set([...a.contexts||[],...r.contexts||[]])]}:r}getSuggestions(t){return this.currentQuery=t,this.getFilteredTasks(t)}getFilteredTasks(t){let r=t.trim().toLowerCase(),a=r.length>0;return this.tasks.filter(i=>!i.archived).filter(i=>a?Tce(i,r):!0).sort((i,s)=>{var p,m;if(a){let f=f2(i,r)-f2(s,r);if(f!==0)return f}let o=Wf(i,this.targetDate,this.plugin.statusManager,this.plugin.settings.defaultTaskStatus),l=Wf(s,this.targetDate,this.plugin.statusManager,this.plugin.settings.defaultTaskStatus);if(o!==l)return o?1:-1;if(a){let f=i.title.localeCompare(s.title);if(f!==0)return f}if(i.due&&!s.due)return-1;if(!i.due&&s.due)return 1;if(i.due&&s.due){let f=i.due.localeCompare(s.due);if(f!==0)return f}let c={high:0,normal:1,low:2},d=(p=c[i.priority])!=null?p:1,u=(m=c[s.priority])!=null?m:1;return d!==u?d-u:i.title.localeCompare(s.title)})}renderSuggestion(t,r){let a=fM(t,this.targetDate,this.plugin.statusManager,this.plugin.settings.defaultTaskStatus),i=pr(a,this.plugin,void 0,{layout:"default",targetDate:this.targetDate});i.classList.add("task-selector-modal__suggestion");let s=i.cloneNode(!0);r.appendChild(s)}onChooseSuggestion(t,r){this.resultHandled=!0,this.options.onResult({type:"selected",task:t})}onClose(){var t;this.inputEl.removeEventListener("input",this.handleInputChange),(t=this.nlpSuggest)==null||t.close(),this.nlpSuggest=null,this.createFooterEl&&(this.createFooterEl.removeEventListener("click",this.handleCreateFooterActivation),this.createFooterEl.removeEventListener("keydown",this.handleCreateFooterKeydown),this.createFooterEl.remove(),this.createFooterEl=null),window.setTimeout(()=>{this.resultHandled||this.options.onResult({type:"cancelled"})},0),super.onClose()}}});function bce(n){let e=String(n.getHours()).padStart(2,"0"),t=String(n.getMinutes()).padStart(2,"0");return`${e}:${t}`}function wce(n,e){let t=null;if(n.scheduled)try{t=et(n.scheduled)}catch(i){t=null}(!t||isNaN(t.getTime()))&&(t=new Date(e)),isNaN(t.getTime())&&(t=new Date),(!n.scheduled||!Jt(n.scheduled))&&t.setHours(9,0,0,0);let r=n.timeEstimate&&n.timeEstimate>0?n.timeEstimate:60,a=new Date(t.getTime()+r*60*1e3);return{date:ae(t),startTime:bce(t),endTime:bce(a)}}var Sce=y(()=>{xe()});function pp(n,e,t){new g2(n.app,n,{placeholder:t==null?void 0:t.placeholder,title:t==null?void 0:t.title,filter:t==null?void 0:t.filter,newFileFolder:t==null?void 0:t.newFileFolder,sortOrder:t==null?void 0:t.sortOrder,onResult:a=>{a.type==="selected"||a.type==="created"?e(a.file):e(null)}}).open()}var oa,jUe,g2,SC=y(()=>{oa=require("obsidian");q();ya();jUe=M({tag:"Modals/FileSelectorModal"}),g2=class extends oa.SuggestModal{constructor(t,r,a){super(t);this.currentQuery="";this.resultHandled=!1;this.createFooterEl=null;this.handleInputChange=()=>{this.currentQuery=this.inputEl.value.trim(),this.updateCreateFooter()};this.plugin=r,this.options=a,this.setPlaceholder(a.placeholder||"Search files or type to create new..."),this.setInstructions([{command:"↑↓",purpose:"to navigate"},{command:"↵",purpose:"to select"},{command:"⇧↵",purpose:"to create new"},{command:"esc",purpose:"to cancel"}]),a.title&&this.titleEl.setText(a.title),this.containerEl.addClass("file-selector-modal"),this.containerEl.addClass("tasknotes-plugin")}onOpen(){super.onOpen(),this.scope.register(["Shift"],"Enter",t=>(t.preventDefault(),t.stopPropagation(),this.createNewFile(),!1)),this.inputEl.addEventListener("input",this.handleInputChange),window.setTimeout(()=>this.createFooter(),0)}createFooter(){var r;let t=this.modalEl.querySelector(".prompt");t&&(this.createFooterEl=((r=t.parentElement)==null?void 0:r.createDiv({cls:"file-selector-create-footer"}))||null,this.createFooterEl&&(this.createFooterEl.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-min-height-800px-997b4c8c"),this.createFooterEl.classList.add("tn-static-display-none-6b99de8b")))}updateCreateFooter(){if(!this.createFooterEl)return;if(!this.currentQuery){this.createFooterEl.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-min-height-800px-997b4c8c"),this.createFooterEl.classList.add("tn-static-display-none-6b99de8b");return}this.createFooterEl.empty(),this.createFooterEl.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),this.createFooterEl.classList.add("tn-static-display-flex-75816cae");let r=this.createFooterEl.createDiv({cls:"file-selector-create-footer__content"}).createDiv({cls:"file-selector-create-footer__title-line"});r.createSpan({cls:"file-selector-create-footer__shortcut",text:"⇧↵"}),r.createSpan({cls:"file-selector-create-footer__hint-text",text:" to create: "}),r.createSpan({cls:"file-selector-create-footer__filename",text:this.getNewFileName()})}getNewFileName(){let t=this.currentQuery;return t.toLowerCase().endsWith(".md")&&(t=t.slice(0,-3)),t+".md"}async createNewFile(){if(!this.currentQuery){new oa.Notice("Please enter a file name");return}try{let t=this.currentQuery;t.toLowerCase().endsWith(".md")&&(t=t.slice(0,-3));let r=this.options.newFileFolder||"",a=r?`${r}/${t}.md`:`${t}.md`;if(this.app.vault.getAbstractFileByPath(a)){new oa.Notice(`File "${a}" already exists`);return}r&&!await this.app.vault.adapter.exists(r)&&await Bb(this.app,r);let s=await mf(this.app,a,"");this.resultHandled=!0,this.close(),this.options.onResult({type:"created",file:s})}catch(t){jUe.error("Error creating file:",{category:"persistence",operation:"creating-file",error:t}),new oa.Notice("Failed to create file")}}getSuggestions(t){this.currentQuery=t.trim(),this.updateCreateFooter();let r=this.app.vault.getAllLoadedFiles(),a=t.toLowerCase(),i,s=this.options.filter||"markdown";typeof s=="function"?i=r.filter(s):s==="markdown"?i=r.filter(c=>c instanceof oa.TFile&&c.extension==="md"&&!c.path.includes(".trash")):i=r.filter(c=>c instanceof oa.TFile&&!c.path.includes(".trash"));let o=this.options.sortOrder||"name-asc",l=[...i].sort((c,d)=>{let u=c instanceof oa.TFile?c.stat.ctime:0,p=d instanceof oa.TFile?d.stat.ctime:0,m=c instanceof oa.TFile?c.stat.mtime:0,f=d instanceof oa.TFile?d.stat.mtime:0;switch(o){case"name-desc":return d.name.localeCompare(c.name);case"path-asc":return c.path.localeCompare(d.path);case"path-desc":return d.path.localeCompare(c.path);case"created-recent":return p-u;case"created-oldest":return u-p;case"modified-recent":return f-m;case"modified-oldest":return m-f;case"name-asc":default:return c.name.localeCompare(d.name)}});return t?l.filter(c=>this.getSearchText(c).toLowerCase().includes(a)).slice(0,50):l.slice(0,50)}getSearchText(t){let r=`${t.name} ${t.path}`;if(t instanceof oa.TFile){let a=this.app.metadataCache.getFileCache(t);if(a!=null&&a.frontmatter){let i=this.plugin.fieldMapper.toUserField("title"),s=a.frontmatter[i];s&&(r+=` ${s}`);let o=(0,oa.parseFrontMatterAliases)(a.frontmatter);o&&o.length>0&&(r+=` ${o.join(" ")}`)}}return r}renderSuggestion(t,r){let a=r.createDiv({cls:"file-selector-suggestion"});if(a.createDiv({cls:"file-selector-suggestion__name",text:t.name}),t instanceof oa.TFile){let i=this.app.metadataCache.getFileCache(t);if(i!=null&&i.frontmatter){let s=this.plugin.fieldMapper.toUserField("title"),o=i.frontmatter[s];if(o)a.createDiv({cls:"file-selector-suggestion__title",text:o});else{let l=(0,oa.parseFrontMatterAliases)(i.frontmatter);l&&l.length>0&&a.createDiv({cls:"file-selector-suggestion__aliases",text:l.join(", ")})}}}t.parent&&t.parent.path!=="/"&&a.createDiv({cls:"file-selector-suggestion__path",text:t.parent.path})}onChooseSuggestion(t,r){this.resultHandled=!0,this.options.onResult({type:"selected",file:t})}onClose(){this.inputEl.removeEventListener("input",this.handleInputChange),this.createFooterEl&&(this.createFooterEl.remove(),this.createFooterEl=null),window.setTimeout(()=>{this.resultHandled||this.options.onResult({type:"cancelled"})},0),super.onClose()}}});function UUe(){return(0,mp.requireApiVersion)("1.11.0")}function zi(n){Promise.resolve().then(n).catch(e=>{$Ue.error("TaskNotes settings callback failed:",{category:"configuration",operation:"settings-callback",error:e})})}function kt(n,e,t){if(UUe()){let r=new mp.SettingGroup(n).setHeading(e.heading);if(e.className&&r.addClass(e.className),e.description){let a=e.description;r.addSetting(i=>{i.setDesc(a),i.settingEl.addClass("settings-view__group-description")})}return t(r),r}else{let r=new y2(n).setHeading(e.heading);if(e.className&&r.addClass(e.className),e.description){let a=e.description;r.addSetting(i=>{i.setDesc(a),i.settingEl.addClass("settings-view__group-description")})}return t(r),r}}function me(n,e){return n.setName(e.name).setDesc(e.desc).addToggle(t=>{t.setValue(e.getValue()).onChange(r=>{zi(()=>e.setValue(r))})})}function rn(n,e){return n.setName(e.name).setDesc(e.desc).addText(t=>{t.setValue(e.getValue());let r=a=>{zi(()=>e.setValue(a))};if(e.debounceMs&&e.debounceMs>0){let a=iv(r,e.debounceMs);t.onChange(a)}else t.onChange(r);return e.placeholder&&t.setPlaceholder(e.placeholder),e.ariaLabel&&t.inputEl.setAttribute("aria-label",e.ariaLabel),t.inputEl.addClass("settings-view__input"),t})}function Ur(n,e){return n.setName(e.name).setDesc(e.desc).addDropdown(t=>(e.options.forEach(r=>{t.addOption(r.value,r.label)}),t.setValue(e.getValue()).onChange(r=>{zi(()=>e.setValue(r))}),e.ariaLabel&&t.selectEl.setAttribute("aria-label",e.ariaLabel),t))}function ui(n,e){let t=e.debounceMs?iv(r=>{zi(()=>e.setValue(r))},e.debounceMs):r=>{zi(()=>e.setValue(r))};return n.setName(e.name).setDesc(e.desc).addText(r=>(r.setValue(e.getValue().toString()).onChange(a=>{let i=parseInt(a);if(!isNaN(i)){if(e.min!==void 0&&ie.max)return;t(i)}}),r.inputEl.type="number",e.placeholder&&r.setPlaceholder(e.placeholder),e.min!==void 0&&r.inputEl.setAttribute("min",e.min.toString()),e.max!==void 0&&r.inputEl.setAttribute("max",e.max.toString()),e.ariaLabel&&r.inputEl.setAttribute("aria-label",e.ariaLabel),r.inputEl.addClass("settings-view__input"),r))}function Xl(n,e){return n.setName(e.name).setDesc(e.desc).addButton(t=>(t.setButtonText(e.buttonText).onClick(()=>{zi(e.onClick)}),e.buttonClass?t.buttonEl.addClass(e.buttonClass):t.buttonEl.addClasses(["tn-btn","tn-btn--ghost"]),t))}function fp(n,e){return new mp.Setting(n).setName(e).setHeading()}function ec(n,e){return n.createEl("p",{text:e,cls:"settings-view__help-note"})}function iv(n,e,t=!1){let r,a,i,s=function(...o){a=o,i=this;let l=()=>{r=void 0,a=void 0,t||n.apply(i,o)},c=t&&!r;window.clearTimeout(r),r=window.setTimeout(l,e),c&&n.apply(this,o)};return s.flush=()=>{r&&a&&(window.clearTimeout(r),r=void 0,n.apply(i,a),a=void 0)},s}var mp,$Ue,y2,tc=y(()=>{mp=require("obsidian");q();$Ue=M({tag:"Settings/Components/SettingHelpers"});y2=class{constructor(e){this.containerEl=e}setHeading(e){return new mp.Setting(this.containerEl).setName(e).setHeading(),this}addClass(e){return this}addSetting(e){let t=new mp.Setting(this.containerEl);return e(t),this}}});function b2(n,e){n.classList.toggle("tasknotes-settings__card--collapsed",e);let t=n.querySelector(":scope > .tasknotes-settings__card-header");t&&(t.title=e?"Expand card":"Collapse card")}function sr(n,e){let t=n.createDiv("tasknotes-settings__card");e.id&&t.setAttribute("data-card-id",e.id),e.draggable&&t.addClass("tasknotes-settings__card--draggable"),e.collapsible&&(t.addClass("tasknotes-settings__card--collapsible"),e.defaultCollapsed&&t.addClass("tasknotes-settings__card--collapsed"));let r=t.createDiv("tasknotes-settings__card-header"),a=null;e.draggable&&(r.addClass("tasknotes-settings__card-header--with-drag-handle"),a=r.createDiv("tasknotes-settings__card-drag-handle"),a.textContent="⋮⋮",a.draggable=!0,a.title="Drag to reorder");let i=r.createDiv();if(i.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),i.classList.add("tn-static-display-flex-75816cae"),i.classList.remove("tn-static-align-items-baseline-4b95b5c7","tn-static-align-items-flex-start-0486f781"),i.classList.add("tn-static-align-items-center-7c619740"),i.classList.remove("tn-static-flex-1-14e3b769","tn-static-margin-top-12px-91e0f558"),i.classList.add("tn-static-flex-1-97445a8d"),i.classList.remove("tn-static-min-width-2px-709d7da0"),i.classList.add("tn-static-min-width-0-3922d326"),e.colorIndicator){let c=i.createDiv("tasknotes-settings__card-color-indicator");c.style.backgroundColor=hr(e.colorIndicator.color),e.colorIndicator.cssVar&&c.style.setProperty("--card-color",hr(e.colorIndicator.color))}let s=i.createDiv("tasknotes-settings__card-info"),o=s.createSpan("tasknotes-settings__card-primary-text");if(o.textContent=e.header.primaryText,e.header.secondaryText){let c=s.createSpan("tasknotes-settings__card-secondary-text");c.textContent=e.header.secondaryText}let l=r.createDiv();if(l.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),l.classList.add("tn-static-display-flex-75816cae"),l.classList.remove("tn-static-align-items-baseline-4b95b5c7","tn-static-align-items-flex-start-0486f781"),l.classList.add("tn-static-align-items-center-7c619740"),l.classList.remove("tn-static-display-flex-8bb39979","tn-static-gap-10px-f3d7ce77","tn-static-gap-12px-ed7b3d87","tn-static-gap-6px-f0abc1db","tn-static-gap-8px-33fcd4c3"),l.classList.add("tn-static-gap-0-5rem-ce2fca4d"),e.header.meta&&e.header.meta.length>0){let c=l.createDiv("tasknotes-settings__card-meta");e.header.meta.forEach(d=>{c.appendChild(d)})}if(e.header.actions&&e.header.actions.length>0){let c=l.querySelector(".tasknotes-settings__card-header-actions")||l.createDiv("tasknotes-settings__card-header-actions");e.header.actions.forEach(d=>{let u=c.createEl("button",{cls:"tasknotes-settings__card-header-btn"});d.variant==="delete"&&u.addClass("tasknotes-settings__card-header-btn--delete");let p=u.createSpan();(0,CC.setIcon)(p,d.icon),d.tooltip&&(u.title=d.tooltip),u.onclick=m=>{m.stopPropagation(),zi(d.onClick)}})}if(e.collapsible){let c=()=>{var p;let u=!t.hasClass("tasknotes-settings__card--collapsed");b2(t,u),t.dispatchEvent(new CustomEvent(T2,{bubbles:!0})),(p=e.onCollapseChange)==null||p.call(e,u)};r.addClass("tasknotes-settings__card-header--clickable"),r.title=e.defaultCollapsed?"Expand card":"Collapse card",r.onclick=d=>{d.target.closest(".tasknotes-settings__card-header-actions")||c()}}if(e.content&&e.content.sections.length>0){let c=t.createDiv("tasknotes-settings__card-content");e.draggable&&c.addClass("tasknotes-settings__card-content--with-drag-handle"),e.content.sections.forEach(d=>{d.rows.forEach(u=>{let p=c.createDiv("tasknotes-settings__card-config-row");u.fullWidth&&(p.classList.remove("tn-static-display-flex-4d51fc62","tn-static-display-flex-8bb39979","tn-static-min-height-800px-997b4c8c"),p.classList.add("tn-static-flex-direction-column-06c8b5ed"),p.classList.remove("tn-static-align-items-baseline-4b95b5c7","tn-static-align-items-center-7c619740"),p.classList.add("tn-static-align-items-flex-start-0486f781"),p.classList.remove("tn-static-display-flex-8bb39979","tn-static-gap-10px-f3d7ce77","tn-static-gap-12px-ed7b3d87","tn-static-gap-6px-f0abc1db","tn-static-gap-8px-33fcd4c3"),p.classList.add("tn-static-gap-0-5rem-ce2fca4d"));let m=p.createSpan("tasknotes-settings__card-config-label");m.textContent=u.label,p.appendChild(u.input)})})}if(e.actions&&e.actions.buttons.length>0){let c=t.createDiv("tasknotes-settings__card-actions");e.draggable&&c.addClass("tasknotes-settings__card-actions--with-drag-handle"),e.actions.buttons.forEach(d=>{let u=c.createEl("button",{text:d.text,cls:"tasknotes-settings__card-action-btn"});if(d.variant&&u.addClass(`tasknotes-settings__card-action-btn--${d.variant}`),d.icon){let p=u.createSpan();(0,CC.setIcon)(p,d.icon),u.insertBefore(p,u.firstChild)}d.disabled&&(u.disabled=!0),u.onclick=()=>{zi(d.onClick)}})}return t}function pi(n,e="default"){let t=activeWindow.createSpan();return t.addClass("tasknotes-settings__card-status-badge"),t.addClass(`tasknotes-settings__card-status-badge--${e}`),t.textContent=n,t}function ol(n,e){return{icon:"trash-2",variant:"delete",tooltip:e||"Delete",onClick:n}}function Ge(n="text",e,t){let r=activeWindow.createEl("input");return r.type=n,r.addClass("tasknotes-settings__card-input"),e&&(r.placeholder=e),t&&(r.value=t),r}function GUe(){if(activeDocument.getElementById(k2))return;let n=activeWindow.createEl("datalist");n.id=k2;for(let e of Bte)n.createEl("option",{value:e});activeDocument.body.appendChild(n)}function v2(n){let e=n==null?void 0:n.trim().match(qUe);if(!e)return null;let t=e[1].toLowerCase();return t.length===3?`#${t[0]}${t[0]}${t[1]}${t[1]}${t[2]}${t[2]}`:`#${t}`}function YUe(n){n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0}))}function KUe(n){var i;if(!n.parentElement)return;if((i=n.tasknotesThemeColorPicker)!=null&&i.isConnected){let s=v2(n.value);s&&(n.tasknotesThemeColorPicker.value=s);return}let t=activeWindow.createEl("input");t.type="color",t.addClass(HUe),t.value=v2(n.value)||WUe,t.title="Open color picker",t.setAttribute("aria-label","Open color picker");let r=()=>{n.value!==t.value&&(n.value=t.value,YUe(n))},a=()=>{let s=v2(n.value);s&&(t.value=s)};t.addEventListener("input",r),t.addEventListener("change",r),n.addEventListener("input",a),n.addEventListener("change",a),n.insertAdjacentElement("afterend",t),n.tasknotesThemeColorPicker=t}function qf(n){let e=n;n.type="text",n.addClass(VUe),n.placeholder=A0,n.setAttribute("list",k2),n.title=A0,GUe(),KUe(e)}function sv(n){let e=Ge("text",A0,xd(n));return qf(e),e}function ov(n,e){let t=hr(n.value,e);return n.value=xd(t),t}function nn(n=!1,e){let t=activeWindow.createDiv(),r=new CC.Setting(t),a=null;if(r.addToggle(i=>{i.setValue(n),e&&i.onChange(s=>{zi(()=>e(s))}),a=i.toggleEl}),!a)throw new Error("Failed to create card toggle");return a}function Wn(n,e){let t=activeWindow.createEl("select");return t.addClass("tasknotes-settings__card-input"),n.forEach(r=>{let a=t.createEl("option",{value:r.value,text:r.label});e===r.value&&(a.selected=!0)}),t}function lv(n,e,t){let r=n.querySelector(".tasknotes-settings__card-drag-handle");if(!r)return;let a=n.getAttribute("data-card-id");a&&(r.addEventListener("dragstart",i=>{i.dataTransfer&&(i.dataTransfer.setData("text/plain",a),n.addClass("tasknotes-settings__card--dragging"))}),r.addEventListener("dragend",()=>{n.removeClass("tasknotes-settings__card--dragging")}),n.addEventListener("dragover",i=>{i.preventDefault();let s=e.querySelector(".tasknotes-settings__card--dragging");if(s&&s!==n){let o=n.getBoundingClientRect(),l=o.top+o.height/2;n.removeClass("tasknotes-settings__card--drag-over-top","tasknotes-settings__card--drag-over-bottom"),i.clientY{n.removeClass("tasknotes-settings__card--drag-over-top","tasknotes-settings__card--drag-over-bottom")}),n.addEventListener("drop",i=>{var l;i.preventDefault(),n.removeClass("tasknotes-settings__card--drag-over-top","tasknotes-settings__card--drag-over-bottom");let s=(l=i.dataTransfer)==null?void 0:l.getData("text/plain");if(!s)return;let o=a;if(s!==o){let c=n.getBoundingClientRect(),d=c.top+c.height/2,u=i.clientY{CC=require("obsidian");Ll();tc();T2="tasknotes:card-collapse-changed";k2="tasknotes-theme-color-options",HUe="tasknotes-theme-color-picker",VUe="tasknotes-theme-color-text-input",WUe="#6366f1",qUe=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i});function C2(n){return n instanceof Error?n.message:typeof n=="string"?n:""}function ZUe(n=gp.getAllDailyNotes){try{return n()}catch(e){let t=C2(e),r=t?`: ${t}`:"";throw new Error(`Failed to read daily notes${r}. ${vM}`)}}function QUe(n){let e=C2(n);return e?`Failed to create timeblock: ${e}`:"Failed to create timeblock. Check console for details."}function JUe(n){return(0,or.moment)(n)}var or,gp,S2,vM,dv,x2=y(()=>{or=require("obsidian");yt();SC();co();xe();Ll();va();ya();gp=tt(od());q();S2=M({tag:"Modals/TimeblockCreationModal"}),vM="Check the Daily Notes core plugin settings and make sure the configured daily notes folder exists.";dv=class extends or.Modal{constructor(t,r,a){super(t);this.selectedAttachments=[];this.keyboardHandler=null;this.plugin=r,this.options=a,this.translate=r.i18n.translate.bind(r.i18n)}onOpen(){let{contentEl:t}=this;t.empty(),t.addClass("timeblock-creation-modal"),this.keyboardHandler=l=>{l.key==="Enter"&&(l.ctrlKey||l.metaKey)&&(l.preventDefault(),this.handleSubmit())},this.containerEl.addEventListener("keydown",this.keyboardHandler),new or.Setting(t).setName(this.translate("modals.timeblockCreation.heading")).setHeading();let r=t.createDiv({cls:"timeblock-date-display"});r.createEl("strong",{text:this.translate("modals.timeblockCreation.dateLabel")});let a=df(this.options.date);r.createSpan({text:a.toLocaleDateString()}),new or.Setting(t).setName(this.translate("modals.timeblockCreation.titleLabel")).setDesc(this.translate("modals.timeblockCreation.titleDesc")).addText(l=>{this.titleInput=l.inputEl,l.setPlaceholder(this.translate("modals.timeblockCreation.titlePlaceholder")).setValue(this.options.prefilledTitle||"").onChange(()=>this.validateForm()),window.setTimeout(()=>this.titleInput.focus(),100)}),new or.Setting(t).setName(this.translate("modals.timeblockCreation.startTimeLabel")).setDesc(this.translate("modals.timeblockCreation.startTimeDesc")).addText(l=>{this.startTimeInput=l.inputEl,l.setPlaceholder(this.translate("modals.timeblockCreation.startTimePlaceholder")).setValue(this.options.startTime||"").onChange(()=>this.validateForm()),this.startTimeInput.type="time"}),new or.Setting(t).setName(this.translate("modals.timeblockCreation.endTimeLabel")).setDesc(this.translate("modals.timeblockCreation.endTimeDesc")).addText(l=>{this.endTimeInput=l.inputEl,l.setPlaceholder(this.translate("modals.timeblockCreation.endTimePlaceholder")).setValue(this.options.endTime||"").onChange(()=>{this.validateForm()}),this.endTimeInput.type="time"}),new or.Setting(t).setName(this.translate("modals.timeblockCreation.descriptionLabel")).setDesc(this.translate("modals.timeblockCreation.descriptionDesc")).addTextArea(l=>{this.descriptionInput=l.inputEl,l.setPlaceholder(this.translate("modals.timeblockCreation.descriptionPlaceholder")).setValue(""),this.descriptionInput.rows=3}),new or.Setting(t).setName(this.translate("modals.timeblockCreation.colorLabel")).setDesc(this.translate("modals.timeblockCreation.colorDesc")).addText(l=>{this.colorInput=l.inputEl,l.setPlaceholder(this.translate("modals.timeblockCreation.colorPlaceholder")).setValue(xd(this.plugin.settings.calendarViewSettings.defaultTimeblockColor)),qf(this.colorInput)}),new or.Setting(t).setName(this.translate("modals.timeblockCreation.attachmentsLabel")).setDesc(this.translate("modals.timeblockCreation.attachmentsDesc")).addButton(l=>{l.setButtonText(this.translate("modals.timeblockCreation.addAttachmentButton")).setTooltip(this.translate("modals.timeblockCreation.addAttachmentTooltip")).onClick(()=>{pp(this.plugin,c=>{c instanceof or.TAbstractFile&&this.addAttachment(c)},{placeholder:"Search files or type to create new...",filter:"all",sortOrder:this.plugin.settings.calendarViewSettings.timeblockAttachmentSearchOrder})})}).addButton(l=>{l.setButtonText("Add task").setTooltip("Select task").onClick(()=>{this.openTaskSelectorForTitle()})}),this.attachmentsList=t.createDiv({cls:"timeblock-attachments-list"}),this.initializePrefilledAttachments(),this.renderAttachmentsList();let i=t.createDiv({cls:"timeblock-modal-buttons"});i.createEl("button",{text:this.translate("common.cancel")}).addEventListener("click",()=>this.close()),i.createEl("button",{text:this.translate("modals.timeblockCreation.createButton"),cls:"mod-cta timeblock-create-button"}).addEventListener("click",()=>{this.handleSubmit()}),this.validateForm()}validateForm(){var o,l,c;let t=this.contentEl.querySelector(".timeblock-create-button");if(!t)return;let r=(o=this.titleInput)==null?void 0:o.value.trim(),a=(l=this.startTimeInput)==null?void 0:l.value,i=(c=this.endTimeInput)==null?void 0:c.value,s=!!(r&&a&&i);if(s&&a&&i){let[d,u]=a.split(":").map(Number),[p,m]=i.split(":").map(Number),f=d*60+u,h=p*60+m;i==="00:00"&&f>0&&(h=1440),h<=f&&(s=!1)}t.disabled=!s,t.style.opacity=s?"1":"0.5"}initializePrefilledAttachments(){let t=this.options.prefilledAttachmentPaths||[];if(t.length===0)return;let r=new Set(t.filter(a=>typeof a=="string"&&a.trim().length>0));for(let a of r){let i=this.app.vault.getAbstractFileByPath(a);i&&this.selectedAttachments.push(i)}}async handleSubmit(){var t,r;try{let a=this.titleInput.value.trim(),i=this.startTimeInput.value,s=this.endTimeInput.value,o=this.descriptionInput.value.trim(),l=hr(this.colorInput.value,this.plugin.settings.calendarViewSettings.defaultTimeblockColor);if(!a||!i||!s){new or.Notice(this.translate("notices.timeblockRequiredFieldsMissing"));return}let c=this.selectedAttachments.map(p=>`[[${p.path}]]`),d={id:Jz(),title:a,startTime:i,endTime:s};o&&(d.description=o),l&&(d.color=l),c.length>0&&(d.attachments=c);let u=await this.saveTimeblockToDailyNote(d);this.plugin.emitter.trigger("data-changed"),(r=(t=this.options).onCreated)==null||r.call(t,{timeblock:d,date:this.options.date,dailyNote:u}),new or.Notice(`Timeblock "${a}" created successfully`),this.close()}catch(a){S2.error("Error creating timeblock:",{category:"internal",operation:"creating-timeblock",error:a}),new or.Notice(QUe(a))}}async saveTimeblockToDailyNote(t){if(!(0,gp.appHasDailyNotesPluginLoaded)())throw new Error(`Daily Notes core plugin is not enabled. ${vM}`);let r=JUe(this.options.date),a=ZUe(),i=(0,gp.getDailyNote)(r,a);if(!i){try{i=await(0,gp.createDailyNote)(r)}catch(u){let p=C2(u),m=p?`: ${p}`:"";throw new Error(`Failed to create daily note${m}. ${vM}`)}if(!i)throw new Error(`Failed to create daily note. ${vM}`)}let s=await this.app.vault.read(i),o={},l=s;if(s.startsWith("---")){let u=s.indexOf("---",3);if(u!==-1){let p=s.substring(3,u);l=s.substring(u+3);try{o=(0,or.parseYaml)(p)||{}}catch(m){S2.error("Error parsing existing frontmatter:",{category:"validation",operation:"parsing-existing-frontmatter",error:m}),o={}}}}o.timeblocks||(o.timeblocks=[]),o.timeblocks.push(t);let d=`--- +${(0,or.stringifyYaml)(o)}---${l}`;return await Gs(this.app,i,d),i}addAttachment(t){if(this.selectedAttachments.some(r=>r.path===t.path)){new or.Notice(this.translate("notices.timeblockAttachmentExists",{fileName:t.name}));return}if(this.titleInput&&!this.titleInput.value.trim()){let r=t instanceof or.TFile?t.basename:t.name;this.titleInput.value=r,this.validateForm()}this.selectedAttachments.push(t),this.renderAttachmentsList(),new or.Notice(this.translate("notices.timeblockAttachmentAdded",{fileName:t.name}))}async openTaskSelectorForTitle(){var t,r,a;try{let s=((a=await((r=(t=this.plugin.cacheManager).getAllTasks)==null?void 0:r.call(t)))!=null?a:[]).filter(o=>!o.archived);if(s.length===0){new or.Notice("No tasks available to select");return}fn(this.plugin,s,o=>{if(!o)return;this.titleInput.value=o.title||"",this.validateForm();let l=this.app.vault.getAbstractFileByPath(o.path);l&&this.addAttachment(l)},{title:"Select task"})}catch(i){S2.error("Failed to open task selector for timeblock creation:",{category:"persistence",operation:"open-task-selector-timeblock-creation",error:i}),new or.Notice("Failed to open task selector")}}removeAttachment(t){this.selectedAttachments=this.selectedAttachments.filter(r=>r.path!==t.path),this.renderAttachmentsList(),new or.Notice(this.translate("notices.timeblockAttachmentRemoved",{fileName:t.name}))}renderAttachmentsList(){if(this.attachmentsList.empty(),this.selectedAttachments.length===0){let t=this.attachmentsList.createDiv({cls:"timeblock-attachments-empty"});t.textContent="No attachments added yet";return}this.selectedAttachments.forEach(t=>{let r=this.attachmentsList.createDiv({cls:"timeblock-attachment-item"}),a=r.createDiv({cls:"timeblock-attachment-info"}),i=a.createSpan({cls:"timeblock-attachment-name"});if(i.textContent=t.name,t.path!==t.name){let o=a.createDiv({cls:"timeblock-attachment-path"});o.textContent=t.path}let s=r.createEl("button",{cls:"timeblock-attachment-remove",text:"×"});(0,or.setTooltip)(s,"Remove attachment",{placement:"top"}),s.addEventListener("click",()=>{this.removeAttachment(t)})})}onClose(){this.keyboardHandler&&(this.containerEl.removeEventListener("keydown",this.keyboardHandler),this.keyboardHandler=null);let{contentEl:t}=this;t.empty()}}});var Cce,yp,E2=y(()=>{Cr();q();Cce=M({tag:"Services/CalendarExportService"}),yp=class{static generateCalendarURL(e){let{type:t,task:r,useScheduledAsDue:a=!0}=e;switch(t){case"google":return this.generateGoogleCalendarURL(r,a);case"outlook":return this.generateOutlookCalendarURL(r,a);case"yahoo":return this.generateYahooCalendarURL(r,a);case"ics":return this.generateICSDownloadURL(r);default:throw new Error("Unsupported calendar type")}}static generateGoogleCalendarURL(e,t){let r="https://calendar.google.com/calendar/render",a=new URLSearchParams;a.append("action","TEMPLATE"),a.append("text",e.title);let i=this.formatGoogleDates(e,t);i&&a.append("dates",i);let s=this.buildDescription(e);return s&&a.append("details",s),e.contexts&&e.contexts.length>0&&a.append("location",e.contexts.join(", ")),`${r}?${a.toString()}`}static generateOutlookCalendarURL(e,t){let r="https://outlook.live.com/calendar/0/deeplink/compose",a=new URLSearchParams;a.append("subject",e.title);let{startISO:i,endISO:s}=this.getTaskDateRange(e,t);i&&a.append("startdt",i),s&&a.append("enddt",s);let o=this.buildDescription(e);return o&&a.append("body",o),e.contexts&&e.contexts.length>0&&a.append("location",e.contexts.join(", ")),a.append("path","/calendar/action/compose"),a.append("rru","addevent"),`${r}?${a.toString()}`}static generateYahooCalendarURL(e,t){let r="https://calendar.yahoo.com/",a=new URLSearchParams;a.append("v","60"),a.append("title",e.title);let{startYahoo:i,endYahoo:s}=this.getYahooDateFormat(e,t);i&&a.append("st",i),s&&a.append("et",s);let o=this.buildDescription(e);return o&&a.append("desc",o),e.contexts&&e.contexts.length>0&&a.append("in_loc",e.contexts.join(", ")),`${r}?${a.toString()}`}static generateICSDownloadURL(e){let t=this.generateICSContent(e);return`data:text/calendar;charset=utf8,${encodeURIComponent(t)}`}static generateICSContent(e,t){let r=`${e.path.replace(/[^a-zA-Z0-9]/g,"-")}-${Date.now()}@tasknotes`,a=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}/,""),i=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//TaskNotes//Task Export//EN","CALSCALE:GREGORIAN","METHOD:PUBLISH","BEGIN:VEVENT",`UID:${r}`,`DTSTAMP:${a}`];i.push(`SUMMARY:${this.escapeICSText(e.title)}`);let{startLine:s,endLine:o}=this.getICSDateProperties(e,!0,t);s&&i.push(s),o&&i.push(o);let l=this.buildDescription(e,t);if(l&&i.push(`DESCRIPTION:${this.escapeICSText(l)}`),e.contexts&&e.contexts.length>0&&i.push(`LOCATION:${this.escapeICSText(e.contexts.join(", "))}`),e.tags&&e.tags.length>0&&i.push(`CATEGORIES:${e.tags.map(c=>this.escapeICSText(c)).join(",")}`),e.priority){let d={highest:"1",high:"3",medium:"5",low:"7",lowest:"9"}[e.priority]||"5";i.push(`PRIORITY:${d}`)}return e.status&&i.push(`STATUS:${this.getVEventStatus(e.status)}`),i.push("END:VEVENT"),i.push("END:VCALENDAR"),i.join(`\r +`)}static buildDescription(e,t){let r=[],a=[];e.priority&&a.push(`Priority: ${e.priority}`),e.status&&a.push(`Status: ${e.status}`),e.projects&&e.projects.length>0&&a.push(`Projects: ${e.projects.join(", ")}`),e.tags&&e.tags.length>0&&a.push(`Tags: ${e.tags.join(", ")}`),e.contexts&&e.contexts.length>0&&a.push(`Contexts: ${e.contexts.join(", ")}`),e.timeEstimate&&a.push(`Estimated time: ${e.timeEstimate} minutes`),a.length>0&&r.push(...a),r.length>0&&r.push(""),r.push(`Exported from TaskNotes: ${e.path}`);let i=this.buildObsidianOpenUri(e,t);return i&&r.push(`Open in Obsidian: ${i}`),r.join(` +`)}static buildObsidianOpenUri(e,t){return!(t!=null&&t.includeObsidianLink)||!t.vaultName?null:`obsidian://open?vault=${encodeURIComponent(t.vaultName)}&file=${encodeURIComponent(e.path)}`}static formatGoogleDates(e,t){let{startICS:r,endICS:a}=this.getICSDateFormat(e,t);if(!r)return null;if(a)return`${r}/${a}`;let i=this.parseICSDate(r),s=new Date(i.getTime()+3600*1e3),o=this.formatDateToICS(s);return`${r}/${o}`}static getTaskDateRange(e,t,r){let a=null,i=null;if(e.scheduled)try{a=this.parseTaskDate(e.scheduled).toISOString()}catch(s){Cce.warn("Invalid scheduled date:",{category:"provider",operation:"invalid-scheduled-date",details:{value:e.scheduled}})}if(r!=null&&r.useDurationForExport&&a&&e.timeEstimate&&e.timeEstimate>0){let s=new Date(a);i=new Date(s.getTime()+e.timeEstimate*60*1e3).toISOString()}else if(e.due)try{i=this.parseTaskDate(e.due).toISOString()}catch(s){Cce.warn("Invalid due date:",{category:"provider",operation:"invalid-due-date",details:{value:e.due}})}else if(t&&a){let s=new Date(a);i=new Date(s.getTime()+3600*1e3).toISOString()}return{startISO:a,endISO:i}}static getYahooDateFormat(e,t){let{startISO:r,endISO:a}=this.getTaskDateRange(e,t),i=s=>{let o=new Date(s);return D(o,"yyyyMMdd'T'HHmmss")};return{startYahoo:r?i(r):null,endYahoo:a?i(a):null}}static getICSDateFormat(e,t=!0,r){let{startISO:a,endISO:i}=this.getTaskDateRange(e,t,r),s=o=>{let l=new Date(o);return this.formatDateToICS(l)};return{startICS:a?s(a):null,endICS:i?s(i):null}}static getICSDateProperties(e,t=!0,r){if(e.scheduled&&!this.hasTimeComponent(e.scheduled)){let s=e.scheduled,o=this.getAllDayEndDate(e,t,r)||s;return{startLine:`DTSTART;VALUE=DATE:${this.formatDateOnlyToICS(s)}`,endLine:`DTEND;VALUE=DATE:${this.formatDateOnlyToICS(o)}`}}let{startICS:a,endICS:i}=this.getICSDateFormat(e,t,r);return{startLine:a?`DTSTART:${a}`:null,endLine:i?`DTEND:${i}`:null}}static formatDateToICS(e){return e.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}/,"")}static parseICSDate(e){let t=e.slice(0,4),r=e.slice(4,6),a=e.slice(6,8),i=e.slice(9,11),s=e.slice(11,13),o=e.slice(13,15);return new Date(`${t}-${r}-${a}T${i}:${s}:${o}Z`)}static parseTaskDate(e){let t=e.trim().replace(" ","T");return this.hasTimeComponent(t)?Na(t):Na(`${t}T00:00:00`)}static hasTimeComponent(e){return/\d{4}-\d{2}-\d{2}[T\s]\d{2}:\d{2}/.test(e)}static formatDateOnlyToICS(e){return e.split(/[T\s]/)[0].replace(/-/g,"")}static getAllDayEndDate(e,t,r){if(!e.scheduled)return null;let a=e.scheduled;if(r!=null&&r.useDurationForExport&&e.timeEstimate&&e.timeEstimate>0){let i=Math.max(1,Math.ceil(e.timeEstimate/1440));return this.addDaysToDateString(e.scheduled,i)}if(e.due)a=e.due;else if(!t)return null;return this.addDaysToDateString(a,1)}static addDaysToDateString(e,t){let r=Na(`${e.split(/[T\s]/)[0]}T00:00:00`);return r.setDate(r.getDate()+t),D(r,"yyyy-MM-dd")}static escapeICSText(e){return e.replace(/\\/g,"\\\\").replace(/;/g,"\\;").replace(/,/g,"\\,").replace(/\n/g,"\\n").replace(/\r/g,"")}static foldICSLines(e){let t=e.split(`\r +`),r=[];return t.forEach(a=>{if(a.length<=75)r.push(a);else{let i=a;for(;i.length>75;)r.push(i.substring(0,75)),i=" "+i.substring(75);i.length>0&&r.push(i)}}),r.join(`\r +`)}static generateMultipleTasksICSContent(e,t){let r=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}/,""),a=this.filterTasksForExport(e,t),i=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//TaskNotes//EN","CALSCALE:GREGORIAN"];return a.forEach((s,o)=>{let l=`${s.path.replace(/[^a-zA-Z0-9]/g,"-")}-${o}-${Date.now()}@tasknotes`;i.push("BEGIN:VEVENT"),i.push(`UID:${l}`),i.push(`DTSTAMP:${r}`),i.push(`SUMMARY:${this.escapeICSText(s.title)}`);let{startLine:c,endLine:d}=this.getICSDateProperties(s,!0,t);if(c){if(!d){let p=c.split(":",2)[1];if(c.includes("VALUE=DATE")){let m=Na(`${p.slice(0,4)}-${p.slice(4,6)}-${p.slice(6,8)}T00:00:00`);m.setDate(m.getDate()+1),d=`DTEND;VALUE=DATE:${D(m,"yyyyMMdd")}`}else{let m=this.parseICSDate(p),f=new Date(m.getTime()+3600*1e3);d=`DTEND:${this.formatDateToICS(f)}`}}}else{let p;if(s.dateCreated?p=new Date(s.dateCreated):p=new Date,c=`DTSTART:${this.formatDateToICS(p)}`,!d){let f=new Date(p.getTime()+36e5);d=`DTEND:${this.formatDateToICS(f)}`}}i.push(c),i.push(d);let u=this.buildDescription(s,t);if(u&&i.push(`DESCRIPTION:${this.escapeICSText(u)}`),s.contexts&&s.contexts.length>0&&i.push(`LOCATION:${this.escapeICSText(s.contexts.join(", "))}`),s.tags&&s.tags.length>0&&i.push(`CATEGORIES:${s.tags.map(p=>this.escapeICSText(p)).join(",")}`),s.priority){let m={highest:"1",high:"3",medium:"5",low:"7",lowest:"9"}[s.priority]||"5";i.push(`PRIORITY:${m}`)}s.status&&i.push(`STATUS:${this.getVEventStatus(s.status)}`),i.push("END:VEVENT")}),i.push("END:VCALENDAR"),this.foldICSLines(i.join(`\r +`))}static filterTasksForExport(e,t){var a;if(!(t!=null&&t.excludeArchived)&&!(t!=null&&t.excludeCompleted)&&!(t!=null&&t.requireDueDate)&&!(t!=null&&t.requireScheduledDate))return e;let r=new Set((a=t.completedStatuses)!=null&&a.length?t.completedStatuses:["done"]);return e.filter(i=>!(t.excludeArchived&&i.archived||t.excludeCompleted&&r.has(i.status)||t.requireDueDate&&!i.due||t.requireScheduledDate&&!i.scheduled))}static getVEventStatus(e){let t=e.trim().toLowerCase();return t==="cancelled"||t==="canceled"?"CANCELLED":t==="tentative"?"TENTATIVE":"CONFIRMED"}static createMultipleTasksICSDownload(e,t){if(!e||e.length===0)return null;let r=this.filterTasksForExport(e,t);if(r.length===0)return null;let a=new Date().toISOString().split("T")[0];return{content:this.generateMultipleTasksICSContent(r,t),filename:`tasknotes-all-tasks-${a}.ics`,taskCount:r.length}}static createTaskICSDownload(e,t){return{content:this.generateICSContent(e,t),filename:`${e.title.replace(/[^a-zA-Z0-9]/g,"-")}.ics`,taskCount:1}}}});function Ze(n,e){return e===void 0?new D2.Notice(n):new D2.Notice(n,e)}var D2,Wd=y(()=>{D2=require("obsidian")});var Ece={};Xe(Ece,{downloadAllTasksICSFile:()=>XUe,downloadTaskICSFile:()=>A2,openCalendarURL:()=>xC});function uv(n,e,t,r){return n?n(e,r):t}function xce(n){let e=new Blob([n.content],{type:"text/calendar"}),t=URL.createObjectURL(e);try{let r=activeWindow.createEl("a");r.href=t,r.download=n.filename,r.click()}finally{URL.revokeObjectURL(t)}}function xC(n,e){try{let t=yp.generateCalendarURL(n);window.open(t,"_blank")}catch(t){P2.error("Failed to generate calendar URL:",{category:"provider",operation:"generate-calendar-url",error:t}),Ze(uv(e,"services.calendarExport.notices.generateLinkFailed","Failed to generate calendar link"))}}function XUe(n,e,t){try{let r=yp.createMultipleTasksICSDownload(n,t);if(!r){Ze(uv(e,"services.calendarExport.notices.noTasksToExport","No tasks found to export"));return}xce(r);let a=r.taskCount===1?"":"s";Ze(uv(e,"services.calendarExport.notices.downloadSuccess",`Downloaded ${r.filename} with ${r.taskCount} task${a}`,{filename:r.filename,count:r.taskCount,plural:a}))}catch(r){P2.error("Failed to download all tasks ICS file:",{category:"provider",operation:"download-all-tasks-ics-file",error:r}),Ze(uv(e,"services.calendarExport.notices.downloadFailed","Failed to download calendar file"))}}function A2(n,e,t){try{let r=yp.createTaskICSDownload(n,t);xce(r),Ze(uv(e,"services.calendarExport.notices.singleDownloadSuccess",`Downloaded ${r.filename}`,{filename:r.filename}))}catch(r){P2.error("Failed to download ICS file:",{category:"provider",operation:"download-ics-file",error:r}),Ze(uv(e,"services.calendarExport.notices.downloadFailed","Failed to download calendar file"))}}var P2,M2=y(()=>{E2();q();Wd();P2=M({tag:"UI/CalendarExportActions"})});async function Pce(n){let{plugin:e,path:t,openInNewLeaf:r=!1}=n,a=e.app.vault.getAbstractFileByPath(t);if(a instanceof Gf.TFile){await e.app.workspace.getLeaf(r).openFile(a);return}await e.app.workspace.openLinkText(t,"",r)}async function pv(n){let{plugin:e,parentTask:t,targetDate:r,openInNewLeaf:a=!1,onUpdate:i}=n,s=ae(r);try{let o=await e.taskService.findMaterializedOccurrence(t,r),l=await e.taskService.materializeOccurrence(t,r);return await Pce({plugin:e,path:l.path,openInNewLeaf:a}),i==null||i(),new Gf.Notice(o?`Opened occurrence note for ${s}`:`Created occurrence note for ${s}`),l}catch(o){let l=o instanceof Error?o.message:String(o);return Dce.error("Error opening or creating occurrence note:",{category:"persistence",operation:"open-or-create-occurrence-note",details:{taskPath:t.path,targetDate:s},error:l}),new Gf.Notice(`Failed to open occurrence note: ${l}`),null}}async function kM(n){let{plugin:e,occurrenceTask:t,openInNewLeaf:r=!1}=n;try{let a=await e.taskService.getMaterializedOccurrenceParent(t);return a?(await Pce({plugin:e,path:a.path,openInNewLeaf:r}),a):(new Gf.Notice("Recurring parent not found"),null)}catch(a){let i=a instanceof Error?a.message:String(a);return Dce.error("Error opening materialized occurrence parent:",{category:"persistence",operation:"open-materialized-occurrence-parent",details:{taskPath:t.path,occurrenceDate:t.occurrence_date},error:i}),new Gf.Notice(`Failed to open recurring parent: ${i}`),null}}var Gf,Dce,TM=y(()=>{Gf=require("obsidian");xe();q();Dce=M({tag:"UI/OccurrenceNoteActions"})});function bM(n){return n.trim()}function EC(n){let e=new Set,t=[];for(let r of n!=null?n:[]){if(typeof r!="string")continue;let a=bM(r);!a||e.has(a)||(e.add(a),t.push(a))}return t}function Ace(n,e){let t=bM(e),r=EC(n);return t?r.includes(t)?r:[...r,t]:r.length>0?r:void 0}function eHe(n,e){let t=bM(e),r=EC(n).filter(a=>a!==t);return r.length>0?r:void 0}function tHe(n,e){let t=bM(e),r=EC(n);return t?r.includes(t)?eHe(r,t):Ace(r,t):r.length>0?r:void 0}function _n(n){return n.setSubmenu()}function I2(n){var t,r;let e=n;return(r=(t=e.dom)!=null?t:e.domEl)!=null?r:null}function mv(n,e=""){let r=(typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"?String(n):"").trim();return r.length>0?r:e}var De,tr,ll,DC=y(()=>{De=require("obsidian");xe();lce();Jy();vC();ya();p2();Fi();Uy();$y();Qy();v$();aC();co();py();Zs();Cn();Md();Id();Sce();x2();b$();M2();TM();q();tr=M({tag:"Components/TaskContextMenu"});ll=class n{constructor(e,t=new ra){this.targetDoc=activeDocument;this.menu=t,this.options=e,this.buildMenu()}static addToMenu(e,t){new n(t,e)}t(e,t){return this.options.plugin.i18n.translate(e,t)}buildMenu(){let{task:e,plugin:t}=this.options,r=this.addPromotedOccurrenceControls(e,t);this.menu.addItem(a=>{a.setTitle(this.t("contextMenus.task.status")),a.setIcon("circle");let i=_n(a);this.addStatusOptions(i,e,t)}),this.menu.addSeparator(),this.menu.addItem(a=>{a.setTitle(this.t("contextMenus.task.priority")),a.setIcon("star");let i=_n(a);this.addPriorityOptions(i,e,t)}),this.menu.addItem(a=>{a.setTitle(this.t("contextMenus.task.tags")),a.setIcon("tags");let i=_n(a);this.addTagOptions(i,e,t)}),this.menu.addSeparator(),this.menu.addItem(a=>{a.setTitle(this.t("contextMenus.task.dueDate")),a.setIcon("calendar");let i=_n(a);this.addDateOptions(i,e.due,async s=>{var o,l;try{await t.updateTaskProperty(e,"due",s||void 0),(l=(o=this.options).onUpdate)==null||l.call(o)}catch(c){let d=c instanceof Error?c.message:String(c);tr.error("Error updating task due date:",{category:"validation",operation:"updating-task-due-date",details:{taskPath:e.path},error:d}),new De.Notice(this.t("contextMenus.task.notices.updateDueDateFailure",{message:d}))}},()=>{t.openDueDateModal(e)})}),this.menu.addItem(a=>{a.setTitle(this.t("contextMenus.task.scheduledDate")),a.setIcon("calendar-clock");let i=_n(a);this.addDateOptions(i,e.scheduled,async s=>{var o,l;try{await t.updateTaskProperty(e,"scheduled",s||void 0),(l=(o=this.options).onUpdate)==null||l.call(o)}catch(c){let d=c instanceof Error?c.message:String(c);tr.error("Error updating task scheduled date:",{category:"validation",operation:"updating-task-scheduled-date",details:{taskPath:e.path},error:d}),new De.Notice(this.t("contextMenus.task.notices.updateScheduledFailure",{message:d}))}},()=>{t.openScheduledDateModal(e)})}),this.addCustomDateFieldMenuItems(e,t),this.addCompleteOrSkipSection(e,t),e.recurrence&&!this.options.promoteOccurrenceControls&&this.addOccurrenceNoteMenuItem(e,t),!r&&e.recurrence_parent&&e.occurrence_date&&this.addMaterializedOccurrenceMenuItems(e,t),this.menu.addItem(a=>{a.setTitle(this.t("contextMenus.task.reminders")),a.setIcon("bell");let i=_n(a);this.addQuickRemindersSection(i,e,t,"due",this.t("contextMenus.task.remindBeforeDue")),this.addQuickRemindersSection(i,e,t,"scheduled",this.t("contextMenus.task.remindBeforeScheduled")),i.addSeparator(),i.addItem(s=>{s.setTitle(this.t("contextMenus.task.manageReminders")),s.setIcon("settings"),s.onClick(()=>{new sl(t.app,t,e,l=>{(async()=>{var c,d;try{await t.updateTaskProperty(e,"reminders",l.length>0?l:void 0),(d=(c=this.options).onUpdate)==null||d.call(c)}catch(u){tr.error("Error updating reminders:",{category:"persistence",operation:"updating-reminders",error:u}),new De.Notice(this.t("contextMenus.task.notices.updateRemindersFailure"))}})()}).open()})}),e.reminders&&e.reminders.length>0&&i.addItem(s=>{s.setTitle(this.t("contextMenus.task.clearReminders")),s.setIcon("trash"),s.onClick(async()=>{var o,l;try{await t.updateTaskProperty(e,"reminders",void 0),(l=(o=this.options).onUpdate)==null||l.call(o)}catch(c){tr.error("Error clearing reminders:",{category:"persistence",operation:"clearing-reminders",error:c}),new De.Notice(this.t("contextMenus.task.notices.clearRemindersFailure"))}})})}),this.menu.addSeparator(),this.menu.addItem(a=>{a.setTitle(this.t("contextMenus.task.dependencies.title")),a.setIcon("git-branch");let i=_n(a);this.addDependencyMenuItems(i,e,t)}),this.menu.addItem(a=>{a.setTitle(this.t("contextMenus.task.organization.title")),a.setIcon("folder-tree");let i=_n(a);this.addOrganizationMenuItems(i,e,t)}),this.menu.addSeparator(),this.menu.addItem(a=>{let i=t.getActiveTimeSession(e);a.setTitle(i?this.t("contextMenus.task.stopTimeTracking"):this.t("contextMenus.task.startTimeTracking")),a.setIcon(i?"pause":"play"),a.onClick(async()=>{var o,l;t.getActiveTimeSession(e)?await t.stopTimeTracking(e):await t.startTimeTracking(e),(l=(o=this.options).onUpdate)==null||l.call(o)})}),this.menu.addItem(a=>{a.setTitle(this.t("contextMenus.task.editTimeEntries")),a.setIcon("clock"),a.onClick(()=>{t.openTimeEntryEditor(e)})}),t.settings.calendarViewSettings.enableTimeblocking&&this.menu.addItem(a=>{a.setTitle("Create timeblock"),a.setIcon("calendar-plus"),a.onClick(()=>{let i=wce(e,this.options.targetDate);new dv(t.app,t,{date:i.date,startTime:i.startTime,endTime:i.endTime,prefilledTitle:e.title,prefilledAttachmentPaths:[e.path]}).open()})}),this.menu.addItem(a=>{a.setTitle(e.archived?this.t("contextMenus.task.unarchive"):this.t("contextMenus.task.archive")),a.setIcon(e.archived?"archive-restore":"archive"),a.onClick(async()=>{var i,s;try{await t.toggleTaskArchive(e),(s=(i=this.options).onUpdate)==null||s.call(i)}catch(o){let l=o instanceof Error?o.message:String(o);tr.error("Error toggling task archive:",{category:"persistence",operation:"toggling-task-archive",details:{taskPath:e.path},error:l}),new De.Notice(this.t("contextMenus.task.notices.archiveFailure",{message:l}))}})}),this.menu.addSeparator(),this.menu.addItem(a=>{a.setTitle(this.t("modals.taskEdit.title")),a.setIcon("pencil"),a.onClick(()=>{t.openTaskEditModal(e,()=>{var i,s;(s=(i=this.options).onUpdate)==null||s.call(i)})})}),this.menu.addItem(a=>{a.setTitle(this.t("contextMenus.task.openNote")),a.setIcon("file-text"),a.onClick(()=>{let i=t.app.vault.getAbstractFileByPath(e.path);i instanceof De.TFile&&t.app.workspace.getLeaf(!1).openFile(i)})}),this.menu.addItem(a=>{a.setTitle(this.t("contextMenus.task.openNoteInNewTab")),a.setIcon("external-link"),a.onClick(()=>{t.app.vault.getAbstractFileByPath(e.path)instanceof De.TFile&&t.app.workspace.openLinkText(e.path,"",!0)})}),this.menu.addItem(a=>{a.setTitle(this.t("contextMenus.task.copyTitle")),a.setIcon("copy"),a.onClick(async()=>{try{await navigator.clipboard.writeText(e.title),new De.Notice(this.t("contextMenus.task.notices.copyTitleSuccess"))}catch(i){new De.Notice(this.t("contextMenus.task.notices.copyFailure"))}})}),this.menu.addItem(a=>{a.setTitle(this.t("contextMenus.task.noteActions")),a.setIcon("file-text");let i=_n(a),s=t.app.vault.getAbstractFileByPath(e.path);if(s instanceof De.TFile){try{t.app.workspace.trigger("file-menu",i,s,"tasknotes-context-menu")}catch(o){tr.debug("Native file menu not available, using fallback",{category:"stale-data",operation:"native-file-menu-not-using-fallback"})}i.addItem(o=>{o.setTitle(this.t("contextMenus.task.rename")),o.setIcon("pencil"),o.onClick(async()=>{try{let l=s.basename,c=await Vy(t.app,{title:this.t("contextMenus.task.renameTitle"),placeholder:this.t("contextMenus.task.renamePlaceholder"),initialValue:l});if(c&&c.trim()!==""&&c!==l){let d=s.extension,u=c.endsWith(`.${d}`)?c:`${c}.${d}`,p=s.parent?`${s.parent.path}/${u}`:u;await Kz(t.app,s,p),new De.Notice(this.t("contextMenus.task.notices.renameSuccess",{name:u})),this.options.onUpdate&&this.options.onUpdate()}}catch(l){tr.error("Error renaming file:",{category:"persistence",operation:"renaming-file",error:l}),new De.Notice(this.t("contextMenus.task.notices.renameFailure"))}})}),i.addItem(o=>{o.setTitle(this.t("contextMenus.task.delete")),o.setIcon("trash"),o.onClick(async()=>{if(await ur(t.app,{title:this.t("contextMenus.task.deleteTitle"),message:this.t("contextMenus.task.deleteMessage",{name:s.name}),confirmText:this.t("contextMenus.task.deleteConfirm"),cancelText:this.t("common.cancel"),isDestructive:!0}))try{await t.taskService.deleteTask(e),this.options.onUpdate&&this.options.onUpdate()}catch(c){let d=c instanceof Error?c.message:String(c);tr.error("Error deleting task:",{category:"persistence",operation:"deleting-task",error:c}),new De.Notice(`Failed to delete task: ${d}`)}})}),i.addSeparator(),i.addItem(o=>{o.setTitle(this.t("contextMenus.task.copyPath")),o.setIcon("copy"),o.onClick(()=>{navigator.clipboard.writeText(s.path).then(()=>{new De.Notice(this.t("contextMenus.task.notices.copyPathSuccess"))}).catch(()=>{new De.Notice(this.t("contextMenus.task.notices.copyFailure"))})})}),i.addItem(o=>{o.setTitle(this.t("contextMenus.task.copyUrl")),o.setIcon("link"),o.onClick(()=>{let l=`obsidian://open?vault=${encodeURIComponent(t.app.vault.getName())}&file=${encodeURIComponent(s.path)}`;navigator.clipboard.writeText(l).then(()=>{new De.Notice(this.t("contextMenus.task.notices.copyUrlSuccess"))}).catch(()=>{new De.Notice(this.t("contextMenus.task.notices.copyFailure"))})})}),i.addSeparator(),i.addItem(o=>{o.setTitle(this.t("contextMenus.task.showInExplorer")),o.setIcon("folder-open"),o.onClick(()=>{t.app.workspace.getLeaf().setViewState({type:"file-explorer",state:{}}).then(()=>{let l=t.app.workspace.getLeavesOfType("file-explorer")[0];l!=null&&l.view&&"revealInFolder"in l.view&&l.view.revealInFolder(s)}).catch(l=>{tr.warn("Failed to reveal task in file explorer:",{category:"persistence",operation:"reveal-task-file-explorer",error:l})})})})}}),this.menu.addSeparator(),this.menu.addItem(a=>{a.setTitle(this.t("contextMenus.task.addToCalendar")),a.setIcon("calendar-plus");let i=_n(a);i.addItem(s=>{s.setTitle(this.t("contextMenus.task.calendar.google")),s.setIcon("external-link"),s.onClick(()=>{xC({type:"google",task:e,useScheduledAsDue:!0},this.t.bind(this))})}),i.addItem(s=>{s.setTitle(this.t("contextMenus.task.calendar.outlook")),s.setIcon("external-link"),s.onClick(()=>{xC({type:"outlook",task:e,useScheduledAsDue:!0},this.t.bind(this))})}),i.addItem(s=>{s.setTitle(this.t("contextMenus.task.calendar.yahoo")),s.setIcon("external-link"),s.onClick(()=>{xC({type:"yahoo",task:e,useScheduledAsDue:!0},this.t.bind(this))})}),i.addSeparator(),i.addItem(s=>{s.setTitle(this.t("contextMenus.task.calendar.downloadIcs")),s.setIcon("download"),s.onClick(()=>{A2(e,this.t.bind(this),{includeObsidianLink:!0,vaultName:t.app.vault.getName()})})}),i.addSeparator(),i.addItem(s=>{s.setTitle(this.t("contextMenus.task.calendar.syncToGoogle")),s.setIcon("refresh-cw"),s.onClick(async()=>{var o,l,c;if(!((o=t.taskCalendarSyncService)!=null&&o.isEnabled())){new De.Notice(this.t("contextMenus.task.calendar.syncToGoogleNotConfigured"));return}try{await t.taskCalendarSyncService.syncTaskToCalendar(e),new De.Notice(this.t("contextMenus.task.calendar.syncToGoogleSuccess")),(c=(l=this.options).onUpdate)==null||c.call(l)}catch(d){tr.error("Failed to sync task to Google Calendar:",{category:"provider",operation:"sync-task-google-calendar",error:d}),new De.Notice(this.t("contextMenus.task.calendar.syncToGoogleFailed"))}})})}),this.menu.addSeparator(),this.menu.addItem(a=>{a.setTitle(this.t("contextMenus.task.recurrence")),a.setIcon("refresh-ccw");let i=_n(a),s=typeof e.recurrence=="string"?e.recurrence:void 0;this.addRecurrenceOptions(i,s,async o=>{var l,c;try{await t.updateTaskProperty(e,"recurrence",o||void 0),(c=(l=this.options).onUpdate)==null||c.call(l)}catch(d){let u=d instanceof Error?d.message:String(d);tr.error("Error updating task recurrence:",{category:"persistence",operation:"updating-task-recurrence",details:{taskPath:e.path},error:u}),new De.Notice(this.t("contextMenus.task.notices.updateRecurrenceFailure",{message:u}))}},t),s&&this.addOccurrencePolicyOptions(i,e,t)}),this.menu.addSeparator(),this.menu.addItem(a=>{a.setTitle(this.t("contextMenus.task.createSubtask")),a.setIcon("plus"),a.onClick(()=>{let i=t.app.vault.getAbstractFileByPath(e.path);i instanceof De.TFile&&t.openTaskCreationModal({...cM(t,e,i)})})}),this.addMobileDismissOption(),window.setTimeout(()=>{this.updateMainMenuIconColors(e,t)},10)}addMobileDismissOption(){De.Platform.isMobile&&(this.menu.addSeparator(),this.menu.addItem(e=>{e.setTitle(this.t("common.close")),e.setIcon("x"),e.onClick(()=>{this.menu.hide()})}))}addCompleteOrSkipSection(e,t){let r=!!e.recurrence;if(t.settings.completionMenuAsSubmenu===!1){this.menu.addSeparator(),this.addCompletionMenuItems(e,t,this.menu),r&&this.addSkipMenuItem(e,t,this.menu),this.menu.addSeparator();return}this.menu.addItem(a=>{a.setTitle(this.t(r?"contextMenus.task.completion.submenu":"contextMenus.task.completion.submenuCompleteOnly")),a.setIcon("check-check");let i=_n(a);this.addCompletionMenuItems(e,t,i),r&&this.addSkipMenuItem(e,t,i)})}addCompletionMenuItems(e,t,r){if(!!!e.recurrence&&t.statusManager.isCompletedStatus(e.status)){r.addItem(i=>{i.setTitle(this.t("contextMenus.task.completion.markIncomplete")),i.setIcon("x"),i.onClick(async()=>{await this.uncompleteNonRecurringTask(e,t)})});return}this.addConcreteCompletionAction(e,t,"today","contextMenus.task.completion.completeToday",r),this.addConcreteCompletionAction(e,t,"asScheduled","contextMenus.task.completion.completeAsScheduled",r),this.addConcreteCompletionAction(e,t,"onDue","contextMenus.task.completion.completeOnDue",r),this.addPickCompletionDateAction(e,t,r)}addConcreteCompletionAction(e,t,r,a,i){let s=!!e.recurrence,o={occurrenceDate:this.options.occurrenceDate},l=c2(e,r,o);i.addItem(c=>{var p,m;if(!l.available){c.setTitle(this.t(a)),c.setIcon("check"),c.setDisabled(!0);let f=I2(c);f&&(0,De.setTooltip)(f,this.t(l.reasonKey));return}let d=l.date,u=s&&((m=(p=e.complete_instances)==null?void 0:p.includes(ae(d)))!=null?m:!1);c.setTitle(u?this.t("contextMenus.task.completion.markIncomplete"):this.t(a)),c.setIcon(u?"x":"check"),c.onClick(async()=>{await this.dispatchCompletion(e,t,d)})})}addPickCompletionDateAction(e,t,r){r.addItem(a=>{a.setTitle(this.t("contextMenus.task.completion.completeOnPicked")),a.setIcon("calendar-plus"),a.onClick(()=>{this.pickCompletionDate(e,t)})})}pickCompletionDate(e,t){this.menu.hide(),new oo(t.app,{currentDate:null,title:this.t("contextMenus.task.completion.pickDateTitle"),showTime:!1,plugin:t,onSelect:a=>{if(!a)return;let i=st(re(a)),s=c2(e,"onPicked",{pickedDate:i});s.available&&this.dispatchCompletion(e,t,s.date)}}).open()}async dispatchCompletion(e,t,r){var a,i;try{if(e.recurrence)await t.toggleRecurringTaskComplete(e,r);else{let s=t.statusManager.getCompletedStatuses()[0];if(!s){new De.Notice(this.t("contextMenus.task.completion.noCompletedStatus"));return}await t.updateTaskProperty(e,"status",s,{completionDate:ae(r)})}(i=(a=this.options).onUpdate)==null||i.call(a)}catch(s){let o=s instanceof Error?s.message:String(s);tr.error("Error completing task:",{category:"persistence",operation:"completing-task",details:{taskPath:e.path},error:o}),new De.Notice(this.t("contextMenus.task.completion.completeFailure",{message:o}))}}async uncompleteNonRecurringTask(e,t){var r,a,i;try{let s=(r=t.settings.defaultTaskStatus)!=null?r:"open";await t.updateTaskProperty(e,"status",s),(i=(a=this.options).onUpdate)==null||i.call(a)}catch(s){let o=s instanceof Error?s.message:String(s);tr.error("Error marking task incomplete:",{category:"persistence",operation:"uncompleting-task",details:{taskPath:e.path},error:o}),new De.Notice(this.t("contextMenus.task.completion.completeFailure",{message:o}))}}addSkipMenuItem(e,t,r){var l;let a=this.options.occurrenceDate,i=a!=null?a:mM(e),s=ae(i),o=((l=e.skipped_instances)==null?void 0:l.includes(s))||!1;r.addItem(c=>{c.setTitle(o?this.t("contextMenus.task.unskipInstance"):this.t("contextMenus.task.skipInstance")),c.setIcon(o?"undo":"x-circle"),c.onClick(async()=>{var d,u;try{await t.taskService.toggleRecurringTaskSkipped(e,a),(u=(d=this.options).onUpdate)==null||u.call(d)}catch(p){let m=p instanceof Error?p.message:String(p);tr.error("Error toggling recurring task skip:",{category:"persistence",operation:"toggling-recurring-task-skip",details:{taskPath:e.path},error:m}),new De.Notice(this.t("contextMenus.task.notices.toggleSkipFailure",{message:m}))}})})}addPromotedOccurrenceControls(e,t){if(!this.options.promoteOccurrenceControls)return!1;let r=!1;return e.recurrence&&(this.addOccurrenceNoteMenuItem(e,t),r=!0),e.recurrence_parent&&e.occurrence_date&&(this.addMaterializedOccurrenceMenuItems(e,t),r=!0),r&&this.menu.addSeparator(),r}addOccurrenceNoteMenuItem(e,t){this.menu.addItem(r=>{r.setTitle("Open or create occurrence note"),r.setIcon("file-plus"),r.onClick(async()=>{await pv({plugin:t,parentTask:e,targetDate:this.getOccurrenceNoteTargetDate(e),onUpdate:this.options.onUpdate})})})}getOccurrenceNoteTargetDate(e){if(this.options.promoteOccurrenceControls||e.recurrence_anchor!=="completion")return this.options.targetDate;try{let t=re(e.scheduled||"");return t?st(t):this.options.targetDate}catch(t){return this.options.targetDate}}addMaterializedOccurrenceMenuItems(e,t){this.menu.addItem(i=>{i.setTitle("Open recurring parent"),i.setIcon("refresh-ccw"),i.onClick(async()=>{await kM({plugin:t,occurrenceTask:e})})});let r=this.getSkippedStatusValue(t),a=this.isSkippedMaterializedOccurrence(e,t);!r&&!a||this.menu.addItem(i=>{i.setTitle(a?"Unskip occurrence":"Skip occurrence"),i.setIcon(a?"undo":"x-circle"),i.onClick(async()=>{var s,o;try{let l=a?await t.taskService.unskipMaterializedOccurrence(e):await t.taskService.skipMaterializedOccurrence(e,r);Object.assign(e,l),(o=(s=this.options).onUpdate)==null||o.call(s)}catch(l){let c=l instanceof Error?l.message:String(l);tr.error("Error updating materialized occurrence skip state:",{category:"persistence",operation:"updating-materialized-occurrence-skip-state",details:{taskPath:e.path,occurrenceDate:e.occurrence_date},error:c}),new De.Notice(`Failed to update occurrence: ${c}`)}})})}getSkippedStatusValue(e){var t,r;return(r=(t=e.settings.customStatuses)==null?void 0:t.find(a=>a.isSkipped))==null?void 0:r.value}isSkippedMaterializedOccurrence(e,t){var r;return((r=t.settings.customStatuses)==null?void 0:r.some(a=>a.isSkipped&&a.value===e.status))===!0}addDependencyMenuItems(e,t,r){var s,o;e.addItem(l=>{l.setTitle(this.t("contextMenus.task.dependencies.addBlockedBy")),l.setIcon("link-2"),l.onClick(()=>{this.menu.hide(),this.openBlockedBySelector(t,r)})});let a=(s=t.blockedBy)!=null?s:[];a.length>0&&e.addItem(l=>{l.setTitle(this.t("contextMenus.task.dependencies.removeBlockedBy")),l.setIcon("unlink");let c=_n(l);a.forEach((d,u)=>{c.addItem(p=>{let m=mv(iB(d),this.t("contextMenus.task.dependencies.unknownDependency"));p.setTitle(m),p.onClick(async()=>{var f,h;try{let g=a.filter((k,T)=>T!==u),v=await r.updateTaskProperty(t,"blockedBy",g.length>0?g:void 0);Object.assign(t,v),new De.Notice(this.t("contextMenus.task.dependencies.notices.blockedByRemoved")),(h=(f=this.options).onUpdate)==null||h.call(f)}catch(g){tr.error("Failed to remove blocked-by dependency:",{category:"persistence",operation:"remove-blocked-by-dependency",error:g}),new De.Notice(this.t("contextMenus.task.dependencies.notices.updateFailed"))}})})})}),e.addSeparator(),e.addItem(l=>{l.setTitle(this.t("contextMenus.task.dependencies.addBlocking")),l.setIcon("git-branch-plus"),l.onClick(()=>{this.menu.hide(),this.openBlockingSelector(t,r)})});let i=(o=t.blocking)!=null?o:[];i.length>0&&e.addItem(l=>{l.setTitle(this.t("contextMenus.task.dependencies.removeBlocking")),l.setIcon("git-branch-minus");let c=_n(l);i.forEach(d=>{let u=r.app.vault.getAbstractFileByPath(d),p=u instanceof De.TFile?r.app.metadataCache.fileToLinktext(u,t.path,!1):d.split("/").pop()||d;c.addItem(m=>{m.setTitle(p),m.onClick(async()=>{var f,h;try{await r.taskService.updateBlockingRelationships(t,[],[d],{});let g=await r.cacheManager.getTaskInfo(t.path);g&&Object.assign(t,g),new De.Notice(this.t("contextMenus.task.dependencies.notices.blockingRemoved")),(h=(f=this.options).onUpdate)==null||h.call(f)}catch(g){tr.error("Failed to remove blocking dependency:",{category:"persistence",operation:"remove-blocking-dependency",error:g}),new De.Notice(this.t("contextMenus.task.dependencies.notices.updateFailed"))}})})})})}dedupeDependencyEntries(e){let t=new Map;for(let r of e){let a=Ai(r);if(!a)continue;let i=this.getDependencyKey(a);t.has(i)||t.set(i,a)}return Array.from(t.values())}async openBlockedBySelector(e,t){let r=new Set((Array.isArray(e.blockedBy)?e.blockedBy:[]).map(a=>a.uid));await this.openTaskDependencySelector(t,a=>{if(a.path===e.path)return!1;let i=Ks(t.app,e.path,a.path,t.settings.useFrontmatterMarkdownLinks);return!r.has(i)},async a=>{await this.handleBlockedBySelection(e,t,a)})}async openBlockingSelector(e,t){var a;let r=new Set((a=e.blocking)!=null?a:[]);await this.openTaskDependencySelector(t,i=>i.path===e.path?!1:!r.has(i.path),async i=>{await this.handleBlockingSelection(e,t,i)})}async openTaskDependencySelector(e,t,r){try{let i=(await e.cacheManager.getAllTasks()).filter(t);if(i.length===0){new De.Notice(this.t("contextMenus.task.dependencies.notices.noEligibleTasks"));return}fn(e,i,s=>{s&&r(s)})}catch(a){tr.error("Failed to open task selector for dependencies:",{category:"persistence",operation:"open-task-selector-dependencies",error:a}),new De.Notice(this.t("contextMenus.task.dependencies.notices.updateFailed"))}}async handleBlockedBySelection(e,t,r){var a,i;if(r.path!==e.path)try{let s={uid:Ks(t.app,e.path,r.path,t.settings.useFrontmatterMarkdownLinks),reltype:Pi},o=Array.isArray(e.blockedBy)?e.blockedBy:[],l=this.dedupeDependencyEntries([...o,s]);if(l.length===o.length)return;let c=await t.updateTaskProperty(e,"blockedBy",l);Object.assign(e,c),new De.Notice(this.t("contextMenus.task.dependencies.notices.blockedByAdded",{count:1})),(i=(a=this.options).onUpdate)==null||i.call(a)}catch(s){tr.error("Failed to add blocked-by dependency via selector:",{category:"persistence",operation:"add-blocked-by-dependency-via-selector",error:s}),new De.Notice(this.t("contextMenus.task.dependencies.notices.updateFailed"))}}async handleBlockingSelection(e,t,r){var i,s,o;let a=r.path;if(a!==e.path&&!((i=e.blocking)!=null&&i.includes(a)))try{let l={uid:Ks(t.app,a,e.path,t.settings.useFrontmatterMarkdownLinks),reltype:Pi};await t.taskService.updateBlockingRelationships(e,[a],[],{[a]:l});let c=await t.cacheManager.getTaskInfo(e.path);c?Object.assign(e,c):Array.isArray(e.blocking)?e.blocking=Array.from(new Set([...e.blocking,a])):e.blocking=[a],new De.Notice(this.t("contextMenus.task.dependencies.notices.blockingAdded",{count:1})),(o=(s=this.options).onUpdate)==null||o.call(s)}catch(l){tr.error("Failed to add blocking dependency via selector:",{category:"persistence",operation:"add-blocking-dependency-via-selector",error:l}),new De.Notice(this.t("contextMenus.task.dependencies.notices.updateFailed"))}}getDependencyKey(e){var t;return`${e.uid}::${e.reltype}::${(t=e.gap)!=null?t:""}`}addOrganizationMenuItems(e,t,r){e.addItem(a=>{a.setTitle(this.t("contextMenus.task.organization.contexts")),a.setIcon("at-sign");let i=_n(a);this.addContextMenuItems(i,t,r)}),e.addSeparator(),e.addItem(a=>{a.setTitle(this.t("contextMenus.task.organization.addToProject")),a.setIcon("folder-plus"),a.onClick(()=>{this.menu.hide(),this.openProjectSelector(t,r)})}),e.addItem(a=>{a.setTitle(this.t("contextMenus.task.organization.addSubtasks")),a.setIcon("indent"),a.onClick(()=>{this.menu.hide(),this.openSubtaskAssignmentSelector(t,r)})})}addContextMenuItems(e,t,r){let a=EC(t.contexts),i=this.getContextOptions(t,r);if(e.addItem(s=>{s.setTitle(this.t("contextMenus.task.organization.addContext")),s.setIcon("plus"),s.onClick(()=>{this.menu.hide(),this.openContextInput(t,r)})}),i.length>0){e.addSeparator();for(let s of i)e.addItem(o=>{let l=a.includes(s);o.setTitle(l?this.t("contextMenus.task.organization.contextSelected",{context:s}):s),o.setIcon(l?"check":"at-sign"),o.onClick(async()=>{await this.updateTaskContexts(t,r,tHe(t.contexts,s))})})}a.length>0&&(e.addSeparator(),e.addItem(s=>{s.setTitle(this.t("contextMenus.task.organization.clearContexts")),s.setIcon("x"),s.onClick(async()=>{await this.updateTaskContexts(t,r,void 0)})}))}getContextOptions(e,t){var i,s,o,l;let r=(o=(s=(i=t.cacheManager).getAllContexts)==null?void 0:s.call(i))!=null?o:[];return EC([...r,...(l=e.contexts)!=null?l:[]]).sort((c,d)=>c.localeCompare(d))}async openContextInput(e,t){let r=await Vy(t.app,{title:this.t("contextMenus.task.organization.addContext"),placeholder:this.t("contextMenus.task.organization.contextPlaceholder"),confirmText:this.t("common.confirm"),cancelText:this.t("common.cancel")});r&&await this.updateTaskContexts(e,t,Ace(e.contexts,r))}async updateTaskContexts(e,t,r){var a,i;try{let s=await t.updateTaskProperty(e,"contexts",r);Object.assign(e,s),(i=(a=this.options).onUpdate)==null||i.call(a)}catch(s){tr.error("Failed to update task contexts:",{category:"validation",operation:"update-task-contexts",error:s}),new De.Notice(this.t("contextMenus.task.organization.notices.updateContextsFailed"))}}addTagOptions(e,t,r){let a=ole(t,r.settings);if(e.addItem(i=>{i.setTitle(this.t("contextMenus.task.addTag")),i.setIcon("plus"),i.onClick(()=>{this.menu.hide(),this.openTagInput(t,r,"add")})}),a.length>0){e.addSeparator();for(let i of a)e.addItem(s=>{s.setTitle(this.t("contextMenus.task.removeTag",{tag:`#${i}`})),s.setIcon("x"),s.onClick(async()=>{await this.updateTaskTags(t,r,sC(t.tags,[i]))})});e.addSeparator(),e.addItem(i=>{i.setTitle(this.t("contextMenus.task.clearTags")),i.setIcon("eraser"),i.onClick(async()=>{await this.updateTaskTags(t,r,VA(t.tags,r.settings))})})}}async openTagInput(e,t,r){let a=await Vy(t.app,{title:r==="add"?this.t("contextMenus.task.addTag"):this.t("contextMenus.task.removeTagInput"),placeholder:this.t("contextMenus.task.tagPlaceholder"),confirmText:this.t("common.confirm"),cancelText:this.t("common.cancel"),onInputReady:o=>{new sp(t.app,o,t)}}),i=iC(a);if(i.length===0)return;let s=r==="add"?HA(e.tags,i):sC(e.tags,i);await this.updateTaskTags(e,t,s)}async updateTaskTags(e,t,r){var a,i;try{let s=await t.updateTaskProperty(e,"tags",r);Object.assign(e,s),(i=(a=this.options).onUpdate)==null||i.call(a)}catch(s){tr.error("Failed to update task tags:",{category:"validation",operation:"update-task-tags",error:s}),new De.Notice(this.t("contextMenus.task.notices.updateTagsFailed"))}}async openProjectSelector(e,t){try{new Ys(t.app,t,a=>{a&&this.addTaskToProject(e,t,a)}).open()}catch(r){tr.error("Failed to open project selector:",{category:"persistence",operation:"open-project-selector",error:r}),new De.Notice(this.t("contextMenus.task.organization.notices.projectSelectFailed"))}}async openSubtaskAssignmentSelector(e,t){try{let a=(await t.cacheManager.getAllTasks()).filter(i=>i.path!==e.path);if(a.length===0){new De.Notice(this.t("contextMenus.task.organization.notices.noEligibleSubtasks"));return}fn(t,a,i=>{i&&this.assignTaskAsSubtask(e,t,i)})}catch(r){tr.error("Failed to open subtask assignment selector:",{category:"persistence",operation:"open-subtask-assignment-selector",error:r}),new De.Notice(this.t("contextMenus.task.organization.notices.subtaskSelectFailed"))}}async addTaskToProject(e,t,r){var a,i;try{if(!(r instanceof De.TFile)){new De.Notice(this.t("contextMenus.task.organization.notices.projectSelectFailed"));return}let s=await rv(t,e,r);s&&(Object.assign(e,s),(i=(a=this.options).onUpdate)==null||i.call(a))}catch(s){tr.error("Failed to add task to project:",{category:"persistence",operation:"add-task-project",error:s}),new De.Notice(this.t("contextMenus.task.organization.notices.addToProjectFailed"))}}async assignTaskAsSubtask(e,t,r){var a,i;try{let s=t.app.vault.getAbstractFileByPath(e.path);if(!(s instanceof De.TFile)){new De.Notice(this.t("contextMenus.task.organization.notices.currentTaskNotFound"));return}let o=await lM(t,s,r);o&&(Object.assign(r,o),(i=(a=this.options).onUpdate)==null||i.call(a))}catch(s){tr.error("Failed to assign task as subtask:",{category:"persistence",operation:"assign-task-as-subtask",error:s}),new De.Notice(this.t("contextMenus.task.organization.notices.addAsSubtaskFailed"))}}buildProjectReference(e,t,r){return Qo(r.app,e,t,"","",r.settings.useFrontmatterMarkdownLinks)}updateMainMenuIconColors(e,t){let r=this.targetDoc.querySelector(".menu");if(!r)return;let a=r.querySelectorAll(".menu-item"),i=this.t("contextMenus.task.status"),s=this.t("contextMenus.task.priority");a.forEach(o=>{let l=o.querySelector(".menu-item-title"),c=o.querySelector(".menu-item-icon");if(l&&c){let d=l.textContent;if(d===i){let u=t.settings.customStatuses.find(p=>p.value===e.status);u&&u.color&&(c.style.color=u.color)}else if(d===s){let u=t.settings.customPriorities.find(p=>p.value===e.priority);u&&u.color&&(c.style.color=u.color)}}})}addStatusOptions(e,t,r){this.getStatusOptions(t,r).forEach((i,s)=>{e.addItem(o=>{let l=mv(i.label,i.value),c=l;o.setIcon(i.icon||"circle"),i.value===t.status&&(c=this.t("contextMenus.task.statusSelected",{label:l})),o.setTitle(c),o.onClick(async()=>{var u,p;try{await r.updateTaskProperty(t,"status",i.value),(p=(u=this.options).onUpdate)==null||p.call(u)}catch(m){let f=m instanceof Error?m.message:String(m);tr.error("Error updating task status:",{category:"persistence",operation:"updating-task-status",details:{taskPath:t.path},error:f}),new De.Notice(`Failed to update task status: ${f}`)}});let d=i.color;d&&window.setTimeout(()=>{let u=I2(o);if(u){let p=u.querySelector(".menu-item-icon");p&&(p.style.color=d)}},10)})})}addPriorityOptions(e,t,r){r.priorityManager.getPrioritiesByWeight().forEach(i=>{let s=mv(i.value);if(!s)return;let o=mv(i.label,s);e.addItem(l=>{let c=o;l.setIcon("star"),s===t.priority&&(c=this.t("contextMenus.task.prioritySelected",{label:o})),l.setTitle(c),l.onClick(async()=>{var d,u;try{await r.updateTaskProperty(t,"priority",s),(u=(d=this.options).onUpdate)==null||u.call(d)}catch(p){let m=p instanceof Error?p.message:String(p);tr.error("Error updating task priority:",{category:"persistence",operation:"updating-task-priority",details:{taskPath:t.path},error:m}),new De.Notice(`Failed to update task priority: ${m}`)}}),i.color&&window.setTimeout(()=>{let d=I2(l);if(d){let u=d.querySelector(".menu-item-icon");u&&(u.style.color=i.color)}},10)})})}addDateOptions(e,t,r,a,i={}){let o=new rl({currentValue:t,onSelect:u=>{r(u)},onCustomDate:a,plugin:this.options.plugin,app:this.options.plugin.app}).getDateOptions(),l=o.filter(u=>u.category==="increment");l.length>0&&(l.forEach(u=>{e.addItem(p=>{u.icon&&p.setIcon(u.icon),p.setTitle(u.label),p.onClick(()=>{r(u.value)})})}),e.addSeparator()),o.filter(u=>u.category==="basic").forEach(u=>{e.addItem(p=>{u.icon&&p.setIcon(u.icon);let f=u.value===t?this.t("contextMenus.date.selected",{label:u.label}):u.label;p.setTitle(f),p.onClick(()=>{r(u.value)})})});let d=o.filter(u=>u.category==="weekday");d.length>0&&(e.addSeparator(),e.addItem(u=>{u.setTitle(this.t("contextMenus.date.weekdaysLabel")),u.setIcon("calendar");let p=_n(u);d.forEach(m=>{p.addItem(f=>{let g=m.value===t?this.t("contextMenus.date.selected",{label:m.label}):m.label;f.setTitle(g),f.setIcon("calendar"),f.onClick(()=>{r(m.value)})})})})),e.addSeparator(),e.addItem(u=>{var p;u.setTitle((p=i.pickDateTitle)!=null?p:this.t("contextMenus.date.pickDateTime")),u.setIcon("calendar"),u.onClick(a)}),t&&e.addItem(u=>{u.setTitle(this.t("contextMenus.date.clearDate")),u.setIcon("x"),u.onClick(()=>{r(null)})})}addCustomDateFieldMenuItems(e,t){let r=this.getCustomDateFields(t);r.length!==0&&this.menu.addItem(a=>{a.setTitle(this.t("contextMenus.task.customDates")),a.setIcon("calendar-days");let i=_n(a);r.forEach(s=>{i.addItem(o=>{let l=this.getCustomFieldLabel(s);o.setTitle(l),o.setIcon("calendar");let c=_n(o),d=this.getCustomDateFieldValue(e,s);this.addDateOptions(c,d,async u=>{await this.updateCustomDateField(e,t,s,u)},()=>{this.openCustomDateFieldPicker(e,t,s,d)},{pickDateTitle:this.t("modals.task.userFields.pickDate",{field:l})})})})})}getCustomDateFields(e){return(e.settings.userFields||[]).filter(t=>t.type==="date"&&t.key.trim().length>0)}getCustomFieldLabel(e){return e.displayName.trim()||e.key||e.id}getCustomDateFieldValue(e,t){var i,s;let a=(s=e[t.key])!=null?s:(i=e.customProperties)==null?void 0:i[t.key];return typeof a=="string"&&a.trim().length>0?a:void 0}openCustomDateFieldPicker(e,t,r,a){this.menu.hide();let i=this.getCustomFieldLabel(r);new oo(t.app,{currentDate:a||null,title:this.t("modals.task.userFields.pickDate",{field:i}),showTime:!1,plugin:t,onSelect:o=>{this.updateCustomDateField(e,t,r,o)}}).open()}async updateCustomDateField(e,t,r,a){var s,o;let i=this.getCustomFieldLabel(r);try{let l=await t.updateTaskProperty(e,r.key,a||void 0);Object.assign(e,l),(o=(s=this.options).onUpdate)==null||o.call(s)}catch(l){let c=l instanceof Error?l.message:String(l);tr.error("Error updating custom date field:",{category:"persistence",operation:"updating-custom-date-field",details:{taskPath:e.path,field:r.key},error:c}),new De.Notice(this.t("contextMenus.task.notices.updateCustomDateFailure",{field:i,message:c}))}}addRecurrenceOptions(e,t,r,a){let i=new Date,s=["SU","MO","TU","WE","TH","FR","SA"],o=[a.i18n.translate("common.months.january"),a.i18n.translate("common.months.february"),a.i18n.translate("common.months.march"),a.i18n.translate("common.months.april"),a.i18n.translate("common.months.may"),a.i18n.translate("common.months.june"),a.i18n.translate("common.months.july"),a.i18n.translate("common.months.august"),a.i18n.translate("common.months.september"),a.i18n.translate("common.months.october"),a.i18n.translate("common.months.november"),a.i18n.translate("common.months.december")],l=s[i.getDay()],c=i.getDate(),d=i.getMonth()+1,u=o[i.getMonth()],p=gC(a),m=i.toLocaleDateString(p||void 0,{weekday:"long"}),f=k=>{let T=k.getFullYear(),b=String(k.getMonth()+1).padStart(2,"0"),w=String(k.getDate()).padStart(2,"0");return`${T}${b}${w}`},h=k=>{let T=["th","st","nd","rd"],b=k%100;return k+(T[(b-20)%10]||T[b]||T[0])},g=f(i);[{label:this.t("modals.task.recurrence.daily"),value:`DTSTART:${g};FREQ=DAILY;INTERVAL=1`,icon:"calendar-days"},{label:this.t("modals.task.recurrence.weeklyOn",{days:m}),value:`DTSTART:${g};FREQ=WEEKLY;INTERVAL=1;BYDAY=${l}`,icon:"calendar"},{label:this.t("modals.task.recurrence.everyTwoWeeks"),value:`DTSTART:${g};FREQ=WEEKLY;INTERVAL=2;BYDAY=${l}`,icon:"calendar"},{label:this.t("modals.task.recurrence.monthlyOnOrdinal",{ordinal:h(c)}),value:`DTSTART:${g};FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=${c}`,icon:"calendar-range"},{label:this.t("modals.task.recurrence.everyThreeMonths"),value:`DTSTART:${g};FREQ=MONTHLY;INTERVAL=3;BYMONTHDAY=${c}`,icon:"calendar-range"},{label:this.t("modals.task.recurrence.yearlyOn",{month:u,day:h(c)}),value:`DTSTART:${g};FREQ=YEARLY;INTERVAL=1;BYMONTH=${d};BYMONTHDAY=${c}`,icon:"calendar-clock"},{label:this.t("modals.task.recurrence.weekdays"),value:tM(g,p),icon:"briefcase"}].forEach(k=>{e.addItem(T=>{let b=k.value===t;T.setTitle(b?`✓ ${k.label}`:k.label),T.setIcon(k.icon),T.onClick(()=>{r(k.value)})})}),e.addSeparator(),e.addItem(k=>{k.setTitle(this.t("contextMenus.task.customRecurrence")),k.setIcon("settings"),k.onClick(()=>{new il({currentValue:typeof t=="string"?t:void 0,currentAnchor:this.options.task.recurrence_anchor||"scheduled",scheduledDate:this.options.task.scheduled,onSelect:b=>{r(b)},app:a.app,plugin:a}).showCustomRecurrenceModal()})}),t&&e.addItem(k=>{k.setTitle(this.t("contextMenus.task.clearRecurrence")),k.setIcon("x"),k.onClick(()=>{r(null)})})}addOccurrencePolicyOptions(e,t,r){let a=t.occurrence_materialization||"manual",i=t.occurrence_next_trigger||"completion";e.addSeparator(),e.addItem(s=>{s.setTitle("Occurrence notes"),s.setIcon("files");let o=_n(s),l=(d,u,p)=>{o.addItem(m=>{m.setTitle(a===d?`✓ ${u}`:u),m.setIcon(p),m.onClick(async()=>{await this.updateOccurrenceMaterializationPolicy(t,r,d)})})};if(l("manual","Create manually","file-plus"),l("on_completion","Create next after completion","check-circle"),o.addItem(d=>{d.setTitle(a==="rolling"?"✓ Rolling window (not automated yet)":"Rolling window (not automated yet)"),d.setIcon("calendar-range"),d.setDisabled(!0)}),a!=="on_completion")return;o.addSeparator(),[{value:"completion",label:"Completion only",icon:"check"},{value:"completion_or_skip",label:"Completion or skip",icon:"check-check"}].forEach(d=>{o.addItem(u=>{u.setTitle(i===d.value?`✓ ${d.label}`:d.label),u.setIcon(d.icon),u.onClick(async()=>{await this.updateOccurrenceNextTrigger(t,r,d.value)})})})})}async updateOccurrenceMaterializationPolicy(e,t,r){var a,i;try{let s=await t.updateTaskProperty(e,"occurrence_materialization",r==="manual"?void 0:r);if(Object.assign(e,s),r!=="on_completion"&&e.occurrence_next_trigger){let o=await t.updateTaskProperty(e,"occurrence_next_trigger",void 0);Object.assign(e,o)}(i=(a=this.options).onUpdate)==null||i.call(a),new De.Notice(r==="manual"?"Occurrence notes set to manual creation":"Occurrence notes will be created after completion")}catch(s){let o=s instanceof Error?s.message:String(s);tr.error("Error updating occurrence materialization policy:",{category:"persistence",operation:"updating-occurrence-materialization-policy",details:{taskPath:e.path,mode:r},error:o}),new De.Notice(`Failed to update occurrence notes setting: ${o}`)}}async updateOccurrenceNextTrigger(e,t,r){var a,i;try{let s=await t.updateTaskProperty(e,"occurrence_next_trigger",r==="completion"?void 0:r);Object.assign(e,s),(i=(a=this.options).onUpdate)==null||i.call(a),new De.Notice(r==="completion"?"Next occurrence note will be created after completion":"Next occurrence note will be created after completion or skip")}catch(s){let o=s instanceof Error?s.message:String(s);tr.error("Error updating occurrence next trigger:",{category:"persistence",operation:"updating-occurrence-next-trigger",details:{taskPath:e.path,trigger:r},error:o}),new De.Notice(`Failed to update occurrence trigger: ${o}`)}}getStatusOptions(e,t){let r=t.settings.customStatuses,a=[];return r&&r.length>0&&[...r].sort((s,o)=>s.order-o.order).forEach(s=>{let o=mv(s.value);o&&a.push({label:mv(s.label,o),value:o,color:typeof s.color=="string"?s.color:void 0,icon:typeof s.icon=="string"?s.icon:void 0})}),a}addQuickRemindersSection(e,t,r,a,i){if(!(a==="due"?t.due:t.scheduled)){e.addItem(o=>{o.setTitle(i),o.setIcon("bell"),o.setDisabled(!0)});return}e.addItem(o=>{o.setTitle(i),o.setIcon("bell");let l=_n(o);[{labelKey:"contextMenus.task.quickReminders.atTime",offset:"PT0M"},{labelKey:"contextMenus.task.quickReminders.fiveMinutes",offset:"-PT5M"},{labelKey:"contextMenus.task.quickReminders.fifteenMinutes",offset:"-PT15M"},{labelKey:"contextMenus.task.quickReminders.oneHour",offset:"-PT1H"},{labelKey:"contextMenus.task.quickReminders.oneDay",offset:"-P1D"}].forEach(d=>{l.addItem(u=>{let p=this.t(d.labelKey);u.setTitle(p),u.onClick(()=>{this.addQuickReminder(t,r,a,d.offset,p)})})})})}async addQuickReminder(e,t,r,a,i){var l,c;let s={id:`rem_${Date.now()}`,type:"relative",relatedTo:r,offset:a,description:i},o=[...e.reminders||[],s];try{await t.updateTaskProperty(e,"reminders",o),(c=(l=this.options).onUpdate)==null||c.call(l)}catch(d){tr.error("Error adding reminder:",{category:"persistence",operation:"adding-reminder",error:d}),new De.Notice("Failed to add reminder")}}show(e){var t,r;(r=(t=e.target)==null?void 0:t.instanceOf)!=null&&r.call(t,HTMLElement)&&(this.targetDoc=e.target.ownerDocument),za(this.menu,e)}showAtElement(e){this.targetDoc=e.ownerDocument,jl(this.menu,e)}}});function rHe(n,e,t){return n.i18n.translate(`ui.taskCard.${e}`,t)}function nHe(n){return M({tag:"TaskCard/ContextMenu",isDebugEnabled:()=>n.settings.enableDebugLogging})}function Mce(n){let{mainRow:e,taskPath:t,plugin:r,targetDate:a,promoteOccurrenceControls:i}=n,s=rHe(r,"taskOptions"),o=e.createDiv({cls:"task-card__context-menu",attr:{"aria-label":s}});return(0,nc.setIcon)(o,"ellipsis-vertical"),(0,nc.setTooltip)(o,s,{placement:"top"}),al(o),o.addEventListener("click",l=>{if(l.stopPropagation(),l.preventDefault(),i===void 0){uo(l,t,r,a);return}uo(l,t,r,a,{promoteOccurrenceControls:i})}),o}async function uo(n,e,t,r,a={}){let i=t.app.vault.getAbstractFileByPath(e),s=()=>{i instanceof nc.TFile&&aHe(n,i,t)};try{let o=await t.cacheManager.getTaskInfo(e);if(!o){s();return}new ll({task:o,plugin:t,targetDate:r,occurrenceDate:a.occurrenceDate,promoteOccurrenceControls:a.promoteOccurrenceControls,onUpdate:()=>{t.app.workspace.trigger("tasknotes:refresh-views")}}).show(n)}catch(o){let l=o instanceof Error?o.message:String(o);nHe(t).error("Error creating context menu",{category:"internal",operation:"create-context-menu",details:{taskPath:e,errorMessage:l},error:o}),new nc.Notice(`Failed to create context menu: ${l}`),s()}}function aHe(n,e,t){var i,s;let r=new nc.Menu,a=!1;try{t.app.workspace.trigger("file-menu",r,e,"tasknotes-bases-view"),a=((s=(i=r.items)==null?void 0:i.length)!=null?s:0)>0}catch(o){a=!1}a||(r.addItem(o=>{o.setTitle("Open"),o.setIcon("file-text"),o.onClick(()=>{t.app.workspace.getLeaf(!1).openFile(e)})}),r.addItem(o=>{o.setTitle("Open in new tab"),o.setIcon("external-link"),o.onClick(()=>{t.app.workspace.openLinkText(e.path,"",!0)})})),r.showAtMouseEvent(n)}var nc,N2=y(()=>{nc=require("obsidian");DC();q();mC()});function iHe(n,e){return Y(e).trim()||Y(n.title)}function Ice(n,e,t,r){n.empty();let a={metadataCache:t.app.metadataCache,workspace:t.app.workspace,sourcePath:e.path};Zl(n,iHe(e,r),a)}function R2(n,e){let t=n.querySelector(".task-card__title"),r=n.querySelector(".task-card__title-text");t==null||t.classList.toggle("completed",e),r==null||r.classList.toggle("completed",e)}function Nce(n){let{contentContainer:e,layout:t,task:r,plugin:a,displayText:i,isCompleted:s=!1}=n,o=e.createEl(t==="inline"?"span":"div",{cls:"task-card__title"}),l=o.createSpan({cls:"task-card__title-text"});return Ice(l,r,a,i),o.classList.toggle("completed",s),l.classList.toggle("completed",s),{titleEl:o,titleTextEl:l}}function Rce(n){let{card:e,task:t,plugin:r,displayText:a,isCompleted:i=!1}=n,s=e.querySelector(".task-card__title-text");s&&Ice(s,t,r,a),R2(e,i)}var _2=y(()=>{dr();cp()});function sHe(n,e,t,r,a){var o;n.classList.toggle("task-card--completed",r),n.classList.toggle("task-card--completed-strikethrough",r&&i2(t)),n.classList.toggle("task-card--archived",!!e.archived),n.classList.toggle("task-card--actively-tracked",t.getActiveTimeSession(e)!==null),n.classList.toggle("task-card--recurring",!!e.recurrence),n.classList.toggle("task-card--chevron-left",((o=t.settings)==null?void 0:o.subtaskChevronPosition)==="left");let i=a2(e,t);n.classList.toggle("task-card--has-details",i),n.dataset.hasDetails=i?"true":"false",F2(n,"task-card--priority-"),e.priority&&n.classList.add(`task-card--priority-${Dd(e.priority)}`),F2(n,"task-card--status-"),a&&n.classList.add(`task-card--status-${Dd(a)}`),F2(n,"task-card--project-");let s=s2(e);n.classList.toggle("task-card--has-projects",s.length>0),s.forEach(l=>n.classList.add(l)),n.dataset.status=a,R2(n,r)}function L2({card:n,statusDot:e,plugin:t,updatedTask:r,effectiveStatus:a,isCompleted:i}){sM(e,t.statusManager.getStatusConfig(a)),iM(n,a,t);let s=n.querySelector(".task-card__checkbox");s&&(s.checked=i),sHe(n,r,t,i,a)}function F2(n,e){for(let t of Array.from(n.classList))t.startsWith(e)&&n.classList.remove(t)}var _ce=y(()=>{yt();l2();n2();_2()});async function Fce(n,e){return new Promise((t,r)=>{new O2(e.app,n,async()=>{try{await e.taskService.deleteTask(n),t()}catch(i){r(i instanceof Error?i:new Error(String(i)))}}).open()})}var PC,oHe,O2,Lce=y(()=>{PC=require("obsidian");q();oHe=M({tag:"Ui/TaskCardDeletion"}),O2=class extends PC.Modal{constructor(e,t,r){super(e),this.task=t,this.onConfirm=r}onOpen(){let{contentEl:e}=this;e.empty(),e.createEl("h2",{text:"Delete task"});let t=e.createEl("p");t.appendText('Are you sure you want to delete the task "'),t.createEl("strong",{text:this.task.title}),t.appendText('"?'),e.createEl("p",{cls:"mod-warning",text:"This action cannot be undone. The task file will be permanently deleted."});let r=e.createDiv({cls:"modal-button-container"});r.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),r.classList.add("tn-static-display-flex-75816cae"),r.classList.remove("tn-static-display-flex-8bb39979","tn-static-gap-0-5rem-ce2fca4d","tn-static-gap-12px-ed7b3d87","tn-static-gap-6px-f0abc1db","tn-static-gap-8px-33fcd4c3"),r.classList.add("tn-static-gap-10px-f3d7ce77"),r.classList.remove("tn-static-justify-content-center-03c4bb6f","tn-static-justify-content-space-between-a562f4fd"),r.classList.add("tn-static-justify-content-flex-end-455f8cca"),r.classList.remove("tn-static-font-size-12px-b0cc7e05","tn-static-margin-top-0-5rem-3dc98b5e","tn-static-margin-top-0-d462248a","tn-static-margin-top-12px-91e0f558","tn-static-margin-top-16px-1b0f4999","tn-static-margin-top-1rem-2239d6d5","tn-static-margin-top-30px-2fbbbcd4","tn-static-margin-top-4px-96ad6099","tn-static-margin-top-8px-8a77e5a3","tn-static-margin-top-8px-f4f01e68"),r.classList.add("tn-static-margin-top-20px-a26bda7d");let a=r.createEl("button",{text:"Cancel"});a.addEventListener("click",()=>{this.close()});let i=r.createEl("button",{text:"Delete",cls:"mod-warning"});i.classList.remove("tn-static-background-color-var-background-mo-94b219f0","tn-static-background-color-var-background-se-9087a23e","tn-static-background-color-var-color-base-40-ef5f175e","tn-static-background-color-var-text-accent-a954c70f"),i.classList.add("tn-static-background-color-var-color-red-134bc721"),i.classList.remove("tn-static-color-var-color-accent-d2cad743","tn-static-color-var-text-accent-65b47ee3","tn-static-color-var-text-muted-5872de20","tn-static-color-var-text-on-accent-f3e1679d","tn-static-color-var-text-warning-783d5f03","tn-static-color-var-tn-text-muted-a90fb6f3","tn-static-cursor-pointer-2723efcc","tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-2px-0-edce9b14","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c"),i.classList.add("tn-static-color-white-0a43e56a"),i.addEventListener("click",()=>{(async()=>{try{await this.onConfirm(),this.close(),new PC.Notice("Task deleted successfully")}catch(s){let o=s instanceof Error?s.message:String(s);new PC.Notice(`Failed to delete task: ${o}`),oHe.error("Error in delete confirmation:",{category:"persistence",operation:"delete-confirmation",error:s})}})()}),a.focus()}onClose(){let{contentEl:e}=this;e.empty()}}});var fv={};Xe(fv,{DEFAULT_TASK_CARD_OPTIONS:()=>z2,cleanupTaskCard:()=>dHe,createTaskCard:()=>pr,refreshParentTaskSubtasks:()=>uHe,showDeleteConfirmationModal:()=>Fce,showTaskContextMenu:()=>uo,toggleBlockedByTasks:()=>jce,toggleBlockingTasks:()=>Bce,toggleSubtasks:()=>zce,updateTaskCard:()=>cHe});function lHe(n){var e;return(e=n._taskCardOptions)!=null?e:{}}function wM(n){return{plugin:n,getRelationshipOptions:lHe,renderTaskCard:(e,t)=>pr(e,n,void 0,t)}}function Oce(n){return{toggleSubtasks:(e,t,r)=>zce(e,t,n,r),toggleBlockingTasks:(e,t,r)=>Bce(e,t,n,r),toggleBlockedByTasks:(e,t,r)=>jce(e,t,n,r)}}function pr(n,e,t,r={}){let a={...z2,...r},i=o2(n,e,a),{targetDate:s,effectiveStatus:o,layout:l,isCompleted:c,hasDetails:d}=i,u=activeWindow.createEl(l==="inline"?"span":"div"),p=u;p._taskPath=n.path,p._taskCardOptions=a,u.className=i.cardClasses.join(" "),u.dataset.taskPath=n.path,u.dataset.key=n.path,u.dataset.status=o,n.priority?u.dataset.priority=n.priority:delete u.dataset.priority,u.dataset.hasDetails=d?"true":"false";let m=u.createEl(l==="inline"?"span":"div",{cls:"task-card__main-row"});e2(u,n,e),t2({mainRow:m,card:u,task:n,plugin:e,effectiveStatus:o,visibleProperties:t,hideStatusIndicator:a.hideStatusIndicator,onClick:z$({task:n,plugin:e,targetDate:s,updateStatusVisuals:(S,C,x)=>{let E=u.querySelector(".task-card__status-dot");E&&L2({card:u,statusDot:E,plugin:e,updatedTask:S,effectiveStatus:C,isCompleted:x})}})}),r2({mainRow:m,task:n,plugin:e,visibleProperties:t,onClick:B$(n,e)});let f=m.createEl(l==="inline"?"span":"div",{cls:"task-card__content"}),h=l!=="inline"?m.createDiv({cls:"task-card__badges"}):null,g=Oce(e);Jle({card:u,badgesContainer:h,task:n,plugin:e,hasDetails:d,propertyOptions:a,handlers:g}),Mce({mainRow:m,taskPath:n.path,plugin:e,targetDate:s,promoteOccurrenceControls:a.promoteOccurrenceControlsInContextMenu}),Nce({contentContainer:f,layout:l,task:n,plugin:e,displayText:a.displayText,isCompleted:c});let v=f.createEl(l==="inline"?"span":"div",{cls:"task-card__metadata"});J$({metadataLine:v,card:u,task:n,plugin:e,visibleProperties:t,propertyOptions:a,handlers:g});let{clickHandler:k,auxclickHandler:T,dblclickHandler:b,contextmenuHandler:w}=fre({task:n,plugin:e,navigationSubpath:a.navigationSubpath,contextMenuHandler:S=>{let C=u.dataset.taskPath;if(C){if(a.promoteOccurrenceControlsInContextMenu===void 0){uo(S,C,e,s);return}uo(S,C,e,s,{promoteOccurrenceControls:a.promoteOccurrenceControlsInContextMenu})}},createBatchContextMenu:(S,C)=>new Gy({plugin:e,selectedPaths:S,onUpdate:C})});return u.addEventListener("click",k),u.addEventListener("auxclick",T),u.addEventListener("dblclick",b),u.addEventListener("contextmenu",w),a.enableHoverPreview&&u.addEventListener("mouseover",hre(n,e)),u}function cHe(n,e,t,r,a={}){let i={...z2,...a},s=o2(e,t,i),{targetDate:o,effectiveStatus:l,isCompleted:c,hasDetails:d}=s;n.className=s.cardClasses.join(" "),n.dataset.status=l,e.priority?n.dataset.priority=e.priority:delete n.dataset.priority,n.dataset.hasDetails=d?"true":"false";let u=n.querySelector(".task-card__main-row");e2(n,e,t);let p=n.querySelector(".task-card__checkbox");p&&(p.checked=t.statusManager.isCompletedStatus(l)),ace({mainRow:u,card:n,task:e,plugin:t,effectiveStatus:l,visibleProperties:r,hideStatusIndicator:i.hideStatusIndicator,onClick:z$({task:e,plugin:t,targetDate:o,updateStatusVisuals:(g,v,k)=>{let T=n.querySelector(".task-card__status-dot");T&&L2({card:n,statusDot:T,plugin:t,updatedTask:g,effectiveStatus:v,isCompleted:k})}})}),sce({mainRow:u,task:e,plugin:t,visibleProperties:r,onClick:B$(e,t)});let m=Oce(t);Xle({card:n,mainRow:u,task:e,plugin:t,hasDetails:d,propertyOptions:i,handlers:m}),Rce({card:n,task:e,plugin:t,displayText:i.displayText,isCompleted:c});let f=n.querySelector(".task-card__badge--blocked");f&&f.remove();let h=n.querySelector(".task-card__metadata");h&&J$({metadataLine:h,card:n,task:e,plugin:t,visibleProperties:r,propertyOptions:i,handlers:m})}function dHe(n){Ule(n)}async function zce(n,e,t,r){await q$(wM(t),n,e,r)}async function Bce(n,e,t,r){await Vle(wM(t),n,e,r)}async function jce(n,e,t,r){await Wle(wM(t),n,e,r)}async function uHe(n,e,t){await qle(wM(e),n,t)}var z2,Ua=y(()=>{oB();w$();ece();G$();U$();n2();l2();Q$();N2();_2();_ce();Lce();N2();z2={layout:"default",showSecondaryBadges:!0,enableHoverPreview:!0}});function B2({plugin:n,sourcePath:e},t){return{dependency:{uid:Ks(n.app,e,t.path,n.settings.useFrontmatterMarkdownLinks),reltype:Pi},path:t.path,name:t.basename}}function $ce({plugin:n,sourcePath:e},t){var s;let r=Ai(t);if(!r){let o=typeof t=="object"&&t&&"uid"in t&&typeof t.uid=="string"?t.uid:Y(t);return{dependency:{uid:o,reltype:Pi},name:o,unresolved:!0}}let a=Jo(n.app,e,r);if(a){let o=((s=a.file)==null?void 0:s.basename)||a.path.split("/").pop()||r.uid;return{dependency:r,path:a.path,name:o}}let i=r.uid.replace(/^\[\[/,"").replace(/\]\]$/,"");return{dependency:r,name:i||t.uid,unresolved:!0}}function Uce({plugin:n,sourcePath:e},t){let r=n.app.vault.getAbstractFileByPath(t);if(r instanceof AC.TFile)return B2({plugin:n,sourcePath:e},r);let i=(t.split("/").pop()||t).replace(/\.md$/i,"");return{dependency:{uid:`[[${i}]]`,reltype:Pi},path:t,name:i,unresolved:!0}}function pHe(n,e){return n.some(t=>t.dependency.uid===e.dependency.uid||!!e.path&&t.path===e.path)}function j2(n,e){return pHe(n,e)?[...n]:[...n,e]}function $2(n,e){return n.filter((t,r)=>r!==e)}async function Hce({plugin:n,listEl:e,items:t,linkServices:r,translate:a,onRemove:i}){if(e&&(e.empty(),t.length!==0))for(let[s,o]of t.entries()){let l=!!(o.path&&!o.unresolved),c=e.createDiv({cls:l?"task-project-item task-project-item--task-card":"task-project-item"});o.unresolved&&(c.addClass("task-project-item--unresolved"),(0,AC.setTooltip)(c,a("contextMenus.task.dependencies.notices.unresolved",{entries:o.dependency.uid}),{placement:"top"}));let d=c.createDiv({cls:l?"task-project-card-host":"task-project-info"});o.path&&!o.unresolved?await mHe(n,d,o,r):fHe(d,o);let u=c.createEl("button",{cls:"task-project-remove",text:"×"});(0,AC.setTooltip)(u,a("modals.task.dependencies.removeTaskTooltip"),{placement:"top"}),u.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),i(s)})}}async function mHe(n,e,t,r){if(!t.path)return;let a=await n.cacheManager.getCachedTaskInfo(t.path);if(a){let s=pr(a,n,void 0,{layout:"default",showSecondaryBadges:!1,enableHoverPreview:!1});e.appendChild(s);return}let i=e.createSpan({cls:"task-project-name clickable-dependency"});nl(i,t.path,t.name,r,{cssClass:"task-dependency-link internal-link",hoverSource:"tasknotes-dependency-link",showErrorNotices:!0}),t.path!==t.name&&e.createDiv({cls:"task-project-path",text:t.path})}function fHe(n,e){var a;let t=n.createSpan({cls:"task-project-name"});t.textContent=e.name;let r=(a=e.path)!=null?a:e.dependency.uid;n.createDiv({cls:"task-project-path",text:r})}function Vce(n,e,t){return Ks(n.app,e,t.path,n.settings.useFrontmatterMarkdownLinks)}function Wce({plugin:n,sourcePath:e,allTasks:t,existingItems:r,currentPath:a}){let i=new Set(r.map(s=>s.dependency.uid));return t.filter(s=>{if(a&&s.path===a)return!1;let o=Vce(n,e,s);return!i.has(o)})}function qce({plugin:n,sourcePath:e,allTasks:t,existingItems:r,currentPath:a}){let i=new Set(r.map(o=>o.path).filter(o=>typeof o=="string")),s=new Set(r.map(o=>o.dependency.uid));return t.filter(o=>{if(a&&o.path===a||i.has(o.path))return!1;let l=Vce(n,e,o);return!s.has(l)})}var AC,Gce=y(()=>{AC=require("obsidian");Zs();cp();Ua();dr()});function hHe(n){return parseInt(n)||0}function Yce(n,e){let t=null,r=new SM.Setting(e.container);if(r.settingEl.addClass("tn-task-modal__wide-text-setting"),r.setName(n.translate("modals.task.contextsLabel")).addText(a=>{a.setPlaceholder(n.translate("modals.task.contextsPlaceholder")).setValue(e.value).onChange(e.onChange),t=a.inputEl,n.attachMobileKeyboardScrollGuard(a.inputEl),new BA(n.app,a.inputEl,n.plugin)}),!t)throw new Error("Failed to create contexts input");return t}function Kce(n,e){let t=null,r=new SM.Setting(e.container);if(r.settingEl.addClass("tn-task-modal__wide-text-setting"),r.setName(n.translate("modals.task.tagsLabel")).addText(a=>{a.setPlaceholder(n.translate("modals.task.tagsPlaceholder")).setValue(e.value).onChange(i=>{e.onChange(ha(i))}),t=a.inputEl,n.attachMobileKeyboardScrollGuard(a.inputEl),new sp(n.app,a.inputEl,n.plugin)}),!t)throw new Error("Failed to create tags input");return t}function Zce(n,e){let t=null;if(new SM.Setting(e.container).setName(n.translate("modals.task.timeEstimateLabel")).addText(r=>{r.setPlaceholder(n.translate("modals.task.timeEstimatePlaceholder")).setValue(e.value.toString()).onChange(a=>{e.onChange(hHe(a))}),t=r.inputEl,n.attachMobileKeyboardScrollGuard(r.inputEl)}),!t)throw new Error("Failed to create time estimate input");return t}var SM,Qce=y(()=>{SM=require("obsidian");yt();aC()});function vp(n){return n==null?"":typeof n=="string"?n:typeof n=="number"||typeof n=="boolean"?String(n):Array.isArray(n)?n.map(vp).join(", "):""}function Xce(n){return Array.isArray(n)?n.map(vp).join(", "):vp(n)}function U2(n){return n.split(",").map(e=>e.trim()).filter(e=>e.length>0)}function ede(n){let e=U2(n);return e.length>0?e:null}function H2(n){let e=parseFloat(n);return isNaN(e)?null:e}function CM(n){return n||null}function V2(n){return n===!0||n==="true"}function tde(n){let e={};for(let[t,r]of Object.entries(n))r!=null&&r!==""&&(e[t]=r);return e}function rde(n,e,t){let r={};for(let a of t){if(!(a!=null&&a.key))continue;let i=n[a.key],s=e[a.key];gHe(i,s)&&(r[a.key]=i==null||i===""?null:i)}return r}function gHe(n,e){let t=Jce(n),r=Jce(e);return Array.isArray(t)||Array.isArray(r)?JSON.stringify(t)!==JSON.stringify(r):t!==r}function Jce(n){return n==null||n===""?null:n}var xM=y(()=>{});function nde(n,e){let{container:t,field:r,values:a,inputRefs:i,toggleRefs:s,onValueChange:o}=e,l=new qd.Setting(t).setName(r.displayName);switch(r.type){case"text":case"list":{l.addText(c=>{let d=a[r.key],u=Array.isArray(d)?d.map(vp).join(", "):vp(d);c.setValue(u).onChange(p=>{o(r.key,r.type==="list"?U2(p):p)}),Yf(n,i,r,c.inputEl)});break}case"number":{l.addText(c=>{let d=a[r.key];c.setValue(vp(d)).onChange(u=>{o(r.key,H2(u))}),c.inputEl.type="number",Yf(n,i,r,c.inputEl,{attachSuggest:!1})});break}case"date":{l.addText(c=>{let d=a[r.key];c.setValue(vp(d)).onChange(u=>{o(r.key,u)}),c.inputEl.type="date",ql(c.inputEl,{onCommit:u=>{o(r.key,u)}}),Yf(n,i,r,c.inputEl,{attachSuggest:!1})});break}case"boolean":{l.addToggle(c=>{let d=a[r.key];c.setValue(d===!0).onChange(u=>{o(r.key,u)}),s.set(r.key,c)});break}}}function ade(n,e){let{container:t,fields:r}=e;r.length>0&&t.createDiv({cls:"tn-task-modal__user-fields"}).createDiv({text:n.translate("modals.task.customFieldsLabel"),cls:"tn-task-modal__section-label"});for(let a of r)!a||!a.key||!a.displayName||yHe(n,e,a)}function ide(n){for(let e of n.fields){let t=n.values[e.key],r=n.inputRefs.get(e.key);r&&(r.value=Xce(t));let a=n.toggleRefs.get(e.key);a&&a.setValue(V2(t))}}function yHe(n,e,t){let r=e.values[t.key]||"";switch(t.type){case"boolean":new qd.Setting(e.container).setName(t.displayName).addToggle(a=>{a.setValue(V2(r)).onChange(i=>{e.onValueChange(t.key,i)}),e.toggleRefs.set(t.key,a)});break;case"number":new qd.Setting(e.container).setName(t.displayName).addText(a=>{a.setPlaceholder(n.translate("modals.task.userFields.numberPlaceholder")).setValue(r?Y(r):"").onChange(i=>{e.onValueChange(t.key,H2(i))}),Yf(n,e.inputRefs,t,a.inputEl,{attachSuggest:!1})});break;case"date":vHe(n,e,t,r);break;case"list":new qd.Setting(e.container).setName(t.displayName).addText(a=>{var o;let i=Array.isArray(r)?r.join(", "):r?Y(r):"";a.setPlaceholder(n.translate("modals.task.userFields.listPlaceholder")).setValue(i).onChange(l=>{e.onValueChange(t.key,ede(l))}),Yf(n,e.inputRefs,t,a.inputEl);let s=e.container.querySelector(".user-field-link-preview");s&&((o=s.detach)==null||o.call(s))});break;case"text":default:new qd.Setting(e.container).setName(t.displayName).addText(a=>{a.setPlaceholder(n.translate("modals.task.userFields.textPlaceholder",{field:t.displayName})).setValue(r?Y(r):"").onChange(i=>{e.onValueChange(t.key,CM(i))}),Yf(n,e.inputRefs,t,a.inputEl)});break}}function vHe(n,e,t,r){new qd.Setting(e.container).setName(t.displayName).addText(a=>{a.setPlaceholder(n.translate("modals.task.userFields.datePlaceholder")).setValue(r?Y(r):"").onChange(o=>{e.onValueChange(t.key,CM(o))}),Yf(n,e.inputRefs,t,a.inputEl,{attachSuggest:!1});let i=a.inputEl.parentElement;i&&i.addClass("tn-date-control"),ql(a.inputEl,{onCommit:o=>{e.onValueChange(t.key,o)}});let s=i==null?void 0:i.createEl("button",{cls:"user-field-date-picker-btn"});s&&(s.setAttribute("aria-label",n.translate("modals.task.userFields.pickDate",{field:t.displayName})),(0,qd.setIcon)(s,"calendar"),s.addEventListener("click",o=>{o.preventDefault(),new oo(n.app,{currentDate:kHe(a)||null,title:n.translate("modals.task.userFields.pickDate",{field:t.displayName}),showTime:!1,plugin:n.plugin,onSelect:c=>{a.setValue(c||""),e.onValueChange(t.key,CM(c))}}).open()}))})}function Yf(n,e,t,r,a={}){e.set(t.key,r),n.attachMobileKeyboardScrollGuard(r),a.attachSuggest!==!1&&new jA(n.app,r,n.plugin,t)}function kHe(n){return typeof n.getValue=="function"?n.getValue():n.inputEl.value}var qd,sde=y(()=>{qd=require("obsidian");$y();rC();dr();aC();xM()});function EM(n,e){var i;let t=e.container.createDiv("modal-button-container tn-task-modal__button-bar");for(let s of(i=e.leadingButtons)!=null?i:[])t.createEl("button",{cls:s.className,text:s.text}).addEventListener("click",s.onClick);let r=t.createEl("button",{cls:"mod-cta",text:n.translate("modals.task.buttons.save")});return r.addEventListener("click",()=>{THe(r,e.onSave,e.onSaved)}),t.createEl("button",{text:n.translate("common.cancel")}).addEventListener("click",e.onCancel),t}async function THe(n,e,t){n.disabled=!0;try{await e(),t()}finally{n.disabled=!1}}var W2=y(()=>{});function q2(n,e){let t=n.createDiv("action-icon");t.setAttribute("aria-label",e.tooltip),t.setAttribute("data-initial-tooltip",e.tooltip),t.setAttribute("tabindex","0"),t.setAttribute("role","button"),e.dataType&&t.setAttribute("data-type",e.dataType),(0,DM.setTooltip)(t,e.tooltip,{placement:"top"});let r=t.createSpan("icon");(0,DM.setIcon)(r,e.iconName);let a=i=>{i.preventDefault(),i.stopPropagation(),e.onClick(t,i)};return t.addEventListener("click",a),t.addEventListener("keydown",i=>{(i.key==="Enter"||i.key===" ")&&a(i)}),t}function ode(n,e){return e.map(t=>q2(n,t))}var DM,lde=y(()=>{DM=require("obsidian")});function dde(n,e,t){n&&(cde(n,e,"due-date",t.dueDate,{activeTooltipKey:"modals.task.tooltips.dueValue",defaultTooltipKey:"modals.task.actions.due"}),cde(n,e,"scheduled-date",t.scheduledDate,{activeTooltipKey:"modals.task.tooltips.scheduledValue",defaultTooltipKey:"modals.task.actions.scheduled"}),wHe(n,e,t),SHe(n,e,t),CHe(n,e,t),xHe(n,e,t.reminderCount))}function cde(n,e,t,r,a){let i=MC(n,t);if(i){if(r){i.classList.add("has-value"),(0,Gd.setTooltip)(i,e.translate(a.activeTooltipKey,{value:r}),{placement:"top"});return}i.classList.remove("has-value"),(0,Gd.setTooltip)(i,e.translate(a.defaultTooltipKey),{placement:"top"})}}function wHe(n,e,t){let r=MC(n,"status");if(!r)return;let a=t.statusConfigs.find(s=>s.value===t.status),i=a?a.label:t.status;ude(r,e,{isActive:!!(t.status&&a&&a.value!==t.defaultStatus),activeTooltipKey:"modals.task.tooltips.statusValue",defaultTooltipKey:"modals.task.actions.status",label:i,color:a==null?void 0:a.color})}function SHe(n,e,t){let r=MC(n,"priority");if(!r)return;let a=t.priorityConfigs.find(s=>s.value===t.priority),i=a?a.label:t.priority;ude(r,e,{isActive:!!(t.priority&&a&&a.value!==t.defaultPriority),activeTooltipKey:"modals.task.tooltips.priorityValue",defaultTooltipKey:"modals.task.actions.priority",label:i,color:a==null?void 0:a.color})}function ude(n,e,t){t.isActive?(n.classList.add("has-value"),(0,Gd.setTooltip)(n,e.translate(t.activeTooltipKey,{value:t.label}),{placement:"top"})):(n.classList.remove("has-value"),(0,Gd.setTooltip)(n,e.translate(t.defaultTooltipKey),{placement:"top"}));let r=n.querySelector(".icon");if(r){if(t.color){r.style.color=t.color;return}r.classList.remove(...bHe),r.style.removeProperty("color")}}function CHe(n,e,t){let r=MC(n,"recurrence");if(r){if(t.recurrenceRule.trim()){r.classList.add("has-value"),(0,Gd.setTooltip)(r,e.translate("modals.task.tooltips.recurrenceValue",{value:t.recurrenceDisplayText}),{placement:"top"});return}r.classList.remove("has-value"),(0,Gd.setTooltip)(r,e.translate("modals.task.actions.recurrence"),{placement:"top"})}}function xHe(n,e,t){let r=MC(n,"reminders");if(r){if(t>0){r.classList.add("has-value");let a=t===1?e.translate("modals.task.tooltips.remindersSingle"):e.translate("modals.task.tooltips.remindersPlural",{count:t});(0,Gd.setTooltip)(r,a,{placement:"top"});return}r.classList.remove("has-value"),(0,Gd.setTooltip)(r,e.translate("modals.task.actions.reminders"),{placement:"top"})}}function MC(n,e){return n.querySelector(`[data-type="${e}"]`)}var Gd,bHe,pde=y(()=>{Gd=require("obsidian"),bHe=["tn-static-color-var-color-accent-d2cad743","tn-static-color-var-text-accent-65b47ee3","tn-static-color-var-text-muted-5872de20","tn-static-color-var-text-on-accent-f3e1679d","tn-static-color-var-text-warning-783d5f03","tn-static-color-var-tn-text-muted-a90fb6f3","tn-static-color-white-0a43e56a","tn-static-cursor-pointer-2723efcc","tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-2px-0-edce9b14","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c"]});function mde(n){return!n||n.length===0?"open":[...n].sort((t,r)=>t.order-r.order)[0].value}function fde(n){return!n||n.length===0?"normal":[...n].sort((t,r)=>t.weight-r.weight)[0].value}function hde(n){return n?n.includes("FREQ=DAILY")?"Daily":n.includes("FREQ=WEEKLY")?PHe(n):n.includes("FREQ=MONTHLY")?AHe(n):n.includes("FREQ=YEARLY")?MHe(n):`Custom${IHe(n)}`:""}function gde(n){let e=["th","st","nd","rd"],t=n%100;return n+(e[(t-20)%10]||e[t]||e[0])}function PHe(n){if(n.includes("INTERVAL=2"))return"Every 2 weeks";if(n.includes("BYDAY=MO,TU,WE,TH,FR"))return"Weekdays";if(!n.includes("BYDAY="))return"Weekly";let e=n.match(/BYDAY=([A-Z]{2})/);return e?`Weekly on ${EHe[e[1]]||e[1]}`:"Weekly"}function AHe(n){if(n.includes("INTERVAL=3"))return"Every 3 months";if(n.includes("BYMONTHDAY=")){let e=n.match(/BYMONTHDAY=(\d+)/);return e?`Monthly on the ${gde(Number.parseInt(e[1],10))}`:"Monthly"}return n.includes("BYDAY=")?"Monthly (by weekday)":"Monthly"}function MHe(n){if(n.includes("BYMONTH=")&&n.includes("BYMONTHDAY=")){let e=n.match(/BYMONTH=(\d+)/),t=n.match(/BYMONTHDAY=(\d+)/);if(e&&t){let r=DHe[Number.parseInt(e[1],10)],a=gde(Number.parseInt(t[1],10));return`Yearly on ${r} ${a}`}}return"Yearly"}function IHe(n){if(n.includes("COUNT=")){let e=n.match(/COUNT=(\d+)/);return e?` (${e[1]} times)`:""}if(n.includes("UNTIL=")){let e=n.match(/UNTIL=(\d{8})/);if(e){let t=e[1];return` (until ${t.slice(0,4)}-${t.slice(4,6)}-${t.slice(6,8)})`}}return""}var EHe,DHe,yde=y(()=>{EHe={SU:"Sunday",MO:"Monday",TU:"Tuesday",WE:"Wednesday",TH:"Thursday",FR:"Friday",SA:"Saturday"},DHe=["","January","February","March","April","May","June","July","August","September","October","November","December"]});function vde(n){return{title:n.title,status:n.status,priority:n.priority,dueDate:n.dueDate,scheduledDate:n.scheduledDate,recurrenceRule:n.recurrenceRule,recurrenceAnchor:n.recurrenceAnchor,reminders:n.reminders||[]}}function kde(n){return{app:n.app,plugin:n.plugin,translate:n.translate,getState:n.getState,setDate:(e,t)=>{if(e==="due"){n.setDueDate(t);return}n.setScheduledDate(t)},setStatus:n.setStatus,setPriority:n.setPriority,setRecurrence:(e,t)=>{n.setRecurrenceRule(e),t!==void 0&&n.setRecurrenceAnchor(t)},setReminders:n.setReminders,onChange:n.onChange}}function Tde(n,e){let t=e.statusConfigs||[],r=e.priorityConfigs||[];return{dueDate:n.dueDate,scheduledDate:n.scheduledDate,status:n.status,priority:n.priority,recurrenceRule:n.recurrenceRule,recurrenceDisplayText:hde(n.recurrenceRule),reminderCount:n.reminders.length,defaultStatus:mde(t),defaultPriority:fde(r),statusConfigs:t,priorityConfigs:r}}var bde=y(()=>{yde()});var PM,wde=y(()=>{Jy();Md();Id();PM=class{constructor(e,t,r,a){this.plugin=e,this.task=t,this.triggerElement=r,this.onUpdate=a}show(e){let t=new ra;this.addQuickRemindersSection(t,"due",this.plugin.i18n.translate("components.reminderContextMenu.remindBeforeDue")),this.addQuickRemindersSection(t,"scheduled",this.plugin.i18n.translate("components.reminderContextMenu.remindBeforeScheduled")),t.addSeparator(),t.addItem(r=>{r.setTitle(this.plugin.i18n.translate("components.reminderContextMenu.manageAllReminders")).setIcon("settings").onClick(()=>{this.openReminderModal()})}),this.task.reminders&&this.task.reminders.length>0&&t.addItem(r=>{r.setTitle(this.plugin.i18n.translate("components.reminderContextMenu.clearAllReminders")).setIcon("trash").onClick(async()=>{await this.clearAllReminders()})}),za(t,e)}addQuickRemindersSection(e,t,r){if(!(t==="due"?this.task.due:this.task.scheduled)){e.addItem(i=>{i.setTitle(r).setIcon("bell").setDisabled(!0)});return}e.addItem(i=>{i.setTitle(r),i.setIcon("bell"),this.addQuickReminderSubmenu(i.setSubmenu(),t)})}addQuickReminderSubmenu(e,t){[{label:this.plugin.i18n.translate("components.reminderContextMenu.quickReminders.atTime"),offset:"PT0M"},{label:this.plugin.i18n.translate("components.reminderContextMenu.quickReminders.fiveMinutesBefore"),offset:"-PT5M"},{label:this.plugin.i18n.translate("components.reminderContextMenu.quickReminders.fifteenMinutesBefore"),offset:"-PT15M"},{label:this.plugin.i18n.translate("components.reminderContextMenu.quickReminders.oneHourBefore"),offset:"-PT1H"},{label:this.plugin.i18n.translate("components.reminderContextMenu.quickReminders.oneDayBefore"),offset:"-P1D"}].forEach(a=>{e.addItem(i=>{i.setTitle(a.label).onClick(async()=>{await this.addQuickReminder(t,a.offset,a.label)})})})}async addQuickReminder(e,t,r){let a={id:`rem_${Date.now()}`,type:"relative",relatedTo:e,offset:t,description:r},i=[...this.task.reminders||[],a];await this.saveReminders(i)}async clearAllReminders(){await this.saveReminders([])}async saveReminders(e){let t;if(this.task.path&&this.task.path.trim()!==""){let r=await this.plugin.cacheManager.getTaskInfo(this.task.path);r?(t={...r,reminders:e},await this.plugin.taskService.updateProperty(t,"reminders",e)):t={...this.task,reminders:e}}else t={...this.task,reminders:e};this.onUpdate(t)}openReminderModal(){new sl(this.plugin.app,this.plugin,this.task,t=>{this.saveReminders(t)}).open()}}});var AM,Sde=y(()=>{Md();Id();AM=class{constructor(e){this.targetDoc=activeDocument;this.menu=new ra,this.options=e,this.buildMenu()}buildMenu(){this.getStatusOptions().forEach((t,r)=>{this.menu.addItem(a=>{let i=t.label;a.setIcon(t.icon||"circle"),t.value===this.options.currentValue&&(i=`✓ ${t.label}`),a.setTitle(i),a.onClick(async()=>{this.options.onSelect(t.value)})})})}getStatusOptions(){let e=this.options.plugin.settings.customStatuses,t=[];return e&&e.length>0&&[...e].sort((a,i)=>a.order-i.order).forEach(a=>{t.push({label:a.label,value:a.value,color:a.color,icon:a.icon})}),t}capitalizeFirst(e){return e.charAt(0).toUpperCase()+e.slice(1)}show(e){var t,r;(r=(t=e.target)==null?void 0:t.instanceOf)!=null&&r.call(t,HTMLElement)&&(this.targetDoc=e.target.ownerDocument),za(this.menu,e),window.setTimeout(()=>{this.applyColorStyling()},10)}showAtElement(e){this.targetDoc=e.ownerDocument,jl(this.menu,e),window.setTimeout(()=>{this.applyColorStyling()},10)}applyColorStyling(){let e=this.getStatusOptions(),t=this.targetDoc.querySelector(".menu");if(!t)return;let r=t.querySelectorAll(".menu-item");e.forEach((a,i)=>{let s=r[i];if(s&&a.color){let o=s.querySelector(".menu-item-icon");o&&(o.style.color=a.color)}})}}});function Cde(n,e){let t=_He(n.getState(),e);new oo(n.app,{currentDate:t?re(t):void 0,currentTime:t?si(t):void 0,title:FHe(n,e),dateRole:e,plugin:n.plugin,onSelect:(a,i)=>{n.setDate(e,NHe(a,i)),n.onChange()}}).open()}function xde(n,e){new AM({currentValue:n.getState().status,onSelect:r=>{n.setStatus(r),n.onChange()},plugin:n.plugin}).show(e)}function Ede(n,e){new Ud({currentValue:n.getState().priority,onSelect:r=>{n.setPriority(r),n.onChange()},plugin:n.plugin}).show(e)}function Dde(n,e){let t=n.getState();new il({currentValue:t.recurrenceRule,currentAnchor:t.recurrenceAnchor,scheduledDate:t.scheduledDate,onSelect:(a,i)=>{n.setRecurrence(a||"",i),n.onChange()},app:n.app,plugin:n.plugin}).show(e)}function MM(n,e,t){new PM(n.plugin,RHe(n.getState(),t),e.target,a=>{n.setReminders(a.reminders||[]),n.onChange()}).show(e)}function NHe(n,e){return n?e?fa(n,e):n:""}function RHe(n,e){return{...e,title:n.title,status:n.status,priority:n.priority,due:n.dueDate,scheduled:n.scheduledDate,path:(e==null?void 0:e.path)||"",archived:(e==null?void 0:e.archived)||!1,reminders:n.reminders}}function _He(n,e){return e==="due"?n.dueDate:n.scheduledDate}function FHe(n,e){return e==="due"?n.translate("modals.task.dateMenu.dueTitle"):n.translate("modals.task.dateMenu.scheduledTitle")}var G2=y(()=>{fC();Qy();wde();Sde();xe();$y()});function IM(n,e){return{file:n,name:n.basename,link:e}}function Mde(n,e,t){let r=[...n];for(let a of e){let i=LHe(a,t);!i||Y2(r,i)||r.push(i)}return r}function Ide(n,e){return n.filter(t=>t!==e)}function Nde(n){return n.map(e=>e.link).join(", ")}function LHe(n,e){if(!n||typeof n!="string"||n.trim()==="")return null;let t=n.match(/^\[\[([^\]]+)\]\]$/);if(t)return zHe(n,t[1],e);let r=n.match(/^\[([^\]]*)\]\(([^)]+)\)$/);return r?BHe(n,r,e):jHe(n,e)}function Y2(n,e){let t=Pde(e);return n.some(r=>{let a=Pde(r);return t.some(i=>a.includes(i))})}function Pde(n){var r;let e=new Set;(r=n.file)!=null&&r.path&&e.add(`path:${Ade(n.file.path)}`);let t=vt(n.link);return t&&e.add(`path:${Ade(t)}`),n.link&&e.add(`link:${n.link.trim().toLowerCase()}`),Array.from(e)}function Ade(n){return n.trim().replace(/\.md$/i,"").toLowerCase()}function Rde({app:n,listEl:e,items:t,sourcePath:r,translate:a,onRemove:i}){if(!e||(e.empty(),t.length===0))return;let s={metadataCache:n.metadataCache,workspace:n.workspace};for(let o of t){let l=e.createDiv({cls:"task-project-item"});o.unresolved&&l.addClass("task-project-item--unresolved");let c=l.createDiv({cls:"task-project-info"}),d=c.createDiv({cls:"task-project-name clickable-project"});if(o.file){let p=H0(n,o.file,r,o.file.name);OHe(d,[p],s),o.file.path!==o.file.name&&c.createDiv({cls:"task-project-path",text:o.file.path})}else d.textContent=o.name,(0,hv.setTooltip)(d,a("contextMenus.task.dependencies.notices.unresolved",{name:o.name}),{placement:"top"});let u=l.createEl("button",{cls:"task-project-remove",text:"×"});(0,hv.setTooltip)(u,a("modals.task.projectsRemoveTooltip"),{placement:"top"}),u.addEventListener("click",()=>{i(o)})}}function OHe(n,e,t){Ky(n,e,t),Array.from(n.childNodes).forEach(r=>{var a;r.nodeType===Node.TEXT_NODE&&((a=r.textContent)==null?void 0:a.trim())==="+"&&r.remove()})}function zHe(n,e,t){let r=t.resolveLink(e,t.sourcePath);return r instanceof hv.TFile?IM(r,n):{name:e.split("|")[0],link:n,unresolved:!0}}function BHe(n,e,t){let r=vt(n),a=t.resolveLink(r,t.sourcePath);return a instanceof hv.TFile?IM(a,n):{name:e[1]||r,link:n,unresolved:!0}}function jHe(n,e){let t=e.getMarkdownFiles().find(r=>r.basename===n||r.name===`${n}.md`);return t?{file:t,name:t.basename,link:`[[${t.basename}]]`}:{name:n,link:n,unresolved:!0}}var hv,_de=y(()=>{hv=require("obsidian");cp();Cn()});function Fde(n,e,t){let r=new Set(e.map(a=>a.path));return n.filter(a=>t&&a.path===t?!1:!r.has(a.path))}function Lde(n,e){return $He(n,e)?[...n]:[...n,e]}function Ode(n,e){return n.filter(t=>t.path!==e.path)}function $He(n,e){return n.some(t=>t.path===e.path)}async function zde({app:n,listEl:e,files:t,sourcePath:r,getCachedTaskInfo:a,createTaskCard:i,translate:s,onRemove:o}){if(!e||(e.empty(),t.length===0))return;let l={metadataCache:n.metadataCache,workspace:n.workspace};for(let c of t){if(!(c instanceof NM.TFile))return;let d=e.createDiv({cls:"task-project-item task-project-item--task-card"}),u=d.createDiv({cls:"task-project-card-host"}),p=await a(c.path);p?u.appendChild(i(p)):UHe(n,u,c,r,l);let m=d.createEl("button",{cls:"task-project-remove",text:"×"});(0,NM.setTooltip)(m,s("modals.task.organization.removeSubtaskTooltip"),{placement:"top"}),m.addEventListener("click",()=>{o(c)})}}function UHe(n,e,t,r,a){let i=e.createDiv({cls:"task-project-info"}),s=i.createDiv({cls:"task-project-name clickable-project"}),o=H0(n,t,r,t.name);HHe(s,[o],a),t.path!==t.name&&i.createDiv({cls:"task-project-path",text:t.path})}function HHe(n,e,t){Ky(n,e,t),Array.from(n.childNodes).forEach(r=>{var a;r.nodeType===Node.TEXT_NODE&&((a=r.textContent)==null?void 0:a.trim())==="+"&&r.remove()})}var NM,Bde=y(()=>{NM=require("obsidian");cp();Cn()});async function RM({plugin:n,getAllTasks:e=async()=>{var p,m,f;return(f=await((m=(p=n.cacheManager).getAllTasks)==null?void 0:m.call(p)))!=null?f:[]},getCandidates:t,onSelect:r,translate:a,noEligibleTasksMessageKey:i,openFailedMessageKey:s,logOperation:o,openSelector:l=fn,selectorOptions:c,showNotice:d=p=>{new jde.Notice(p)},logger:u=VHe}){var p;try{let m=(p=await e())!=null?p:[],f=[...t(m)];if(f.length===0)return d(a(i)),"empty";let h=g=>{g&&r(g)};return c?l(n,f,h,c):l(n,f,h),"opened"}catch(m){return u.error("Failed to open task selector",{category:"stale-data",operation:o,error:m}),d(a(s)),"error"}}var jde,VHe,$de=y(()=>{jde=require("obsidian");q();co();VHe=M({tag:"TaskModal/TaskSelector"})});function Vde({container:n,className:e,placeholder:t,value:r,onChange:a,attachFocusScrollGuard:i}){let s=n.createEl("textarea",{cls:e});return s.placeholder=t,s.rows=1,s.spellcheck=!0,s.setAttribute("aria-label",t),s.addEventListener("keydown",o=>{o.key==="Enter"&&!o.ctrlKey&&!o.metaKey&&o.preventDefault()}),WHe(s,{value:r,onChange:a,attachFocusScrollGuard:i}),s}function WHe(n,{value:e,onChange:t,attachFocusScrollGuard:r}){n.value=e,n.addEventListener("input",a=>{let i=a.target,s=qHe(i.value);i.value!==s&&(i.value=s),t(s),Ude(i)}),r==null||r(n),Ude(n)}function qHe(n){return n.replace(/\s*\n+\s*/g," ")}function Ude(n){var u;let e=n.ownerDocument.defaultView,t=(u=e==null?void 0:e.HTMLTextAreaElement)!=null?u:HTMLTextAreaElement;if(!(n instanceof t))return;let r=e==null?void 0:e.getComputedStyle(n),a=r?Number.parseFloat(r.lineHeight):0,i=r&&Number.parseFloat(r.paddingTop)||0,s=r&&Number.parseFloat(r.paddingBottom)||0,o=r&&Number.parseFloat(r.borderTopWidth)||0,l=r&&Number.parseFloat(r.borderBottomWidth)||0,c=(a>0?a*3:72)+i+s+o+l;Hde(n,{"--tn-task-modal-title-height":"auto"});let d=Math.min(n.scrollHeight,c);Hde(n,{"--tn-task-modal-title-height":`${d}px`,"--tn-task-modal-title-overflow-y":n.scrollHeight>c?"auto":"hidden"})}function Hde(n,e){if(typeof n.setCssProps=="function"){n.setCssProps(e);return}for(let[t,r]of Object.entries(e))n.style.setProperty(t,r)}var Wde=y(()=>{});function LM({detailsContainer:n,splitRightColumn:e}){FM(n),n.classList.add(_M),e&&(FM(e),e.classList.add(_M))}function Qde({containerEl:n,detailsContainer:e,splitRightColumn:t,timerWindow:r}){var i;FM(e,_M),e.classList.add(YHe),n.classList.add("expanded"),t&&(FM(t,_M),t.style.removeProperty("display")),e.classList.remove(Gde,Yde),e.classList.add(qde),e.classList.remove(Zde),e.classList.add(Kde),((i=r!=null?r:e.ownerDocument.defaultView)!=null?i:window).setTimeout(()=>{e.classList.remove(Gde,qde),e.classList.add(Yde),e.classList.remove(Kde),e.classList.add(Zde)},50)}function FM(n,...e){n.classList.remove(...GHe,...e)}var GHe,_M,YHe,qde,Gde,Yde,Kde,Zde,K2=y(()=>{GHe=["tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-min-height-800px-997b4c8c"],_M="tn-static-display-none-6b99de8b",YHe="tn-static-display-block-2a1b75c9",qde="tn-static-opacity-0-8d919cb5",Gde="tn-static-opacity-0-6-d95b59ac",Yde="tn-static-opacity-1-c6e7979d",Kde="tn-static-transform-translatey-10px-5b91bf02",Zde="tn-static-transform-translatey-0-1b976432"});function Z2(n,e){var t;return((t=n.instanceOf)==null?void 0:t.call(n,e))===!0||Object.prototype.isPrototypeOf.call(e.prototype,n)}var OM,Jde=y(()=>{OM=class{constructor(e){this.guardedTitleInputs=new WeakSet;this.guardedMobileKeyboardInputs=new WeakSet;this.pendingTitleFocusScrollPositions=null;this.mobileKeyboardFocusCleanups=[];this.mobileKeyboardScrollTimers=[];this.activeMobileKeyboardInput=null;this.elements=e}focusTitleInput(e){this.getWindow().setTimeout(()=>{this.pendingTitleFocusScrollPositions=this.captureTitleFocusScrollPositions(e),e.focus({preventScroll:!0}),e.select(),this.restoreTitleFocusScrollPositions(this.pendingTitleFocusScrollPositions)},this.getInitialFocusDelay())}getInitialFocusDelay(){return this.isMobileLikeEnvironment()?350:100}isMobileLikeEnvironment(){var r,a;let e=this.elements.containerEl.ownerDocument,t=e.defaultView||window;return e.body.classList.contains("is-mobile")||((a=(r=t.matchMedia)==null?void 0:r.call(t,"(pointer: coarse)"))==null?void 0:a.matches)===!0}attachTitleFocusScrollGuard(e){if(this.guardedTitleInputs.has(e))return;this.guardedTitleInputs.add(e);let t=()=>{this.pendingTitleFocusScrollPositions=this.captureTitleFocusScrollPositions(e)};e.addEventListener("pointerdown",t,{capture:!0}),e.addEventListener("touchstart",t,{capture:!0}),e.addEventListener("focus",()=>{this.pendingTitleFocusScrollPositions&&this.scheduleTitleFocusScrollRestore(this.pendingTitleFocusScrollPositions)})}attachMobileKeyboardScrollGuard(e,t={}){var l,c;if(this.guardedMobileKeyboardInputs.has(e))return;this.guardedMobileKeyboardInputs.add(e);let r=(l=t.scrollOnFocus)!=null?l:!0,a=d=>{if(!this.isMobileLikeEnvironment())return;let u=d.target;this.activeMobileKeyboardInput=u,this.elements.containerEl.addClass("is-mobile-keyboard-focused"),r&&this.scheduleMobileKeyboardScrollIntoView(u)},i=(c=e.ownerDocument.defaultView)==null?void 0:c.visualViewport,s=()=>{let d=this.activeMobileKeyboardInput;r&&d&&e.contains(d)&&this.scheduleMobileKeyboardScrollIntoView(d)},o=()=>{let u=(e.ownerDocument.defaultView||window).setTimeout(()=>{this.mobileKeyboardScrollTimers=this.mobileKeyboardScrollTimers.filter(m=>m!==u);let p=e.ownerDocument.activeElement;(!p||!this.elements.modalEl.contains(p)||!this.isKeyboardTextEntryElement(p))&&(this.activeMobileKeyboardInput=null,this.elements.containerEl.removeClass("is-mobile-keyboard-focused"))},100);this.mobileKeyboardScrollTimers.push(u)};e.addEventListener("focus",a,!0),e.addEventListener("blur",o,!0),i==null||i.addEventListener("resize",s),this.mobileKeyboardFocusCleanups.push(()=>{e.removeEventListener("focus",a,!0),e.removeEventListener("blur",o,!0),i==null||i.removeEventListener("resize",s)})}destroy(){for(let t of this.mobileKeyboardFocusCleanups)t();this.mobileKeyboardFocusCleanups=[];let e=this.getWindow();for(let t of this.mobileKeyboardScrollTimers)e.clearTimeout(t);this.mobileKeyboardScrollTimers=[],this.activeMobileKeyboardInput=null,this.elements.containerEl.removeClass("is-mobile-keyboard-focused"),this.pendingTitleFocusScrollPositions=null}captureTitleFocusScrollPositions(e){if(!this.isMobileLikeEnvironment())return null;let t=new Set,r=i=>{var l;let s=i==null?void 0:i.ownerDocument.defaultView,o=(l=s==null?void 0:s.HTMLElement)!=null?l:HTMLElement;i instanceof o&&t.add(i)};r(this.elements.containerEl),r(this.elements.modalEl),r(this.elements.contentEl),this.elements.modalEl.querySelectorAll(".modal-content, .minimalist-modal-container, .modal-split-content, .modal-split-left, .modal-split-right, .details-container").forEach(r);let a=e.parentElement;for(;a&&a!==this.elements.containerEl.parentElement;)r(a),a=a.parentElement;return Array.from(t).map(i=>({element:i,scrollTop:i.scrollTop,scrollLeft:i.scrollLeft}))}restoreTitleFocusScrollPositions(e){if(e)for(let{element:t,scrollTop:r,scrollLeft:a}of e)t.scrollTop=r,t.scrollLeft=a}scheduleTitleFocusScrollRestore(e){this.restoreTitleFocusScrollPositions(e);let t=this.getWindow();t.requestAnimationFrame?t.requestAnimationFrame(()=>this.restoreTitleFocusScrollPositions(e)):t.setTimeout(()=>this.restoreTitleFocusScrollPositions(e),16),t.setTimeout(()=>this.restoreTitleFocusScrollPositions(e),50),t.setTimeout(()=>{this.restoreTitleFocusScrollPositions(e),this.pendingTitleFocusScrollPositions===e&&(this.pendingTitleFocusScrollPositions=null)},250)}isKeyboardTextEntryElement(e){var o,l,c;let t=e.ownerDocument.defaultView||window,r=(o=t.HTMLInputElement)!=null?o:HTMLInputElement,a=(l=t.HTMLTextAreaElement)!=null?l:HTMLTextAreaElement,i=(c=t.HTMLElement)!=null?c:HTMLElement;return Z2(e,i)&&e.isContentEditable||Z2(e,a)?!0:Z2(e,r)?!new Set(["button","checkbox","color","file","hidden","radio","range","reset","submit"]).has(e.type):!1}scheduleMobileKeyboardScrollIntoView(e){let t=e.ownerDocument.defaultView||window;for(let r of[0,150,350]){let a=t.setTimeout(()=>{this.mobileKeyboardScrollTimers=this.mobileKeyboardScrollTimers.filter(i=>i!==a),this.activeMobileKeyboardInput===e&&this.scrollMobileKeyboardTargetIntoView(e)},r);this.mobileKeyboardScrollTimers.push(a)}}scrollMobileKeyboardTargetIntoView(e){var r;if(!this.isMobileLikeEnvironment())return;let t=(r=e.closest(".setting-item"))!=null?r:e;t.scrollIntoView({block:"nearest",inline:"nearest",behavior:"auto"}),this.nudgeFocusedFieldInsideVisualViewport(t)}nudgeFocusedFieldInsideVisualViewport(e){var d,u,p;let t=e.ownerDocument.defaultView||window,r=t.visualViewport,a=r&&Number.isFinite(r.height)?r.offsetTop+r.height:t.innerHeight;if(!Number.isFinite(a)||a<=0)return;let i=(u=(d=e.closest(".modal-split-content"))!=null?d:e.closest(".modal-content"))!=null?u:this.elements.contentEl,s=e.getBoundingClientRect(),o=i.getBoundingClientRect(),l=Math.max((p=r==null?void 0:r.offsetTop)!=null?p:0,o.top)+24,c=Math.min(a,o.bottom)-24;s.bottom>c?i.scrollTop+=s.bottom-c:s.top{gv=require("obsidian");Y1();WX();nz();yt();py();Zs();Cn();pre();Ua();Gce();Qce();sde();W2();lde();pde();bde();G2();_de();Bde();$de();vC();Wde();K2();Jde();q();KHe=M({tag:"Modals/TaskModal"}),yv=class extends gv.Modal{constructor(t,r){super(t);this.keyboardHandler=null;this.title="";this.details="";this.originalDetails="";this.dueDate="";this.scheduledDate="";this.priority="normal";this.status="open";this.contexts="";this.projects="";this.tags="";this.timeEstimate=0;this.recurrenceRule="";this.recurrenceAnchor="scheduled";this.reminders=[];this.userFields={};this.userFieldInputs=new Map;this.userFieldToggles=new Map;this.blockedByItems=[];this.blockingItems=[];this.blockedByList=void 0;this.blockingList=void 0;this.selectedProjectItems=[];this.selectedSubtaskFiles=[];this.initialSubtaskFiles=[];this.titleInput=void 0;this.detailsInput=void 0;this.detailsMarkdownEditor=null;this.contextsInput=void 0;this.projectsInput=void 0;this.tagsInput=void 0;this.timeEstimateInput=void 0;this.projectsList=void 0;this.subtasksList=void 0;this.actionBar=void 0;this.detailsContainer=void 0;this.isExpanded=!1;this.splitRightColumn=void 0;this.plugin=r,this.focusGuards=new OM({containerEl:this.containerEl,modalEl:this.modalEl,contentEl:this.contentEl})}createDependencyItemFromFile(t,r={}){var a;return B2({plugin:this.plugin,sourcePath:(a=r.sourcePath)!=null?a:this.getDependencySourcePath()},t)}createDependencyItemFromDependency(t,r){return $ce({plugin:this.plugin,sourcePath:r!=null?r:this.getDependencySourcePath()},t)}createDependencyItemFromPath(t){return Uce({plugin:this.plugin,sourcePath:this.getDependencySourcePath()},t)}getDependencySourcePath(){var t;return this.getCurrentTaskPath()||((t=this.plugin.app.workspace.getActiveFile())==null?void 0:t.path)||""}getCurrentTaskPath(){}getModalEditorFile(){let t=this.getCurrentTaskPath();if(!t)return this.app.workspace.getActiveFile();let r=this.app.vault.getAbstractFileByPath(t);return r instanceof gv.TFile?r:this.app.workspace.getActiveFile()}async openTaskNote(){}renderDependencyLists(){this.renderBlockedByList(),this.renderBlockingList()}getLinkServices(){var t;return{metadataCache:this.plugin.app.metadataCache,workspace:this.plugin.app.workspace,sourcePath:this.getCurrentTaskPath()||((t=this.plugin.app.workspace.getActiveFile())==null?void 0:t.path)||""}}renderBlockedByList(){this.renderDependencyList(this.blockedByList,this.blockedByItems,t=>{this.blockedByItems=$2(this.blockedByItems,t),this.renderBlockedByList()})}renderBlockingList(){this.renderDependencyList(this.blockingList,this.blockingItems,t=>{this.blockingItems=$2(this.blockingItems,t),this.renderBlockingList()})}async renderDependencyList(t,r,a){t&&await Hce({plugin:this.plugin,listEl:t,items:r,linkServices:this.getLinkServices(),translate:(i,s)=>this.t(i,s),onRemove:a})}extractDetailsFromContent(t){let{body:r}=Gu(t);return r.replace(/\r\n/g,` +`).trimEnd()}normalizeDetails(t){return t.replace(/\r\n/g,` +`).trimEnd()}addBlockedByTask(t){let r={uid:Ks(this.plugin.app,this.getDependencySourcePath(),t.path,this.plugin.settings.useFrontmatterMarkdownLinks),reltype:Pi};this.addBlockedByDependency(r)}addBlockingTask(t){this.addBlockingTaskFromPath(t.path)}addBlockedByDependency(t){let r=this.getDependencySourcePath(),a=this.createDependencyItemFromDependency(t,r),i=j2(this.blockedByItems,a);i.length!==this.blockedByItems.length&&(this.blockedByItems=i,this.renderBlockedByList())}addBlockingTaskFromPath(t){let r=this.getCurrentTaskPath();if(r&&t===r)return;let a=this.createDependencyItemFromPath(t),i=j2(this.blockingItems,a);i.length!==this.blockingItems.length&&(this.blockingItems=i,this.renderBlockingList())}async openBlockedBySelector(){let t=this.getDependencySourcePath();await RM({plugin:this.plugin,getCandidates:r=>Wce({plugin:this.plugin,sourcePath:t,allTasks:r,existingItems:this.blockedByItems,currentPath:this.getCurrentTaskPath()}),onSelect:r=>{let a={uid:Ks(this.plugin.app,t,r.path),reltype:Pi};this.addBlockedByDependency(a)},translate:r=>this.t(r),noEligibleTasksMessageKey:"contextMenus.task.dependencies.notices.noEligibleTasks",openFailedMessageKey:"contextMenus.task.dependencies.notices.updateFailed",logOperation:"open-blocked-by-selector"})}async openBlockingSelector(){let t=this.getDependencySourcePath();await RM({plugin:this.plugin,getCandidates:r=>qce({plugin:this.plugin,sourcePath:t,allTasks:r,existingItems:this.blockingItems,currentPath:this.getCurrentTaskPath()}),onSelect:r=>{this.addBlockingTaskFromPath(r.path)},translate:r=>this.t(r),noEligibleTasksMessageKey:"contextMenus.task.dependencies.notices.noEligibleTasks",openFailedMessageKey:"contextMenus.task.dependencies.notices.updateFailed",logOperation:"open-blocking-selector"})}getApp(){return this.app}getPlugin(){return this.plugin}t(t,r){return this.plugin.i18n.translate(t,r)}getFileByPath(t){return this.app.vault.getAbstractFileByPath(t)}getMarkdownFiles(){return this.app.vault.getMarkdownFiles()}getFileCache(t){return this.app.metadataCache.getFileCache(t)}resolveLink(t,r){return this.app.metadataCache.getFirstLinkpathDest(t,r)}isEditMode(){return!1}isCreationMode(){return!1}async handleSubmitShortcut(t){await this.handleSave()}onOpen(){this.containerEl.addClass("tasknotes-plugin","minimalist-task-modal"),this.plugin.settings.enableModalSplitLayout&&this.containerEl.addClass("split-layout-enabled"),this.modalEl.addClass("mod-tasknotes"),this.titleEl.setText(this.getModalTitle()),this.keyboardHandler=t=>{if(t.key==="Enter"&&(t.ctrlKey||t.metaKey)){if(t.target.closest(".cm-editor"))return;t.preventDefault(),this.handleSubmitShortcut(t.shiftKey)}},this.containerEl.addEventListener("keydown",this.keyboardHandler),this.initializeFormData().then(()=>{this.createModalContent(),this.focusTitleInput()})}createModalContent(){let{contentEl:t}=this;t.empty();let r=t.createDiv("minimalist-modal-container");this.splitContentWrapper=r.createDiv("modal-split-content"),this.splitLeftColumn=this.splitContentWrapper.createDiv("modal-split-left"),this.createPrimaryInput(this.splitLeftColumn),this.createActionBar(this.splitLeftColumn),this.splitRightColumn=this.splitLeftColumn.createDiv("modal-split-right"),this.createDetailsSection(r),this.createAdditionalSections(this.splitLeftColumn),this.createActionButtons(r)}createPrimaryInput(t){this.createTitleInput(t)}createAdditionalSections(t){}createTitleInput(t){let r=t.createDiv("title-input-container");this.titleInput=this.createTitleTextarea(r,"title-input",this.t("modals.task.titlePlaceholder"))}createTitleTextarea(t,r,a){return Vde({container:t,className:r,placeholder:a,value:this.title,onChange:i=>{this.title=i},attachFocusScrollGuard:i=>{this.attachTitleFocusScrollGuard(i),this.attachMobileKeyboardScrollGuard(i,{scrollOnFocus:!1})}})}createActionBar(t){this.actionBar=t.createDiv("tn-task-modal__action-bar"),this.createCoreActionIcons(this.actionBar),this.updateIconStates()}createCoreActionIcons(t){return ode(t,this.getCoreActionIconSpecs())}getCoreActionIconSpecs(){return[{iconName:"dot-square",tooltip:this.t("modals.task.actions.status"),onClick:(t,r)=>{this.showStatusContextMenu(r)},dataType:"status"},{iconName:"star",tooltip:this.t("modals.task.actions.priority"),onClick:(t,r)=>{this.showPriorityContextMenu(r)},dataType:"priority"},{iconName:"calendar",tooltip:this.t("modals.task.actions.due"),onClick:(t,r)=>{this.showDateContextMenu(r,"due")},dataType:"due-date"},{iconName:"calendar-clock",tooltip:this.t("modals.task.actions.scheduled"),onClick:(t,r)=>{this.showDateContextMenu(r,"scheduled")},dataType:"scheduled-date"},{iconName:"refresh-ccw",tooltip:this.t("modals.task.actions.recurrence"),onClick:(t,r)=>{this.showRecurrenceContextMenu(r)},dataType:"recurrence"},{iconName:"bell",tooltip:this.t("modals.task.actions.reminders"),onClick:(t,r)=>{this.showReminderContextMenu(r)},dataType:"reminders"}]}createActionIcon(t,r,a,i,s){return q2(t,{iconName:r,tooltip:a,onClick:i,dataType:s})}createDetailsSection(t){this.userFieldInputs.clear(),this.userFieldToggles.clear(),this.detailsContainer=this.splitLeftColumn?this.splitLeftColumn.createDiv("details-container"):t.createDiv("details-container"),this.isExpanded||LM({detailsContainer:this.detailsContainer,splitRightColumn:this.splitRightColumn});let r=this.plugin.settings.modalFieldsConfig,a=this.shouldShowField("title",r),i=this.shouldShowField("details",r);this.splitContentWrapper.classList.toggle("modal-split-content--right-empty",!i);let s=this.isEditMode(),o=this.isCreationMode()&&this.plugin.settings.enableNaturalLanguageInput;if(a&&(s||o)){let l=this.detailsContainer.createDiv("detail-label");l.textContent=this.t("modals.task.titleLabel");let c=this.createTitleTextarea(this.detailsContainer,"title-input-detailed",this.t("modals.task.titleDetailedPlaceholder"));(s||o)&&!this.titleInput&&(this.titleInput=c)}if(i){let l=this.splitRightColumn||this.detailsContainer;this.detailsMarkdownEditor=XX({app:this.app,parent:l,label:this.t("modals.task.detailsLabel"),value:this.details,placeholder:this.t("modals.task.detailsPlaceholder"),file:this.getModalEditorFile(),tabMovesFocus:this.plugin.settings.taskModalTabMovesFocus,onChange:c=>{this.details=c},onSubmit:c=>{this.handleSubmitShortcut(c)},onEscape:()=>{this.close()},focusNextField:()=>this.focusNextField(),focusPreviousField:()=>this.focusPreviousField(),attachMobileKeyboardScrollGuard:c=>{this.attachMobileKeyboardScrollGuard(c)}})}this.createAdditionalFields(this.detailsContainer)}shouldShowField(t,r){return UX(t,r,this.isCreationMode())}createAdditionalFields(t){let r=this.plugin.settings.modalFieldsConfig;if(!r){KHe.error("TaskModal: modalFieldsConfig is not initialized. This should never happen.",{category:"configuration",operation:"taskmodal-modalfieldsconfig-not-initialized-this-should-never-happen"});return}this.createFieldsFromConfig(t,r)}createFieldsFromConfig(t,r){VX({container:t,config:r,isCreationMode:this.isCreationMode(),fieldRenderers:this.getFieldRenderers(),renderUserField:(a,i)=>{this.createUserFieldByConfig(a,i)}})}createField(t,r){K1({container:t,fieldConfig:r,fieldRenderers:this.getFieldRenderers(),renderUserField:(a,i)=>{this.createUserFieldByConfig(a,i)}})}getFieldRenderers(){return{contexts:t=>this.createContextsField(t),tags:t=>this.createTagsField(t),"time-estimate":t=>this.createTimeEstimateField(t),projects:t=>this.createProjectsField(t),subtasks:t=>this.createSubtasksField(t),"blocked-by":t=>this.createBlockedByField(t),blocking:t=>this.createBlockingField(t)}}createContextsField(t){this.contextsInput=Yce(this.getMetadataFieldContext(),{container:t,value:this.contexts,onChange:r=>{this.contexts=r}})}createTagsField(t){this.tagsInput=Kce(this.getMetadataFieldContext(),{container:t,value:this.tags,onChange:r=>{this.tags=r}})}createTimeEstimateField(t){this.timeEstimateInput=Zce(this.getMetadataFieldContext(),{container:t,value:this.timeEstimate,onChange:r=>{this.timeEstimate=r}})}getMetadataFieldContext(){return{app:this.app,plugin:this.plugin,translate:t=>this.t(t),attachMobileKeyboardScrollGuard:t=>{this.attachMobileKeyboardScrollGuard(t)}}}createProjectsField(t){this.projectsList=lre(this.getOrganizationFieldContext(),{container:t,onButtonClick:()=>{new Ys(this.app,this.plugin,a=>{this.addProject(a)}).open()},listElement:this.projectsList}),this.renderOrganizationLists()}createSubtasksField(t){this.subtasksList=cre(this.getOrganizationFieldContext(),{container:t,onButtonClick:()=>{this.openSubtaskSelector()},listElement:this.subtasksList}),this.renderOrganizationLists()}getOrganizationFieldContext(){return{translate:t=>this.t(t)}}getUserFieldContext(){return{app:this.app,plugin:this.plugin,translate:(t,r)=>this.t(t,r),attachMobileKeyboardScrollGuard:t=>{this.attachMobileKeyboardScrollGuard(t)}}}createBlockedByField(t){this.blockedByList=dre(this.getOrganizationFieldContext(),{container:t,onButtonClick:()=>{this.openBlockedBySelector()},listElement:this.blockedByList}),this.renderDependencyLists()}createBlockingField(t){this.blockingList=ure(this.getOrganizationFieldContext(),{container:t,onButtonClick:()=>{this.openBlockingSelector()},listElement:this.blockingList}),this.renderDependencyLists()}createUserFieldByConfig(t,r){var i;let a=(i=this.plugin.settings.userFields)==null?void 0:i.find(s=>s.id===r.id);a&&nde(this.getUserFieldContext(),{container:t,field:a,values:this.userFields,inputRefs:this.userFieldInputs,toggleRefs:this.userFieldToggles,onValueChange:(s,o)=>{this.userFields[s]=o}})}updateUserFieldControls(){var t;ide({fields:((t=this.plugin.settings)==null?void 0:t.userFields)||[],values:this.userFields,inputRefs:this.userFieldInputs,toggleRefs:this.userFieldToggles})}createUserFields(t){var r;ade(this.getUserFieldContext(),{container:t,fields:((r=this.plugin.settings)==null?void 0:r.userFields)||[],values:this.userFields,inputRefs:this.userFieldInputs,toggleRefs:this.userFieldToggles,onValueChange:(a,i)=>{this.userFields[a]=i}})}createActionButtons(t){let r=[];this.isEditMode()&&r.push({className:"tn-task-modal__open-note-button",text:this.t("modals.task.buttons.openNote"),onClick:()=>{this.openTaskNote()}}),EM(this.getActionButtonContext(),{container:t,leadingButtons:r,onSave:()=>this.handleSave(),onSaved:()=>{this.close()},onCancel:()=>{this.close()}})}getActionButtonContext(){return{translate:t=>this.t(t)}}expandModal(){this.isExpanded||(this.isExpanded=!0,Qde({containerEl:this.containerEl,detailsContainer:this.detailsContainer,splitRightColumn:this.splitRightColumn}))}showDateContextMenu(t,r){Cde(this.getActionMenuContext(),r)}showStatusContextMenu(t){xde(this.getActionMenuContext(),t)}showPriorityContextMenu(t){Ede(this.getActionMenuContext(),t)}showRecurrenceContextMenu(t){Dde(this.getActionMenuContext(),t)}showReminderContextMenu(t){MM(this.getActionMenuContext(),t)}getActionMenuState(){return vde({title:this.title,status:this.status,priority:this.priority,dueDate:this.dueDate,scheduledDate:this.scheduledDate,recurrenceRule:this.recurrenceRule,recurrenceAnchor:this.recurrenceAnchor,reminders:this.reminders})}getActionMenuContext(){return kde({app:this.app,plugin:this.plugin,translate:(t,r)=>this.t(t,r),getState:()=>this.getActionMenuState(),setDueDate:t=>{this.dueDate=t},setScheduledDate:t=>{this.scheduledDate=t},setStatus:t=>{this.status=t},setPriority:t=>{this.priority=t},setRecurrenceRule:t=>{this.recurrenceRule=t},setRecurrenceAnchor:t=>{this.recurrenceAnchor=t},setReminders:t=>{this.reminders=t},onChange:()=>this.updateIconStates()})}updateDateIconState(){this.updateIconStates()}updateStatusIconState(){this.updateIconStates()}updatePriorityIconState(){this.updateIconStates()}updateRecurrenceIconState(){this.updateIconStates()}updateReminderIconState(){this.updateIconStates()}updateIconStates(){let t=this.getActionMenuState();dde(this.actionBar,{translate:(r,a)=>this.t(r,a)},Tde(t,{statusConfigs:this.plugin.settings.customStatuses||[],priorityConfigs:this.plugin.settings.customPriorities||[]}))}focusTitleInput(){this.focusGuards.focusTitleInput(this.titleInput)}getInitialFocusDelay(){return this.focusGuards.getInitialFocusDelay()}isMobileLikeEnvironment(){return this.focusGuards.isMobileLikeEnvironment()}attachTitleFocusScrollGuard(t){this.focusGuards.attachTitleFocusScrollGuard(t)}attachMobileKeyboardScrollGuard(t,r){this.focusGuards.attachMobileKeyboardScrollGuard(t,r)}addProject(t){if(t instanceof gv.TFile){let r=IM(t,this.buildProjectReference(t,this.getCurrentTaskPath()||""));if(Y2(this.selectedProjectItems,r))return;this.selectedProjectItems.push(r)}this.updateProjectsFromFiles(),this.renderProjectsList()}removeProject(t){this.selectedProjectItems=Ide(this.selectedProjectItems,t),this.updateProjectsFromFiles(),this.renderProjectsList()}updateProjectsFromFiles(){this.projects=Nde(this.selectedProjectItems)}buildProjectReference(t,r){return Qo(this.app,t,r,"","",this.plugin.settings.useFrontmatterMarkdownLinks)}initializeProjectsFromStrings(t){this.selectedProjectItems=[],this.addProjectsFromStrings(t)}addProjectsFromStrings(t){this.selectedProjectItems=Mde(this.selectedProjectItems,t,this.getProjectStringContext()),this.updateProjectsFromFiles()}getProjectStringContext(){return{sourcePath:this.getCurrentTaskPath()||"",getMarkdownFiles:()=>this.getMarkdownFiles(),resolveLink:(t,r)=>this.resolveLink(t,r)}}renderProjectsList(){Rde({app:this.app,listEl:this.projectsList,items:this.selectedProjectItems,sourcePath:this.getCurrentTaskPath()||"",translate:(t,r)=>this.t(t,r),onRemove:t=>this.removeProject(t)})}async openSubtaskSelector(){let t=this.getCurrentTaskPath(),r=t?this.app.vault.getAbstractFileByPath(t):null,a=t?await this.plugin.cacheManager.getTaskInfo(t):null,i=r instanceof gv.TFile&&a?cM(this.plugin,a,r):void 0;await RM({plugin:this.plugin,selectorOptions:i?{creationDefaults:i}:void 0,getCandidates:s=>Fde(s,this.selectedSubtaskFiles,this.getCurrentTaskPath()),onSelect:s=>{let o=this.app.vault.getAbstractFileByPath(s.path);o&&this.addSubtask(o)},translate:s=>this.t(s),noEligibleTasksMessageKey:"modals.task.organization.notices.noEligibleSubtasks",openFailedMessageKey:"modals.task.organization.notices.subtaskSelectFailed",logOperation:"open-subtask-selector"})}addSubtask(t){let r=Lde(this.selectedSubtaskFiles,t);r.length!==this.selectedSubtaskFiles.length&&(this.selectedSubtaskFiles=r,this.renderSubtasksList())}removeSubtask(t){this.selectedSubtaskFiles=Ode(this.selectedSubtaskFiles,t),this.renderSubtasksList()}async renderSubtasksList(){await zde({app:this.app,listEl:this.subtasksList,files:this.selectedSubtaskFiles,sourcePath:this.getCurrentTaskPath()||"",getCachedTaskInfo:t=>this.plugin.cacheManager.getCachedTaskInfo(t),createTaskCard:t=>pr(t,this.plugin,void 0,{layout:"default",showSecondaryBadges:!1,enableHoverPreview:!1}),translate:(t,r)=>this.t(t,r),onRemove:t=>this.removeSubtask(t)})}renderOrganizationLists(){this.renderProjectsList(),this.renderSubtasksList()}toggleProjectsList(){this.projectsList&&this.projectsList.toggleClass("collapsed",!this.projectsList.hasClass("collapsed"))}toggleSubtasksList(){this.subtasksList&&this.subtasksList.toggleClass("collapsed",!this.subtasksList.hasClass("collapsed"))}validateForm(){return this.title.trim().length>0}focusNextField(){let t=this.contextsInput||this.tagsInput||this.timeEstimateInput;return t?(window.setTimeout(()=>{t.focus()},50),!0):!1}focusPreviousField(){return this.titleInput?(window.setTimeout(()=>{var t;(t=this.titleInput)==null||t.focus()},50),!0):!1}onClose(){this.keyboardHandler&&(this.containerEl.removeEventListener("keydown",this.keyboardHandler),this.keyboardHandler=null),this.focusGuards.destroy(),tee(this.detailsMarkdownEditor),this.detailsMarkdownEditor=null,super.onClose()}}});var zM,Xde=y(()=>{zM=class{constructor(e,t=[]){this.config=e,this.userFields=t,this.triggerMap=new Map,this.propertyMap=new Map,this.buildMaps()}buildMaps(){this.triggerMap.clear(),this.propertyMap.clear();for(let e of this.config.triggers)e.enabled&&(this.triggerMap.set(e.trigger,e),this.propertyMap.set(e.propertyId,e))}getTriggerForProperty(e){return this.propertyMap.get(e)}getPropertyForTrigger(e){var t;return(t=this.triggerMap.get(e))==null?void 0:t.propertyId}getAllEnabledTriggers(){return this.config.triggers.filter(e=>e.enabled)}getTriggersOrderedByLength(){return this.getAllEnabledTriggers().sort((e,t)=>t.trigger.length-e.trigger.length)}usesNativeTagSuggester(){let e=this.getTriggerForProperty("tags");return(e==null?void 0:e.trigger)==="#"&&(e==null?void 0:e.enabled)}getTagTrigger(){let e=this.getTriggerForProperty("tags");return e!=null&&e.enabled?e.trigger:void 0}getContextTrigger(){let e=this.getTriggerForProperty("contexts");return e!=null&&e.enabled?e.trigger:void 0}getProjectTrigger(){let e=this.getTriggerForProperty("projects");return e!=null&&e.enabled?e.trigger:void 0}getStatusTrigger(){let e=this.getTriggerForProperty("status");return e!=null&&e.enabled?e.trigger:void 0}getPriorityTrigger(){let e=this.getTriggerForProperty("priority");return e!=null&&e.enabled?e.trigger:void 0}getUserField(e){return this.userFields.find(t=>t.id===e)}isUserField(e){return this.userFields.some(t=>t.id===e)}getSuggesterType(e){if(e==="tags")return this.usesNativeTagSuggester()?"native-tag":"list";if(e==="contexts")return"list";if(e==="projects")return"file";if(e==="status")return"status";if(e==="priority")return"priority";let t=this.getUserField(e);if(t)switch(t.type){case"text":case"list":return t.autosuggestFilter?"file":"list";case"boolean":return"boolean";default:return"none"}return"none"}updateConfig(e){this.config=e,this.buildMaps()}updateUserFields(e){this.userFields=e}}});function tue(n){let e=(0,ac.autocompletion)({override:[JHe(n)],activateOnTyping:!0,closeOnBlur:!0,maxRenderedOptions:10,addToOptions:[{render:(r,a,i)=>XHe(r,i.dom.ownerDocument),position:100}]}),t=J2.Prec.high(eue.keymap.of([{key:"ArrowDown",run:(0,ac.moveCompletionSelection)(!0)},{key:"ArrowUp",run:(0,ac.moveCompletionSelection)(!1)},{key:"Enter",run:ac.acceptCompletion},{key:"Tab",run:ac.acceptCompletion},{key:"Escape",run:ac.closeCompletion}]));return[J2.Prec.high(e),t]}function JHe(n){return async e=>{let t=new zM(n.settings.nlpTriggers,n.settings.userFields||[]),r=e.state.doc.lineAt(e.pos),a=r.text.slice(0,e.pos-r.from),i=(f,h)=>{if(f===-1)return!1;if(f===0)return!0;let g=h[f-1];return!/\w/.test(g)},s=t.getTriggersOrderedByLength(),o=[];for(let f of s){if(f.propertyId==="tags"&&f.trigger==="#")continue;let h=a.lastIndexOf(f.trigger);i(h,a)&&o.push({propertyId:f.propertyId,trigger:f.trigger,index:h,triggerLength:f.trigger.length})}if(o.length===0)return null;o.sort((f,h)=>h.index-f.index);let l=o[0],c=l.index+l.triggerLength,d=a.slice(c);if(l.propertyId==="projects"&&/^\[\[[^\]]*\]\]/.test(d)||l.propertyId!=="projects"&&(d.includes(" ")||d.includes(` +`)))return null;let u=await eVe(l.propertyId,d,n,t);if(!u||u.length===0)return null;let p=e.pos,m=r.text.slice(e.pos-r.from);return l.propertyId==="status"&&m.startsWith(l.trigger)&&(p=Math.min(r.to,e.pos+l.triggerLength)),{from:r.from+l.index+l.triggerLength,to:p,options:u,validFor:/^[\w\s-]*$/}}}function XHe(n,e=activeDocument){let t=n;if(!t.projectMetadata)return null;let r=Ie(e,"div");r.className="cm-project-suggestion__metadata";for(let a of t.projectMetadata){let i=Ie(e,"div");i.className="cm-project-suggestion__meta",a.forEach((s,o)=>{o>0&&i.appendChild(e.createTextNode(" "));let l=Ie(e,"span");l.className=s.kind==="value"?"cm-project-suggestion__meta-value":s.kind==="label"?"cm-project-suggestion__meta-label":"cm-project-suggestion__meta-literal",s.searchable&&l.classList.add("cm-project-suggestion__meta-searchable"),s.searchable&&t.projectQuery?aVe(l,s.text,t.projectQuery):l.textContent=s.text,i.appendChild(l)}),r.appendChild(i)}return r}async function eVe(n,e,t,r){switch(r.getSuggesterType(n)){case"list":return tVe(n,e,t);case"file":return rVe(n,e,t,r);case"status":return iVe(e,t);case"priority":return sVe(e,t);case"boolean":return oVe(e);case"native-tag":return null;default:return null}}function tVe(n,e,t){let r=[],a=n;switch(n){case"tags":r=t.cacheManager.getAllTags(),a="Tag";break;case"contexts":r=t.cacheManager.getAllContexts(),a="Context";break;default:r=[],a=n;break}return r.filter(i=>i&&typeof i=="string").filter(i=>i.toLowerCase().includes(e.toLowerCase())).slice(0,10).map(i=>({label:i,apply:i+" ",type:"text",info:a}))}async function rVe(n,e,t,r){var a,i,s;try{let o;if(n==="projects")o=t.settings.projectAutosuggest;else{let c=r.getUserField(n);o=c==null?void 0:c.autosuggestFilter}let l=await nB.suggest(t,e,20,o);if(n==="projects"){let c=new Yu({getFrontmatter:u=>u.frontmatter}),d=((s=(i=(a=t.settings)==null?void 0:a.projectAutosuggest)==null?void 0:i.rows)!=null?s:[]).slice(0,3);return l.map(u=>{var g;let p=u.displayText||u.insertText,m=u.insertText,f=t.app.vault.getMarkdownFiles().find(v=>v.path===u.path),h=[];if(f&&d.length>0){let v=t.app.metadataCache.getFileCache(f),k=(v==null?void 0:v.frontmatter)||{},T=t.fieldMapper.mapFromFrontmatter(k,f.path,t.settings.storeTitleInFilename),b=typeof T.title=="string"?T.title:"",w=Array.isArray(k.aliases)?k.aliases.filter(C=>typeof C=="string"):[],S={basename:f.basename,name:f.name,path:f.path,parent:((g=f.parent)==null?void 0:g.path)||"",title:b,aliases:w,frontmatter:k};h=nVe(d,S,c)}return{label:p,apply:`[[${m}]] `,type:"text",info:"Project",projectMetadata:h.length>0?h:void 0,projectQuery:e}})}return l.map(c=>{let d=c.displayText||c.insertText,u=c.insertText;return{label:d,apply:`[[${u}]] `,type:"text",info:n==="projects"?"Project":n}})}catch(o){return ZHe.error(`Error getting file suggestions for ${n}:`,{category:"persistence",operation:"getting-file-suggestions",error:o}),[]}}function nVe(n,e,t){var i;let r=[],a=Math.min(n.length,3);for(let s=0;sd.text.trim().length>0)&&r.push(c)}catch(l){}}return r}function aVe(n,e,t){let r=n.ownerDocument,a=t.toLowerCase().split(/\s+/).filter(Boolean);if(a.length===0){n.textContent=e;return}let i=e.toLowerCase(),s=[];for(let c of a){let d=i.indexOf(c);for(;d!==-1;)s.push({start:d,end:d+c.length}),d=i.indexOf(c,d+1)}s.sort((c,d)=>c.start-d.start);let o=[];for(let c of s){let d=o[o.length-1];(!d||c.start>=d.end)&&o.push(c)}if(o.length===0){n.textContent=e;return}let l=0;for(let c of o){c.start>l&&n.appendChild(r.createTextNode(e.slice(l,c.start)));let d=Ie(r,"mark");d.textContent=e.slice(c.start,c.end),n.appendChild(d),l=c.end}l({label:a.display,apply:a.value+" ",type:"text",info:"Status"}))}function sVe(n,e){return(e.settings.customPriorities||[]).filter(r=>r.label.toLowerCase().includes(n.toLowerCase())).slice(0,10).map(r=>({label:r.label,apply:r.value+" ",type:"text",info:"Priority"}))}function oVe(n){return["true","false"].filter(t=>t.toLowerCase().includes(n.toLowerCase())).map(t=>({label:t,apply:t+" ",type:"text",info:"Boolean"}))}var ac,J2,eue,ZHe,QHe,rue=y(()=>{ac=require("@codemirror/autocomplete"),J2=require("@codemirror/state"),eue=require("@codemirror/view");Wl();Xde();Hb();O0();$b();q();Li();ZHe=M({tag:"Editor/NLPCodeMirrorAutocomplete"}),QHe=new Set(["title","aliases","file.basename"])});function nue(n){let e=qe(),t=n.contexts.split(",").map(l=>l.trim()).filter(l=>l.length>0),r=ms(n.projects),a=ha(n.tags).split(",").map(l=>l.trim()).filter(l=>l.length>0);n.taskIdentificationMethod==="tag"&&n.taskTag&&!a.includes(n.taskTag)&&a.unshift(n.taskTag);let i={title:n.title.trim(),due:n.dueDate||void 0,scheduled:n.scheduledDate||void 0,priority:n.priority,status:n.status,contexts:t.length>0?t:void 0,projects:r.length>0?r:void 0,tags:a.length>0?a:void 0,timeEstimate:n.timeEstimate>0?n.timeEstimate:void 0,recurrence:n.recurrenceRule||void 0,recurrence_anchor:n.recurrenceRule?n.recurrenceAnchor:void 0,reminders:n.reminders.length>0?n.reminders:void 0,creationContext:n.creationContext||"manual-creation",dateCreated:e,dateModified:e,customFrontmatter:tde(n.userFields)},s=n.blockedByItems.map(l=>({...l.dependency}));s.length>0&&(i.blockedBy=s);let o=n.normalizeDetails(n.details).trimEnd();return o.length>0&&(i.details=o),i}function aue(n){let e=[],t={},r=[];return n.forEach(a=>{a.path?e.includes(a.path)||(e.push(a.path),t[a.path]={...a.dependency}):r.push(a.dependency.uid)}),{added:e,raw:t,unresolved:r}}var iue=y(()=>{xe();yt();Ku();xM()});var lue={};Xe(lue,{convertDefaultRemindersToReminders:()=>IC,hasAnyUserFieldsEnabled:()=>sue,isUserFieldConfigComplete:()=>oue,isUserFieldEnabled:()=>lVe});function IC(n,e){return n.map(t=>{let r={id:`rem_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,type:t.type,description:t.description};if(t.type==="relative"){if(t.relatedTo&&t.offset!==void 0&&t.unit&&t.direction){let a="PT";t.unit==="days"?a=`P${t.offset}D`:t.unit==="hours"?a=`PT${t.offset}H`:a=`PT${t.offset}M`,t.direction==="before"&&(a="-"+a),r.relatedTo=t.relatedTo,r.offset=a}}else t.type==="absolute"&&t.absoluteDate&&t.absoluteTime&&(r.absoluteTime=`${t.absoluteDate}T${t.absoluteTime}:00`);return r}).filter(t=>t.type==="relative"?t.relatedTo&&t.offset:!!t.absoluteTime)}function sue(n){let e=n.userFields;return!e||e.length===0?!1:e.some(t=>!!(t&&t.displayName&&t.key&&t.type))}function oue(n){return!n||!n.enabled?!1:!!(n.displayName&&n.key&&n.type)}function lVe(n){return n.userFields&&n.userFields.length>0?sue(n):oue(n.userField)}var BM=y(()=>{});function cue(n){let e=n.taskCreationDefaults,t={title:"",dueDate:Ol(e.defaultDueDate,e.defaultDueTime),scheduledDate:Ol(e.defaultScheduledDate,e.defaultScheduledTime),priority:n.defaultPriority,status:n.defaultStatus,contexts:e.defaultContexts||"",tags:e.defaultTags||"",projectStrings:e.defaultProjects?ms(e.defaultProjects):[],timeEstimate:e.defaultTimeEstimate&&e.defaultTimeEstimate>0?e.defaultTimeEstimate:0,recurrenceRule:"",recurrenceAnchor:"scheduled",reminders:e.defaultReminders&&e.defaultReminders.length>0?IC(e.defaultReminders):[],userFields:cVe(n.userFields||[])};return n.prePopulatedValues&&uVe(t,n.prePopulatedValues,n.taskTag),t}function cVe(n){let e={};for(let t of n)if(t.defaultValue!==void 0){if(t.type==="date"&&typeof t.defaultValue=="string"){let r=dVe(t.defaultValue);r&&(e[t.key]=r);continue}e[t.key]=t.defaultValue}return e}function dVe(n){return n!=="none"&&n!=="today"&&n!=="tomorrow"&&n!=="next-week"?"":jb(n)}function uVe(n,e,t){if(e.title!==void 0&&(n.title=e.title),e.due!==void 0&&(n.dueDate=e.due),e.scheduled!==void 0&&(n.scheduledDate=e.scheduled),e.priority!==void 0&&(n.priority=e.priority),e.status!==void 0&&(n.status=e.status),e.contexts!==void 0&&(n.contexts=e.contexts.join(", ")),e.projects!==void 0&&(n.projectStrings=e.projects.filter(r=>r&&typeof r=="string"&&r.trim()!=="")),e.tags!==void 0&&(n.tags=ha(e.tags.filter(r=>r!==t).join(", "))),e.timeEstimate!==void 0&&(n.timeEstimate=e.timeEstimate),e.recurrence!==void 0&&typeof e.recurrence=="string"&&(n.recurrenceRule=e.recurrence),e.recurrence_anchor!==void 0&&(n.recurrenceAnchor=e.recurrence_anchor),e.customFrontmatter)for(let[r,a]of Object.entries(e.customFrontmatter))n.userFields[r]=a}var due=y(()=>{yt();BM();Ku()});async function uue(n){var t;let e={updated:0,missing:0,skipped:0,failed:0};if(!n.currentTaskFile)return e;for(let r of n.subtaskFiles)try{let a=await n.getTaskInfo(r.path);if(!a){e.missing+=1;continue}let i=n.buildProjectReference(n.currentTaskFile,r.path),s=X2(a.projects,i,pVe(n.currentTaskFile));if(!s){e.skipped+=1;continue}await n.updateTaskProjects(a,s),e.updated+=1}catch(a){e.failed+=1,(t=n.onError)==null||t.call(n,a,r)}return e}function X2(n,e,t){let a=(Array.isArray(n)?n:[]).filter(i=>typeof i=="string");return a.includes(e)||a.includes(t)?null:[...a,e]}function pVe(n){return`[[${n.basename}]]`}var eU=y(()=>{});function pue(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}async function mue(n,e){return n.getAbstractFileByPath(e)?!0:n.adapter.exists(e,!1)}function fue(n,e){if(!n||!e)throw new Error("Invalid context or settings provided");if(!n.title||typeof n.title!="string")throw new Error("Context must have a valid title");if(n.title.trim().length===0)throw new Error("Title cannot be empty");let t=n.date||new Date;if(!(t instanceof Date)||isNaN(t.getTime()))throw new Error("Invalid date provided in context");try{let r=e.icsIntegration;if(r)switch(r.icsNoteFilenameFormat){case"title":return Ir(n.title);case"zettel":return Kf(t);case"timestamp":return gue(t);case"custom":{let a={icsEventTitle:n.icsEventTitle?Ir(n.icsEventTitle):Ir(n.title),icsEventLocation:n.icsEventLocation?Ir(n.icsEventLocation):"",icsEventDescription:n.icsEventDescription?Ir(n.icsEventDescription.substring(0,50)):"",icsEventTitleWithDate:Ir(`${n.icsEventTitle||n.title} - ${D(t,"PPP")}`)};return tU(n,r.customICSNoteFilenameTemplate,t,a)}default:return Ir(n.title)}return Ir(n.title)}catch(r){return Zf.error("Error generating ICS note filename:",{category:"provider",operation:"generating-ics-note-filename",error:r}),Ir(n.title)}}function hue(n,e){if(!n||!e)throw new Error("Invalid context or settings provided");if(!n.title||typeof n.title!="string")throw new Error("Context must have a valid title");if(n.title.trim().length===0)throw new Error("Title cannot be empty");let t=n.date||new Date;if(!(t instanceof Date)||isNaN(t.getTime()))throw new Error("Invalid date provided in context");if(e.storeTitleInFilename)return Ir(n.title);try{switch(e.taskFilenameFormat){case"title":return Ir(n.title);case"zettel":return Kf(t);case"timestamp":return gue(t);case"uuid":return yue();case"custom":return tU(n,e.customFilenameTemplate,t);default:return Kf(t)}}catch(r){return Zf.error("Error generating filename:",{category:"persistence",operation:"generating-filename",error:r}),Kf(t)}}function jM(n,e,t){if(!n.storeTitleInFilename&&n.taskFilenameFormat!=="title")return!1;let r=Ir(e);return t.startsWith("task-")&&t!==r}function Kf(n){let e=D(n,"yyMMdd"),t=new Date(n);t.setHours(0,0,0,0);let a=Math.floor((n.getTime()-t.getTime())/1e3).toString(36);return`${e}${a}`}function gue(n){return D(n,"yyyy-MM-dd-HHmmss")}function yue(){let n=typeof window!="undefined"?window.crypto:void 0;if(typeof(n==null?void 0:n.randomUUID)=="function")return n.randomUUID();let e=new Uint8Array(16);if(typeof(n==null?void 0:n.getRandomValues)=="function")n.getRandomValues(e);else for(let r=0;rr.toString(16).padStart(2,"0"));return`${t.slice(0,4).join("")}-${t.slice(4,6).join("")}-${t.slice(6,8).join("")}-${t.slice(8,10).join("")}-${t.slice(10,16).join("")}`}function mVe(n){return Array.isArray(n)?n.map(e=>Zo(e).trim()).filter(e=>e.length>0).map(e=>Ir(e)):[]}function fVe(n){return n?n.replace(/[^a-zA-Z0-9]/g,"").substring(0,4).toUpperCase():""}function tU(n,e,t,r){var a;if(!n||!e||!t)throw new Error("Invalid inputs for custom filename generation");if(typeof e!="string"||e.trim().length===0)throw new Error("Template must be a non-empty string");if(!(t instanceof Date)||isNaN(t.getTime()))throw new Error("Invalid date for filename generation");try{let i=Ir(n.title),s=n.priority&&["low","normal","medium","high"].includes(n.priority)?n.priority:"normal",o=n.status?Ir(n.status):"open",l=Array.isArray(n.contexts)?n.contexts:[],c=mVe(n.projects),d=Array.isArray(n.tags)?n.tags:[],u={title:i,date:D(t,"yyyy-MM-dd"),time:D(t,"HHmmss"),priority:s,status:o,timestamp:D(t,"yyyy-MM-dd-HHmmss"),dateTime:D(t,"yyyy-MM-dd-HHmm"),year:D(t,"yyyy"),month:D(t,"MM"),day:D(t,"dd"),hour:D(t,"HH"),minute:D(t,"mm"),second:D(t,"ss"),dueDate:n.dueDate||"",scheduledDate:n.scheduledDate||"",context:l[0]?Ir(l[0]):"",contexts:l.map(m=>Ir(m)).join("/"),project:c[0]||"",projects:c.join("/"),projectId:fVe(c[0]),tags:d.map(m=>Ir(m)).join(", "),hashtags:d.map(m=>`#${Ir(m)}`).join(" "),timeEstimate:((a=n.timeEstimate)==null?void 0:a.toString())||"",details:n.details?Ir(n.details.substring(0,50)):"",parentNote:n.parentNote?Ir(n.parentNote):"",shortDate:D(t,"yyMMdd"),shortYear:D(t,"yy"),monthName:D(t,"MMMM"),monthNameShort:D(t,"MMM"),dayName:D(t,"EEEE"),dayNameShort:D(t,"EEE"),week:D(t,"ww"),quarter:D(t,"q"),time12:D(t,"hh:mm a"),time24:D(t,"HH:mm"),hourPadded:D(t,"HH"),hour12:D(t,"hh"),ampm:D(t,"a"),unix:Math.floor(t.getTime()/1e3).toString(),unixMs:t.getTime().toString(),milliseconds:D(t,"SSS"),ms:D(t,"SSS"),timezone:D(t,"xxx"),timezoneShort:D(t,"xx"),utcOffset:D(t,"xxx"),utcOffsetShort:D(t,"xx"),utcZ:"Z",priorityShort:s.substring(0,1).toUpperCase(),statusShort:o.substring(0,1).toUpperCase(),titleLower:i.toLowerCase(),titleUpper:i.toUpperCase(),titleSnake:i.toLowerCase().replace(/\s+/g,"_"),titleKebab:i.toLowerCase().replace(/\s+/g,"-"),titleCamel:i.replace(/(?:^\w|[A-Z]|\b\w)/g,(m,f)=>f===0?m.toLowerCase():m.toUpperCase()).replace(/\s+/g,""),titlePascal:i.replace(/(?:^\w|[A-Z]|\b\w)/g,m=>m.toUpperCase()).replace(/\s+/g,""),zettel:Kf(t),uuid:yue(),nano:Date.now().toString()+Math.random().toString(36).substring(2,7),...r||{}},p=e;if(e.length>500)throw new Error("Template too long");return Object.entries(u).forEach(([m,f])=>{try{let h=new RegExp(`\\{\\{${m}\\}\\}`,"g");p=p.replace(h,f);let g=new RegExp(`\\{${m}\\}`,"g");p=p.replace(g,f)}catch(h){Zf.warn(`Error replacing template variable ${m}:`,{category:"persistence",operation:"replacing-template-variable",error:h})}}),p=p.replace(/\{\{[^}]+\}\}/g,""),p=p.replace(/\{[^}]+\}/g,""),p.trim()||(p=i||Kf(t)),Ir(p)}catch(i){return Zf.error("Error generating custom filename:",{category:"persistence",operation:"generating-custom-filename",error:i}),Ir(n.title)||Kf(t)}}function Ir(n){if(!n||typeof n!="string")return"untitled";try{let e=n.trim().replace(/\s+/g," ").replace(/[<>:"/\\|?*#[\]]/g,"").replace(/./g,r=>{let a=r.charCodeAt(0);return a<=31||a>=127&&a<=159?"":r}).replace(/^\.+|\.+$/g,"").trim();return(!e||e.length===0)&&(e="untitled"),["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"].includes(e.toUpperCase())&&(e=`task-${e}`),e}catch(e){return Zf.error("Error sanitizing filename:",{category:"persistence",operation:"sanitizing-filename",error:e}),"untitled"}}async function vv(n,e,t){if(!n||typeof n!="string")throw new Error("Base filename must be a non-empty string");if(typeof e!="string")throw new Error("Folder path must be a string");if(!t)throw new Error("Vault must be provided");let r=Ir(n);if(!r)throw new Error("Base filename cannot be sanitized to a valid name");let a=e.replace(/\.\./g,"").trim();try{let i=pue(`${a}/${r}.md`);if(i.length>260)throw new Error("Generated path too long");if(!await mue(t,i))return r;for(let l=2;l<=999;l++){let c=`${r}-${l}`,d=pue(`${a}/${c}.md`);if(d.length>260)break;if(!await mue(t,d))return c}let s=Date.now().toString(36),o=`${r.substring(0,50)}-${s}`;return Ir(o)}catch(i){return Zf.error("Error generating unique filename:",{category:"persistence",operation:"generating-unique-filename",error:i}),`task-${Date.now().toString(36)}`}}function hVe(n){let e=et(n);if(!(e instanceof Date)||isNaN(e.getTime()))throw new Error(`Invalid occurrence date: ${n}`);return{occurrenceDate:D(e,"yyyy-MM-dd"),occurrenceWeek:D(e,"RRRR-'W'II"),occurrenceMonth:D(e,"yyyy-MM"),occurrenceYear:D(e,"yyyy"),occurrenceMonthName:D(e,"MMMM")}}function vue(n,e,t){try{let r=hVe(t);return tU(n,e,n.date||new Date,r)}catch(r){return Zf.error("Error generating occurrence filename:",{category:"persistence",operation:"generating-occurrence-filename",error:r}),Ir(n.title)}}var Zf,kv=y(()=>{Cr();Cn();q();xe();Zf=M({tag:"Utils/FilenameGenerator"})});var Sue={};Xe(Sue,{TaskCreationModal:()=>kp,getTaskCreationFailureNoticeMessage:()=>Tue,openCreatedTaskFileAfterSave:()=>wue,shouldOpenCreatedTaskAfterSave:()=>bue});function vVe(n){return n.disabled?!1:n.tabIndex>=0||yVe.has(n.tagName)}function Tue(n){let e=n instanceof Error&&n.message?n.message:String(n);return e.startsWith(kue)?e.slice(kue.length):e}function bue(n,e,t){return(n==="same-tab"||n==="new-tab")&&!e.createAnother&&!t}async function wue(n,e,t){await(t==="new-tab"?n.workspace.getLeaf("tab"):n.workspace.getLeaf(!1)).openFile(e)}function kVe(n,e,t){let r=(tz(),BP(ez));return new r.EmbeddableMarkdownEditor(n,e,t)}var xs,$M,kue,gVe,yVe,kp,UM=y(()=>{xs=require("obsidian");Q2();yt();Wl();xe();rue();iue();due();eU();m2();kv();nz();K2();q();$M=M({tag:"Modals/TaskCreationModal"}),kue="Failed to create task: ",gVe=["button","a[href]","input","select","textarea","[tabindex]:not([tabindex='-1'])",".tn-task-modal__markdown-editor--nlp"].join(", "),yVe=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA"]);kp=class n extends yv{constructor(t,r,a={}){super(t,r);this.nlInput=void 0;this.nlMarkdownEditor=null;this.nlPreviewContainer=void 0;this.nlButtonContainer=void 0;this.nlpSuggest=null;this.eventListeners=[];this.options=a,this.nlParser=Nn.fromPlugin(r)}getModalTitle(){return this.t("modals.taskCreation.title")}isCreationMode(){return!0}addTrackedEventListener(t,r,a){t.addEventListener(r,a),this.eventListeners.push({element:t,event:r,handler:a})}removeAllEventListeners(){for(let{element:t,event:r,handler:a}of this.eventListeners)t.removeEventListener(r,a);this.eventListeners=[]}createPrimaryInput(t){this.plugin.settings.enableNaturalLanguageInput?this.createNaturalLanguageInput(t):(this.createTitleInput(t),this.isExpanded=!0,this.containerEl.addClass("expanded"))}createAdditionalSections(t){(this.options.prePopulatedValues&&this.options.prePopulatedValues.projects||this.selectedProjectItems.length>0)&&this.renderProjectsList()}createNaturalLanguageInput(t){let r=t.createDiv("nl-input-container"),a=r.createDiv("tn-task-modal__markdown-editor tn-task-modal__markdown-editor--nlp");a.setAttribute("role","textbox"),a.setAttribute("aria-label",this.t("modals.taskCreation.nlPlaceholder")),a.setAttribute("aria-multiline","true"),this.nlPreviewContainer=r.createDiv("nl-preview-container"),this.nlPreviewContainer.setAttribute("role","status"),this.nlPreviewContainer.setAttribute("aria-live","polite"),this.nlPreviewContainer.setAttribute("aria-label","Task preview");try{let i=tue(this.plugin);this.nlMarkdownEditor=kVe(this.app,a,{value:"",placeholder:this.t("modals.taskCreation.nlPlaceholder"),cls:"nlp-editor",extensions:i,enterVimInsertMode:!0,onChange:s=>{s.trim()?this.updateNaturalLanguagePreview(s.trim()):this.clearNaturalLanguagePreview()},onSubmit:(s,o)=>{this.handleSubmitShortcut(o)},onEscape:()=>{this.close()},onTab:(s,o)=>o?this.focusPreviousNaturalLanguageField(a):(this.isExpanded||this.expandModal(),window.setTimeout(()=>{let l=this.modalEl.querySelector(".title-input-detailed");l&&l.focus()},50),!0),onEnter:(s,o,l)=>!!o})}catch(i){$M.error("Failed to create NLP markdown editor:",{category:"persistence",operation:"create-nlp-markdown-editor",error:i}),this.nlInput=a.createEl("textarea",{cls:"nl-input",attr:{placeholder:this.t("modals.taskCreation.nlPlaceholder"),rows:"3"}});let s=()=>{let l=this.nlInput.value.trim();l?this.updateNaturalLanguagePreview(l):this.clearNaturalLanguagePreview()};this.addTrackedEventListener(this.nlInput,"input",s);let o=l=>{let c=this.nlInput.value.trim();if(!c)return;let d=l;d.key==="Enter"&&(d.ctrlKey||d.metaKey)?(d.preventDefault(),this.handleSubmitShortcut(d.shiftKey)):d.key==="Tab"&&d.shiftKey&&(d.preventDefault(),this.parseAndFillForm(c))};this.addTrackedEventListener(this.nlInput,"keydown",o),this.nlpSuggest=new nv(this.app,this.nlInput,this.plugin)}}focusPreviousNaturalLanguageField(t){let r=this.modalEl.contains(t)?this.modalEl:this.contentEl,a=Array.from(r.querySelectorAll(gVe)),i=a.findIndex(o=>o===t||t.contains(o));if(i<=0)return!0;let s=a.slice(0,i).reverse().find(vVe);return s&&window.setTimeout(()=>{s.focus()},50),!0}focusTitleInput(){if(!this.plugin.settings.enableNaturalLanguageInput){super.focusTitleInput();return}window.setTimeout(()=>{var r,a;let t=(a=(r=this.nlMarkdownEditor)==null?void 0:r.editor)==null?void 0:a.cm;if(t){t.focus(),t.scrollDOM.scrollTop=0;return}this.nlInput&&(this.nlInput.focus({preventScroll:!0}),this.nlInput.select())},this.getInitialFocusDelay())}updateNaturalLanguagePreview(t){if(!this.nlPreviewContainer)return;let r=this.nlParser.parseInput(t),a=this.nlParser.getPreviewData(r);a.length>0&&r.title?(this.nlPreviewContainer.empty(),this.nlPreviewContainer.classList.add("nl-preview-container--visible"),this.nlPreviewContainer.classList.remove("tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),a.forEach(i=>{let s=this.nlPreviewContainer.createDiv("nl-preview-item");s.textContent=i.text})):this.clearNaturalLanguagePreview()}clearNaturalLanguagePreview(){this.nlPreviewContainer&&(this.nlPreviewContainer.empty(),this.nlPreviewContainer.classList.remove("nl-preview-container--visible"),this.nlPreviewContainer.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-min-height-800px-997b4c8c"))}getNLPInputValue(){return this.nlMarkdownEditor?this.nlMarkdownEditor.value:this.nlInput?this.nlInput.value:""}createActionBar(t){if(this.actionBar=t.createDiv("tn-task-modal__action-bar"),this.plugin.settings.enableNaturalLanguageInput){this.createActionIcon(this.actionBar,"wand",this.t("modals.taskCreation.actions.fillFromNaturalLanguage"),(a,i)=>{let s=this.getNLPInputValue().trim();s&&this.parseAndFillForm(s)}),this.createActionIcon(this.actionBar,this.isExpanded?"chevron-up":"chevron-down",this.isExpanded?this.t("modals.taskCreation.actions.hideDetailedOptions"):this.t("modals.taskCreation.actions.showDetailedOptions"),(a,i)=>{this.toggleDetailedForm();let s=a.querySelector(".icon");s&&(0,xs.setIcon)(s,this.isExpanded?"chevron-up":"chevron-down"),(0,xs.setTooltip)(a,this.isExpanded?this.t("modals.taskCreation.actions.hideDetailedOptions"):this.t("modals.taskCreation.actions.showDetailedOptions"),{placement:"top"})});let r=this.actionBar.createDiv("action-separator");r.classList.remove("tn-static-width-100-0466783d","tn-static-width-12px-fbf353fb","tn-static-width-16px-7375d50b","tn-static-width-200px-2acaf3b5","tn-static-width-60px-bd09c419","tn-static-width-80px-8573bae3"),r.classList.add("tn-static-width-1px-aa77e27e"),r.classList.remove("tn-static-display-flex-4d51fc62","tn-static-height-0-7a31cef0","tn-static-height-100-62264068","tn-static-height-12px-06c0747e","tn-static-height-16px-30de4aee","tn-static-min-height-800px-997b4c8c"),r.classList.add("tn-static-height-24px-29a11d37"),r.classList.remove("tn-static-background-color-var-background-se-9087a23e","tn-static-background-color-var-color-base-40-ef5f175e","tn-static-background-color-var-color-red-134bc721","tn-static-background-color-var-text-accent-a954c70f"),r.classList.add("tn-static-background-color-var-background-mo-94b219f0"),r.classList.remove("tn-static-margin-0-11696618","tn-static-margin-0-auto-266e9b04","tn-static-margin-0-db0d5f36","tn-static-margin-2px-0-edce9b14","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-padding-12px-43bef435","tn-static-padding-20px-ebe8e48c"),r.classList.add("tn-static-margin-0-var-size-4-2-77f7dc08")}this.createCoreActionIcons(this.actionBar),this.updateIconStates()}parseAndFillForm(t){let r=this.nlParser.parseInput(t);this.applyParsedData(r),this.isExpanded||this.expandModal()}applyParsedData(t){var r;if(t.title&&(this.title=t.title),t.status&&(this.status=t.status),t.priority&&(this.priority=t.priority),t.dueDate&&(this.dueDate=t.dueTime?fa(t.dueDate,t.dueTime):t.dueDate),t.scheduledDate&&(this.scheduledDate=t.scheduledTime?fa(t.scheduledDate,t.scheduledTime):t.scheduledDate),t.contexts&&t.contexts.length>0&&(this.contexts=t.contexts.join(", ")),t.tags&&t.tags.length>0&&(this.tags=ha(t.tags.join(", "))),t.details&&(this.details=t.details),t.recurrence&&(this.recurrenceRule=t.recurrence),t.estimate!==void 0&&(this.timeEstimate=t.estimate>0?t.estimate:0,this.timeEstimateInput&&(this.timeEstimateInput.value=this.timeEstimate>0?this.timeEstimate.toString():"")),this.titleInput&&(this.titleInput.value=this.title),this.detailsInput&&(this.detailsInput.value=this.details),eee(this.detailsMarkdownEditor,this.details),this.contextsInput&&(this.contextsInput.value=this.contexts),this.tagsInput&&(this.tagsInput.value=this.tags),t.projects&&t.projects.length>0&&(this.addProjectsFromStrings(t.projects),this.renderProjectsList()),t.userFields){for(let[a,i]of Object.entries(t.userFields)){let s=(r=this.plugin.settings.userFields)==null?void 0:r.find(o=>o.id===a);s&&(this.userFields[s.key]=i)}this.updateUserFieldControls()}this.updateIconStates()}toggleDetailedForm(){this.isExpanded?(this.isExpanded=!1,LM({detailsContainer:this.detailsContainer,splitRightColumn:this.splitRightColumn}),this.containerEl.removeClass("expanded")):this.expandModal()}async initializeFormData(){let t=cue({defaultPriority:this.plugin.settings.defaultTaskPriority,defaultStatus:this.plugin.settings.defaultTaskStatus,taskCreationDefaults:this.plugin.settings.taskCreationDefaults,taskTag:this.plugin.settings.taskTag,userFields:this.plugin.settings.userFields,prePopulatedValues:this.options.prePopulatedValues});this.title=t.title,this.dueDate=t.dueDate,this.scheduledDate=t.scheduledDate,this.priority=t.priority,this.status=t.status,this.contexts=t.contexts,this.tags=t.tags,this.timeEstimate=t.timeEstimate,this.recurrenceRule=t.recurrenceRule,this.recurrenceAnchor=t.recurrenceAnchor,this.reminders=t.reminders,this.userFields=t.userFields,t.projectStrings.length>0&&this.initializeProjectsFromStrings(t.projectStrings),this.details=this.normalizeDetails(this.details),this.originalDetails=this.details}async handleSubmitShortcut(t){await this.handleSave({createAnother:t})}async handleSave(t={}){if(this.plugin.settings.enableNaturalLanguageInput){let r=this.getNLPInputValue().trim();if(r&&!this.title.trim()){let a=this.nlParser.parseInput(r);this.applyParsedData(a)}}if(!this.validateForm()){new xs.Notice(this.t("modals.taskCreation.notices.titleRequired"));return}try{let r=this.buildTaskData(),a=await this.plugin.taskService.createTask(r,{applyDefaults:!1}),i=a.taskInfo;if(jM(this.plugin.settings,a.taskInfo.title,a.file.basename)?new xs.Notice(this.t("modals.taskCreation.notices.successShortened",{title:i.title})):new xs.Notice(this.t("modals.taskCreation.notices.success",{title:i.title})),this.blockingItems.length>0){let s=aue(this.blockingItems);if(s.added.length>0){await this.plugin.taskService.updateBlockingRelationships(i,s.added,[],s.raw);let o=await this.plugin.cacheManager.getTaskInfo(i.path);o&&(i=o)}s.unresolved.length>0&&new xs.Notice(this.t("modals.taskCreation.notices.blockingUnresolved",{entries:s.unresolved.join(", ")})),this.blockingItems=[]}this.selectedSubtaskFiles.length>0&&await this.applySubtaskAssignments(i),this.options.onTaskCreated&&this.options.onTaskCreated(i),await this.openCreatedTaskIfConfigured(a.file,t),this.close(),t.createAnother&&window.setTimeout(()=>{new n(this.app,this.plugin,this.options).open()},0)}catch(r){$M.error("Failed to create task:",{category:"persistence",operation:"create-task",error:r});let a=Tue(r);new xs.Notice(this.t("modals.taskCreation.notices.failure",{message:a}))}}async openCreatedTaskIfConfigured(t,r){var i;let a=(i=this.plugin.settings.openTaskAfterCreation)!=null?i:"none";if(bue(a,r,!!this.options.onTaskCreated))try{await wue(this.app,t,a)}catch(s){$M.error("Failed to open created task note:",{category:"persistence",operation:"open-created-task-note",error:s}),new xs.Notice(this.t("modals.taskCreation.notices.openCreatedTaskFailure"))}}buildTaskData(){var a;let t=nue({title:this.title,dueDate:this.dueDate,scheduledDate:this.scheduledDate,priority:this.priority,status:this.status,contexts:this.contexts,projects:this.projects,tags:this.tags,timeEstimate:this.timeEstimate,recurrenceRule:this.recurrenceRule,recurrenceAnchor:this.recurrenceAnchor,reminders:this.reminders,blockedByItems:this.blockedByItems,details:this.details,userFields:this.userFields,creationContext:this.options.creationContext,taskIdentificationMethod:this.plugin.settings.taskIdentificationMethod,taskTag:this.plugin.settings.taskTag,normalizeDetails:i=>this.normalizeDetails(i)}),r=(a=this.options.prePopulatedValues)==null?void 0:a.customFrontmatter;return r&&(t.customFrontmatter={...r,...t.customFrontmatter}),t}createTitleInput(t){this.plugin.settings.enableNaturalLanguageInput||super.createTitleInput(t)}async applySubtaskAssignments(t){let r=this.app.vault.getAbstractFileByPath(t.path);r instanceof xs.TFile&&await uue({currentTaskFile:r,subtaskFiles:this.selectedSubtaskFiles,getTaskInfo:a=>this.plugin.cacheManager.getTaskInfo(a),buildProjectReference:(a,i)=>this.buildProjectReference(a,i),updateTaskProjects:(a,i)=>this.plugin.updateTaskProperty(a,"projects",i),onError:a=>{$M.error("Failed to assign subtask:",{category:"persistence",operation:"assign-subtask",error:a})}})}onClose(){this.nlMarkdownEditor&&(this.nlMarkdownEditor.destroy(),this.nlMarkdownEditor=null),this.nlpSuggest&&(this.nlpSuggest.close(),this.nlpSuggest=null),this.removeAllEventListeners(),super.onClose()}}});var wv,YM,uU=y(()=>{wv=class{constructor(){this.inFlightRequests=new Map;this.prefetchQueue=new Set;this.prefetchPromises=new Map;this.activeTimeouts=new Set}async execute(e,t,r=5e3){if(this.inFlightRequests.has(e))return this.inFlightRequests.get(e);let a=this.createRequest(e,t,r);return this.inFlightRequests.set(e,a),a}async createRequest(e,t,r){try{let a=await t(),i=window.setTimeout(()=>{this.inFlightRequests.delete(e),this.activeTimeouts.delete(i)},r);return this.activeTimeouts.add(i),a}catch(a){throw this.inFlightRequests.delete(e),a}}prefetch(e,t,r="low"){if(!(this.inFlightRequests.has(e)||this.prefetchPromises.has(e)))if(r==="high")this.executePrefetch(e,t);else if(this.prefetchQueue.add(e),"requestIdleCallback"in window)requestIdleCallback(()=>{this.processPrefetchQueue(e,t)});else{let i=window.setTimeout(()=>{this.processPrefetchQueue(e,t),this.activeTimeouts.delete(i)},50);this.activeTimeouts.add(i)}}async executePrefetch(e,t){try{let r=t();this.prefetchPromises.set(e,r),await r;let a=window.setTimeout(()=>{this.prefetchPromises.delete(e),this.activeTimeouts.delete(a)},3e4);this.activeTimeouts.add(a)}catch(r){this.prefetchPromises.delete(e)}}processPrefetchQueue(e,t){this.prefetchQueue.has(e)&&(this.prefetchQueue.delete(e),this.executePrefetch(e,t))}getPrefetchedData(e){return this.prefetchPromises.get(e)||null}cancel(e){this.inFlightRequests.delete(e),this.prefetchPromises.delete(e),this.prefetchQueue.delete(e)}cancelAll(){this.inFlightRequests.clear(),this.prefetchPromises.clear(),this.prefetchQueue.clear();for(let e of this.activeTimeouts)window.clearTimeout(e);this.activeTimeouts.clear()}getStats(){return{inFlightCount:this.inFlightRequests.size,prefetchCount:this.prefetchPromises.size,queuedCount:this.prefetchQueue.size}}},YM=class{constructor(e){this.lastAccessTime=new Map;this.deduplicator=e}recordAccess(e,t,r){let a=this.getDateKey(e);this.lastAccessTime.set(a,Date.now()),this.prefetchAdjacentDates(e,t,r)}prefetchAdjacentDates(e,t,r){this.getAdjacentDates(e).forEach(({date:i,priority:s})=>{let o=`${t}-${this.getDateKey(i)}`;this.deduplicator.prefetch(o,()=>r(i),s)})}getAdjacentDates(e){let t=[],r=new Date(e);r.setDate(e.getDate()-1),t.push({date:r,priority:"high"});let a=new Date(e);a.setDate(e.getDate()+1),t.push({date:a,priority:"high"});for(let i=2;i<=7;i++){let s=new Date(e);s.setDate(e.getDate()-i),t.push({date:s,priority:"low"});let o=new Date(e);o.setDate(e.getDate()+i),t.push({date:o,priority:"low"})}return t}getDateKey(e){return e.toISOString().split("T")[0]}cleanup(){let e=Date.now(),t=1440*60*1e3;for(let[r,a]of this.lastAccessTime)e-a>t&&this.lastAccessTime.delete(r)}}});var zVe,Sv,KM,Yue=y(()=>{q();zVe=M({tag:"Utils/DOMReconciler"}),Sv=class{constructor(){this.updateQueue=[];this.isProcessing=!1;this.activeTimeouts=new Set}scheduleUpdate(e){this.updateQueue.push(e),this.isProcessing||(this.isProcessing=!0,window.requestAnimationFrame(()=>{this.processUpdates()}))}processUpdates(){let e=[...this.updateQueue];this.updateQueue=[];try{e.forEach(t=>{try{t()}catch(r){zVe.error("Error processing DOM update:",{category:"validation",operation:"processing-dom-update",error:r})}})}finally{this.isProcessing=!1,this.updateQueue.length>0&&window.requestAnimationFrame(()=>{this.processUpdates()})}}updateAttributes(e,t){for(let[r,a]of Object.entries(t))a===null?e.removeAttribute(r):e.getAttribute(r)!==a&&e.setAttribute(r,a)}updateClasses(e,t){for(let[r,a]of Object.entries(t))a?e.classList.add(r):e.classList.remove(r)}updateTextContent(e,t){e.textContent!==t&&(e.textContent=t)}updateStyles(e,t){for(let[r,a]of Object.entries(t))a===null?e.style.removeProperty(r):e.style.setProperty(r,a)}preserveState(e){let t={scrollTop:e.scrollTop,scrollLeft:e.scrollLeft,focused:activeDocument.activeElement===e,selection:null};return(e.instanceOf(HTMLInputElement)||e.instanceOf(HTMLTextAreaElement))&&(t.selection={start:e.selectionStart||0,end:e.selectionEnd||0}),t}restoreState(e,t){e.scrollTop=t.scrollTop,e.scrollLeft=t.scrollLeft,t.focused&&e.focus(),t.selection&&(e.instanceOf(HTMLInputElement)||e.instanceOf(HTMLTextAreaElement))&&e.setSelectionRange(t.selection.start,t.selection.end)}animateUpdate(e,t,r=1500){e.classList.add(`task-${t}`);let a=window.setTimeout(()=>{e.classList.remove(`task-${t}`),this.activeTimeouts.delete(a)},r);this.activeTimeouts.add(a)}updateList(e,t,r,a,i){let s=new Map,o=new Set;Array.from(e.children).forEach(d=>{let u=d.dataset.key;u&&(s.set(u,d),o.add(u))});let l=new Set(t.map(r)),c=activeWindow.createFragment();t.forEach(d=>{let u=r(d),p=s.get(u);if(p)i&&i(p,d),c.appendChild(p);else{let m=a(d);m.dataset.key=u,c.appendChild(m)}}),o.forEach(d=>{if(!l.has(d)){let u=s.get(d);u&&u.parentNode&&u.remove()}}),e.replaceChildren(c)}createOptimisticUpdate(e,t,r){return t(e),{commit:()=>{},revert:()=>{r(e)}}}destroy(){this.updateQueue=[],this.isProcessing=!1;for(let e of this.activeTimeouts)window.clearTimeout(e);this.activeTimeouts.clear()}},KM=class{constructor(){this.stateMap=new Map}saveState(e,t){let r=new Sv;this.stateMap.set(e,r.preserveState(t))}restoreState(e,t){let r=this.stateMap.get(e);r&&new Sv().restoreState(t,r)}clearState(e){e?this.stateMap.delete(e):this.stateMap.clear()}destroy(){this.stateMap.clear()}}});var Kue=y(()=>{yz()});var Cv,pU=y(()=>{wb();Ll();Cv=class n{constructor(e,t="open"){this.statuses=e;this.defaultStatus=t}normalizeStatusValue(e){var t;return(t=zu(e,this.statuses))!=null?t:String(e)}findStatusIndex(e,t){let r=this.normalizeStatusValue(t);return e.findIndex(a=>this.normalizeStatusValue(a.value)===r)}getCycleStatuses(){return this.getStatusesByOrder().filter(e=>!e.excludeFromCycle)}getNextStatus(e){var l,c;let t=this.getStatusConfig(e),r=t?this.normalizeStatusValue(t.value):void 0,a=t!=null&&t.nextStatus?this.normalizeStatusValue(t.nextStatus):void 0,i=a&&a!==r?this.getStatusConfig(a):void 0;if(i)return i.value;let s=this.getCycleStatuses(),o=this.findStatusIndex(s,e);if(s.length===0)return(t==null?void 0:t.value)||this.defaultStatus;if(o!==-1){let d=(o+1)%s.length;return s[d].value}return t?((c=s.find(d=>d.order>t.order))==null?void 0:c.value)||s[0].value:((l=s[0])==null?void 0:l.value)||this.defaultStatus}getPreviousStatus(e){var i,s,o;let t=this.getCycleStatuses(),r=this.findStatusIndex(t,e);if(t.length===0)return((i=this.getStatusConfig(e))==null?void 0:i.value)||this.defaultStatus;if(r!==-1){let l=(r-1+t.length)%t.length;return t[l].value}let a=this.getStatusConfig(e);return a?((o=[...t].reverse().find(l=>l.orderthis.normalizeStatusValue(r.value)===t)}getCompletedStatuses(){return this.statuses.filter(e=>e.isCompleted).map(e=>e.value)}getOpenStatuses(){return this.statuses.filter(e=>!e.isCompleted).map(e=>e.value)}getStatusesByOrder(){return[...this.statuses].sort((e,t)=>e.order-t.order)}isCompletedStatus(e){let t=this.getStatusConfig(e);return(t==null?void 0:t.isCompleted)||!1}getStatusOrder(e){let t=this.getStatusConfig(e);return(t==null?void 0:t.order)||0}getStatusColorVariables(){return this.statuses.map(e=>[`--status-${e.value.replace(/[^a-zA-Z0-9-]/g,"-")}-color`,hr(e.color)])}getAllStatuses(){return[...this.statuses]}getNonCompletionStatuses(){return this.statuses.filter(e=>!e.isCompleted)}updateStatuses(e){this.statuses=e}static validateStatuses(e){let t=[];e.length<2&&t.push("At least 2 statuses are required"),e.some(l=>l.isCompleted)||t.push("At least one status must be marked as completed");let a=e.map(l=>l.value),i=new Set(a);a.length!==i.size&&t.push("Status values must be unique");let s=e.map(l=>l.id),o=new Set(s);s.length!==o.size&&t.push("Status IDs must be unique");for(let l of e){if(!l.value||l.value.trim()===""){t.push("Status values cannot be empty");break}if(!l.label||l.label.trim()===""){t.push("Status labels cannot be empty");break}if(!M0(l.color)){t.push("Status colors must be valid CSS colors or Obsidian theme colors");break}}return{valid:t.length===0,errors:t}}static generateStatusId(e){let t=new Set(e.map(i=>i.id)),r=1,a=`status-${r}`;for(;t.has(a);)r++,a=`status-${r}`;return a}static createDefaultStatus(e){let t=n.generateStatusId(e),r=Math.max(...e.map(a=>a.order),0)+1;return{id:t,value:"new-status",label:"New status",color:"#808080",isCompleted:!1,excludeFromCycle:!1,order:r,autoArchive:!1,autoArchiveDelay:5}}}});var ZM,Zue=y(()=>{wb();Ll();ZM=class n{constructor(e){this.priorities=e}normalizePriorityValue(e){var t;return(t=Bu(e,this.priorities))!=null?t:String(e)}getPriorityConfig(e){let t=this.normalizePriorityValue(e);return this.priorities.find(r=>r.value===t)}getPrioritiesByWeight(){return[...this.priorities].sort((e,t)=>t.weight-e.weight)}getPrioritiesByWeightAsc(){return[...this.priorities].sort((e,t)=>e.weight-t.weight)}getNextPriority(e){var s;let t=this.getPrioritiesByWeightAsc(),r=this.normalizePriorityValue(e),a=t.findIndex(o=>o.value===r);if(a===-1)return((s=t[0])==null?void 0:s.value)||"normal";let i=(a+1)%t.length;return t[i].value}comparePriorities(e,t){let r=this.getPriorityConfig(e),a=this.getPriorityConfig(t),i=(r==null?void 0:r.weight)||0;return((a==null?void 0:a.weight)||0)-i}getPriorityColorVariables(){return this.priorities.map(e=>[`--priority-${e.value.replace(/[^a-zA-Z0-9-]/g,"-")}-color`,hr(e.color)])}getAllPriorities(){return[...this.priorities]}updatePriorities(e){this.priorities=e}getHighestPriority(){var t;return(t=this.getPrioritiesByWeight()[0])==null?void 0:t.value}getLowestPriority(){var t;return(t=this.getPrioritiesByWeightAsc()[0])==null?void 0:t.value}getPriorityWeight(e){let t=this.getPriorityConfig(e);return(t==null?void 0:t.weight)||0}isHigherPriority(e,t){return this.comparePriorities(e,t)>0}static validatePriorities(e){let t=[];e.length<1&&t.push("At least 1 priority is required");let r=e.map(c=>c.value),a=new Set(r);r.length!==a.size&&t.push("Priority values must be unique");let i=e.map(c=>c.id),s=new Set(i);i.length!==s.size&&t.push("Priority IDs must be unique");let o=e.map(c=>c.weight),l=new Set(o);o.length!==l.size&&t.push("Priority weights must be unique");for(let c of e){if(!c.value||c.value.trim()===""){t.push("Priority values cannot be empty");break}if(!c.label||c.label.trim()===""){t.push("Priority labels cannot be empty");break}if(!M0(c.color)){t.push("Priority colors must be valid CSS colors or Obsidian theme colors");break}if(typeof c.weight!="number"||c.weight<0){t.push("Priority weights must be non-negative numbers");break}}return{valid:t.length===0,errors:t}}static generatePriorityId(e){let t=new Set(e.map(i=>i.id)),r=1,a=`priority-${r}`;for(;t.has(a);)r++,a=`priority-${r}`;return a}static generatePriorityWeight(e){let t=e.map(r=>r.weight);return t.length===0?1:Math.max(...t)+1}static createDefaultPriority(e){let t=n.generatePriorityId(e),r=n.generatePriorityWeight(e);return{id:t,value:"new-priority",label:"New priority",color:"#808080",weight:r}}}});function Que({path:n,mappedTask:e,defaultTaskStatus:t,isBlocked:r,blockingTasks:a}){let i=e.timeEntries?oi(e.timeEntries):0;return{...e,id:n,path:n,title:e.title||"Untitled task",status:e.status||t,priority:e.priority||"normal",archived:e.archived||!1,tags:Array.isArray(e.tags)?e.tags:[],contexts:Array.isArray(e.contexts)?e.contexts:[],projects:Array.isArray(e.projects)?e.projects:[],totalTrackedTime:i,isBlocked:r,isBlocking:a.length>0,blocking:a.length>0?a:void 0}}var Jue=y(()=>{yt()});function BVe(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}function Xue(n,e){if(typeof n=="boolean"){let t=e.toLowerCase();if(t==="true"||t==="false")return n===(t==="true")}return n===e}function epe(n,e){if(!BVe(n))return!1;if(e.taskIdentificationMethod==="property"){let r=e.taskPropertyName,a=e.taskPropertyValue;if(!r||!a)return!1;let i=n[r];return i===void 0?!1:Array.isArray(i)?i.some(s=>Xue(s,a)):Xue(i,a)}return qo(n.tags).some(r=>ir.matchesHierarchicalTagExact(r,e.taskTag))}var tpe=y(()=>{Ad();Yg()});var po,Jf,QM,rpe=y(()=>{po=require("obsidian");Pr();wb();xe();hb();Jue();tpe();q();Jf=M({tag:"Utils/TaskManager"}),QM=class extends po.Events{constructor(t,r,a){super();this.initialized=!1;this.eventListeners=[];this.debouncedHandlers=new Map;this.DEBOUNCE_DELAY=300;this.pendingTaskInfoByPath=new Map;this.filterIndexesBuilt=!1;this.indexedTaskPaths=new Set;this.taskFilterEntries=new Map;this.statusIndex=new Map;this.priorityIndex=new Map;this.dueDateIndex=new Map;this.scheduledDateIndex=new Map;this.tagCounts=new Map;this.contextCounts=new Map;this.projectCounts=new Map;this._dependencyCache=void 0;this.app=t,this.settings=r,this.taskTag=r.taskTag,this.excludedFolders=Il(r.excludedFolders),this.fieldMapper=a,this.disableNoteIndexing=r.disableNoteIndexing,this.storeTitleInFilename=r.storeTitleInFilename}initialize(){this.initialized||(this.setupNativeEventListeners(),this.initialized=!0,this.trigger("cache-initialized",{message:"Task manager ready"}))}getApp(){return this.app}isTaskFile(t){return epe(t,this.settings)}setupNativeEventListeners(){let t=this.app.metadataCache.on("changed",(i,s,o)=>{i instanceof po.TFile&&i.extension==="md"&&this.isValidFile(i.path)&&this.handleFileChangedDebounced(i,o)});this.eventListeners.push(t);let r=this.app.metadataCache.on("deleted",(i,s)=>{i instanceof po.TFile&&i.extension==="md"&&this.handleFileDeleted(i.path,s)});this.eventListeners.push(r);let a=this.app.vault.on("rename",(i,s)=>{i instanceof po.TFile&&i.extension==="md"&&this.handleFileRenamed(i,s)});this.eventListeners.push(a)}handleFileChangedDebounced(t,r){let a=t.path,i=this.debouncedHandlers.get(a);i&&window.clearTimeout(i);let s=window.setTimeout(()=>{this.debouncedHandlers.delete(a),this.handleFileChanged(t,r)},this.DEBOUNCE_DELAY);this.debouncedHandlers.set(a,s)}async handleFileChanged(t,r){let a=null,i=!1;if(r&&typeof r=="object"&&"frontmatter"in r){let s=r.frontmatter;if(s&&this.isTaskFile(s)){let o=this.extractTaskInfoFromNative(t.path,s),l=this.getPendingTaskInfo(t.path);l&&this.shouldUsePendingTaskInfo(l,o)?a=l:(this.pendingTaskInfoByPath.delete(t.path),a=o)}else this.pendingTaskInfoByPath.delete(t.path)}i=this.updateFilterIndexesForFile(t.path,r),this.trigger("file-updated",{path:t.path,file:t,updatedTask:a,filterIndexChanged:i}),a&&this.trigger(rt,{path:t.path,task:a,taskInfo:a,updatedTask:a}),this.trigger("data-changed")}handleFileDeleted(t,r){this.pendingTaskInfoByPath.delete(t),this.removeFilterIndexEntry(t);let a=this.debouncedHandlers.get(t);a&&(window.clearTimeout(a),this.debouncedHandlers.delete(t)),this.trigger("file-deleted",{path:t,prevCache:r}),this.trigger("data-changed")}handleFileRenamed(t,r){let a=this.pendingTaskInfoByPath.get(r);a&&(this.pendingTaskInfoByPath.delete(r),this.pendingTaskInfoByPath.set(t.path,{...a,id:t.path,path:t.path}));let i=this.debouncedHandlers.get(r);i&&(window.clearTimeout(i),this.debouncedHandlers.delete(r)),this.removeFilterIndexEntry(r),this.updateFilterIndexesForFile(t.path,this.app.metadataCache.getFileCache(t)),this.trigger("file-renamed",{oldPath:r,newPath:t.path,file:t}),this.trigger("data-changed")}isValidFile(t){return!qg(t,this.excludedFolders)}async getTaskInfo(t){if(!this.isValidFile(t))return null;let r=this.app.vault.getAbstractFileByPath(t);if(!(r instanceof po.TFile))return null;let a=this.getPendingTaskInfo(t),i=this.app.metadataCache.getFileCache(r);if(!(i!=null&&i.frontmatter)){if(a)return a;if(i)return null;let o=await this.readFrontmatterFromFile(r);return!o||!this.isTaskFile(o)?null:this.extractTaskInfoFromNative(t,o)}let s=this.isTaskFile(i.frontmatter)?this.extractTaskInfoFromNative(t,i.frontmatter):null;return a&&this.shouldUsePendingTaskInfo(a,s)?a:(this.pendingTaskInfoByPath.delete(t),s)}getPendingTaskInfo(t){var a;let r=this.pendingTaskInfoByPath.get(t);return r?{...r,id:(a=r.id)!=null?a:t,path:t}:null}shouldUsePendingTaskInfo(t,r){return r?t.dateModified?r.dateModified!==t.dateModified:!1:!0}extractTaskInfoFromNative(t,r){if(!r||!this.fieldMapper||!this.isTaskFile(r))return null;try{let a=this.fieldMapper.mapFromFrontmatter(r,t,this.storeTitleInFilename),i=!1,s=[];return this._dependencyCache?(i=this._dependencyCache.isTaskBlocked(t),s=this._dependencyCache.getBlockedTaskPaths(t)):i=Array.isArray(a.blockedBy)&&a.blockedBy.length>0,Que({path:t,mappedTask:a,defaultTaskStatus:this.settings.defaultTaskStatus,isBlocked:i,blockingTasks:s})}catch(a){return Jf.error(`Error extracting task info from native metadata for ${t}:`,{category:"persistence",operation:"extracting-task-info-native-metadata",error:a}),null}}ensureFilterIndexes(){if(!this.filterIndexesBuilt){this.clearFilterIndexes();for(let t of this.app.vault.getMarkdownFiles()){if(!this.isValidFile(t.path))continue;let r=this.app.metadataCache.getFileCache(t);if(r!=null&&r.frontmatter&&this.isTaskFile(r.frontmatter)){let a=this.createFilterIndexEntry(t.path,r.frontmatter);this.addFilterIndexEntry(a)}}this.filterIndexesBuilt=!0}}updateFilterIndexesForFile(t,r){var o;if(!this.filterIndexesBuilt)return!0;if(!this.isValidFile(t))return this.removeFilterIndexEntry(t);let a=(o=this.getFrontmatterFromCache(r))!=null?o:this.getFrontmatterForPath(t);if(!a||!this.isTaskFile(a))return this.removeFilterIndexEntry(t);let i=this.createFilterIndexEntry(t,a),s=this.taskFilterEntries.get(t);return(s==null?void 0:s.signature)===i.signature?!1:(s&&this.removeFilterIndexEntry(t),this.addFilterIndexEntry(i),!0)}updateFilterIndexesFromTaskInfo(t,r){if(!this.filterIndexesBuilt)return!0;if(!this.isValidFile(t))return this.removeFilterIndexEntry(t);let a=this.createFilterIndexEntryFromTaskInfo(t,r),i=this.taskFilterEntries.get(t);return(i==null?void 0:i.signature)===a.signature?!1:(i&&this.removeFilterIndexEntry(t),this.addFilterIndexEntry(a),!0)}getFrontmatterFromCache(t){if(!t||typeof t!="object"||!("frontmatter"in t))return null;let r=t.frontmatter;return!r||typeof r!="object"||Array.isArray(r)?null:r}getFrontmatterForPath(t){let r=this.app.vault.getAbstractFileByPath(t);return r instanceof po.TFile?this.getFrontmatterFromCache(this.app.metadataCache.getFileCache(r)):null}createFilterIndexEntry(t,r){var w,S,C,x,E,_,F,I,A,R;let a=((w=this.fieldMapper)==null?void 0:w.toUserField("status"))||"status",i=((S=this.fieldMapper)==null?void 0:S.toUserField("priority"))||"priority",s=((C=this.fieldMapper)==null?void 0:C.toUserField("scheduled"))||"scheduled",o=((x=this.fieldMapper)==null?void 0:x.toUserField("due"))||"due",l=((E=this.fieldMapper)==null?void 0:E.toUserField("contexts"))||"context",c=((_=this.fieldMapper)==null?void 0:_.toUserField("projects"))||"project",d=((F=this.fieldMapper)==null?void 0:F.toUserField("timeEstimate"))||"timeEstimate",u=(I=zu(r[a],this.settings.customStatuses))!=null?I:void 0,p=(A=Bu(r[i],this.settings.customPriorities))!=null?A:void 0,m=this.normalizeDateValue(r[o]),f=this.normalizeDateValue(r[s]),h=this.normalizeStringValues(r.tags,!1),g=this.normalizeStringValues(r[l],!0),v=this.normalizeStringValues(r[c],!0),k=r[d],T=typeof k=="number"&&k>0?k:void 0,b=((R=this.settings.customStatuses)==null?void 0:R.some(O=>O.value===u&&O.isCompleted))||!1;return this.withFilterIndexSignature({path:t,status:u,priority:p,dueDate:m,scheduledDate:f,tags:h,contexts:g,projects:v,timeEstimate:T,isCompleted:b,signature:""})}createFilterIndexEntryFromTaskInfo(t,r){var m,f,h;let a=(m=zu(r.status,this.settings.customStatuses))!=null?m:void 0,i=(f=Bu(r.priority,this.settings.customPriorities))!=null?f:void 0,s=this.normalizeDateValue(r.due),o=this.normalizeDateValue(r.scheduled),l=this.normalizeStringValues(r.tags,!1),c=this.normalizeStringValues(r.contexts,!0),d=this.normalizeStringValues(r.projects,!0),u=typeof r.timeEstimate=="number"&&r.timeEstimate>0?r.timeEstimate:void 0,p=((h=this.settings.customStatuses)==null?void 0:h.some(g=>g.value===a&&g.isCompleted))||!1;return this.withFilterIndexSignature({path:t,status:a,priority:i,dueDate:s,scheduledDate:o,tags:l,contexts:c,projects:d,timeEstimate:u,isCompleted:p,signature:""})}withFilterIndexSignature(t){return{...t,signature:JSON.stringify({contexts:t.contexts,dueDate:t.dueDate,isCompleted:t.isCompleted,priority:t.priority,projects:t.projects,scheduledDate:t.scheduledDate,status:t.status,tags:t.tags,timeEstimate:t.timeEstimate})}}normalizeDateValue(t){if(typeof t!="string"||t.length===0)return;let r=re(t);return r.length>0?r:void 0}normalizeStringValues(t,r){let a=Array.isArray(t)?t:r&&t?[t]:[],i=new Set;for(let s of a){if(typeof s!="string")continue;let o=s.trim();o&&i.add(o)}return Array.from(i).sort()}addFilterIndexEntry(t){this.taskFilterEntries.set(t.path,t),this.indexedTaskPaths.add(t.path),this.addPathToIndex(this.statusIndex,t.status,t.path),this.addPathToIndex(this.priorityIndex,t.priority,t.path),this.addPathToIndex(this.dueDateIndex,t.dueDate,t.path),this.addPathToIndex(this.scheduledDateIndex,t.scheduledDate,t.path),this.incrementValues(this.tagCounts,t.tags),this.incrementValues(this.contextCounts,t.contexts),this.incrementValues(this.projectCounts,t.projects)}removeFilterIndexEntry(t){if(!this.filterIndexesBuilt)return!1;let r=this.taskFilterEntries.get(t);return r?(this.taskFilterEntries.delete(t),this.indexedTaskPaths.delete(t),this.removePathFromIndex(this.statusIndex,r.status,t),this.removePathFromIndex(this.priorityIndex,r.priority,t),this.removePathFromIndex(this.dueDateIndex,r.dueDate,t),this.removePathFromIndex(this.scheduledDateIndex,r.scheduledDate,t),this.decrementValues(this.tagCounts,r.tags),this.decrementValues(this.contextCounts,r.contexts),this.decrementValues(this.projectCounts,r.projects),!0):!1}addPathToIndex(t,r,a){if(!r)return;let i=t.get(r);if(i){i.add(a);return}t.set(r,new Set([a]))}removePathFromIndex(t,r,a){if(!r)return;let i=t.get(r);i&&(i.delete(a),i.size===0&&t.delete(r))}incrementValues(t,r){var a;for(let i of r)t.set(i,((a=t.get(i))!=null?a:0)+1)}decrementValues(t,r){var a;for(let i of r){let s=((a=t.get(i))!=null?a:0)-1;s>0?t.set(i,s):t.delete(i)}}sortedCountKeys(t){return Array.from(t.keys()).sort()}clearFilterIndexes(){this.indexedTaskPaths.clear(),this.taskFilterEntries.clear(),this.statusIndex.clear(),this.priorityIndex.clear(),this.dueDateIndex.clear(),this.scheduledDateIndex.clear(),this.tagCounts.clear(),this.contextCounts.clear(),this.projectCounts.clear()}async getAllTasks(){let t=[],r=this.app.vault.getMarkdownFiles();for(let a of r){if(!this.isValidFile(a.path))continue;let i=await this.getTaskInfo(a.path);i&&t.push(i)}return t}getAllCachedTasks(){let t=[],r=this.app.vault.getMarkdownFiles();for(let a of r){if(!this.isValidFile(a.path))continue;let i=this.getCachedTaskInfoSync(a.path);i&&t.push(i)}return t}getAllTaskPaths(){return this.ensureFilterIndexes(),new Set(this.indexedTaskPaths)}getTasksForDate(t){var a,i;let r=re(t);return this.ensureFilterIndexes(),Array.from(new Set([...(a=this.scheduledDateIndex.get(r))!=null?a:[],...(i=this.dueDateIndex.get(r))!=null?i:[]]))}getTaskPathsForDateRange(t,r,a){this.ensureFilterIndexes();let i=re(a),s=t==="due"?this.dueDateIndex:this.scheduledDateIndex,o=new Set;for(let[l,c]of s)if(this.matchesDateRange(l,r,i))for(let d of c)o.add(d);return o}matchesDateRange(t,r,a){switch(r){case"is-before":return ta;case"is-on-or-before":return t<=a;case"is-on-or-after":return t>=a;default:return!1}}getTaskPathsByStatus(t){var a,i;let r=(a=zu(t,this.settings.customStatuses))!=null?a:t;return this.ensureFilterIndexes(),Array.from((i=this.statusIndex.get(r))!=null?i:[])}getTaskPathsByPriority(t){var a,i;let r=(a=Bu(t,this.settings.customPriorities))!=null?a:t;return this.ensureFilterIndexes(),Array.from((i=this.priorityIndex.get(r))!=null?i:[])}getOverdueTaskPaths(){let t=new Set,r=zr();this.ensureFilterIndexes();for(let[a,i]of this.dueDateIndex)if(cf(a,r))for(let s of i){let o=this.taskFilterEntries.get(s);o&&!o.isCompleted&&t.add(s)}return t}getAllStatuses(){return this.ensureFilterIndexes(),Array.from(this.statusIndex.keys()).sort()}getAllPriorities(){return this.ensureFilterIndexes(),Array.from(this.priorityIndex.keys()).sort()}getAllTags(){return this.ensureFilterIndexes(),this.sortedCountKeys(this.tagCounts)}getAllContexts(){return this.ensureFilterIndexes(),this.sortedCountKeys(this.contextCounts)}getAllProjects(){return this.ensureFilterIndexes(),this.sortedCountKeys(this.projectCounts)}getAllTimeEstimates(){let t=new Map;this.ensureFilterIndexes();for(let[r,a]of this.taskFilterEntries)a.timeEstimate!==void 0&&t.set(r,a.timeEstimate);return t}async getNotesForDate(t){if(this.disableNoteIndexing)return[];let r=[],a=ae(t),i=this.app.vault.getMarkdownFiles();for(let s of i){if(!this.isValidFile(s.path))continue;let o=this.app.metadataCache.getFileCache(s);if(!(o!=null&&o.frontmatter)||this.isTaskFile(o.frontmatter))continue;(o.frontmatter.date||o.frontmatter.scheduled)===a&&r.push({path:s.path,title:this.storeTitleInFilename?s.basename:o.frontmatter.title||s.basename,tags:o.frontmatter.tags||[]})}return r}async getTaskByPath(t){return this.getTaskInfo(t)}async getCachedTaskInfo(t){return this.getTaskInfo(t)}getCachedTaskInfoSync(t){if(!this.isValidFile(t))return null;let r=this.app.vault.getAbstractFileByPath(t);if(!(r instanceof po.TFile))return null;let a=this.getPendingTaskInfo(t),i=this.app.metadataCache.getFileCache(r);if(!(i!=null&&i.frontmatter))return a;let s=this.isTaskFile(i.frontmatter)?this.extractTaskInfoFromNative(t,i.frontmatter):null;return a&&this.shouldUsePendingTaskInfo(a,s)?a:(this.pendingTaskInfoByPath.delete(t),s)}async readFrontmatterFromFile(t){try{let r=await this.app.vault.read(t);return this.parseFrontmatterFromContent(r,t.path)}catch(r){return Jf.warn(`TaskManager: Failed to read frontmatter fallback for ${t.path}`,{category:"validation",operation:"taskmanager-read-frontmatter-fallback",error:r}),null}}parseFrontmatterFromContent(t,r){let a=t.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);if(!a)return null;try{let i=(0,po.parseYaml)(a[1]||"");return!i||typeof i!="object"||Array.isArray(i)?null:i}catch(i){let s=r?` for ${r}`:"";return Jf.warn(`TaskManager: Failed to parse frontmatter fallback${s}`,{category:"validation",operation:"taskmanager-parse-frontmatter-fallback",details:r?{path:r}:void 0,error:i}),null}}isInitialized(){return this.initialized}destroy(){this.debouncedHandlers.forEach(t=>{window.clearTimeout(t)}),this.debouncedHandlers.clear(),this.eventListeners.forEach(t=>{this.app.metadataCache.offref(t)}),this.eventListeners=[],this.clearFilterIndexes(),this.filterIndexesBuilt=!1,this.initialized=!1}setDependencyCache(t){this._dependencyCache=t}getBlockingTaskPaths(t){return this._dependencyCache?this._dependencyCache.getBlockingTaskPaths(t):(Jf.warn("DependencyCache not set in TaskManager",{category:"stale-data",operation:"dependencycache-not-set-taskmanager"}),[])}getBlockedTaskPaths(t){return this._dependencyCache?this._dependencyCache.getBlockedTaskPaths(t):(Jf.warn("DependencyCache not set in TaskManager",{category:"stale-data",operation:"dependencycache-not-set-taskmanager"}),[])}isTaskBlocked(t){return this._dependencyCache?this._dependencyCache.isTaskBlocked(t):!1}getTasksReferencingProject(t){return this._dependencyCache?this._dependencyCache.getTasksReferencingProject(t):(Jf.warn("DependencyCache not set in TaskManager",{category:"stale-data",operation:"dependencycache-not-set-taskmanager"}),[])}isFileUsedAsProject(t){return this._dependencyCache?this._dependencyCache.isFileUsedAsProject(t):!1}async waitForFreshTaskData(t,r=10){let a=typeof t=="string"?t:t.path,i=typeof t=="string"?this.app.vault.getAbstractFileByPath(a):t;if(!(i instanceof po.TFile)){await new Promise(s=>window.setTimeout(s,100));return}for(let s=0;swindow.setTimeout(l,50*(s+1)))}Jf.warn(`TaskManager: Metadata cache not ready for ${a} after ${r} retries`,{category:"stale-data",operation:"taskmanager-metadata-cache-not-ready"})}updateConfig(t){this.settings=t,this.taskTag=t.taskTag,this.excludedFolders=Il(t.excludedFolders),this.disableNoteIndexing=t.disableNoteIndexing,this.storeTitleInFilename=t.storeTitleInFilename,this.clearFilterIndexes(),this.filterIndexesBuilt=!1,this.pruneExcludedPendingTaskInfo(),this.trigger("data-changed")}pruneExcludedPendingTaskInfo(){for(let t of this.pendingTaskInfoByPath.keys())this.isValidFile(t)||this.pendingTaskInfoByPath.delete(t)}subscribe(t,r){return this.on(t,r),()=>{this.off(t,r)}}async getCalendarData(t,r){let a=await this.getAllTasks(),i={};for(let s of a)s.scheduled&&(i[s.scheduled]||(i[s.scheduled]=[]),i[s.scheduled].push(s)),s.due&&(i[s.due]||(i[s.due]=[]),i[s.due].includes(s)||i[s.due].push(s));return i}async getTaskInfoForDate(t){let r=ae(t),a=this.getTasksForDate(r),i=[];for(let s of a){let o=await this.getTaskInfo(s);o&&i.push(o)}return i}getTaskPathsByDate(t){return new Set(this.getTasksForDate(t))}getAllProjectsWithDetails(){return[]}getAllProjectFiles(){return[]}async rebuildDailyNotesCache(t,r){}async clearAllCaches(){this.pendingTaskInfoByPath.clear(),this.clearFilterIndexes(),this.filterIndexesBuilt=!1,this.trigger("data-changed")}clearCacheEntry(t){this.pendingTaskInfoByPath.delete(t),this.removeFilterIndexEntry(t)}updateTaskInfoInCache(t,r){var i;let a=!1;if(!this.isValidFile(t)){this.pendingTaskInfoByPath.delete(t),a=this.removeFilterIndexEntry(t),this.trigger("data-changed");return}this.pendingTaskInfoByPath.set(t,{...r,id:(i=r.id)!=null?i:t,path:t}),a=this.updateFilterIndexesFromTaskInfo(t,r),this.trigger("file-updated",{path:t,updatedTask:r,filterIndexChanged:a})}}});var Xf,JM,bp,XM,mU=y(()=>{Xf=require("obsidian");Zs();hb();q();JM=M({tag:"Utils/DependencyCache"}),bp="dependency-cache-changed",XM=class extends Xf.Events{constructor(t,r,a,i,s){super();this.dependencySources=new Map;this.dependencyTargets=new Map;this.activeDependencySources=new Map;this.activeDependencyTargets=new Map;this.projectReferences=new Map;this.projectReferenceSources=new Map;this.relationshipFingerprints=new Map;this.completedStatusByPath=new Map;this.initialized=!1;this.indexesBuilt=!1;this.eventListeners=[];this.app=t,this.settings=r,this.excludedFolders=Il(r.excludedFolders),this.fieldMapper=a,this.statusManager=i,this.isTaskFileCallback=s}initialize(){this.initialized||(this.setupEventListeners(),this.initialized=!0)}async buildIndexes(){if(this.indexesBuilt)return;let t=this.app.vault.getMarkdownFiles();for(let r of t){if(!this.isValidFile(r.path))continue;let a=this.app.metadataCache.getFileCache(r);!(a!=null&&a.frontmatter)||!this.isTaskFileCallback(a.frontmatter)||this.indexTaskFile(r.path,a.frontmatter)}this.indexesBuilt=!0,this.trigger(bp)}setupEventListeners(){let t=this.app.metadataCache.on("changed",(i,s,o)=>{i instanceof Xf.TFile&&i.extension==="md"&&this.handleFileChanged(i,o)});this.eventListeners.push(t);let r=this.app.metadataCache.on("deleted",(i,s)=>{i instanceof Xf.TFile&&i.extension==="md"&&this.handleFileDeleted(i.path)});this.eventListeners.push(r);let a=this.app.vault.on("rename",(i,s)=>{i instanceof Xf.TFile&&i.extension==="md"&&this.handleFileRenamed(i,s)});this.eventListeners.push(a)}handleFileChanged(t,r){var o;let a=this.getFileRelationshipSignature(t.path);if(!this.isValidFile(t.path)){this.clearFileFromIndexes(t.path),this.triggerIfFileRelationshipsChanged(t.path,a);return}let i=(o=this.getFrontmatterFromCache(r))!=null?o:this.getFrontmatterForFile(t);if(this.updateCompletionState(t.path,i),!i){this.hasForwardRelationships(t.path)&&this.clearForwardDependencies(t.path),this.triggerIfFileRelationshipsChanged(t.path,a);return}if(!this.isTaskFileCallback(i)){this.hasForwardRelationships(t.path)&&this.clearForwardDependencies(t.path),this.triggerIfFileRelationshipsChanged(t.path,a);return}let s=this.buildRelationshipFingerprint(i);if(this.relationshipFingerprints.get(t.path)===s){this.triggerIfFileRelationshipsChanged(t.path,a);return}this.clearForwardDependencies(t.path),this.indexTaskFile(t.path,i),this.triggerIfFileRelationshipsChanged(t.path,a)}triggerIfFileRelationshipsChanged(t,r){this.getFileRelationshipSignature(t)!==r&&this.trigger(bp)}getFileRelationshipSignature(t){let r=this.sortedSetValues(this.dependencySources.get(t)),a=this.sortedSetValues(this.activeDependencyTargets.get(t)),i=this.sortedSetValues(this.projectReferenceSources.get(t)),s=this.sortedSetValues(this.projectReferences.get(t));return JSON.stringify({blockedTasks:a,blockingTasks:r,projectTasks:s,referencedProjects:i})}sortedSetValues(t){return t?Array.from(t).sort():[]}handleFileDeleted(t){this.clearFileFromIndexes(t),this.trigger(bp)}handleFileRenamed(t,r){let a=this.getFrontmatterForFile(t);this.clearFileFromIndexes(r),this.isValidFile(t.path)&&a&&this.isTaskFileCallback(a)&&this.indexTaskFile(t.path,a),this.trigger(bp)}getFrontmatterForFile(t){let r=this.app.metadataCache.getFileCache(t);return this.getFrontmatterFromCache(r)}getFrontmatterFromCache(t){if(!t||typeof t!="object"||!("frontmatter"in t))return null;let r=t.frontmatter;return!r||typeof r!="object"||Array.isArray(r)?null:r}resolveProjectReference(t,r){if(!r||typeof r!="string")return null;let a=r.trim();if(!a)return null;let i=Jo(this.app,t,a);return(i==null?void 0:i.path)||null}indexTaskFile(t,r){var l,c;if(!this.isValidFile(t))return;this.relationshipFingerprints.set(t,this.buildRelationshipFingerprint(r)),this.completedStatusByPath.set(t,this.isCompletedFrontmatter(r));let a=((l=this.fieldMapper)==null?void 0:l.toUserField("blockedBy"))||"blockedBy",i=((c=this.fieldMapper)==null?void 0:c.toUserField("projects"))||"project",s=r[a];if(s){let d=yf(s);if(d){let u=new Set;for(let p of d){let m=Jo(this.app,t,p);m!=null&&m.path&&this.isValidFile(m.path)&&this.addDependencyLink(t,m.path,u)}u.size>0&&this.dependencySources.set(t,u)}}let o=r[i];if(o){let d=Array.isArray(o)?o:[o];for(let u of d)if(typeof u=="string"){let p=this.resolveProjectReference(t,u);p&&this.isValidFile(p)&&(this.projectReferences.has(p)||this.projectReferences.set(p,new Set),this.projectReferences.get(p).add(t),this.projectReferenceSources.has(t)||this.projectReferenceSources.set(t,new Set),this.projectReferenceSources.get(t).add(p))}}}addDependencyLink(t,r,a){a.add(r),this.dependencyTargets.has(r)||this.dependencyTargets.set(r,new Set),this.dependencyTargets.get(r).add(t),this.isCompletedPath(r)||this.addActiveDependencyLink(t,r)}addActiveDependencyLink(t,r){this.activeDependencySources.has(t)||this.activeDependencySources.set(t,new Set),this.activeDependencySources.get(t).add(r),this.activeDependencyTargets.has(r)||this.activeDependencyTargets.set(r,new Set),this.activeDependencyTargets.get(r).add(t)}removeActiveDependencyLink(t,r){let a=this.activeDependencySources.get(t);a&&(a.delete(r),a.size===0&&this.activeDependencySources.delete(t));let i=this.activeDependencyTargets.get(r);i&&(i.delete(t),i.size===0&&this.activeDependencyTargets.delete(r))}rebuildActiveLinksForBlocker(t){let r=this.dependencyTargets.get(t);if(this.activeDependencyTargets.delete(t),!!r){for(let a of r){let i=this.activeDependencySources.get(a);i&&(i.delete(t),i.size===0&&this.activeDependencySources.delete(a))}if(!this.isCompletedPath(t))for(let a of r)this.addActiveDependencyLink(a,t)}}buildRelationshipFingerprint(t){var o,l,c;let r=((o=this.fieldMapper)==null?void 0:o.toUserField("blockedBy"))||"blockedBy",a=((l=this.fieldMapper)==null?void 0:l.toUserField("projects"))||"project",i=((c=yf(t[r]))!=null?c:[]).map(d=>d.uid).filter(d=>d.length>0).sort(),s=this.normalizeProjectFingerprintValues(t[a]);return JSON.stringify({dependencies:i,projects:s})}normalizeProjectFingerprintValues(t){let r=Array.isArray(t)?t:t?[t]:[],a=new Set;for(let i of r){if(typeof i!="string")continue;let s=i.trim();s&&a.add(s)}return Array.from(a).sort()}hasForwardRelationships(t){return this.relationshipFingerprints.has(t)||this.dependencySources.has(t)||this.projectReferenceSources.has(t)}updateCompletionState(t,r){var s;let a=(s=this.completedStatusByPath.get(t))!=null?s:!1,i=r?this.isCompletedFrontmatter(r):!1;this.completedStatusByPath.set(t,i),a!==i&&this.rebuildActiveLinksForBlocker(t)}isCompletedPath(t){let r=this.completedStatusByPath.get(t);if(r!==void 0)return r;let a=this.app.vault.getAbstractFileByPath(t);if(!(a instanceof Xf.TFile))return this.completedStatusByPath.set(t,!1),!1;let i=this.getFrontmatterForFile(a),s=i?this.isCompletedFrontmatter(i):!1;return this.completedStatusByPath.set(t,s),s}isCompletedFrontmatter(t){var s;let r=((s=this.fieldMapper)==null?void 0:s.toUserField("status"))||"status",a=t[r],i=this.stringifyStatusValue(a);return!!(i&&this.statusManager.isCompletedStatus(i))}stringifyStatusValue(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"?String(t):null}clearForwardDependencies(t){let r=this.dependencySources.get(t);if(r){for(let i of r){let s=this.dependencyTargets.get(i);s&&(s.delete(t),s.size===0&&this.dependencyTargets.delete(i)),this.removeActiveDependencyLink(t,i)}this.dependencySources.delete(t)}this.activeDependencySources.delete(t);let a=this.projectReferenceSources.get(t);if(a){for(let i of a){let s=this.projectReferences.get(i);s&&(s.delete(t),s.size===0&&this.projectReferences.delete(i))}this.projectReferenceSources.delete(t)}this.relationshipFingerprints.delete(t)}clearFileFromIndexes(t){let r=this.dependencySources.get(t);if(r){for(let o of r){let l=this.dependencyTargets.get(o);l&&(l.delete(t),l.size===0&&this.dependencyTargets.delete(o)),this.removeActiveDependencyLink(t,o)}this.dependencySources.delete(t)}this.activeDependencySources.delete(t);let a=this.dependencyTargets.get(t);if(a){for(let o of a){let l=this.dependencySources.get(o);l&&(l.delete(t),l.size===0&&this.dependencySources.delete(o)),this.removeActiveDependencyLink(o,t)}this.dependencyTargets.delete(t)}this.activeDependencyTargets.delete(t);let i=this.projectReferenceSources.get(t);if(i){for(let o of i){let l=this.projectReferences.get(o);l&&(l.delete(t),l.size===0&&this.projectReferences.delete(o))}this.projectReferenceSources.delete(t)}let s=this.projectReferences.get(t);if(s){for(let o of s){let l=this.projectReferenceSources.get(o);l&&(l.delete(t),l.size===0&&this.projectReferenceSources.delete(o))}this.projectReferences.delete(t)}this.relationshipFingerprints.delete(t),this.completedStatusByPath.delete(t)}getBlockingTaskPaths(t){this.indexesBuilt||(JM.warn("DependencyCache: getBlockingTaskPaths called before indexes built, building now...",{category:"stale-data",operation:"dependencycache-getblockingtaskpaths-called-indexes-built-building-now"}),this.buildIndexesSync());let r=this.dependencySources.get(t);return r?Array.from(r):[]}getBlockedTaskPaths(t){this.indexesBuilt||(JM.warn("DependencyCache: getBlockedTaskPaths called before indexes built, building now...",{category:"stale-data",operation:"dependencycache-getblockedtaskpaths-called-indexes-built-building-now"}),this.buildIndexesSync());let r=this.activeDependencyTargets.get(t);return r?Array.from(r):[]}isTaskBlocked(t){var r,a;return this.indexesBuilt||this.buildIndexesSync(),((a=(r=this.activeDependencySources.get(t))==null?void 0:r.size)!=null?a:0)>0}getTasksReferencingProject(t){this.indexesBuilt||(JM.warn("DependencyCache: getTasksReferencingProject called before indexes built, building now...",{category:"stale-data",operation:"dependencycache-gettasksreferencingproject-called-indexes-built-building-now"}),this.buildIndexesSync());let r=this.projectReferences.get(t);return r?Array.from(r):[]}isFileUsedAsProject(t){return this.indexesBuilt||(JM.warn("DependencyCache: isFileUsedAsProject called before indexes built, building now...",{category:"stale-data",operation:"dependencycache-isfileusedasproject-called-indexes-built-building-now"}),this.buildIndexesSync()),this.projectReferences.has(t)}buildIndexesSync(){if(this.indexesBuilt)return;let t=this.app.vault.getMarkdownFiles();for(let r of t){if(!this.isValidFile(r.path))continue;let a=this.app.metadataCache.getFileCache(r);!(a!=null&&a.frontmatter)||!this.isTaskFileCallback(a.frontmatter)||this.indexTaskFile(r.path,a.frontmatter)}this.indexesBuilt=!0,this.trigger(bp)}updateConfig(t){this.settings=t,this.excludedFolders=Il(t.excludedFolders),this.clearIndexes(),this.indexesBuilt=!1}isValidFile(t){return!qg(t,this.excludedFolders)}clearIndexes(){this.dependencySources.clear(),this.dependencyTargets.clear(),this.activeDependencySources.clear(),this.activeDependencyTargets.clear(),this.projectReferences.clear(),this.projectReferenceSources.clear(),this.relationshipFingerprints.clear(),this.completedStatusByPath.clear()}destroy(){this.eventListeners.forEach(t=>{this.app.metadataCache.offref(t)}),this.eventListeners=[],this.clearIndexes(),this.initialized=!1,this.indexesBuilt=!1}}});function mo(n){let e=cpe(n),t=e.match(tI);if(t){let[,a,i,s]=t,o=Number(a),l=Number(i),c=Number(s);if(!upe(o,l,c))throw new Error(`Invalid date "${n}".`);return new Date(Date.UTC(o,l-1,c,0,0,0,0))}if(!dpe(e))throw new Error(`Invalid date "${n}".`);let r=new Date(e);if(!rI(r))throw new Error(`Invalid date "${n}".`);return r}function $Ve(n){let e=cpe(n),t=e.match(tI);if(t){let[,a,i,s]=t,o=Number(a),l=Number(i),c=Number(s),d=new Date(o,l-1,c,0,0,0,0);if(!rI(d)||d.getFullYear()!==o||d.getMonth()!==l-1||d.getDate()!==c)throw new Error(`Invalid date "${n}".`);return d}if(!dpe(e))throw new Error(`Invalid date "${n}".`);let r=new Date(e);if(!rI(r))throw new Error(`Invalid date "${n}".`);return r}function sc(n){if(!rI(n))return"";let e=n.getUTCFullYear(),t=String(n.getUTCMonth()+1).padStart(2,"0"),r=String(n.getUTCDate()).padStart(2,"0");return`${e}-${t}-${r}`}function UVe(n){return sc(n)}function HVe(){let n=new Date,e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),r=String(n.getDate()).padStart(2,"0");return`${e}-${t}-${r}`}function hU(n){return mo(wp(n))}function VVe(n){if(!/^\d{4}-\d{2}-\d{2}$/.test(n))throw new Error(`Invalid date "${n}". Expected YYYY-MM-DD.`);return mo(n),n}function WVe(n){return n?/T\d{2}:\d{2}/.test(n):!1}function wp(n){if(!n)return"";let e=n.trim();if(tI.test(e))return e;let t=e.indexOf("T");if(t>-1)return e.slice(0,t);let r=e.indexOf(" ");return r>-1&&tI.test(e.slice(0,r))?e.slice(0,r):sc(mo(e))}function cpe(n,e="Date string cannot be empty"){if(!n||n.trim().length===0)throw new Error(e);return n.trim()}function dpe(n){let e=n.match(jVe);if(!e)return!1;let[,t,r,a,i,s,o,,l,c,d]=e;return upe(Number(t),Number(r),Number(a))&&qVe(Number(i),Number(s),Number(o))&&GVe(l,c,d)}function upe(n,e,t){let r=new Date(Date.UTC(n,e-1,t,0,0,0,0));return r.getUTCFullYear()===n&&r.getUTCMonth()===e-1&&r.getUTCDate()===t}function qVe(n,e,t){return n>=0&&n<=23&&e>=0&&e<=59&&t>=0&&t<=59}function GVe(n,e,t){if(!n)return!0;let r=Number(e),a=Number(t);return!(r>14||a>59||r===14&&a!==0)}function rI(n){return n instanceof Date&&!Number.isNaN(n.getTime())}function ppe(n,e){if(!n.recurrence||typeof n.recurrence!="string")return!0;try{let t=fpe(n);if(!t)return!1;let r=hU(UVe(e));return t.between(r,new Date(r.getTime()+1440*60*1e3-1),!0).length>0}catch(t){return!0}}function mpe(n,e,t){if(!n.recurrence||typeof n.recurrence!="string")return[];try{let r=fpe(n);if(!r)return[];let a=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,0,0)),i=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),23,59,59,999));return r.between(a,i,!0)}catch(r){let a=[],i=new Date(e);for(;i<=t;)ppe(n,i)&&a.push(new Date(i)),i.setUTCDate(i.getUTCDate()+1);return a}}function YVe(n,e={}){return n.recurrence?(n.recurrence_anchor||"scheduled")==="completion"?nWe(n,e):rWe(n,e):null}function KVe(n,e=!0,t={}){let r=YVe(n,t),a=null,i=null,s=null;if(r){try{let o=n.scheduled?mo(wp(n.scheduled)):null,l=n.due?mo(wp(n.due)):null;if(o&&l){let c=!e&&l.getTime()=t)return c}return null}function nWe(n,e){if(!n.recurrence||typeof n.recurrence!="string")return null;let t=mo(e.today||lpe()),r=hpe(n.recurrence),a=gU(n.recurrence),i=a||t,s=new Date(i.getTime()+r*24*60*60*1e3),o=mpe(n,i,s),l=new Set(n.skipped_instances||[]),c=a?a.getTime():0;for(let d of o){let u=sc(d);if(d.getTime()>c&&d>=t&&!l.has(u))return d}return null}function aWe(n){let e=n.toLowerCase();return e==="true"||e==="false"?e==="true":n}function iWe(n){let e=n.trim(),t=e.match(/^\[\[([^|\]#]+)(?:#[^\]|]+)?(?:\|[^\]]+)?\]\]$/);if(t)return t[1].trim();let r=e.match(/^\[[^\]]+\]\(([^)#]+)(?:#[^)]+)?\)$/);return r?decodeURI(r[1].trim()):e}function ype(n,e="manual"){return lWe(n.occurrence_materialization)?n.occurrence_materialization:e}function sWe(n,e="completion"){return cWe(n.occurrence_next_trigger)?n.occurrence_next_trigger:e}function FC(n){return typeof n.recurrence_parent=="string"&&typeof n.occurrence_date=="string"}function eh(n){return n?iWe(n).replace(/\\/g,"/").replace(/^\/+/,"").replace(/\.md$/i,"").trim().toLowerCase():""}function vpe(n){return`[[${n.path.replace(/\.md$/i,"")}]]`}function yU(n,e,t,r=vpe(e)){let a=eh(e.path),i=eh(r);return n.find(s=>{if(s.occurrence_date!==t||!s.recurrence_parent)return!1;let o=eh(s.recurrence_parent);return o===a||o===i})}function vU({parentTask:n,targetDate:e,currentTimestamp:t,existingOccurrences:r=[],parentLink:a,defaultStatus:i=n.status,defaultPriority:s=n.priority,templateTask:o={},overrides:l={},allowNonGeneratedTarget:c=!0}){var v,k,T,b,w,S,C,x,E,_,F,I,A,R;if(!n.recurrence)throw new Error("occurrence_parent_not_recurring");let d=kU(e),u=a||vpe(n),p=yU(r,n,d,u),m=[];if(yWe(n,d)||m.push({code:"materialization_target_not_generated",message:`Target date "${d}" is not generated by the parent recurrence rule.`,severity:c?"warning":"error",field:"occurrence_date"}),p)return{kind:"occurrence.materialize",parentTask:n,targetDate:d,parentReference:u,created:!1,existingOccurrence:p,occurrenceTask:p,fields:xv(p),issues:m,metadata:{idempotent:!0}};let f=dWe(n,d),h=hWe(f.customProperties,o.customProperties,l.customProperties),g=Epe({...f,...o,...l,id:void 0,path:void 0,archived:void 0,status:(k=(v=l.status)!=null?v:o.status)!=null?k:i,priority:(w=(b=(T=l.priority)!=null?T:o.priority)!=null?b:n.priority)!=null?w:s,scheduled:(x=(C=(S=l.scheduled)!=null?S:o.scheduled)!=null?C:f.scheduled)!=null?x:d,due:(_=(E=l.due)!=null?E:o.due)!=null?_:f.due,customProperties:h,recurrence:void 0,recurrence_anchor:void 0,complete_instances:void 0,skipped_instances:void 0,recurrence_parent:u,occurrence_date:d,occurrence_materialization:void 0,occurrence_next_trigger:void 0,occurrence_template:void 0,occurrence_past_horizon:void 0,occurrence_future_horizon:void 0,completedDate:void 0,timeEntries:void 0,totalTrackedTime:void 0,icsEventId:void 0,googleCalendarEventId:void 0,googleCalendarExceptionEventId:void 0,googleCalendarExceptionOriginalScheduled:void 0,googleCalendarMovedOriginalDates:void 0,basesData:void 0,blocking:void 0,isBlocked:void 0,isBlocking:void 0,hasSubtasks:void 0,dateCreated:(I=(F=l.dateCreated)!=null?F:o.dateCreated)!=null?I:t,dateModified:(R=(A=l.dateModified)!=null?A:o.dateModified)!=null?R:t});return{kind:"occurrence.materialize",parentTask:n,targetDate:d,parentReference:u,created:!0,occurrenceTask:g,fields:xv(g),issues:m,metadata:{idempotent:!1,template:n.occurrence_template}}}function kpe({occurrenceTask:n,parentTask:e,completedStatus:t,currentTimestamp:r,targetDate:a,completionDate:i,maintainDueDateOffsetInRecurring:s}){let o=nI(n,a);if(aI(n,o),!e.recurrence)throw new Error("occurrence_parent_not_recurring");let l=i===void 0?o:kU(i),c=(e.recurrence_anchor||"scheduled")==="completion"?l:o,d=Dpe(Ev(e.complete_instances),o),u=Ev(e.skipped_instances).filter(v=>v!==o),p=xpe({parentTask:e,targetDate:c,completeInstances:d,skippedInstances:u,currentTimestamp:r,maintainDueDateOffsetInRecurring:s,advanceCompletionAnchor:!0}),m={status:t,completedDate:l,dateModified:r},f={...e,...p},h={...n,...m},g=ype(e)==="on_completion"?wp(f.scheduled||""):void 0;return iI({kind:"occurrence.complete",targetDate:o,occurrenceTask:n,parentTask:e,updatedOccurrenceTask:h,updatedParentTask:f,occurrenceUpdates:m,parentUpdates:p,currentTimestamp:r,materializeNextDate:g,metadata:{trigger:"completion"}})}function Tpe({occurrenceTask:n,parentTask:e,activeStatus:t,currentTimestamp:r,targetDate:a}){let i=nI(n,a);aI(n,i);let s={complete_instances:Ev(e.complete_instances).filter(l=>l!==i),dateModified:r},o={status:t,completedDate:void 0,dateModified:r};return iI({kind:"occurrence.uncomplete",targetDate:i,occurrenceTask:n,parentTask:e,updatedOccurrenceTask:{...n,...o},updatedParentTask:{...e,...s},occurrenceUpdates:o,parentUpdates:s,currentTimestamp:r,metadata:{trigger:"uncomplete"}})}function bpe({occurrenceTask:n,parentTask:e,skippedStatus:t,currentTimestamp:r,targetDate:a,maintainDueDateOffsetInRecurring:i}){if(!t)throw new Error("missing_skipped_status");let s=nI(n,a);if(aI(n,s),!e.recurrence)throw new Error("occurrence_parent_not_recurring");let o=Dpe(Ev(e.skipped_instances),s),l=Ev(e.complete_instances).filter(m=>m!==s),c=xpe({parentTask:e,targetDate:s,completeInstances:l,skippedInstances:o,currentTimestamp:r,maintainDueDateOffsetInRecurring:i,advanceCompletionAnchor:!1}),d={status:t,completedDate:void 0,dateModified:r},u={...e,...c},p=ype(e)==="on_completion"&&sWe(e)==="completion_or_skip"?wp(u.scheduled||""):void 0;return iI({kind:"occurrence.skip",targetDate:s,occurrenceTask:n,parentTask:e,updatedOccurrenceTask:{...n,...d},updatedParentTask:u,occurrenceUpdates:d,parentUpdates:c,currentTimestamp:r,materializeNextDate:p,metadata:{trigger:"skip"}})}function wpe({occurrenceTask:n,parentTask:e,activeStatus:t,currentTimestamp:r,targetDate:a}){let i=nI(n,a);aI(n,i);let s={skipped_instances:Ev(e.skipped_instances).filter(l=>l!==i),dateModified:r},o={status:t,completedDate:void 0,dateModified:r};return iI({kind:"occurrence.unskip",targetDate:i,occurrenceTask:n,parentTask:e,updatedOccurrenceTask:{...n,...o},updatedParentTask:{...e,...s},occurrenceUpdates:o,parentUpdates:s,currentTimestamp:r,metadata:{trigger:"unskip"}})}function Spe(n,e){let t=[];for(let[r,a]of Object.entries(n)){let i=oWe(e,r);i&&(a===void 0||Array.isArray(a)&&a.length===0?t.push({op:"delete",field:i}):r==="status"?t.push({op:"set",field:i,value:aWe(String(a))}):t.push({op:"set",field:i,value:a}))}return t}function xv(n){let e={};return xr(e,"title",n.title),xr(e,"status",n.status),xr(e,"priority",n.priority),xr(e,"due",n.due),xr(e,"scheduled",n.scheduled),xr(e,"completedDate",n.completedDate),xr(e,"dateCreated",n.dateCreated),xr(e,"dateModified",n.dateModified),xr(e,"recurrence",n.recurrence),xr(e,"recurrenceAnchor",n.recurrence_anchor),xr(e,"completeInstances",n.complete_instances),xr(e,"skippedInstances",n.skipped_instances),xr(e,"recurrenceParent",n.recurrence_parent),xr(e,"occurrenceDate",n.occurrence_date),xr(e,"occurrenceMaterialization",n.occurrence_materialization),xr(e,"occurrenceNextTrigger",n.occurrence_next_trigger),xr(e,"occurrenceTemplate",n.occurrence_template),xr(e,"occurrencePastHorizon",n.occurrence_past_horizon),xr(e,"occurrenceFutureHorizon",n.occurrence_future_horizon),xr(e,"timeEntries",n.timeEntries),xr(e,"tags",n.tags),xr(e,"contexts",n.contexts),xr(e,"projects",n.projects),xr(e,"attachments",n.attachments),xr(e,"timeEstimate",n.timeEstimate),xr(e,"blockedBy",n.blockedBy),xr(e,"reminders",n.reminders),e}function oWe(n,e){let r={title:"title",status:"status",priority:"priority",due:"due",scheduled:"scheduled",contexts:"contexts",projects:"projects",attachments:"attachments",timeEstimate:"timeEstimate",completedDate:"completedDate",dateCreated:"dateCreated",dateModified:"dateModified",recurrence:"recurrence",recurrence_anchor:"recurrenceAnchor",complete_instances:"completeInstances",skipped_instances:"skippedInstances",recurrence_parent:"recurrenceParent",occurrence_date:"occurrenceDate",occurrence_materialization:"occurrenceMaterialization",occurrence_next_trigger:"occurrenceNextTrigger",occurrence_template:"occurrenceTemplate",occurrence_past_horizon:"occurrencePastHorizon",occurrence_future_horizon:"occurrenceFutureHorizon",timeEntries:"timeEntries",blockedBy:"blockedBy",reminders:"reminders",sortOrder:"sortOrder"}[e];return r?n[r]:void 0}function lWe(n){return n==="manual"||n==="on_completion"||n==="rolling"}function cWe(n){return n==="completion"||n==="completion_or_skip"}function kU(n){return VVe(n instanceof Date?sc(n):wp(n))}function nI(n,e){var t;return kU((t=e!=null?e:n.occurrence_date)!=null?t:"")}function aI(n,e){if(!n.recurrence_parent||!n.occurrence_date)throw new Error("task_not_materialized_occurrence");if(n.occurrence_date!==e)throw new Error("occurrence_date_mismatch")}function dWe(n,e){let t=n.scheduled?ape(n.scheduled,n.scheduled,e):e,r=n.due?ape(n.due,n.scheduled||n.due,e):void 0;return Epe({title:n.title,priority:n.priority,due:r,scheduled:t,contexts:eI(n.contexts),projects:eI(n.projects),attachments:eI(n.attachments),tags:eI(n.tags),timeEstimate:n.timeEstimate,reminders:ipe(n.reminders),blockedBy:ipe(n.blockedBy),details:n.details,customProperties:fWe(n.customProperties)})}function ape(n,e,t){try{let r=wp(n),a=wp(e);if(!r||!a)return;let i=pWe(a,r),s=mWe(t,i);return uWe(n,s)}catch(r){return}}function uWe(n,e){var a;let r=n.trim().match(/^(\d{4}-\d{2}-\d{2})(.*)$/);return r?`${e}${(a=r[2])!=null?a:""}`:e}function pWe(n,e){let r=mo(n).getTime(),a=mo(e).getTime();return Math.round((a-r)/864e5)}function mWe(n,e){let t=mo(n);return t.setUTCDate(t.getUTCDate()+e),sc(t)}function eI(n){return Array.isArray(n)?[...n]:void 0}function ipe(n){return Array.isArray(n)?n.map(e=>({...e})):void 0}function fWe(n){if(!(!n||Object.keys(n).length===0))return Cpe(n)}function hWe(...n){let e={};for(let t of n)t&&Object.assign(e,Cpe(t));return Object.keys(e).length>0?e:void 0}function Cpe(n){let e={};for(let[t,r]of Object.entries(n))Array.isArray(r)?e[t]=[...r]:gWe(r)?e[t]={...r}:e[t]=r;return e}function gWe(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function yWe(n,e){try{return ppe(n,mo(e))}catch(t){return!1}}function xpe({parentTask:n,targetDate:e,completeInstances:t,skippedInstances:r,currentTimestamp:a,maintainDueDateOffsetInRecurring:i,advanceCompletionAnchor:s}){let o=n.recurrence;typeof o=="string"&&o.length>0&&(s&&(n.recurrence_anchor||"scheduled")==="completion"?o=QVe(o,e)||o:o.includes("DTSTART:")||(o=ZVe(n)||o));let l={...n,recurrence:o,complete_instances:t,skipped_instances:r},c=KVe(l,i,{today:e}),d={recurrence:o,complete_instances:t,skipped_instances:r,dateModified:a};return c.scheduled&&(d.scheduled=c.scheduled),c.due&&(d.due=c.due),d}function iI({kind:n,targetDate:e,occurrenceTask:t,parentTask:r,updatedOccurrenceTask:a,updatedParentTask:i,occurrenceUpdates:s,parentUpdates:o,currentTimestamp:l,materializeNextDate:c,metadata:d}){return{kind:n,targetDate:e,updatedOccurrenceTask:a,updatedParentTask:i,occurrenceUpdates:s,parentUpdates:o,occurrenceFields:xv(s),parentFields:xv(o),dateModified:l,changed:spe(t,s)||spe(r,o),materializeNextDate:c||void 0,metadata:d}}function spe(n,e){return Object.entries(e).some(([t,r])=>n[t]!==r)}function Epe(n){let e={};for(let[t,r]of Object.entries(n))r!==void 0&&(e[t]=r);return e}function xr(n,e,t){t!==void 0&&(n[e]=t)}function Dpe(n,e){return n.includes(e)?n:[...n,e]}function Ev(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}var tI,jVe,lpe,fU,ope,npe,TU=y(()=>{ny();tI=/^(\d{4})-(\d{2})-(\d{2})$/,jVe=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{1,3})?(?:Z|([+-])(\d{2}):(\d{2}))?$/;lpe=HVe;fU=Reflect.get(Uu,"default"),npe=(ope=ye)!=null?ope:fU==null?void 0:fU.RRule});function rr(n){if(n&&typeof n=="object")switch(n[mi]){case cl:case Yd:return!0}return!1}function Rt(n){if(n&&typeof n=="object")switch(n[mi]){case sI:case cl:case Es:case Yd:return!0}return!1}var sI,oI,cl,bU,Es,Yd,mi,fo,ho,go,Et,dt,yo,lI,Wt=y(()=>{sI=Symbol.for("yaml.alias"),oI=Symbol.for("yaml.document"),cl=Symbol.for("yaml.map"),bU=Symbol.for("yaml.pair"),Es=Symbol.for("yaml.scalar"),Yd=Symbol.for("yaml.seq"),mi=Symbol.for("yaml.node.type"),fo=n=>!!n&&typeof n=="object"&&n[mi]===sI,ho=n=>!!n&&typeof n=="object"&&n[mi]===oI,go=n=>!!n&&typeof n=="object"&&n[mi]===cl,Et=n=>!!n&&typeof n=="object"&&n[mi]===bU,dt=n=>!!n&&typeof n=="object"&&n[mi]===Es,yo=n=>!!n&&typeof n=="object"&&n[mi]===Yd;lI=n=>(dt(n)||rr(n))&&!!n.anchor});function dl(n,e){let t=Ape(e);ho(n)?Dv(null,n.contents,t,Object.freeze([n]))===oc&&(n.contents=null):Dv(null,n,t,Object.freeze([]))}function Dv(n,e,t,r){let a=Mpe(n,e,t,r);if(Rt(a)||Et(a))return Ipe(n,r,a),Dv(n,a,t,r);if(typeof a!="symbol"){if(rr(e)){r=Object.freeze(r.concat(e));for(let i=0;i{Wt();Bi=Symbol("break visit"),Ppe=Symbol("skip children"),oc=Symbol("remove node");dl.BREAK=Bi;dl.SKIP=Ppe;dl.REMOVE=oc;LC.BREAK=Bi;LC.SKIP=Ppe;LC.REMOVE=oc});var vWe,kWe,lc,wU=y(()=>{Wt();OC();vWe={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},kWe=n=>n.replace(/[!,[\]{}]/g,e=>vWe[e]),lc=class n{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},n.defaultYaml,e),this.tags=Object.assign({},n.defaultTags,t)}clone(){let e=new n(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new n(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:n.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},n.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:n.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},n.defaultTags),this.atNextDocument=!1);let r=e.trim().split(/[ \t]+/),a=r.shift();switch(a){case"%TAG":{if(r.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[i,s]=r;return this.tags[i]=s,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[i]=r;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let s=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,s),!1}}default:return t(0,`Unknown directive ${a}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let s=e.slice(2,-1);return s==="!"||s==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),s)}let[,r,a]=e.match(/^(.*!)([^!]*)$/s);a||t(`The ${e} tag has no suffix`);let i=this.tags[r];if(i)try{return i+decodeURIComponent(a)}catch(s){return t(String(s)),null}return r==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,r]of Object.entries(this.tags))if(e.startsWith(r))return t+kWe(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),a;if(e&&r.length>0&&Rt(e.contents)){let i={};dl(e.contents,(s,o)=>{Rt(o)&&o.tag&&(i[o.tag]=!0)}),a=Object.keys(i)}else a=[];for(let[i,s]of r)i==="!!"&&s==="tag:yaml.org,2002:"||(!e||a.some(o=>o.startsWith(s)))&&t.push(`%TAG ${i} ${s}`);return t.join(` +`)}};lc.defaultYaml={explicit:!1,version:"1.2"};lc.defaultTags={"!!":"tag:yaml.org,2002:"}});function cI(n){if(/[\x00-\x19\s,[\]{}]/.test(n)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(n)}`;throw new Error(t)}return!0}function SU(n){let e=new Set;return dl(n,{Value(t,r){r.anchor&&e.add(r.anchor)}}),e}function CU(n,e){for(let t=1;;++t){let r=`${n}${t}`;if(!e.has(r))return r}}function Npe(n,e){let t=[],r=new Map,a=null;return{onAnchor:i=>{t.push(i),a!=null||(a=SU(n));let s=CU(e,a);return a.add(s),s},setAnchors:()=>{for(let i of t){let s=r.get(i);if(typeof s=="object"&&s.anchor&&(dt(s.node)||rr(s.node)))s.node.anchor=s.anchor;else{let o=new Error("Failed to resolve repeated object (this should not happen)");throw o.source=i,o}}},sourceObjects:r}}var dI=y(()=>{Wt();OC()});function Sp(n,e,t,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let a=0,i=r.length;a{});function Gn(n,e,t){if(Array.isArray(n))return n.map((r,a)=>Gn(r,String(a),t));if(n&&typeof n.toJSON=="function"){if(!t||!lI(n))return n.toJSON(e,t);let r={aliasCount:0,count:1,res:void 0};t.anchors.set(n,r),t.onCreate=i=>{r.res=i,delete t.onCreate};let a=n.toJSON(e,t);return t.onCreate&&t.onCreate(a),a}return typeof n=="bigint"&&!(t!=null&&t.keep)?Number(n):n}var Cp=y(()=>{Wt()});var xp,uI=y(()=>{xU();Wt();Cp();xp=class{constructor(e){Object.defineProperty(this,mi,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:r,onAnchor:a,reviver:i}={}){if(!ho(e))throw new TypeError("A document argument is required");let s={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},o=Gn(this,"",s);if(typeof a=="function")for(let{count:l,res:c}of s.anchors.values())a(c,l);return typeof i=="function"?Sp(i,{"":o},"",o):o}}});function pI(n,e,t){if(fo(e)){let r=e.resolve(n),a=t&&r&&t.get(r);return a?a.count*a.aliasCount:0}else if(rr(e)){let r=0;for(let a of e.items){let i=pI(n,a,t);i>r&&(r=i)}return r}else if(Et(e)){let r=pI(n,e.key,t),a=pI(n,e.value,t);return Math.max(r,a)}return 1}var cc,zC=y(()=>{dI();OC();Wt();uI();Cp();cc=class extends xp{constructor(e){super(sI),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if((t==null?void 0:t.maxAliasCount)===0)throw new ReferenceError("Alias resolution is disabled");let r;t!=null&&t.aliasResolveCache?r=t.aliasResolveCache:(r=[],dl(e,{Node:(i,s)=>{(fo(s)||lI(s))&&r.push(s)}}),t&&(t.aliasResolveCache=r));let a;for(let i of r){if(i===this)break;i.anchor===this.source&&(a=i)}return a}toJSON(e,t){if(!t)return{source:this.source};let{anchors:r,doc:a,maxAliasCount:i}=t,s=this.resolve(a,t);if(!s){let l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let o=r.get(s);if(o||(Gn(s,null,t),o=r.get(s)),(o==null?void 0:o.res)===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(i>=0&&(o.count+=1,o.aliasCount===0&&(o.aliasCount=pI(a,s,r)),o.count*o.aliasCount>i)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return o.res}toString(e,t,r){let a=`*${this.source}`;if(e){if(cI(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${a} `}return a}}});var mI,Pe,Fn=y(()=>{Wt();uI();Cp();mI=n=>!n||typeof n!="function"&&typeof n!="object",Pe=class extends xp{constructor(e){super(Es),this.value=e}toJSON(e,t){return t!=null&&t.keep?this.value:Gn(this.value,e,t)}toString(){return String(this.value)}};Pe.BLOCK_FOLDED="BLOCK_FOLDED";Pe.BLOCK_LITERAL="BLOCK_LITERAL";Pe.PLAIN="PLAIN";Pe.QUOTE_DOUBLE="QUOTE_DOUBLE";Pe.QUOTE_SINGLE="QUOTE_SINGLE"});function bWe(n,e,t){var r;if(e){let a=t.filter(s=>s.tag===e),i=(r=a.find(s=>!s.format))!=null?r:a[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(a=>{var i;return((i=a.identify)==null?void 0:i.call(a,n))&&!a.format})}function Kd(n,e,t){var u,p,m,f;if(ho(n)&&(n=n.contents),Rt(n))return n;if(Et(n)){let h=(p=(u=t.schema[cl]).createNode)==null?void 0:p.call(u,t.schema,null,t);return h.items.push(n),h}(n instanceof String||n instanceof Number||n instanceof Boolean||typeof BigInt!="undefined"&&n instanceof BigInt)&&(n=n.valueOf());let{aliasDuplicateObjects:r,onAnchor:a,onTagObj:i,schema:s,sourceObjects:o}=t,l;if(r&&n&&typeof n=="object"){if(l=o.get(n),l)return(m=l.anchor)!=null||(l.anchor=a(n)),new cc(l.anchor);l={anchor:null,node:null},o.set(n,l)}e!=null&&e.startsWith("!!")&&(e=TWe+e.slice(2));let c=bWe(n,e,s.tags);if(!c){if(n&&typeof n.toJSON=="function"&&(n=n.toJSON()),!n||typeof n!="object"){let h=new Pe(n);return l&&(l.node=h),h}c=n instanceof Map?s[cl]:Symbol.iterator in Object(n)?s[Yd]:s[cl]}i&&(i(c),delete t.onTagObj);let d=c!=null&&c.createNode?c.createNode(t.schema,n,t):typeof((f=c==null?void 0:c.nodeClass)==null?void 0:f.from)=="function"?c.nodeClass.from(t.schema,n,t):new Pe(n);return e?d.tag=e:c.default||(d.tag=c.tag),l&&(l.node=d),d}var TWe,BC=y(()=>{zC();Wt();Fn();TWe="tag:yaml.org,2002:"});function jC(n,e,t){let r=t;for(let a=e.length-1;a>=0;--a){let i=e[a];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let s=[];s[i]=r,r=s}else r=new Map([[i,r]])}return Kd(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:n,sourceObjects:new Map})}var Mv,Av,fI=y(()=>{BC();Wt();uI();Mv=n=>n==null||typeof n=="object"&&!!n[Symbol.iterator]().next().done,Av=class extends xp{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(r=>Rt(r)||Et(r)?r.clone(e):r),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Mv(e))this.add(t);else{let[r,...a]=e,i=this.get(r,!0);if(rr(i))i.addIn(a,t);else if(i===void 0&&this.schema)this.set(r,jC(this.schema,a,t));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let a=this.get(t,!0);if(rr(a))return a.deleteIn(r);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...a]=e,i=this.get(r,!0);return a.length===0?!t&&dt(i)?i.value:i:rr(i)?i.getIn(a,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!Et(t))return!1;let r=t.value;return r==null||e&&dt(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let a=this.get(t,!0);return rr(a)?a.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let i=this.get(r,!0);if(rr(i))i.setIn(a,t);else if(i===void 0&&this.schema)this.set(r,jC(this.schema,a,t));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}}});function vo(n,e){return/^\n+$/.test(n)?n.substring(1):e?n.replace(/^(?! *$)/gm,e):n}var Rpe,dc,$C=y(()=>{Rpe=n=>n.replace(/^(?!$)(?: $)?/gm,"#");dc=(n,e,t)=>n.endsWith(` +`)?vo(t,e):t.includes(` +`)?` +`+vo(t,e):(n.endsWith(" ")?"":" ")+t});function HC(n,e,t="flow",{indentAtStart:r,lineWidth:a=80,minContentWidth:i=20,onFold:s,onOverflow:o}={}){if(!a||a<0)return n;aa-Math.max(2,i)?c.push(0):u=a-r);let p,m,f=!1,h=-1,g=-1,v=-1;t===hI&&(h=_pe(n,h,e.length),h!==-1&&(u=h+l));for(let T;T=n[h+=1];){if(t===UC&&T==="\\"){switch(g=h,n[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}v=h}if(T===` +`)t===hI&&(h=_pe(n,h,e.length)),u=h+e.length+l,p=void 0;else{if(T===" "&&m&&m!==" "&&m!==` +`&&m!==" "){let b=n[h+1];b&&b!==" "&&b!==` +`&&b!==" "&&(p=h)}if(h>=u)if(p)c.push(p),u=p+l,p=void 0;else if(t===UC){for(;m===" "||m===" ";)m=T,T=n[h+=1],f=!0;let b=h>v+1?h-2:g-1;if(d[b])return n;c.push(b),d[b]=!0,u=b+l,p=void 0}else f=!0}m=T}if(f&&o&&o(),c.length===0)return n;s&&s();let k=n.slice(0,c[0]);for(let T=0;T{EU="flow",hI="block",UC="quoted"});function wWe(n,e,t){if(!e||e<0)return!1;let r=e-t,a=n.length;if(a<=r)return!1;for(let i=0,s=0;ir)return!0;if(s=i+1,a-s<=r)return!1}return!0}function VC(n,e){let t=JSON.stringify(n);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:r}=e,a=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(vI(n)?" ":""),s="",o=0;for(let l=0,c=t[l];c;c=t[++l])if(c===" "&&t[l+1]==="\\"&&t[l+2]==="n"&&(s+=t.slice(o,l)+"\\ ",l+=1,o=l,c="\\"),c==="\\")switch(t[l+1]){case"u":{s+=t.slice(o,l);let d=t.substr(l+2,4);switch(d){case"0000":s+="\\0";break;case"0007":s+="\\a";break;case"000b":s+="\\v";break;case"001b":s+="\\e";break;case"0085":s+="\\N";break;case"00a0":s+="\\_";break;case"2028":s+="\\L";break;case"2029":s+="\\P";break;default:d.substr(0,2)==="00"?s+="\\x"+d.substr(2):s+=t.substr(l,6)}l+=5,o=l+1}break;case"n":if(r||t[l+2]==='"'||t.length +`;let u,p;for(p=t.length;p>0;--p){let w=t[p-1];if(w!==` +`&&w!==" "&&w!==" ")break}let m=t.substring(p),f=m.indexOf(` +`);f===-1?u="-":t===m||f!==m.length-1?(u="+",i&&i()):u="",m&&(t=t.slice(0,-m.length),m[m.length-1]===` +`&&(m=m.slice(0,-1)),m=m.replace(PU,`$&${c}`));let h=!1,g,v=-1;for(g=0;g{S=!0});let x=HC(`${k}${w}${m}`,c,hI,C);if(!S)return`>${b} +${c}${x}`}return t=t.replace(/\n+/g,`$&${c}`),`|${b} +${c}${k}${t}${m}`}function SWe(n,e,t,r){let{type:a,value:i}=n,{actualString:s,implicitKey:o,indent:l,indentStep:c,inFlow:d}=e;if(o&&i.includes(` +`)||d&&/[[\]{},]/.test(i))return Iv(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return o||d||!i.includes(` +`)?Iv(i,e):gI(n,e,t,r);if(!o&&!d&&a!==Pe.PLAIN&&i.includes(` +`))return gI(n,e,t,r);if(vI(i)){if(l==="")return e.forceBlockIndent=!0,gI(n,e,t,r);if(o&&l===c)return Iv(i,e)}let u=i.replace(/\n+/g,`$& +${l}`);if(s){let p=h=>{var g;return h.default&&h.tag!=="tag:yaml.org,2002:str"&&((g=h.test)==null?void 0:g.test(u))},{compat:m,tags:f}=e.doc.schema;if(f.some(p)||m!=null&&m.some(p))return Iv(i,e)}return o?u:HC(u,l,EU,yI(e,!1))}function Zd(n,e,t,r){let{implicitKey:a,inFlow:i}=e,s=typeof n.value=="string"?n:Object.assign({},n,{value:String(n.value)}),{type:o}=n;o!==Pe.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value)&&(o=Pe.QUOTE_DOUBLE);let l=d=>{switch(d){case Pe.BLOCK_FOLDED:case Pe.BLOCK_LITERAL:return a||i?Iv(s.value,e):gI(s,e,t,r);case Pe.QUOTE_DOUBLE:return VC(s.value,e);case Pe.QUOTE_SINGLE:return DU(s.value,e);case Pe.PLAIN:return SWe(s,e,t,r);default:return null}},c=l(o);if(c===null){let{defaultKeyType:d,defaultStringType:u}=e.options,p=a&&d||u;if(c=l(p),c===null)throw new Error(`Unsupported default string type ${p}`)}return c}var yI,vI,PU,WC=y(()=>{Fn();Fpe();yI=(n,e)=>({indentAtStart:e?n.indent.length:n.indentAtStart,lineWidth:n.options.lineWidth,minContentWidth:n.options.minContentWidth}),vI=n=>/^(%|---|\.\.\.)/m.test(n);try{PU=new RegExp(`(^|(?c.tag===e.tag);if(l.length>0)return(a=l.find(c=>c.format===e.format))!=null?a:l[0]}let t,r;if(dt(e)){r=e.value;let l=n.filter(c=>{var d;return(d=c.identify)==null?void 0:d.call(c,r)});if(l.length>1){let c=l.filter(d=>d.test);c.length>0&&(l=c)}t=(i=l.find(c=>c.format===e.format))!=null?i:l.find(c=>!c.format)}else r=e,t=n.find(l=>l.nodeClass&&r instanceof l.nodeClass);if(!t){let l=(o=(s=r==null?void 0:r.constructor)==null?void 0:s.name)!=null?o:r===null?"null":typeof r;throw new Error(`Tag not resolved for ${l} value`)}return t}function xWe(n,e,{anchors:t,doc:r}){var o;if(!r.directives)return"";let a=[],i=(dt(n)||rr(n))&&n.anchor;i&&cI(i)&&(t.add(i),a.push(`&${i}`));let s=(o=n.tag)!=null?o:e.default?null:e.tag;return s&&a.push(r.directives.tagString(s)),a.join(" ")}function Qd(n,e,t,r){var l,c;if(Et(n))return n.toString(e,t,r);if(fo(n)){if(e.doc.directives)return n.toString(e);if((l=e.resolvedAliases)!=null&&l.has(n))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(n):e.resolvedAliases=new Set([n]),n=n.resolve(e.doc)}let a,i=Rt(n)?n:e.doc.createNode(n,{onTagObj:d=>a=d});a!=null||(a=CWe(e.doc.schema.tags,i));let s=xWe(i,a,e);s.length>0&&(e.indentAtStart=((c=e.indentAtStart)!=null?c:0)+s.length+1);let o=typeof a.stringify=="function"?a.stringify(i,e,t,r):dt(i)?Zd(i,e,t,r):i.toString(e,t,r);return s?dt(i)||o[0]==="{"||o[0]==="["?`${s} ${o}`:`${s} +${e.indent}${o}`:o}var qC=y(()=>{dI();Wt();$C();WC()});function Lpe({key:n,value:e},t,r,a){var C,x;let{allNullValues:i,doc:s,indent:o,indentStep:l,options:{commentString:c,indentSeq:d,simpleKeys:u}}=t,p=Rt(n)&&n.comment||null;if(u){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(rr(n)||!Rt(n)&&typeof n=="object"){let E="With simple keys, collection cannot be used as a key value";throw new Error(E)}}let m=!u&&(!n||p&&e==null&&!t.inFlow||rr(n)||(dt(n)?n.type===Pe.BLOCK_FOLDED||n.type===Pe.BLOCK_LITERAL:typeof n=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!m&&(u||!i),indent:o+l});let f=!1,h=!1,g=Qd(n,t,()=>f=!0,()=>h=!0);if(!m&&!t.inFlow&&g.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(t.inFlow){if(i||e==null)return f&&r&&r(),g===""?"?":m?`? ${g}`:g}else if(i&&!u||e==null&&m)return g=`? ${g}`,p&&!f?g+=dc(g,t.indent,c(p)):h&&a&&a(),g;f&&(p=null),m?(p&&(g+=dc(g,t.indent,c(p))),g=`? ${g} +${o}:`):(g=`${g}:`,p&&(g+=dc(g,t.indent,c(p))));let v,k,T;Rt(e)?(v=!!e.spaceBefore,k=e.commentBefore,T=e.comment):(v=!1,k=null,T=null,e&&typeof e=="object"&&(e=s.createNode(e))),t.implicitKey=!1,!m&&!p&&dt(e)&&(t.indentAtStart=g.length+1),h=!1,!d&&l.length>=2&&!t.inFlow&&!m&&yo(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let b=!1,w=Qd(e,t,()=>b=!0,()=>h=!0),S=" ";if(p||v||k){if(S=v?` +`:"",k){let E=c(k);S+=` +${vo(E,t.indent)}`}w===""&&!t.inFlow?S===` +`&&T&&(S=` + +`):S+=` +${t.indent}`}else if(!m&&rr(e)){let E=w[0],_=w.indexOf(` +`),F=_!==-1,I=(x=(C=t.inFlow)!=null?C:e.flow)!=null?x:e.items.length===0;if(F||!I){let A=!1;if(F&&(E==="&"||E==="!")){let R=w.indexOf(" ");E==="&"&&R!==-1&&R<_&&w[R+1]==="!"&&(R=w.indexOf(" ",R+1)),(R===-1||_{Wt();Fn();qC();$C()});function TI(n,e){(n==="debug"||n==="warn")&&console.warn(e)}var AU=y(()=>{});function IU(n,e,t){let r=Bpe(n,t);if(yo(r))for(let a of r.items)MU(n,e,a);else if(Array.isArray(r))for(let a of r)MU(n,e,a);else MU(n,e,r)}function MU(n,e,t){let r=Bpe(n,t);if(!go(r))throw new Error("Merge sources must be maps or map aliases");let a=r.toJSON(null,n,Map);for(let[i,s]of a)e instanceof Map?e.has(i)||e.set(i,s):e instanceof Set?e.add(i):Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{value:s,writable:!0,enumerable:!0,configurable:!0});return e}function Bpe(n,e){return n&&fo(e)?e.resolve(n.doc,n):e}var bI,ul,zpe,wI=y(()=>{Wt();Fn();bI="<<",ul={identify:n=>n===bI||typeof n=="symbol"&&n.description===bI,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Pe(Symbol(bI)),{addToJSMap:IU}),stringify:()=>bI},zpe=(n,e)=>(ul.identify(e)||dt(e)&&(!e.type||e.type===Pe.PLAIN)&&ul.identify(e.value))&&(n==null?void 0:n.doc.schema.tags.some(t=>t.tag===ul.tag&&t.default))});function SI(n,e,{key:t,value:r}){if(Rt(t)&&t.addToJSMap)t.addToJSMap(n,e,r);else if(zpe(n,t))IU(n,e,r);else{let a=Gn(t,"",n);if(e instanceof Map)e.set(a,Gn(r,a,n));else if(e instanceof Set)e.add(a);else{let i=EWe(t,a,n),s=Gn(r,i,n);i in e?Object.defineProperty(e,i,{value:s,writable:!0,enumerable:!0,configurable:!0}):e[i]=s}}return e}function EWe(n,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(Rt(n)&&(t!=null&&t.doc)){let r=kI(t.doc,{});r.anchors=new Set;for(let i of t.anchors.keys())r.anchors.add(i.anchor);r.inFlow=!0,r.inStringifyKey=!0;let a=n.toString(r);if(!t.mapKeyWarned){let i=JSON.stringify(a);i.length>40&&(i=i.substring(0,36)+'..."'),TI(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return a}return JSON.stringify(e)}var NU=y(()=>{AU();wI();qC();Wt();Cp()});function Nv(n,e,t){let r=Kd(n,void 0,t),a=Kd(e,void 0,t);return new an(r,a)}var an,Ep=y(()=>{BC();Ope();NU();Wt();an=class n{constructor(e,t=null){Object.defineProperty(this,mi,{value:bU}),this.key=e,this.value=t}clone(e){let{key:t,value:r}=this;return Rt(t)&&(t=t.clone(e)),Rt(r)&&(r=r.clone(e)),new n(t,r)}toJSON(e,t){let r=t!=null&&t.mapAsMap?new Map:{};return SI(t,r,this)}toString(e,t,r){return e!=null&&e.doc?Lpe(this,e,t,r):JSON.stringify(this)}}});function xI(n,e,t){var i;return(((i=e.inFlow)!=null?i:n.flow)?PWe:DWe)(n,e,t)}function DWe({comment:n,items:e},t,{blockItemPrefix:r,flowChars:a,itemIndent:i,onChompKeep:s,onComment:o}){let{indent:l,options:{commentString:c}}=t,d=Object.assign({},t,{indent:i,type:null}),u=!1,p=[];for(let f=0;fg=null,()=>u=!0);g&&(v+=dc(v,i,c(g))),u&&g&&(u=!1),p.push(r+v)}let m;if(p.length===0)m=a.start+a.end;else{m=p[0];for(let f=1;fg=null);c||(c=u.length>d||v.includes(` +`)),f0&&(c||(c=u.reduce((k,T)=>k+T.length+2,2)+(v.length+2)>e.options.lineWidth)),c&&(v+=",")),g&&(v+=dc(v,r,o(g))),u.push(v),d=u.length}let{start:p,end:m}=t;if(u.length===0)return p+m;if(!c){let f=u.reduce((h,g)=>h+g.length+2,2);c=e.options.lineWidth>0&&f>e.options.lineWidth}if(c){let f=p;for(let h of u)f+=h?` +${i}${a}${h}`:` +`;return`${f} +${a}${m}`}else return`${p}${s}${u.join(" ")}${s}${m}`}function CI({indent:n,options:{commentString:e}},t,r,a){if(r&&a&&(r=r.replace(/^\n+/,"")),r){let i=vo(e(r),n);t.push(i.trimStart())}}var RU=y(()=>{Wt();qC();$C()});function Dp(n,e){let t=dt(e)?e.value:e;for(let r of n)if(Et(r)&&(r.key===e||r.key===t||dt(r.key)&&r.key.value===t))return r}var hn,Pp=y(()=>{RU();NU();fI();Wt();Ep();Fn();hn=class extends Av{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(cl,e),this.items=[]}static from(e,t,r){let{keepUndefined:a,replacer:i}=r,s=new this(e),o=(l,c)=>{if(typeof i=="function")c=i.call(t,l,c);else if(Array.isArray(i)&&!i.includes(l))return;(c!==void 0||a)&&s.items.push(Nv(l,c,r))};if(t instanceof Map)for(let[l,c]of t)o(l,c);else if(t&&typeof t=="object")for(let l of Object.keys(t))o(l,t[l]);return typeof e.sortMapEntries=="function"&&s.items.sort(e.sortMapEntries),s}add(e,t){var s;let r;Et(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new an(e,e==null?void 0:e.value):r=new an(e.key,e.value);let a=Dp(this.items,r.key),i=(s=this.schema)==null?void 0:s.sortMapEntries;if(a){if(!t)throw new Error(`Key ${r.key} already set`);dt(a.value)&&mI(r.value)?a.value.value=r.value:a.value=r.value}else if(i){let o=this.items.findIndex(l=>i(r,l)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(e){let t=Dp(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){var i;let r=Dp(this.items,e),a=r==null?void 0:r.value;return(i=!t&&dt(a)?a.value:a)!=null?i:void 0}has(e){return!!Dp(this.items,e)}set(e,t){this.add(new an(e,t),!0)}toJSON(e,t,r){let a=r?new r:t!=null&&t.mapAsMap?new Map:{};t!=null&&t.onCreate&&t.onCreate(a);for(let i of this.items)SI(t,a,i);return a}toString(e,t,r){if(!e)return JSON.stringify(this);for(let a of this.items)if(!Et(a))throw new Error(`Map items must all be pairs; found ${JSON.stringify(a)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),xI(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:t})}}});var pl,Rv=y(()=>{Wt();Pp();pl={collection:"map",default:!0,nodeClass:hn,tag:"tag:yaml.org,2002:map",resolve(n,e){return go(n)||e("Expected a mapping for this tag"),n},createNode:(n,e,t)=>hn.from(n,e,t)}});function EI(n){let e=dt(n)?n.value:n;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}var ka,Ap=y(()=>{BC();RU();fI();Wt();Fn();Cp();ka=class extends Av{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Yd,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=EI(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let r=EI(e);if(typeof r!="number")return;let a=this.items[r];return!t&&dt(a)?a.value:a}has(e){let t=EI(e);return typeof t=="number"&&t{Wt();Ap();ml={collection:"seq",default:!0,nodeClass:ka,tag:"tag:yaml.org,2002:seq",resolve(n,e){return yo(n)||e("Expected a sequence for this tag"),n},createNode:(n,e,t)=>ka.from(n,e,t)}});var Mp,GC=y(()=>{WC();Mp={identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify(n,e,t,r){return e=Object.assign({actualString:!0},e),Zd(n,e,t,r)}}});var th,DI=y(()=>{Fn();th={identify:n=>n==null,createNode:()=>new Pe(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Pe(null),stringify:({source:n},e)=>typeof n=="string"&&th.test.test(n)?n:e.options.nullStr}});var YC,_U=y(()=>{Fn();YC={identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:n=>new Pe(n[0]==="t"||n[0]==="T"),stringify({source:n,value:e},t){if(n&&YC.test.test(n)){let r=n[0]==="t"||n[0]==="T";if(e===r)return n}return e?t.options.trueStr:t.options.falseStr}}});function Ha({format:n,minFractionDigits:e,tag:t,value:r}){if(typeof r=="bigint")return String(r);let a=typeof r=="number"?r:Number(r);if(!isFinite(a))return isNaN(a)?".nan":a<0?"-.inf":".inf";let i=Object.is(r,-0)?"-0":JSON.stringify(r);if(!n&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^-?\d/.test(i)&&!i.includes("e")){let s=i.indexOf(".");s<0&&(s=i.length,i+=".");let o=e-(i.length-s-1);for(;o-- >0;)i+="0"}return i}var Fv=y(()=>{});var PI,AI,MI,FU=y(()=>{Fn();Fv();PI={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ha},AI={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():Ha(n)}},MI={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(n){let e=new Pe(parseFloat(n)),t=n.indexOf(".");return t!==-1&&n[n.length-1]==="0"&&(e.minFractionDigits=n.length-t-1),e},stringify:Ha}});function jpe(n,e,t){let{value:r}=n;return II(r)&&r>=0?t+r.toString(e):Ha(n)}var II,LU,NI,RI,_I,OU=y(()=>{Fv();II=n=>typeof n=="bigint"||Number.isInteger(n),LU=(n,e,t,{intAsBigInt:r})=>r?BigInt(n):parseInt(n.substring(e),t);NI={identify:n=>II(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(n,e,t)=>LU(n,2,8,t),stringify:n=>jpe(n,8,"0o")},RI={identify:II,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(n,e,t)=>LU(n,0,10,t),stringify:Ha},_I={identify:n=>II(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(n,e,t)=>LU(n,2,16,t),stringify:n=>jpe(n,16,"0x")}});var $pe,Upe=y(()=>{Rv();DI();_v();GC();_U();FU();OU();$pe=[pl,ml,Mp,th,YC,NI,RI,_I,PI,AI,MI]});function Hpe(n){return typeof n=="bigint"||Number.isInteger(n)}var FI,AWe,MWe,Vpe,Wpe=y(()=>{Fn();Rv();_v();FI=({value:n})=>JSON.stringify(n),AWe=[{identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify:FI},{identify:n=>n==null,createNode:()=>new Pe(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:FI},{identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:n=>n==="true",stringify:FI},{identify:Hpe,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(n,e,{intAsBigInt:t})=>t?BigInt(n):parseInt(n,10),stringify:({value:n})=>Hpe(n)?n.toString():JSON.stringify(n)},{identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:n=>parseFloat(n),stringify:FI}],MWe={default:!0,tag:"",test:/^/,resolve(n,e){return e(`Unresolved plain scalar ${JSON.stringify(n)}`),n}},Vpe=[pl,ml].concat(AWe,MWe)});var KC,zU=y(()=>{Fn();WC();KC={identify:n=>n instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(n,e){if(typeof atob=="function"){let t=atob(n.replace(/[\n\r]/g,"")),r=new Uint8Array(t.length);for(let a=0;a1&&e("Each pair must have its own sequence indicator");let i=a.items[0]||new an(new Pe(null));if(a.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${a.commentBefore} +${i.key.commentBefore}`:a.commentBefore),a.comment){let s=(t=i.value)!=null?t:i.key;s.comment=s.comment?`${a.comment} +${s.comment}`:a.comment}a=i}n.items[r]=Et(a)?a:new an(a)}}else e("Expected a sequence for this tag");return n}function jU(n,e,t){let{replacer:r}=t,a=new ka(n);a.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let s of e){typeof r=="function"&&(s=r.call(e,String(i++),s));let o,l;if(Array.isArray(s))if(s.length===2)o=s[0],l=s[1];else throw new TypeError(`Expected [key, value] tuple: ${s}`);else if(s&&s instanceof Object){let c=Object.keys(s);if(c.length===1)o=c[0],l=s[o];else throw new TypeError(`Expected tuple with one key, not ${c.length} keys`)}else o=s;a.items.push(Nv(o,l,t))}return a}var ZC,LI=y(()=>{Wt();Ep();Fn();Ap();ZC={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:BU,createNode:jU}});var Lv,QC,$U=y(()=>{Wt();Cp();Pp();Ap();LI();Lv=class n extends ka{constructor(){super(),this.add=hn.prototype.add.bind(this),this.delete=hn.prototype.delete.bind(this),this.get=hn.prototype.get.bind(this),this.has=hn.prototype.has.bind(this),this.set=hn.prototype.set.bind(this),this.tag=n.tag}toJSON(e,t){if(!t)return super.toJSON(e);let r=new Map;t!=null&&t.onCreate&&t.onCreate(r);for(let a of this.items){let i,s;if(Et(a)?(i=Gn(a.key,"",t),s=Gn(a.value,i,t)):i=Gn(a,"",t),r.has(i))throw new Error("Ordered maps must not include duplicate keys");r.set(i,s)}return r}static from(e,t,r){let a=jU(e,t,r),i=new this;return i.items=a.items,i}};Lv.tag="tag:yaml.org,2002:omap";QC={collection:"seq",identify:n=>n instanceof Map,nodeClass:Lv,default:!1,tag:"tag:yaml.org,2002:omap",resolve(n,e){let t=BU(n,e),r=[];for(let{key:a}of t.items)dt(a)&&(r.includes(a.value)?e(`Ordered maps must not include duplicate keys: ${a.value}`):r.push(a.value));return Object.assign(new Lv,t)},createNode:(n,e,t)=>Lv.from(n,e,t)}});function qpe({value:n,source:e},t){return e&&(n?UU:HU).test.test(e)?e:n?t.options.trueStr:t.options.falseStr}var UU,HU,Gpe=y(()=>{Fn();UU={identify:n=>n===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Pe(!0),stringify:qpe},HU={identify:n=>n===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Pe(!1),stringify:qpe}});var Ype,Kpe,Zpe,Qpe=y(()=>{Fn();Fv();Ype={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ha},Kpe={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n.replace(/_/g,"")),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():Ha(n)}},Zpe={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(n){let e=new Pe(parseFloat(n.replace(/_/g,""))),t=n.indexOf(".");if(t!==-1){let r=n.substring(t+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:Ha}});function OI(n,e,t,{intAsBigInt:r}){let a=n[0];if((a==="-"||a==="+")&&(e+=1),n=n.substring(e).replace(/_/g,""),r){switch(t){case 2:n=`0b${n}`;break;case 8:n=`0o${n}`;break;case 16:n=`0x${n}`;break}let s=BigInt(n);return a==="-"?BigInt(-1)*s:s}let i=parseInt(n,t);return a==="-"?-1*i:i}function VU(n,e,t){let{value:r}=n;if(JC(r)){let a=r.toString(e);return r<0?"-"+t+a.substr(1):t+a}return Ha(n)}var JC,Jpe,Xpe,eme,tme,rme=y(()=>{Fv();JC=n=>typeof n=="bigint"||Number.isInteger(n);Jpe={identify:JC,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(n,e,t)=>OI(n,2,2,t),stringify:n=>VU(n,2,"0b")},Xpe={identify:JC,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(n,e,t)=>OI(n,1,8,t),stringify:n=>VU(n,8,"0")},eme={identify:JC,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(n,e,t)=>OI(n,0,10,t),stringify:Ha},tme={identify:JC,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(n,e,t)=>OI(n,2,16,t),stringify:n=>VU(n,16,"0x")}});var Ov,XC,WU=y(()=>{Wt();Ep();Pp();Ov=class n extends hn{constructor(e){super(e),this.tag=n.tag}add(e){let t;Et(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new an(e.key,null):t=new an(e,null),Dp(this.items,t.key)||this.items.push(t)}get(e,t){let r=Dp(this.items,e);return!t&&Et(r)?dt(r.key)?r.key.value:r.key:r}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let r=Dp(this.items,e);r&&!t?this.items.splice(this.items.indexOf(r),1):!r&&t&&this.items.push(new an(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,r);throw new Error("Set items must all have null values")}static from(e,t,r){let{replacer:a}=r,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let s of t)typeof a=="function"&&(s=a.call(t,s,s)),i.items.push(Nv(s,null,r));return i}};Ov.tag="tag:yaml.org,2002:set";XC={collection:"map",identify:n=>n instanceof Set,nodeClass:Ov,default:!1,tag:"tag:yaml.org,2002:set",createNode:(n,e,t)=>Ov.from(n,e,t),resolve(n,e){if(go(n)){if(n.hasAllNullValues(!0))return Object.assign(new Ov,n);e("Set items must all have null values")}else e("Expected a mapping for this tag");return n}}});function qU(n,e){let t=n[0],r=t==="-"||t==="+"?n.substring(1):n,a=s=>e?BigInt(s):Number(s),i=r.replace(/_/g,"").split(":").reduce((s,o)=>s*a(60)+a(o),a(0));return t==="-"?a(-1)*i:i}function nme(n){let{value:e}=n,t=s=>s;if(typeof e=="bigint")t=s=>BigInt(s);else if(isNaN(e)||!isFinite(e))return Ha(n);let r="";e<0&&(r="-",e*=t(-1));let a=t(60),i=[e%a];return e<60?i.unshift(0):(e=(e-i[0])/a,i.unshift(e%a),e>=60&&(e=(e-i[0])/a,i.unshift(e))),r+i.map(s=>String(s).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var zI,BI,zv,GU=y(()=>{Fv();zI={identify:n=>typeof n=="bigint"||Number.isInteger(n),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(n,e,{intAsBigInt:t})=>qU(n,t),stringify:nme},BI={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:n=>qU(n,!1),stringify:nme},zv={identify:n=>n instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(n){let e=n.match(zv.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,r,a,i,s,o]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0,c=Date.UTC(t,r-1,a,i||0,s||0,o||0,l),d=e[8];if(d&&d!=="Z"){let u=qU(d,!1);Math.abs(u)<30&&(u*=60),c-=6e4*u}return new Date(c)},stringify:({value:n})=>{var e;return(e=n==null?void 0:n.toISOString().replace(/(T00:00:00)?\.000Z$/,""))!=null?e:""}}});var YU,ame=y(()=>{Rv();DI();_v();GC();zU();Gpe();Qpe();rme();wI();$U();LI();WU();GU();YU=[pl,ml,Mp,th,UU,HU,Jpe,Xpe,eme,tme,Ype,Kpe,Zpe,KC,ul,QC,ZC,XC,zI,BI,zv]});function jI(n,e,t){let r=ime.get(e);if(r&&!n)return t&&!r.includes(ul)?r.concat(ul):r.slice();let a=r;if(!a)if(Array.isArray(n))a=[];else{let i=Array.from(ime.keys()).filter(s=>s!=="yaml11").map(s=>JSON.stringify(s)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(n))for(let i of n)a=a.concat(i);else typeof n=="function"&&(a=n(a.slice()));return t&&(a=a.concat(ul)),a.reduce((i,s)=>{let o=typeof s=="string"?sme[s]:s;if(!o){let l=JSON.stringify(s),c=Object.keys(sme).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${c}`)}return i.includes(o)||i.push(o),i},[])}var ime,sme,ome,lme=y(()=>{Rv();DI();_v();GC();_U();FU();OU();Upe();Wpe();zU();wI();$U();LI();ame();WU();GU();ime=new Map([["core",$pe],["failsafe",[pl,ml,Mp]],["json",Vpe],["yaml11",YU],["yaml-1.1",YU]]),sme={binary:KC,bool:YC,float:MI,floatExp:AI,floatNaN:PI,floatTime:BI,int:RI,intHex:_I,intOct:NI,intTime:zI,map:pl,merge:ul,null:th,omap:QC,pairs:ZC,seq:ml,set:XC,timestamp:zv},ome={"tag:yaml.org,2002:binary":KC,"tag:yaml.org,2002:merge":ul,"tag:yaml.org,2002:omap":QC,"tag:yaml.org,2002:pairs":ZC,"tag:yaml.org,2002:set":XC,"tag:yaml.org,2002:timestamp":zv}});var IWe,Bv,KU=y(()=>{Wt();Rv();_v();GC();lme();IWe=(n,e)=>n.keye.key?1:0,Bv=class n{constructor({compat:e,customTags:t,merge:r,resolveKnownTags:a,schema:i,sortMapEntries:s,toStringDefaults:o}){this.compat=Array.isArray(e)?jI(e,"compat"):e?jI(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=a?ome:{},this.tags=jI(t,this.name,r),this.toStringOptions=o!=null?o:null,Object.defineProperty(this,cl,{value:pl}),Object.defineProperty(this,Es,{value:Mp}),Object.defineProperty(this,Yd,{value:ml}),this.sortMapEntries=typeof s=="function"?s:s===!0?IWe:null}clone(){let e=Object.create(n.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}});function cme(n,e){var l;let t=[],r=e.directives===!0;if(e.directives!==!1&&n.directives){let c=n.directives.toString(n);c?(t.push(c),r=!0):n.directives.docStart&&(r=!0)}r&&t.push("---");let a=kI(n,e),{commentString:i}=a.options;if(n.commentBefore){t.length!==1&&t.unshift("");let c=i(n.commentBefore);t.unshift(vo(c,""))}let s=!1,o=null;if(n.contents){if(Rt(n.contents)){if(n.contents.spaceBefore&&r&&t.push(""),n.contents.commentBefore){let u=i(n.contents.commentBefore);t.push(vo(u,""))}a.forceBlockIndent=!!n.comment,o=n.contents.comment}let c=o?void 0:()=>s=!0,d=Qd(n.contents,a,()=>o=null,c);o&&(d+=dc(d,"",i(o))),(d[0]==="|"||d[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${d}`:t.push(d)}else t.push(Qd(n.contents,a));if((l=n.directives)!=null&&l.docEnd)if(n.comment){let c=i(n.comment);c.includes(` +`)?(t.push("..."),t.push(vo(c,""))):t.push(`... ${c}`)}else t.push("...");else{let c=n.comment;c&&s&&(c=c.replace(/^\n+/,"")),c&&((!s||o)&&t[t.length-1]!==""&&t.push(""),t.push(vo(i(c),"")))}return t.join(` +`)+` +`}var dme=y(()=>{Wt();qC();$C()});function jv(n){if(rr(n))return!0;throw new Error("Expected a YAML collection as document contents")}var uc,ex=y(()=>{zC();fI();Wt();Ep();Cp();KU();dme();dI();xU();BC();wU();uc=class n{constructor(e,t,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,mi,{value:oI});let a=null;typeof t=="function"||Array.isArray(t)?a=t:r===void 0&&t&&(r=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=i;let{version:s}=i;r!=null&&r._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(s=this.directives.yaml.version)):this.directives=new lc({version:s}),this.setSchema(s,r),this.contents=e===void 0?null:this.createNode(e,a,r)}clone(){let e=Object.create(n.prototype,{[mi]:{value:oI}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=Rt(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){jv(this.contents)&&this.contents.add(e)}addIn(e,t){jv(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let r=SU(this);e.anchor=!t||r.has(t)?CU(t||"a",r):t}return new cc(e.anchor)}createNode(e,t,r){let a;if(typeof t=="function")e=t.call({"":e},"",e),a=t;else if(Array.isArray(t)){let g=k=>typeof k=="number"||k instanceof String||k instanceof Number,v=t.filter(g).map(String);v.length>0&&(t=t.concat(v)),a=t}else r===void 0&&t&&(r=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:s,flow:o,keepUndefined:l,onTagObj:c,tag:d}=r!=null?r:{},{onAnchor:u,setAnchors:p,sourceObjects:m}=Npe(this,s||"a"),f={aliasDuplicateObjects:i!=null?i:!0,keepUndefined:l!=null?l:!1,onAnchor:u,onTagObj:c,replacer:a,schema:this.schema,sourceObjects:m},h=Kd(e,d,f);return o&&rr(h)&&(h.flow=!0),p(),h}createPair(e,t,r={}){let a=this.createNode(e,null,r),i=this.createNode(t,null,r);return new an(a,i)}delete(e){return jv(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Mv(e)?this.contents==null?!1:(this.contents=null,!0):jv(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return rr(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Mv(e)?!t&&dt(this.contents)?this.contents.value:this.contents:rr(this.contents)?this.contents.getIn(e,t):void 0}has(e){return rr(this.contents)?this.contents.has(e):!1}hasIn(e){return Mv(e)?this.contents!==void 0:rr(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=jC(this.schema,[e],t):jv(this.contents)&&this.contents.set(e,t)}setIn(e,t){Mv(e)?this.contents=t:this.contents==null?this.contents=jC(this.schema,Array.from(e),t):jv(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new lc({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new lc({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let a=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${a}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(r)this.schema=new Bv(Object.assign(r,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:r,maxAliasCount:a,onAnchor:i,reviver:s}={}){let o={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof a=="number"?a:100},l=Gn(this.contents,t!=null?t:"",o);if(typeof i=="function")for(let{count:c,res:d}of o.anchors.values())i(d,c);return typeof s=="function"?Sp(s,{"":l},"",l):l}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return cme(this,e)}}});var $v,Ds,Uv,tx,rx=y(()=>{$v=class extends Error{constructor(e,t,r,a){super(),this.name=e,this.code=r,this.message=a,this.pos=t}},Ds=class extends $v{constructor(e,t,r){super("YAMLParseError",e,t,r)}},Uv=class extends $v{constructor(e,t,r){super("YAMLWarning",e,t,r)}},tx=(n,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(o=>e.linePos(o));let{line:r,col:a}=t.linePos[0];t.message+=` at line ${r}, column ${a}`;let i=a-1,s=n.substring(e.lineStarts[r-1],e.lineStarts[r]).replace(/[\n\r]+$/,"");if(i>=60&&s.length>80){let o=Math.min(i-39,s.length-79);s="…"+s.substring(o),i-=o-1}if(s.length>80&&(s=s.substring(0,79)+"…"),r>1&&/^ *$/.test(s.substring(0,i))){let o=n.substring(e.lineStarts[r-2],e.lineStarts[r-1]);o.length>80&&(o=o.substring(0,79)+`… +`),s=o+s}if(/[^ ]/.test(s)){let o=1,l=t.linePos[1];(l==null?void 0:l.line)===r&&l.col>a&&(o=Math.max(1,Math.min(l.col-a,80-i)));let c=" ".repeat(i)+"^".repeat(o);t.message+=`: + +${s} +${c} +`}}});function pc(n,{flow:e,indicator:t,next:r,offset:a,onError:i,parentIndent:s,startOnNewline:o}){let l=!1,c=o,d=o,u="",p="",m=!1,f=!1,h=null,g=null,v=null,k=null,T=null,b=null,w=null;for(let x of n)switch(f&&(x.type!=="space"&&x.type!=="newline"&&x.type!=="comma"&&i(x.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),f=!1),h&&(c&&x.type!=="comment"&&x.type!=="newline"&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),x.type){case"space":!e&&(t!=="doc-start"||(r==null?void 0:r.type)!=="flow-collection")&&x.source.includes(" ")&&(h=x),d=!0;break;case"comment":{d||i(x,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let E=x.source.substring(1)||" ";u?u+=p+E:u=E,p="",c=!1;break}case"newline":c?u?u+=x.source:(!b||t!=="seq-item-ind")&&(l=!0):p+=x.source,c=!0,m=!0,(g||v)&&(k=x),d=!0;break;case"anchor":g&&i(x,"MULTIPLE_ANCHORS","A node can have at most one anchor"),x.source.endsWith(":")&&i(x.offset+x.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=x,w!=null||(w=x.offset),c=!1,d=!1,f=!0;break;case"tag":{v&&i(x,"MULTIPLE_TAGS","A node can have at most one tag"),v=x,w!=null||(w=x.offset),c=!1,d=!1,f=!0;break}case t:(g||v)&&i(x,"BAD_PROP_ORDER",`Anchors and tags must be after the ${x.source} indicator`),b&&i(x,"UNEXPECTED_TOKEN",`Unexpected ${x.source} in ${e!=null?e:"collection"}`),b=x,c=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){T&&i(x,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),T=x,c=!1,d=!1;break}default:i(x,"UNEXPECTED_TOKEN",`Unexpected ${x.type} token`),c=!1,d=!1}let S=n[n.length-1],C=S?S.offset+S.source.length:a;return f&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&i(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(c&&h.indent<=s||(r==null?void 0:r.type)==="block-map"||(r==null?void 0:r.type)==="block-seq")&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:T,found:b,spaceBefore:l,comment:u,hasNewline:m,anchor:g,tag:v,newlineAfterProp:k,end:C,start:w!=null?w:C}}var nx=y(()=>{});function Ip(n){if(!n)return null;switch(n.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(n.source.includes(` +`))return!0;if(n.end){for(let e of n.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of n.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(Ip(e.key)||Ip(e.value))return!0}return!1;default:return!0}}var $I=y(()=>{});function ax(n,e,t){if((e==null?void 0:e.type)==="flow-collection"){let r=e.end[0];r.indent===n&&(r.source==="]"||r.source==="}")&&Ip(e)&&t(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}var ZU=y(()=>{$I()});function UI(n,e,t){let{uniqueKeys:r}=n.options;if(r===!1)return!1;let a=typeof r=="function"?r:(i,s)=>i===s||dt(i)&&dt(s)&&i.value===s.value;return e.some(i=>a(i.key,t))}var QU=y(()=>{Wt()});function pme({composeNode:n,composeEmptyNode:e},t,r,a,i){var d,u;let s=(d=i==null?void 0:i.nodeClass)!=null?d:hn,o=new s(t.schema);t.atRoot&&(t.atRoot=!1);let l=r.offset,c=null;for(let p of r.items){let{start:m,key:f,sep:h,value:g}=p,v=pc(m,{indicator:"explicit-key-ind",next:f!=null?f:h==null?void 0:h[0],offset:l,onError:a,parentIndent:r.indent,startOnNewline:!0}),k=!v.found;if(k){if(f&&(f.type==="block-seq"?a(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&a(l,"BAD_INDENT",ume)),!v.anchor&&!v.tag&&!h){c=v.end,v.comment&&(o.comment?o.comment+=` +`+v.comment:o.comment=v.comment);continue}(v.newlineAfterProp||Ip(f))&&a(f!=null?f:m[m.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else((u=v.found)==null?void 0:u.indent)!==r.indent&&a(l,"BAD_INDENT",ume);t.atKey=!0;let T=v.end,b=f?n(t,f,v,a):e(t,T,m,null,v,a);t.schema.compat&&ax(r.indent,f,a),t.atKey=!1,UI(t,o.items,b)&&a(T,"DUPLICATE_KEY","Map keys must be unique");let w=pc(h!=null?h:[],{indicator:"map-value-ind",next:g,offset:b.range[2],onError:a,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(l=w.end,w.found){k&&((g==null?void 0:g.type)==="block-map"&&!w.hasNewline&&a(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&v.start{Ep();Pp();nx();$I();ZU();QU();ume="All mapping items must start at the same column"});function fme({composeNode:n,composeEmptyNode:e},t,r,a,i){var d;let s=(d=i==null?void 0:i.nodeClass)!=null?d:ka,o=new s(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=r.offset,c=null;for(let{start:u,value:p}of r.items){let m=pc(u,{indicator:"seq-item-ind",next:p,offset:l,onError:a,parentIndent:r.indent,startOnNewline:!0});if(!m.found)if(m.anchor||m.tag||p)(p==null?void 0:p.type)==="block-seq"?a(m.end,"BAD_INDENT","All sequence items must start at the same column"):a(l,"MISSING_CHAR","Sequence item without - indicator");else{c=m.end,m.comment&&(o.comment=m.comment);continue}let f=p?n(t,p,m,a):e(t,m.end,u,null,m,a);t.schema.compat&&ax(r.indent,p,a),l=f.range[2],o.items.push(f)}return o.range=[r.offset,l,c!=null?c:l],o}var hme=y(()=>{Ap();nx();ZU()});function mc(n,e,t,r){let a="";if(n){let i=!1,s="";for(let o of n){let{source:l,type:c}=o;switch(c){case"space":i=!0;break;case"comment":{t&&!i&&r(o,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=l.substring(1)||" ";a?a+=s+d:a=d,s="";break}case"newline":a&&(s+=l),i=!0;break;default:r(o,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}e+=l.length}}return{comment:a,offset:e}}var Hv=y(()=>{});function gme({composeNode:n,composeEmptyNode:e},t,r,a,i){var g,v,k;let s=r.start.source==="{",o=s?"flow map":"flow sequence",l=(g=i==null?void 0:i.nodeClass)!=null?g:s?hn:ka,c=new l(t.schema);c.flow=!0;let d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=r.offset+r.start.source.length;for(let T=0;T0){let T=mc(f,h,t.options.strict,a);T.comment&&(c.comment?c.comment+=` +`+T.comment:c.comment=T.comment),c.range=[r.offset,h,T.offset]}else c.range=[r.offset,h,h];return c}var JU,XU,yme=y(()=>{Wt();Ep();Pp();Ap();Hv();nx();$I();QU();JU="Block collections are not allowed within flow collections",XU=n=>n&&(n.type==="block-map"||n.type==="block-seq")});function eH(n,e,t,r,a,i){let s=t.type==="block-map"?pme(n,e,t,r,i):t.type==="block-seq"?fme(n,e,t,r,i):gme(n,e,t,r,i),o=s.constructor;return a==="!"||a===o.tagName?(s.tag=o.tagName,s):(a&&(s.tag=a),s)}function vme(n,e,t,r,a){var p,m,f;let i=r.tag,s=i?e.directives.tagName(i.source,h=>a(i,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){let{anchor:h,newlineAfterProp:g}=r,v=h&&i?h.offset>i.offset?h:i:h!=null?h:i;v&&(!g||g.offseth.tag===s&&h.collection===o);if(!l){let h=e.schema.knownTags[s];if((h==null?void 0:h.collection)===o)e.schema.tags.push(Object.assign({},h,{default:!1})),l=h;else return h?a(i,"BAD_COLLECTION_TYPE",`${h.tag} used for ${o} collection, but expects ${(p=h.collection)!=null?p:"scalar"}`,!0):a(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${s}`,!0),eH(n,e,t,a,s)}let c=eH(n,e,t,a,s,l),d=(f=(m=l.resolve)==null?void 0:m.call(l,c,h=>a(i,"TAG_RESOLVE_FAILED",h),e.options))!=null?f:c,u=Rt(d)?d:new Pe(d);return u.range=c.range,u.tag=s,l!=null&&l.format&&(u.format=l.format),u}var kme=y(()=>{Wt();Fn();Pp();Ap();mme();hme();yme()});function HI(n,e,t){let r=e.offset,a=NWe(e,n.options.strict,t);if(!a)return{value:"",type:null,comment:"",range:[r,r,r]};let i=a.mode===">"?Pe.BLOCK_FOLDED:Pe.BLOCK_LITERAL,s=e.source?RWe(e.source):[],o=s.length;for(let h=s.length-1;h>=0;--h){let g=s[h][1];if(g===""||g==="\r")o=h;else break}if(o===0){let h=a.chomp==="+"&&s.length>0?` +`.repeat(Math.max(1,s.length-1)):"",g=r+a.length;return e.source&&(g+=e.source.length),{value:h,type:i,comment:a.comment,range:[r,g,g]}}let l=e.indent+a.indent,c=e.offset+a.length,d=0;for(let h=0;hl&&(l=g.length);else{g.length=o;--h)s[h][0].length>l&&(o=h+1);let u="",p="",m=!1;for(let h=0;hl||v[0]===" "?(p===" "?p=` +`:!m&&p===` +`&&(p=` + +`),u+=p+g.slice(l)+v,p=` +`,m=!0):v===""?p===` +`?u+=` +`:p=` +`:(u+=p+v,p=" ",m=!1)}switch(a.chomp){case"-":break;case"+":for(let h=o;h{Fn()});function VI(n,e,t){let{offset:r,type:a,source:i,end:s}=n,o,l,c=(p,m,f)=>t(r+p,m,f);switch(a){case"scalar":o=Pe.PLAIN,l=_We(i,c);break;case"single-quoted-scalar":o=Pe.QUOTE_SINGLE,l=FWe(i,c);break;case"double-quoted-scalar":o=Pe.QUOTE_DOUBLE,l=LWe(i,c);break;default:return t(n,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${a}`),{value:"",type:null,comment:"",range:[r,r+i.length,r+i.length]}}let d=r+i.length,u=mc(s,d,e,t);return{value:l,type:o,comment:u.comment,range:[r,d,u.offset]}}function _We(n,e){let t="";switch(n[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${n[0]}`;break}case"@":case"`":{t=`reserved character ${n[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),Tme(n)}function FWe(n,e){return(n[n.length-1]!=="'"||n.length===1)&&e(n.length,"MISSING_CHAR","Missing closing 'quote"),Tme(n.slice(1,-1)).replace(/''/g,"'")}function Tme(n){var l;let e,t;try{e=new RegExp(`(.*?)(?i?n.slice(i,r+1):a)}else t+=a}return(n[n.length-1]!=='"'||n.length===1)&&e(n.length,"MISSING_CHAR",'Missing closing "quote'),t}function OWe(n,e){let t="",r=n[e+1];for(;(r===" "||r===" "||r===` +`||r==="\r")&&!(r==="\r"&&n[e+2]!==` +`);)r===` +`&&(t+=` +`),e+=1,r=n[e+1];return t||(t=" "),{fold:t,offset:e}}function BWe(n,e,t,r){let a=n.substr(e,t),s=a.length===t&&/^[0-9a-fA-F]+$/.test(a)?parseInt(a,16):NaN;try{return String.fromCodePoint(s)}catch(o){let l=n.substr(e-2,t+2);return r(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${l}`),l}}var zWe,rH=y(()=>{Fn();Hv();zWe={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` +`,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "}});function nH(n,e,t,r){let{value:a,type:i,comment:s,range:o}=e.type==="block-scalar"?HI(n,e,r):VI(e,n.options.strict,r),l=t?n.directives.tagName(t.source,u=>r(t,"TAG_RESOLVE_FAILED",u)):null,c;n.options.stringKeys&&n.atKey?c=n.schema[Es]:l?c=jWe(n.schema,a,l,t,r):e.type==="scalar"?c=$We(n,a,e,r):c=n.schema[Es];let d;try{let u=c.resolve(a,p=>r(t!=null?t:e,"TAG_RESOLVE_FAILED",p),n.options);d=dt(u)?u:new Pe(u)}catch(u){let p=u instanceof Error?u.message:String(u);r(t!=null?t:e,"TAG_RESOLVE_FAILED",p),d=new Pe(a)}return d.range=o,d.source=a,i&&(d.type=i),l&&(d.tag=l),c.format&&(d.format=c.format),s&&(d.comment=s),d}function jWe(n,e,t,r,a){var o;if(t==="!")return n[Es];let i=[];for(let l of n.tags)if(!l.collection&&l.tag===t)if(l.default&&l.test)i.push(l);else return l;for(let l of i)if((o=l.test)!=null&&o.test(e))return l;let s=n.knownTags[t];return s&&!s.collection?(n.tags.push(Object.assign({},s,{default:!1,test:void 0})),s):(a(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),n[Es])}function $We({atKey:n,directives:e,schema:t},r,a,i){var o;let s=t.tags.find(l=>{var c;return(l.default===!0||n&&l.default==="key")&&((c=l.test)==null?void 0:c.test(r))})||t[Es];if(t.compat){let l=(o=t.compat.find(c=>{var d;return c.default&&((d=c.test)==null?void 0:d.test(r))}))!=null?o:t[Es];if(s.tag!==l.tag){let c=e.tagString(s.tag),d=e.tagString(l.tag),u=`Value may be parsed as either ${c} or ${d}`;i(a,"TAG_RESOLVE_FAILED",u,!0)}}return s}var bme=y(()=>{Wt();Fn();tH();rH()});function wme(n,e,t){if(e){t!=null||(t=e.length);for(let r=t-1;r>=0;--r){let a=e[r];switch(a.type){case"space":case"comment":case"newline":n-=a.source.length;continue}for(a=e[++r];(a==null?void 0:a.type)==="space";)n+=a.source.length,a=e[++r];break}}return n}var Sme=y(()=>{});function aH(n,e,t,r){let a=n.atKey,{spaceBefore:i,comment:s,anchor:o,tag:l}=t,c,d=!0;switch(e.type){case"alias":c=HWe(n,e,r),(o||l)&&r(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=nH(n,e,l,r),o&&(c.anchor=o.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{c=vme(UWe,n,e,t,r),o&&(c.anchor=o.source.substring(1))}catch(u){let p=u instanceof Error?u.message:String(u);r(e,"RESOURCE_EXHAUSTION",p)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",u),d=!1}}return c!=null||(c=WI(n,e.offset,void 0,null,t,r)),o&&c.anchor===""&&r(o,"BAD_ALIAS","Anchor cannot be an empty string"),a&&n.options.stringKeys&&(!dt(c)||typeof c.value!="string"||c.tag&&c.tag!=="tag:yaml.org,2002:str")&&r(l!=null?l:e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(c.spaceBefore=!0),s&&(e.type==="scalar"&&e.source===""?c.comment=s:c.commentBefore=s),n.options.keepSourceTokens&&d&&(c.srcToken=e),c}function WI(n,e,t,r,{spaceBefore:a,comment:i,anchor:s,tag:o,end:l},c){let d={type:"scalar",offset:wme(e,t,r),indent:-1,source:""},u=nH(n,d,o,c);return s&&(u.anchor=s.source.substring(1),u.anchor===""&&c(s,"BAD_ALIAS","Anchor cannot be an empty string")),a&&(u.spaceBefore=!0),i&&(u.comment=i,u.range[2]=l),u}function HWe({options:n},{offset:e,source:t,end:r},a){let i=new cc(t.substring(1));i.source===""&&a(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&a(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let s=e+t.length,o=mc(r,s,n.strict,a);return i.range=[e,s,o.offset],o.comment&&(i.comment=o.comment),i}var UWe,Cme=y(()=>{zC();Wt();kme();bme();Hv();Sme();UWe={composeNode:aH,composeEmptyNode:WI}});function xme(n,e,{offset:t,start:r,value:a,end:i},s){let o=Object.assign({_directives:e},n),l=new uc(void 0,o),c={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},d=pc(r,{indicator:"doc-start",next:a!=null?a:i==null?void 0:i[0],offset:t,onError:s,parentIndent:0,startOnNewline:!0});d.found&&(l.directives.docStart=!0,a&&(a.type==="block-map"||a.type==="block-seq")&&!d.hasNewline&&s(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=a?aH(c,a,d,s):WI(c,d.end,r,null,d,s);let u=l.contents.range[2],p=mc(i,u,!1,s);return p.comment&&(l.comment=p.comment),l.range=[t,u,p.offset],l}var Eme=y(()=>{ex();Cme();Hv();nx()});function ix(n){if(typeof n=="number")return[n,n+1];if(Array.isArray(n))return n.length===2?n:[n[0],n[1]];let{offset:e,source:t}=n;return[e,e+(typeof t=="string"?t.length:1)]}function Dme(n){var a;let e="",t=!1,r=!1;for(let i=0;i{wU();ex();rx();Wt();Eme();Hv();rh=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,r,a,i)=>{let s=ix(t);i?this.warnings.push(new Uv(s,r,a)):this.errors.push(new Ds(s,r,a))},this.directives=new lc({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:r,afterEmptyLine:a}=Dme(this.prelude);if(r){let i=e.contents;if(t)e.comment=e.comment?`${e.comment} +${r}`:r;else if(a||e.directives.docStart||!i)e.commentBefore=r;else if(rr(i)&&!i.flow&&i.items.length>0){let s=i.items[0];Et(s)&&(s=s.key);let o=s.commentBefore;s.commentBefore=o?`${r} +${o}`:r}else{let s=i.commentBefore;i.commentBefore=s?`${r} +${s}`:r}}if(t){for(let i=0;i{let i=ix(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",r,a)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=xme(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new Ds(ix(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new Ds(ix(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let t=mc(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let r=this.doc.comment;this.doc.comment=r?`${r} +${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Ds(ix(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),a=new uc(void 0,r);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),a.range=[0,t,t],this.decorate(a,!1),yield a}}}});function Pme(n,e=!0,t){if(n){let r=(a,i,s)=>{let o=typeof a=="number"?a:Array.isArray(a)?a[0]:a.offset;if(t)t(o,i,s);else throw new Ds([o,o+1],i,s)};switch(n.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return VI(n,e,r);case"block-scalar":return HI({options:{strict:e}},n,r)}}return null}function Ame(n,e){var c;let{implicitKey:t=!1,indent:r,inFlow:a=!1,offset:i=-1,type:s="PLAIN"}=e,o=Zd({type:s,value:n},{implicitKey:t,indent:r>0?" ".repeat(r):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}}),l=(c=e.end)!=null?c:[{type:"newline",offset:-1,indent:r,source:` +`}];switch(o[0]){case"|":case">":{let d=o.indexOf(` +`),u=o.substring(0,d),p=o.substring(d+1)+` +`,m=[{type:"block-scalar-header",offset:i,indent:r,source:u}];return Ime(m,l)||m.push({type:"newline",offset:-1,indent:r,source:` +`}),{type:"block-scalar",offset:i,indent:r,props:m,source:p}}case'"':return{type:"double-quoted-scalar",offset:i,indent:r,source:o,end:l};case"'":return{type:"single-quoted-scalar",offset:i,indent:r,source:o,end:l};default:return{type:"scalar",offset:i,indent:r,source:o,end:l}}}function Mme(n,e,t={}){let{afterKey:r=!1,implicitKey:a=!1,inFlow:i=!1,type:s}=t,o="indent"in n?n.indent:null;if(r&&typeof o=="number"&&(o+=2),!s)switch(n.type){case"single-quoted-scalar":s="QUOTE_SINGLE";break;case"double-quoted-scalar":s="QUOTE_DOUBLE";break;case"block-scalar":{let c=n.props[0];if(c.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s=c.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:s="PLAIN"}let l=Zd({type:s,value:e},{implicitKey:a||o===null,indent:o!==null&&o>0?" ".repeat(o):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":VWe(n,l);break;case'"':sH(n,l,"double-quoted-scalar");break;case"'":sH(n,l,"single-quoted-scalar");break;default:sH(n,l,"scalar")}}function VWe(n,e){let t=e.indexOf(` +`),r=e.substring(0,t),a=e.substring(t+1)+` +`;if(n.type==="block-scalar"){let i=n.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=r,n.source=a}else{let{offset:i}=n,s="indent"in n?n.indent:-1,o=[{type:"block-scalar-header",offset:i,indent:s,source:r}];Ime(o,"end"in n?n.end:void 0)||o.push({type:"newline",offset:-1,indent:s,source:` +`});for(let l of Object.keys(n))l!=="type"&&l!=="offset"&&delete n[l];Object.assign(n,{type:"block-scalar",indent:s,props:o,source:a})}}function Ime(n,e){if(e)for(let t of e)switch(t.type){case"space":case"comment":n.push(t);break;case"newline":return n.push(t),!0}return!1}function sH(n,e,t){switch(n.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":n.type=t,n.source=e;break;case"block-scalar":{let r=n.props.slice(1),a=e.length;n.props[0].type==="block-scalar-header"&&(a-=n.props[0].source.length);for(let i of r)i.offset+=a;delete n.props,Object.assign(n,{type:t,source:e,end:r});break}case"block-map":case"block-seq":{let a={type:"newline",offset:n.offset+e.length,indent:n.indent,source:` +`};delete n.items,Object.assign(n,{type:t,source:e,end:[a]});break}default:{let r="indent"in n?n.indent:-1,a="end"in n&&Array.isArray(n.end)?n.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(n))i!=="type"&&i!=="offset"&&delete n[i];Object.assign(n,{type:t,indent:r,source:e,end:a})}}}var Nme=y(()=>{tH();rH();rx();WC()});function GI(n){switch(n.type){case"block-scalar":{let e="";for(let t of n.props)e+=GI(t);return e+n.source}case"block-map":case"block-seq":{let e="";for(let t of n.items)e+=qI(t);return e}case"flow-collection":{let e=n.start.source;for(let t of n.items)e+=qI(t);for(let t of n.end)e+=t.source;return e}case"document":{let e=qI(n);if(n.end)for(let t of n.end)e+=t.source;return e}default:{let e=n.source;if("end"in n&&n.end)for(let t of n.end)e+=t.source;return e}}}function qI({start:n,key:e,sep:t,value:r}){let a="";for(let i of n)a+=i.source;if(e&&(a+=GI(e)),t)for(let i of t)a+=i.source;return r&&(a+=GI(r)),a}var Rme,_me=y(()=>{Rme=n=>"type"in n?GI(n):qI(n)});function Np(n,e){"type"in n&&n.type==="document"&&(n={start:n.start,value:n.value}),Lme(Object.freeze([]),n,e)}function Lme(n,e,t){let r=t(e,n);if(typeof r=="symbol")return r;for(let a of["key","value"]){let i=e[a];if(i&&"items"in i){for(let s=0;s{oH=Symbol("break visit"),WWe=Symbol("skip children"),Fme=Symbol("remove item");Np.BREAK=oH;Np.SKIP=WWe;Np.REMOVE=Fme;Np.itemAtPath=(n,e)=>{let t=n;for(let[r,a]of e){let i=t==null?void 0:t[r];if(i&&"items"in i)t=i.items[a];else return}return t};Np.parentCollection=(n,e)=>{let t=Np.itemAtPath(n,e.slice(0,-1)),r=e[e.length-1][0],a=t==null?void 0:t[r];if(a&&"items"in a)return a;throw new Error("Parent collection not found")}});var cH={};Xe(cH,{BOM:()=>sx,DOCUMENT:()=>ox,FLOW_END:()=>lx,SCALAR:()=>Vv,createScalarToken:()=>Ame,isCollection:()=>qWe,isScalar:()=>GWe,prettyToken:()=>YWe,resolveAsScalar:()=>Pme,setScalarValue:()=>Mme,stringify:()=>Rme,tokenType:()=>lH,visit:()=>Np});function YWe(n){switch(n){case sx:return"";case ox:return"";case lx:return"";case Vv:return"";default:return JSON.stringify(n)}}function lH(n){switch(n){case sx:return"byte-order-mark";case ox:return"doc-mode";case lx:return"flow-error-end";case Vv:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case` +`:case`\r +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(n[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}var sx,ox,lx,Vv,qWe,GWe,YI=y(()=>{Nme();_me();Ome();sx="\uFEFF",ox="",lx="",Vv="",qWe=n=>!!n&&"items"in n,GWe=n=>!!n&&(n.type==="scalar"||n.type==="single-quoted-scalar"||n.type==="double-quoted-scalar"||n.type==="block-scalar")});function fl(n){switch(n){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var zme,KWe,KI,ZWe,dH,Wv,uH=y(()=>{YI();zme=new Set("0123456789ABCDEFabcdef"),KWe=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),KI=new Set(",[]{}"),ZWe=new Set(` ,[]{} +\r `),dH=n=>!n||ZWe.has(n),Wv=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){var a;if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let r=(a=this.next)!=null?a:"stream";for(;r&&(t||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===` +`?!0:t==="\r"?this.buffer[e+1]===` +`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let r=0;for(;t===" ";)t=this.buffer[++r+e];if(t==="\r"){let a=this.buffer[r+e+1];if(a===` +`||!a&&!this.atEnd)return e+r+1}return t===` +`||r>=this.indentNext||!t&&!this.atEnd?e+r:-1}if(t==="-"||t==="."){let r=this.buffer.substr(e,3);if((r==="---"||r==="...")&&fl(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!fl(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&fl(t)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(dH),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,r=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=r=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let a=this.getLine();if(a===null)return this.setNext("flow");if((r!==-1&&r"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>fl(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,r;e:for(let i=this.pos;r=this.buffer[i];++i)switch(r){case" ":t+=1;break;case` +`:e=i,t=0;break;case"\r":{let s=this.buffer[i+1];if(!s&&!this.atEnd)return this.setNext("block-scalar");if(s===` +`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let i=this.continueScalar(e+1);if(i===-1)break;e=this.buffer.indexOf(` +`,i)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let a=e+1;for(r=this.buffer[a];r===" ";)r=this.buffer[++a];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===` +`;)r=this.buffer[++a];e=a-1}else if(!this.blockScalarKeep)do{let i=e-1,s=this.buffer[i];s==="\r"&&(s=this.buffer[--i]);let o=i;for(;s===" ";)s=this.buffer[--i];if(s===` +`&&i>=this.pos&&i+1+t>o)e=i;else break}while(!0);return yield Vv,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,r=this.pos-1,a;for(;a=this.buffer[++r];)if(a===":"){let i=this.buffer[r+1];if(fl(i)||e&&KI.has(i))break;t=r}else if(fl(a)){let i=this.buffer[r+1];if(a==="\r"&&(i===` +`?(r+=1,a=` +`,i=this.buffer[r+1]):t=r),i==="#"||e&&KI.has(i))break;if(a===` +`){let s=this.continueScalar(r+1);if(s===-1)break;r=Math.max(r,s-2)}}else{if(e&&KI.has(a))break;t=r}return!a&&!this.atEnd?this.setNext("plain-scalar"):(yield Vv,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(t&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(dH),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,r=this.charAt(1);if(fl(r)||t&&KI.has(r)){t?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!fl(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(KWe.has(t))t=this.buffer[++e];else if(t==="%"&&zme.has(this.buffer[e+1])&&zme.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` +`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===` +`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,r;do r=this.buffer[++t];while(r===" "||e&&r===" ");let a=t-this.pos;return a>0&&(yield this.buffer.substr(this.pos,a),this.pos=t),a}*pushUntil(e){let t=this.pos,r=this.buffer[t];for(;!e(r);)r=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}});var qv,pH=y(()=>{qv=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,r=this.lineStarts.length;for(;t>1;this.lineStarts[i]=0;)switch(n[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;((t=n[++e])==null?void 0:t.type)==="space";);return n.splice(e,n.length)}function QI(n,e){if(e.length<1e5)Array.prototype.push.apply(n,e);else for(let t=0;t{YI();uH();nh=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Wv,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(e,t))yield*this.next(r);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=lH(e);if(t)if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let r=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&(e==null?void 0:e.type)!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e!=null?e:this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let r=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in r?r.indent:0:t.type==="flow-collection"&&r.type==="document"&&(t.indent=0),t.type==="flow-collection"&&jme(t),r.type){case"document":r.value=t;break;case"block-scalar":r.props.push(t);break;case"block-map":{let a=r.items[r.items.length-1];if(a.value){r.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(a.sep)a.value=t;else{Object.assign(a,{key:t,sep:[]}),this.onKeyLine=!a.explicitKey;return}break}case"block-seq":{let a=r.items[r.items.length-1];a.value?r.items.push({start:[],value:t}):a.value=t;break}case"flow-collection":{let a=r.items[r.items.length-1];!a||a.value?r.items.push({start:[],key:t,sep:[]}):a.sep?a.value=t:Object.assign(a,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let a=t.items[t.items.length-1];a&&!a.sep&&!a.value&&a.start.length>0&&Bme(a.start)===-1&&(t.indent===0||a.start.every(i=>i.type!=="comment"||i.indent=e.indent){let a=!this.onKeyLine&&this.indent===e.indent,i=a&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",s=[];if(i&&t.sep&&!t.value){let o=[];for(let l=0;le.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):i||t.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Rp(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if($me(t.key)&&!Rp(t.sep,"newline")){let o=Gv(t.start),l=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:l,sep:c}]})}else s.length>0?t.sep=t.sep.concat(s,this.sourceToken):t.sep.push(this.sourceToken);else if(Rp(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=Gv(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:s,key:null,sep:[this.sourceToken]}):Rp(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);i||t.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Rp(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else a&&e.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){var r;let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let a="end"in t.value?t.value.end:void 0,i=Array.isArray(a)?a[a.length-1]:void 0;(i==null?void 0:i.type)==="comment"?a==null||a.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let a=e.items[e.items.length-2],i=(r=a==null?void 0:a.value)==null?void 0:r.end;if(Array.isArray(i)){QI(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||Rp(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let a=this.startBlockValue(e);if(a){this.stack.push(a);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while((r==null?void 0:r.type)==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let a=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:a,sep:[]}):t.sep?this.stack.push(a):Object.assign(t,{key:a,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let a=ZI(r),i=Gv(a);jme(e);let s=e.end.splice(1,e.end.length);s.push(this.sourceToken);let o={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=o}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(` +`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(` +`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=ZI(e),r=Gv(t);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=ZI(e),r=Gv(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}}});function Ume(n){let e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new qv||null,prettyErrors:e}}function Hme(n,e={}){let{lineCounter:t,prettyErrors:r}=Ume(e),a=new nh(t==null?void 0:t.addNewLine),i=new rh(e),s=Array.from(i.compose(a.parse(n)));if(r&&t)for(let o of s)o.errors.forEach(tx(n,t)),o.warnings.forEach(tx(n,t));return s.length>0?s:Object.assign([],{empty:!0},i.streamInfo())}function fH(n,e={}){let{lineCounter:t,prettyErrors:r}=Ume(e),a=new nh(t==null?void 0:t.addNewLine),i=new rh(e),s=null;for(let o of i.compose(a.parse(n),!0,n.length))if(!s)s=o;else if(s.options.logLevel!=="silent"){s.errors.push(new Ds(o.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&t&&(s.errors.forEach(tx(n,t)),s.warnings.forEach(tx(n,t))),s}function Vme(n,e,t){let r;typeof e=="function"?r=e:t===void 0&&e&&typeof e=="object"&&(t=e);let a=fH(n,t);if(!a)return null;if(a.warnings.forEach(i=>TI(a.options.logLevel,i)),a.errors.length>0){if(a.options.logLevel!=="silent")throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},t))}function Wme(n,e,t){var a;let r=null;if(typeof e=="function"||Array.isArray(e)?r=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let i=Math.round(t);t=i<1?void 0:i>8?{indent:8}:{indent:i}}if(n===void 0){let{keepUndefined:i}=(a=t!=null?t:e)!=null?a:{};if(!i)return}return ho(n)&&!r?n.toString(t):new uc(n,r,t).toString(t)}var qme=y(()=>{iH();ex();rx();AU();Wt();pH();mH()});var hH={};Xe(hH,{Alias:()=>cc,CST:()=>cH,Composer:()=>rh,Document:()=>uc,Lexer:()=>Wv,LineCounter:()=>qv,Pair:()=>an,Parser:()=>nh,Scalar:()=>Pe,Schema:()=>Bv,YAMLError:()=>$v,YAMLMap:()=>hn,YAMLParseError:()=>Ds,YAMLSeq:()=>ka,YAMLWarning:()=>Uv,isAlias:()=>fo,isCollection:()=>rr,isDocument:()=>ho,isMap:()=>go,isNode:()=>Rt,isPair:()=>Et,isScalar:()=>dt,isSeq:()=>yo,parse:()=>Vme,parseAllDocuments:()=>Hme,parseDocument:()=>fH,stringify:()=>Wme,visit:()=>dl,visitAsync:()=>LC});var gH=y(()=>{iH();ex();KU();rx();zC();Wt();Ep();Fn();Pp();Ap();YI();uH();pH();mH();qme();OC()});var Yv,cx=y(()=>{gH();gH();Yv=hH});function dx(n,e){let t=QWe(n),r=t.frontmatter?JWe(t.frontmatter,e):{},a=XWe(t.body,e);return{frontmatter:r,body:a}}function QWe(n){var t,r;let e=n.split(` +`);if(((t=e[0])==null?void 0:t.trim())==="---"){let a=-1;for(let i=1;i0){let s=e.slice(1,a).join(` +`),l=e.slice(a+1).join(` +`);return{frontmatter:s.trim()||null,body:l}}}return{frontmatter:null,body:n}}function JWe(n,e){try{let t=tqe(eqe(n,e)),r=Yv.parse(t);return typeof r!="object"||r===null?(Gme.warn("Template frontmatter did not parse to a valid object",{category:"validation",operation:"template-frontmatter-did-not-parse-valid-object"}),{}):r}catch(t){return Gme.error("Error processing template frontmatter:",{category:"validation",operation:"processing-template-frontmatter",error:t}),{}}}function XWe(n,e){return nqe(n,e)}function eqe(n,e){var g;let t=n,r=new Date,a=e.title||"";t=ah(t,"title",a),t=t.replace(/\{\{priority\}\}/g,e.priority||""),t=t.replace(/\{\{status\}\}/g,e.status||"");let i=Array.isArray(e.contexts)?e.contexts.join(", "):"";t=t.replace(/\{\{contexts\}\}/g,i);let s=Array.isArray(e.tags)?e.tags.join(", "):"";t=t.replace(/\{\{tags\}\}/g,s);let o=Array.isArray(e.tags)?e.tags.map(v=>`#${v}`).join(" "):"";t=t.replace(/\{\{hashtags\}\}/g,o),t=t.replace(/\{\{timeEstimate\}\}/g,((g=e.timeEstimate)==null?void 0:g.toString())||""),t=t.replace(/\{\{dueDate\}\}/g,e.dueDate||""),t=t.replace(/\{\{scheduledDate\}\}/g,e.scheduledDate||""),t=t.replace(/\{\{details\}\}/g,e.details||"");let l=e.parentNote||"";t=ah(t,"parentNote",l,{alwaysQuote:!0}),t=t.replace(/\{\{date\}\}/g,D(r,"yyyy-MM-dd")),t=t.replace(/\{\{time\}\}/g,D(r,"HH:mm")),t=t.replace(/\{\{year\}\}/g,D(r,"yyyy")),t=t.replace(/\{\{month\}\}/g,D(r,"MM")),t=t.replace(/\{\{day\}\}/g,D(r,"dd")),t=t.replace(/\{\{hour\}\}/g,D(r,"HH")),t=t.replace(/\{\{minute\}\}/g,D(r,"mm")),t=t.replace(/\{\{second\}\}/g,D(r,"ss")),t=t.replace(/\{\{timestamp\}\}/g,D(r,"yyyy-MM-dd-HHmmss")),t=t.replace(/\{\{dateTime\}\}/g,D(r,"yyyy-MM-dd-HHmm")),t=t.replace(/\{\{shortDate\}\}/g,D(r,"yyMMdd")),t=t.replace(/\{\{shortYear\}\}/g,D(r,"yy")),t=t.replace(/\{\{monthName\}\}/g,D(r,"MMMM")),t=t.replace(/\{\{monthNameShort\}\}/g,D(r,"MMM")),t=t.replace(/\{\{dayName\}\}/g,D(r,"EEEE")),t=t.replace(/\{\{dayNameShort\}\}/g,D(r,"EEE")),t=t.replace(/\{\{week\}\}/g,D(r,"ww")),t=t.replace(/\{\{quarter\}\}/g,D(r,"q")),t=t.replace(/\{\{time12\}\}/g,D(r,"hh:mm a")),t=t.replace(/\{\{time24\}\}/g,D(r,"HH:mm")),t=t.replace(/\{\{hourPadded\}\}/g,D(r,"HH")),t=t.replace(/\{\{hour12\}\}/g,D(r,"hh")),t=t.replace(/\{\{ampm\}\}/g,D(r,"a")),t=t.replace(/\{\{unix\}\}/g,Math.floor(r.getTime()/1e3).toString()),t=t.replace(/\{\{unixMs\}\}/g,r.getTime().toString()),t=t.replace(/\{\{milliseconds\}\}/g,D(r,"SSS")),t=t.replace(/\{\{ms\}\}/g,D(r,"SSS")),t=t.replace(/\{\{timezone\}\}/g,D(r,"xxx")),t=t.replace(/\{\{timezoneShort\}\}/g,D(r,"xx")),t=t.replace(/\{\{utcOffset\}\}/g,D(r,"xxx")),t=t.replace(/\{\{utcOffsetShort\}\}/g,D(r,"xx")),t=t.replace(/\{\{utcZ\}\}/g,"Z");let c=D(r,"yyMMdd"),d=new Date(r);d.setHours(0,0,0,0);let u=Math.floor((r.getTime()-d.getTime())/1e3),p=`${c}${u.toString(36)}`;t=t.replace(/\{\{zettel\}\}/g,p),t=t.replace(/\{\{nano\}\}/g,Date.now().toString()+Math.random().toString(36).substring(2,7));let m=e.priority||"",f=e.status||"";t=t.replace(/\{\{priorityShort\}\}/g,m.substring(0,1).toUpperCase()),t=t.replace(/\{\{statusShort\}\}/g,f.substring(0,1).toUpperCase());let h=e.title||"";if(t=t.replace(/\{\{titleLower\}\}/g,h.toLowerCase()),t=t.replace(/\{\{titleUpper\}\}/g,h.toUpperCase()),t=t.replace(/\{\{titleSnake\}\}/g,h.toLowerCase().replace(/\s+/g,"_")),t=t.replace(/\{\{titleKebab\}\}/g,h.toLowerCase().replace(/\s+/g,"-")),t=t.replace(/\{\{titleCamel\}\}/g,h.replace(/(?:^\w|[A-Z]|\b\w)/g,(v,k)=>k===0?v.toLowerCase():v.toUpperCase()).replace(/\s+/g,"")),t=t.replace(/\{\{titlePascal\}\}/g,h.replace(/(?:^\w|[A-Z]|\b\w)/g,v=>v.toUpperCase()).replace(/\s+/g,"")),"icsEventTitle"in e){let v=e,k=v.icsEventTitle||"";t=ah(t,"icsEventTitle",k),t=t.replace(/\{\{icsEventStart\}\}/g,v.icsEventStart||""),t=t.replace(/\{\{icsEventEnd\}\}/g,v.icsEventEnd||"");let T=v.icsEventLocation||"";t=ah(t,"icsEventLocation",T);let b=v.icsEventDescription||"";t=ah(t,"icsEventDescription",b),t=t.replace(/\{\{icsEventUrl\}\}/g,v.icsEventUrl||"");let w=v.icsEventSubscription||"";t=ah(t,"icsEventSubscription",w);let S=v.icsEventId||"";t=ah(t,"icsEventId",S,{alwaysQuote:!0})}return t}function ah(n,e,t,r={}){let a=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`(["'])\\{\\{${a}\\}\\}\\1`,"g"),s=t||"",o=n.replace(i,(d,u)=>{let p=u==="'"?s.replace(/'/g,"''"):yH(s);return`${u}${p}${u}`}),l=s&&(r.alwaysQuote||rqe(s))?`"${yH(s)}"`:s,c=new RegExp(`\\{\\{${a}\\}\\}`,"g");return o=o.replace(c,l),o}function tqe(n){return n.replace(/^(\s*[^#\n][^:\n]*:\s*)(<%.*?%>)(\s*)$/gm,(e,t,r,a)=>`${t}"${yH(r)}"${a}`)}function rqe(n){if(!n)return!1;let e=/[[\]{}:>|*&!%#`@,]/,t=/^[-?]/,r=/^\d+\.?\d*$/,a=/^(true|false|yes|no|on|off)$/i;return e.test(n)||t.test(n)||r.test(n)||a.test(n)}function yH(n){return n?n.replace(/\\/g,"\\\\").replace(/"/g,'\\"'):""}function nqe(n,e){var f;let t=n,r=new Date;t=t.replace(/\{\{title\}\}/g,e.title||""),t=t.replace(/\{\{priority\}\}/g,e.priority||""),t=t.replace(/\{\{status\}\}/g,e.status||"");let a=Array.isArray(e.contexts)?e.contexts.join(", "):"";t=t.replace(/\{\{contexts\}\}/g,a);let i=Array.isArray(e.tags)?e.tags.join(", "):"";t=t.replace(/\{\{tags\}\}/g,i);let s=Array.isArray(e.tags)?e.tags.map(h=>`#${h}`).join(" "):"";t=t.replace(/\{\{hashtags\}\}/g,s),t=t.replace(/\{\{timeEstimate\}\}/g,((f=e.timeEstimate)==null?void 0:f.toString())||""),t=t.replace(/\{\{dueDate\}\}/g,e.dueDate||""),t=t.replace(/\{\{scheduledDate\}\}/g,e.scheduledDate||""),t=t.replace(/\{\{details\}\}/g,e.details||""),t=t.replace(/\{\{parentNote\}\}/g,e.parentNote||""),t=t.replace(/\{\{date\}\}/g,D(r,"yyyy-MM-dd")),t=t.replace(/\{\{time\}\}/g,D(r,"HH:mm")),t=t.replace(/\{\{year\}\}/g,D(r,"yyyy")),t=t.replace(/\{\{month\}\}/g,D(r,"MM")),t=t.replace(/\{\{day\}\}/g,D(r,"dd")),t=t.replace(/\{\{hour\}\}/g,D(r,"HH")),t=t.replace(/\{\{minute\}\}/g,D(r,"mm")),t=t.replace(/\{\{second\}\}/g,D(r,"ss")),t=t.replace(/\{\{timestamp\}\}/g,D(r,"yyyy-MM-dd-HHmmss")),t=t.replace(/\{\{dateTime\}\}/g,D(r,"yyyy-MM-dd-HHmm")),t=t.replace(/\{\{shortDate\}\}/g,D(r,"yyMMdd")),t=t.replace(/\{\{shortYear\}\}/g,D(r,"yy")),t=t.replace(/\{\{monthName\}\}/g,D(r,"MMMM")),t=t.replace(/\{\{monthNameShort\}\}/g,D(r,"MMM")),t=t.replace(/\{\{dayName\}\}/g,D(r,"EEEE")),t=t.replace(/\{\{dayNameShort\}\}/g,D(r,"EEE")),t=t.replace(/\{\{week\}\}/g,D(r,"ww")),t=t.replace(/\{\{quarter\}\}/g,D(r,"q")),t=t.replace(/\{\{time12\}\}/g,D(r,"hh:mm a")),t=t.replace(/\{\{time24\}\}/g,D(r,"HH:mm")),t=t.replace(/\{\{hourPadded\}\}/g,D(r,"HH")),t=t.replace(/\{\{hour12\}\}/g,D(r,"hh")),t=t.replace(/\{\{ampm\}\}/g,D(r,"a")),t=t.replace(/\{\{unix\}\}/g,Math.floor(r.getTime()/1e3).toString()),t=t.replace(/\{\{unixMs\}\}/g,r.getTime().toString()),t=t.replace(/\{\{milliseconds\}\}/g,D(r,"SSS")),t=t.replace(/\{\{ms\}\}/g,D(r,"SSS")),t=t.replace(/\{\{timezone\}\}/g,D(r,"xxx")),t=t.replace(/\{\{timezoneShort\}\}/g,D(r,"xx")),t=t.replace(/\{\{utcOffset\}\}/g,D(r,"xxx")),t=t.replace(/\{\{utcOffsetShort\}\}/g,D(r,"xx")),t=t.replace(/\{\{utcZ\}\}/g,"Z");let o=D(r,"yyMMdd"),l=new Date(r);l.setHours(0,0,0,0);let c=Math.floor((r.getTime()-l.getTime())/1e3),d=`${o}${c.toString(36)}`;t=t.replace(/\{\{zettel\}\}/g,d),t=t.replace(/\{\{nano\}\}/g,Date.now().toString()+Math.random().toString(36).substring(2,7));let u=e.priority||"",p=e.status||"";t=t.replace(/\{\{priorityShort\}\}/g,u.substring(0,1).toUpperCase()),t=t.replace(/\{\{statusShort\}\}/g,p.substring(0,1).toUpperCase());let m=e.title||"";if(t=t.replace(/\{\{titleLower\}\}/g,m.toLowerCase()),t=t.replace(/\{\{titleUpper\}\}/g,m.toUpperCase()),t=t.replace(/\{\{titleSnake\}\}/g,m.toLowerCase().replace(/\s+/g,"_")),t=t.replace(/\{\{titleKebab\}\}/g,m.toLowerCase().replace(/\s+/g,"-")),t=t.replace(/\{\{titleCamel\}\}/g,m.replace(/(?:^\w|[A-Z]|\b\w)/g,(h,g)=>g===0?h.toLowerCase():h.toUpperCase()).replace(/\s+/g,"")),t=t.replace(/\{\{titlePascal\}\}/g,m.replace(/(?:^\w|[A-Z]|\b\w)/g,h=>h.toUpperCase()).replace(/\s+/g,"")),"icsEventTitle"in e){let h=e;t=t.replace(/\{\{icsEventTitle\}\}/g,h.icsEventTitle||""),t=t.replace(/\{\{icsEventStart\}\}/g,h.icsEventStart||""),t=t.replace(/\{\{icsEventEnd\}\}/g,h.icsEventEnd||""),t=t.replace(/\{\{icsEventLocation\}\}/g,h.icsEventLocation||""),t=t.replace(/\{\{icsEventDescription\}\}/g,h.icsEventDescription||""),t=t.replace(/\{\{icsEventUrl\}\}/g,h.icsEventUrl||""),t=t.replace(/\{\{icsEventSubscription\}\}/g,h.icsEventSubscription||""),t=t.replace(/\{\{icsEventId\}\}/g,h.icsEventId||"")}return t}function Yme(n,e){return{...e,...n}}var Gme,JI=y(()=>{Cr();cx();q();Gme=M({tag:"Utils/TemplateProcessor"})});function oqe(n,e){return n.replace(sqe,t=>D(e,iqe[t]))}function lqe(n){return n.replace(/\\/g,"/").split("/").some(e=>e==="."||e==="..")}function cqe(n){let e=n.replace(/\\/g,"/"),t=e.endsWith("/"),r=[];for(let i of e.split("/"))if(!(!i||i===".")){if(i===".."){r.pop();continue}r.push(i)}let a=r.join("/");return t&&a?`${a}/`:a}function XI(n){return n.replace(/\.md$/i,"")}function dqe(n){let e=n.trim();if(!e)return"";if(e.startsWith("[[")&&e.endsWith("]]")){let r=e.slice(2,-2).trim(),a=r.indexOf("|"),i=a!==-1?r.slice(0,a):r;return XI(i.trim())}let t=e.match(/^\[[^\]]*\]\(([^)]+)\)$/);if(t){let r=t[1].trim();r.startsWith("<")&&r.endsWith(">")&&(r=r.slice(1,-1).trim());try{r=decodeURIComponent(r)}catch(a){aqe.debug("Failed to decode project path:",{category:"persistence",operation:"decode-project-path",details:{value:r},error:a})}return XI(r)}return XI(e)}function uqe(n){return XI(n.trim()).replace(/\\/g,"/").split("/").filter(t=>t.length>0).map(t=>t.replace(/[<>:"|?*]/g,"_")).join("/")}function vH(n,e){let t=e?e(n):dqe(n);return uqe(t)}function Kme(n,e){let t=vH(n,e);return t?t.split("/").slice(0,-1).join("/"):""}function eN(n,e={}){if(!n)return n;let{date:t=new Date,taskData:r,icsData:a,extractProjectBasename:i,extractProjectFilePath:s}=e,o=n,l=lqe(n);if(o=oqe(o,t),r){let u=Array.isArray(r.contexts)&&r.contexts.length>0?r.contexts[0]:"";o=o.replace(/\{\{context\}\}/g,u);let p=Array.isArray(r.projects)&&r.projects.length>0?i?i(r.projects[0]):r.projects[0]:"";o=o.replace(/\{\{project\}\}/g,p);let m=Array.isArray(r.projects)&&r.projects.length>0?r.projects.map(U=>i?i(U):U).join("/"):"";o=o.replace(/\{\{projects\}\}/g,m);let f=Array.isArray(r.projects)&&r.projects.length>0?vH(r.projects[0],s):"";o=o.replace(/\{\{projectFilePath\}\}/g,f);let h=Array.isArray(r.projects)&&r.projects.length>0?r.projects.map(U=>vH(U,s)).filter(U=>U.length>0).join("/"):"";o=o.replace(/\{\{projectFilePaths\}\}/g,h);let g=Array.isArray(r.projects)&&r.projects.length>0?Kme(r.projects[0],s):"";o=o.replace(/\{\{projectFolder\}\}/g,g);let v=Array.isArray(r.projects)&&r.projects.length>0?r.projects.map(U=>Kme(U,s)).filter(U=>U.length>0).join("/"):"";o=o.replace(/\{\{projectFolders\}\}/g,v);let k=Array.isArray(r.contexts)&&r.contexts.length>0?r.contexts.join("/"):"";o=o.replace(/\{\{contexts\}\}/g,k);let T=r.priority||"";o=o.replace(/\{\{priority\}\}/g,T);let b=r.status||"";o=o.replace(/\{\{status\}\}/g,b);let w=r.title?r.title.replace(/[<>:"/\\|?*]/g,"_"):"";o=o.replace(/\{\{title\}\}/g,w);let S=r.due||"";o=o.replace(/\{\{dueDate\}\}/g,S);let C=r.scheduled||"";o=o.replace(/\{\{scheduledDate\}\}/g,C);let x=T?T.substring(0,1).toUpperCase():"";o=o.replace(/\{\{priorityShort\}\}/g,x);let E=b?b.substring(0,1).toUpperCase():"";o=o.replace(/\{\{statusShort\}\}/g,E);let _=w?w.toLowerCase():"";o=o.replace(/\{\{titleLower\}\}/g,_);let F=w?w.toUpperCase():"";o=o.replace(/\{\{titleUpper\}\}/g,F);let I=w?w.toLowerCase().replace(/\s+/g,"_"):"";o=o.replace(/\{\{titleSnake\}\}/g,I);let A=w?w.toLowerCase().replace(/\s+/g,"-"):"";o=o.replace(/\{\{titleKebab\}\}/g,A);let R=w?w.replace(/(?:^\w|[A-Z]|\b\w)/g,(U,pe)=>pe===0?U.toLowerCase():U.toUpperCase()).replace(/\s+/g,""):"";o=o.replace(/\{\{titleCamel\}\}/g,R);let O=w?w.replace(/(?:^\w|[A-Z]|\b\w)/g,U=>U.toUpperCase()).replace(/\s+/g,""):"";o=o.replace(/\{\{titlePascal\}\}/g,O)}if(a){let u=a.title?a.title.replace(/[<>:"/\\|?*]/g,"_"):"";o=o.replace(/\{\{icsEventTitle\}\}/g,u);let p=u?u.toLowerCase():"";o=o.replace(/\{\{icsEventTitleLower\}\}/g,p);let m=u?u.toUpperCase():"";o=o.replace(/\{\{icsEventTitleUpper\}\}/g,m);let f=u?u.toLowerCase().replace(/\s+/g,"_"):"";o=o.replace(/\{\{icsEventTitleSnake\}\}/g,f);let h=u?u.toLowerCase().replace(/\s+/g,"-"):"";o=o.replace(/\{\{icsEventTitleKebab\}\}/g,h);let g=u?u.replace(/(?:^\w|[A-Z]|\b\w)/g,(b,w)=>w===0?b.toLowerCase():b.toUpperCase()).replace(/\s+/g,""):"";o=o.replace(/\{\{icsEventTitleCamel\}\}/g,g);let v=u?u.replace(/(?:^\w|[A-Z]|\b\w)/g,b=>b.toUpperCase()).replace(/\s+/g,""):"";o=o.replace(/\{\{icsEventTitlePascal\}\}/g,v);let k=a.location?a.location.replace(/[<>:"/\\|?*]/g,"_"):"";o=o.replace(/\{\{icsEventLocation\}\}/g,k);let T=a.description?a.description.replace(/[<>:"/\\|?*]/g,"_"):"";o=o.replace(/\{\{icsEventDescription\}\}/g,T)}o=o.replace(/\{\{year\}\}/g,D(t,"yyyy")),o=o.replace(/\{\{month\}\}/g,D(t,"MM")),o=o.replace(/\{\{day\}\}/g,D(t,"dd")),o=o.replace(/\{\{date\}\}/g,D(t,"yyyy-MM-dd")),o=o.replace(/\{\{time\}\}/g,D(t,"HHmmss")),o=o.replace(/\{\{timestamp\}\}/g,D(t,"yyyy-MM-dd-HHmmss")),o=o.replace(/\{\{dateTime\}\}/g,D(t,"yyyy-MM-dd-HHmm")),o=o.replace(/\{\{hour\}\}/g,D(t,"HH")),o=o.replace(/\{\{minute\}\}/g,D(t,"mm")),o=o.replace(/\{\{second\}\}/g,D(t,"ss")),o=o.replace(/\{\{shortDate\}\}/g,D(t,"yyMMdd")),o=o.replace(/\{\{shortYear\}\}/g,D(t,"yy")),o=o.replace(/\{\{monthName\}\}/g,D(t,"MMMM")),o=o.replace(/\{\{monthNameShort\}\}/g,D(t,"MMM")),o=o.replace(/\{\{dayName\}\}/g,D(t,"EEEE")),o=o.replace(/\{\{dayNameShort\}\}/g,D(t,"EEE")),o=o.replace(/\{\{week\}\}/g,D(t,"ww")),o=o.replace(/\{\{quarter\}\}/g,D(t,"q")),o=o.replace(/\{\{time12\}\}/g,D(t,"hh:mm a")),o=o.replace(/\{\{time24\}\}/g,D(t,"HH:mm")),o=o.replace(/\{\{hourPadded\}\}/g,D(t,"HH")),o=o.replace(/\{\{hour12\}\}/g,D(t,"hh")),o=o.replace(/\{\{ampm\}\}/g,D(t,"a")),o=o.replace(/\{\{unix\}\}/g,Math.floor(t.getTime()/1e3).toString()),o=o.replace(/\{\{unixMs\}\}/g,t.getTime().toString()),o=o.replace(/\{\{milliseconds\}\}/g,D(t,"SSS")),o=o.replace(/\{\{ms\}\}/g,D(t,"SSS")),o=o.replace(/\{\{timezone\}\}/g,D(t,"xxx")),o=o.replace(/\{\{timezoneShort\}\}/g,D(t,"xx")),o=o.replace(/\{\{utcOffset\}\}/g,D(t,"xxx")),o=o.replace(/\{\{utcOffsetShort\}\}/g,D(t,"xx")),o=o.replace(/\{\{utcZ\}\}/g,"Z");let c=(()=>{let u=D(t,"yyMMdd"),p=new Date(t);p.setHours(0,0,0,0);let f=Math.floor((t.getTime()-p.getTime())/1e3).toString(36);return`${u}${f}`})();o=o.replace(/\{\{zettel\}\}/g,c);let d=Date.now().toString()+Math.random().toString(36).substring(2,7);if(o=o.replace(/\{\{nano\}\}/g,d),e.currentNote){let u=e.currentNote;o=o.replace(/\{\{currentNote(Path|Title)\}\}/g,(p,m)=>m==="Path"?u.path:u.title)}return l?cqe(o):o}var aqe,iqe,sqe,kH=y(()=>{Cr();q();aqe=M({tag:"Utils/FolderTemplateProcessor"}),iqe={YYYY:"yyyy",YY:"yy",MMMM:"MMMM",MMM:"MMM",MM:"MM",DD:"dd",dddd:"EEEE",ddd:"EEE"},sqe=/YYYY|MMMM|dddd|MMM|ddd|YY|MM|DD/g});var Zme,tN,rN,Qme=y(()=>{Zme=require("obsidian");Pr();pf();kv();yt();xe();dr();JI();Yg();q();tN=M({tag:"Services/TaskService/TaskCreationService"}),rN=class{constructor(e){this.deps=e}setWebhookNotifier(e){this.deps.webhookNotifier=e}async createTask(e,t={}){var s,o,l;let{applyDefaults:r=!0,applyTemplate:a=!0}=t,{runtime:i}=this.deps;try{if(r&&(e=await this.deps.applyTaskCreationDefaults(e)),!e.title||!e.title.trim())throw new Error("Title is required");let c=e.title.trim(),d=this.deps.sanitizeTitleForStorage(c),u=i.settings.storeTitleInFilename?this.deps.sanitizeTitleForFilename(c):d,p=e.priority||i.settings.defaultTaskPriority,m=e.status||i.settings.defaultTaskStatus,f=e.dateCreated||qe(),h=e.dateModified||qe(),g=e.recurrence||void 0,v=g?void 0:e.completedDate||((s=i.statusManager)!=null&&s.isCompletedStatus(m)?Yo():void 0),k=e.contexts||[],T=e.projects||[],b=qo(e.tags||[]);if(i.settings.taskIdentificationMethod==="tag"){let le=(o=qo(i.settings.taskTag)[0])!=null?o:i.settings.taskTag;le&&!b.includes(le)&&(b=[le,...b])}let w={title:u,priority:p,status:m,date:new Date,dueDate:e.due,scheduledDate:e.scheduled,contexts:k,projects:T,tags:b,timeEstimate:e.timeEstimate,details:e.details,parentNote:e.parentNote},S=(l=e.occurrenceFilenameTemplate)==null?void 0:l.trim(),C=S&&e.occurrence_date?vue(w,S,e.occurrence_date):hue(w,i.settings),x=await this.resolveTargetFolder(e);x&&await qu(i.app.vault,x);let E=await vv(C,x,i.app.vault),_=x?`${x}/${E}.md`:`${E}.md`,F=S&&e.occurrence_date?C:u,I=i.settings.storeTitleInFilename&&E===F&&d===u,A={title:d,status:m,priority:p,due:e.due||void 0,scheduled:e.scheduled||void 0,contexts:k.length>0?k:void 0,projects:T.length>0?T:void 0,timeEstimate:e.timeEstimate&&e.timeEstimate>0?e.timeEstimate:void 0,dateCreated:f,dateModified:h,recurrence:g,completedDate:v,recurrence_anchor:e.recurrence_anchor||void 0,recurrence_parent:e.recurrence_parent||void 0,occurrence_date:e.occurrence_date||void 0,occurrence_materialization:e.occurrence_materialization||void 0,occurrence_next_trigger:e.occurrence_next_trigger||void 0,occurrence_template:e.occurrence_template||void 0,occurrence_past_horizon:e.occurrence_past_horizon||void 0,occurrence_future_horizon:e.occurrence_future_horizon||void 0,reminders:e.reminders&&e.reminders.length>0?e.reminders:void 0,customProperties:e.customProperties||void 0,icsEventId:e.icsEventId||void 0,blockedBy:e.blockedBy&&e.blockedBy.length>0?e.blockedBy:void 0},R=i.fieldMapper.getUserFields();if(R.length>0){let le=e,at=A;for(let He of R)Object.prototype.hasOwnProperty.call(le,He.key)&&le[He.key]!==void 0&&(at[He.key]=le[He.key])}if(A.recurrence&&typeof A.recurrence=="string"&&!A.recurrence.includes("DTSTART:")){let le={...A,title:d,status:m,priority:p,path:"",archived:!1},at=uf(le);at&&(A.recurrence=at)}let U=i.settings.taskIdentificationMethod==="tag"?i.settings.taskTag:void 0,pe=i.fieldMapper.mapToFrontmatter(A,U,I);if(i.settings.taskIdentificationMethod==="property"){let le=i.settings.taskPropertyName,at=i.settings.taskPropertyValue;le&&at&&Gg(pe,le,at),b.length>0&&(pe.tags=b)}else pe.tags=b;let oe=a?await this.deps.applyTemplate(e):{frontmatter:{},body:""},X=oe.body?oe.body.replace(/\r\n/g,` +`).trimEnd():e.details?e.details.replace(/\r\n/g,` +`).trimEnd():"",de=Yme(pe,oe.frontmatter);e.customFrontmatter&&(de={...de,...e.customFrontmatter}),I&&delete de[i.fieldMapper.toUserField("title")],i.settings.taskIdentificationMethod==="property"&&Gg(de,i.settings.taskPropertyName,i.settings.taskPropertyValue),b=qo(de.tags);let Q=`--- +${(0,Zme.stringifyYaml)(de)}--- + +`;X.length>0&&(Q+=`${X} +`);let Z=await i.app.vault.create(_,Q),Ue={...A,...de,title:Y(de.title||A.title||d),status:Y(de.status||A.status||m),priority:Y(de.priority||A.priority||p),path:Z.path,tags:b,archived:!1,details:X};try{i.cacheManager.waitForFreshTaskData&&await i.cacheManager.waitForFreshTaskData(Z),i.cacheManager.updateTaskInfoInCache(Z.path,Ue)}catch(le){tN.error("Error updating cache for new task:",{category:"stale-data",operation:"updating-cache-new-task",error:le})}if(i.emitter.trigger(rt,{path:Z.path,updatedTask:Ue}),this.deps.webhookNotifier)try{await this.deps.webhookNotifier.triggerWebhook("task.created",{task:Ue})}catch(le){tN.warn("Failed to trigger webhook for task creation:",{category:"provider",operation:"trigger-webhook-task-creation",error:le})}return i.taskCalendarSyncService&&i.settings.googleCalendarExport.enabled&&i.settings.googleCalendarExport.syncOnTaskCreate&&i.taskCalendarSyncService.syncTaskToCalendar(Ue).catch(le=>{tN.warn("Failed to sync task to Google Calendar:",{category:"provider",operation:"sync-task-google-calendar",error:le})}),{file:Z,taskInfo:Ue}}catch(c){let d=c instanceof Error?c.message:String(c);throw tN.error("Error creating task:",{category:"persistence",operation:"creating-task",details:{stack:c instanceof Error?c.stack:void 0,taskData:e},error:d}),new Error(`Failed to create task: ${d}`)}}async resolveTargetFolder(e){let{runtime:t}=this.deps;if(e.creationContext==="inline-conversion"||e.creationContext==="modal-inline-creation"){let a=t.settings.inlineTaskConvertFolder||"";if(a.trim())return this.deps.processFolderTemplate(a,e);let i=t.settings.tasksFolder||"";return this.deps.processFolderTemplate(i,e)}let r=t.settings.tasksFolder||"";return this.deps.processFolderTemplate(r,e)}}});function Jme(n){return Array.isArray(n.timeEntries)?{...n,timeEntries:n.timeEntries.map(pqe)}:{...n}}function pqe(n){let e={...n};return delete e.duration,e}function nN(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}function mqe(n,e){let t=new Set(nN(n.complete_instances)),r=new Set(nN(n.skipped_instances)),a,i=s=>{(!a||s>a)&&(a=s)};if(Object.prototype.hasOwnProperty.call(e,"complete_instances"))for(let s of nN(e.complete_instances))t.has(s)||i(s);if(Object.prototype.hasOwnProperty.call(e,"skipped_instances"))for(let s of nN(e.skipped_instances))r.has(s)||i(s);return a}function Xme(n){return Object.prototype.hasOwnProperty.call(n,"details")?typeof n.details=="string"?n.details.replace(/\r\n/g,` +`):"":null}function efe({originalTask:n,updates:e,maintainDueDateOffsetInRecurring:t,updateToNextScheduledOccurrenceFn:r=Cd,addDTSTARTToRecurrenceRuleFn:a=uf}){var o,l;let i={};if(e.recurrence!==void 0&&e.recurrence!==n.recurrence){let c={...n,...e},d=r(c,t);if(d.scheduled&&(i.scheduled=d.scheduled),d.due&&(i.due=d.due),typeof e.recurrence=="string"&&e.recurrence&&!e.recurrence.includes("DTSTART:")){let u={...n,...e,...i},p=a(u);p&&(i.recurrence=p)}}else if(e.recurrence!==void 0&&!n.recurrence&&e.recurrence&&typeof e.recurrence=="string"&&!e.recurrence.includes("DTSTART:")){let c={...n,...e},d=a(c);d&&(i.recurrence=d)}if(e.scheduled!==void 0&&e.scheduled!==n.scheduled&&n.recurrence&&typeof n.recurrence=="string"&&!n.recurrence.includes("DTSTART:")){let c={...n,...e},d=a(c);d&&(i.recurrence=d)}if(Object.prototype.hasOwnProperty.call(e,"scheduled")){let c={...n,...e,...i},d=mqe(n,e),u=d?r({...n,complete_instances:(o=e.complete_instances)!=null?o:n.complete_instances,skipped_instances:(l=e.skipped_instances)!=null?l:n.skipped_instances},t):void 0;d&&e.scheduled!==n.scheduled&&e.scheduled===(u==null?void 0:u.scheduled)&&(e.recurrence===void 0||e.recurrence===n.recurrence)?kC(n,d,c):dM(n,e.scheduled,c),i.googleCalendarExceptionOriginalScheduled=c.googleCalendarExceptionOriginalScheduled,i.googleCalendarMovedOriginalDates=c.googleCalendarMovedOriginalDates}let s={...n,...e,...i};return Vf(s),i.googleCalendarExceptionOriginalScheduled=s.googleCalendarExceptionOriginalScheduled,i.googleCalendarMovedOriginalDates=s.googleCalendarMovedOriginalDates,i}function tfe({frontmatter:n,originalTask:e,updates:t,recurrenceUpdates:r,dateModified:a,fieldMapper:i,taskIdentification:s,storeTitleInFilename:o,updateCompletedDateInFrontmatter:l}){let c={tags:qo(n.tags),...t,...r,dateModified:a},d=i.mapToFrontmatter(c,s.method==="tag"?s.tag:void 0,o);if(fqe(n,t,d,i),Object.entries(d).forEach(([u,p])=>{p!==void 0&&(n[u]=p)}),t.status!==void 0&&l(n,t.status,!!e.recurrence),s.method==="property"&&hqe(n,s),t.customFrontmatter&&Object.entries(t.customFrontmatter).forEach(([u,p])=>{p===null?delete n[u]:n[u]=p}),gqe(n,{...t,...r},i),o&&t.title!==void 0&&t.title!==e.title&&delete n[i.toUserField("title")],Object.prototype.hasOwnProperty.call(t,"tags")){let u=qo(t.tags);u.length>0?n.tags=u:delete n.tags}return s.method==="property"&&Gg(n,s.propertyName,s.propertyValue),{finalTags:qo(n.tags)}}function fqe(n,e,t,r){if(Object.prototype.hasOwnProperty.call(e,"title"))return;let a=r.toUserField("title");Object.prototype.hasOwnProperty.call(n,a)&&delete t[a]}function hqe(n,e){e.propertyName&&e.propertyValue&&Gg(n,e.propertyName,e.propertyValue)}function gqe(n,e,t){if(Object.prototype.hasOwnProperty.call(e,"due")&&e.due===void 0&&delete n[t.toUserField("due")],Object.prototype.hasOwnProperty.call(e,"scheduled")&&e.scheduled===void 0&&delete n[t.toUserField("scheduled")],Object.prototype.hasOwnProperty.call(e,"contexts")&&(!Array.isArray(e.contexts)||e.contexts.length===0)&&delete n[t.toUserField("contexts")],Object.prototype.hasOwnProperty.call(e,"projects")){let r=t.toUserField("projects"),a=Array.isArray(e.projects)?e.projects:[];a.length>0?n[r]=a:delete n[r]}Object.prototype.hasOwnProperty.call(e,"timeEstimate")&&e.timeEstimate===void 0&&delete n[t.toUserField("timeEstimate")],Object.prototype.hasOwnProperty.call(e,"completedDate")&&e.completedDate===void 0&&delete n[t.toUserField("completedDate")],Object.prototype.hasOwnProperty.call(e,"recurrence")&&e.recurrence===void 0&&delete n[t.toUserField("recurrence")],Object.prototype.hasOwnProperty.call(e,"googleCalendarExceptionOriginalScheduled")&&e.googleCalendarExceptionOriginalScheduled===void 0&&delete n[t.toUserField("googleCalendarExceptionOriginalScheduled")],Object.prototype.hasOwnProperty.call(e,"googleCalendarMovedOriginalDates")&&(!Array.isArray(e.googleCalendarMovedOriginalDates)||e.googleCalendarMovedOriginalDates.length===0)&&delete n[t.toUserField("googleCalendarMovedOriginalDates")],Object.prototype.hasOwnProperty.call(e,"blockedBy")&&(!Array.isArray(e.blockedBy)||e.blockedBy.length===0)&&delete n[t.toUserField("blockedBy")],Object.prototype.hasOwnProperty.call(e,"reminders")&&(!Array.isArray(e.reminders)||e.reminders.length===0)&&delete n[t.toUserField("reminders")]}function rfe({originalTask:n,updates:e,recurrenceUpdates:t,newPath:r,dateModified:a,currentDateString:i,normalizedDetails:s,finalTags:o,isCompletedStatus:l}){let c={...n,...e,...t,path:r,dateModified:a};return o&&(c.tags=o),s!==null&&(c.details=s),e.status!==void 0&&!n.recurrence&&(l(e.status)?n.completedDate||(c.completedDate=i):c.completedDate=void 0),c}var nfe=y(()=>{pf();uM();Yg()});var aN,Kv,iN,afe=y(()=>{aN=require("obsidian");Pr();yt();kv();xe();nfe();q();ya();Kv=M({tag:"Services/TaskService/TaskUpdateService"}),iN=class{constructor(e){this.deps=e}setWebhookNotifier(e){this.deps.webhookNotifier=e}setAutoArchiveService(e){this.deps.autoArchiveService=e}async updateTask(e,t){var a;let{runtime:r}=this.deps;try{let i=Jme(t),s=r.app.vault.getAbstractFileByPath(e.path);if(!(s instanceof aN.TFile))throw new Error(`Cannot find task file: ${e.path}`);let o=r.settings.storeTitleInFilename&&i.title&&i.title!==e.title,l=e.path;if(o&&i.title){let h=s.parent?s.parent.path:"",g=await vv(i.title,h,r.app.vault);l=h?`${h}/${g}.md`:`${g}.md`}let c={},d=Xme(i),u,p=qe(),m=i.status!==void 0?Yo():"";if(await yr(r.app,s,h=>{let g=r.fieldMapper.mapFromFrontmatter(h,e.path,r.settings.storeTitleInFilename);e={id:e.id,basesData:e.basesData,details:e.details,blocking:e.blocking,isBlocked:e.isBlocked,isBlocking:e.isBlocking,hasSubtasks:e.hasSubtasks,path:e.path,title:e.title,status:e.status,priority:e.priority,archived:!1,...g},c=efe({originalTask:e,updates:i,maintainDueDateOffsetInRecurring:r.settings.maintainDueDateOffsetInRecurring}),u=tfe({frontmatter:h,originalTask:e,updates:i,recurrenceUpdates:c,dateModified:p,fieldMapper:r.fieldMapper,taskIdentification:{method:r.settings.taskIdentificationMethod,tag:r.settings.taskTag,propertyName:r.settings.taskPropertyName,propertyValue:r.settings.taskPropertyValue},storeTitleInFilename:r.settings.storeTitleInFilename,updateCompletedDateInFrontmatter:(k,T,b)=>this.deps.updateCompletedDateInFrontmatter(k,T,b)}).finalTags}),o&&await r.app.fileManager.renameFile(s,l),d!==null){let h=r.app.vault.getAbstractFileByPath(l);h instanceof aN.TFile&&await Ob(r.app,h,g=>{let{frontmatter:v}=Gu(g),k=v!==null?`--- +${v} +--- + +`:"",T=d.trimEnd(),b=T.length>0?`${T} +`:"";return`${k}${b}`})}let f=rfe({originalTask:e,updates:i,recurrenceUpdates:c,newPath:l,dateModified:p,currentDateString:m,normalizedDetails:d,finalTags:u,isCompletedStatus:h=>r.statusManager.isCompletedStatus(h)});o&&(r.cacheManager.clearCacheEntry(e.path),r.expandedProjectsService.renamePath(e.path,l),r.projectSubtasksService.invalidateIndex());try{let h=r.app.vault.getAbstractFileByPath(l);if(h instanceof aN.TFile&&r.cacheManager.waitForFreshTaskData){let g={};i.title!==void 0&&(g.title=i.title),i.status!==void 0&&(g.status=i.status),i.priority!==void 0&&(g.priority=i.priority),Object.keys(g).length>0&&await r.cacheManager.waitForFreshTaskData(h)}r.cacheManager.updateTaskInfoInCache(l,f)}catch(h){Kv.error("Error updating task cache:",{category:"stale-data",operation:"updating-task-cache",details:{taskPath:l},error:h instanceof Error?h.message:String(h)})}try{r.emitter.trigger(rt,{path:l,originalTask:e,updatedTask:f})}catch(h){Kv.error("Error emitting task update event:",{category:"validation",operation:"emitting-task-update-event",details:{taskPath:l},error:h instanceof Error?h.message:String(h)})}if(this.deps.webhookNotifier)try{let h=r.statusManager.isCompletedStatus(e.status),g=r.statusManager.isCompletedStatus(f.status);!h&&g?await this.deps.webhookNotifier.triggerWebhook("task.completed",{task:f}):await this.deps.webhookNotifier.triggerWebhook("task.updated",{task:f,previous:e})}catch(h){Kv.warn("Failed to trigger webhook for task update:",{category:"provider",operation:"trigger-webhook-task-update",error:h})}if((a=r.taskCalendarSyncService)!=null&&a.isEnabled()){let h=r.statusManager.isCompletedStatus(e.status),g=r.statusManager.isCompletedStatus(f.status);(!h&&g?r.taskCalendarSyncService.completeTaskInCalendar(f):r.taskCalendarSyncService.updateTaskInCalendar(f,e)).catch(k=>{Kv.warn("Failed to sync task update to Google Calendar:",{category:"provider",operation:"sync-task-update-google-calendar",error:k})})}return await this.handleAutoArchive(e,f,i.status),f}catch(i){let s=i instanceof Error?i.message:String(i);throw Kv.error("Error updating task:",{category:"validation",operation:"updating-task",details:{stack:i instanceof Error?i.stack:void 0,taskPath:e.path,updates:t},error:s}),new Error(`Failed to update task: ${s}`)}}async handleAutoArchive(e,t,r){if(!(!this.deps.autoArchiveService||r===void 0||r===e.status))try{let a=this.deps.runtime.statusManager.getStatusConfig(t.status);if(!a)return;a.autoArchive?await this.deps.autoArchiveService.scheduleAutoArchive(t,a):await this.deps.autoArchiveService.cancelAutoArchive(t.path)}catch(a){Kv.warn("Failed to handle auto-archive for status change:",{category:"validation",operation:"handle-auto-archive-status-change",error:a})}}}});function ife(n,e,t={}){var l,c,d,u;let r=e.taskCreationDefaults,a=(l=t.calculateDefaultDate)!=null?l:jb,i=(c=t.calculateDefaultDateTime)!=null?c:Ol,s=(d=t.convertDefaultRemindersToReminders)!=null?d:IC,o={...n,customFrontmatter:n.customFrontmatter?{...n.customFrontmatter}:void 0};return o.due===void 0&&r.defaultDueDate!=="none"&&(o.due=i(r.defaultDueDate,r.defaultDueTime)),o.scheduled===void 0&&r.defaultScheduledDate!=="none"&&(o.scheduled=i(r.defaultScheduledDate,r.defaultScheduledTime)),!o.contexts&&r.defaultContexts&&(o.contexts=TH(r.defaultContexts)),!o.projects&&r.defaultProjects&&(o.projects=TH(r.defaultProjects)),!o.tags&&r.defaultTags&&(o.tags=TH(r.defaultTags)),!o.timeEstimate&&r.defaultTimeEstimate>0&&(o.timeEstimate=r.defaultTimeEstimate),!o.recurrence&&r.defaultRecurrence!=="none"&&(o.recurrence=yqe[r.defaultRecurrence]),!o.reminders&&r.defaultReminders&&r.defaultReminders.length>0&&(o.reminders=s(r.defaultReminders)),vqe(o,(u=e.userFields)!=null?u:[],a),o}function TH(n){return n.split(",").map(e=>e.trim()).filter(e=>e.length>0)}function vqe(n,e,t){if(e.length!==0){n.customFrontmatter||(n.customFrontmatter={});for(let r of e){let a=kqe(r);if(a!==void 0&&n.customFrontmatter[r.key]===void 0)if(r.type==="date"&&typeof a=="string"){let i=t(a);i&&(n.customFrontmatter[r.key]=i)}else n.customFrontmatter[r.key]=a}}}function kqe(n){if(n.defaultValue!==void 0)return n.defaultValue;if(n.type==="boolean")return!1}var yqe,sfe=y(()=>{yt();BM();yqe={none:void 0,daily:"FREQ=DAILY",weekly:"FREQ=WEEKLY",monthly:"FREQ=MONTHLY",yearly:"FREQ=YEARLY"}});function lfe(n){return n.replace(/./g,e=>{let t=e.charCodeAt(0);return t<=31||t>=127&&t<=159?"":e})}function cfe(n){return n.trim().replace(/\s+/g," ")}function dfe(n){return n.length>0?n:ux}function ufe(n){if(!n||typeof n!="string")return ux;try{let e=lfe(cfe(n)).replace(/[<>:"/\\|?*#[\]]/g,"").replace(/^\.+|\.+$/g,"").trim();return dfe(e)}catch(e){return ofe.error("Error sanitizing title:",{category:"validation",operation:"sanitizing-title",error:e}),ux}}function pfe(n){if(!n||typeof n!="string")return ux;try{return dfe(lfe(cfe(n)).trim())}catch(e){return ofe.error("Error sanitizing title:",{category:"validation",operation:"sanitizing-title",error:e}),ux}}var ofe,ux,mfe=y(()=>{q();ofe=M({tag:"Services/TaskService/TaskTitleSanitizer"}),ux="untitled"});function bH(n,e,t,r){return e!=="status"?null:{wasCompleted:n.statusManager.isCompletedStatus(n.normalizeStatusValue(t)),isCompleted:n.statusManager.isCompletedStatus(n.normalizeStatusValue(r))}}async function Tqe(n,e){try{n.cacheManager.waitForFreshTaskData&&await n.cacheManager.waitForFreshTaskData(e.file),n.cacheManager.updateTaskInfoInCache(e.originalTask.path,e.updatedTask)}catch(t){Zv.error("Error updating task cache:",{category:"stale-data",operation:"updating-task-cache",details:{taskPath:e.originalTask.path},error:t instanceof Error?t.message:String(t)})}}async function bqe(n,e){try{n.emitter.trigger(rt,{path:e.originalTask.path,originalTask:e.originalTask,updatedTask:e.updatedTask});let t=bH(n,e.property,e.oldValue,e.newValue);if(!t||t.wasCompleted===t.isCompleted)return;let r=n.cacheManager.getBlockedTaskPaths(e.originalTask.path);for(let a of r)try{let i=await n.cacheManager.getTaskInfo(a);i&&n.emitter.trigger(rt,{path:a,originalTask:i,updatedTask:i})}catch(i){Zv.error(`Error triggering update for dependent task ${a}:`,{category:"validation",operation:"triggering-update-dependent-task",error:i})}}catch(t){Zv.error("Error emitting task update event:",{category:"validation",operation:"emitting-task-update-event",details:{taskPath:e.originalTask.path},error:t instanceof Error?t.message:String(t)})}}async function wqe(n,e){if(n.webhookNotifier)try{let t=bH(n,e.property,e.oldValue,e.newValue);if(t&&!t.wasCompleted&&t.isCompleted){await n.webhookNotifier.triggerWebhook("task.completed",{task:e.updatedTask});return}await n.webhookNotifier.triggerWebhook("task.updated",{task:e.updatedTask,previous:e.originalTask})}catch(t){Zv.warn("Failed to trigger webhook for property update:",{category:"provider",operation:"trigger-webhook-property-update",error:t})}}function Sqe(n,e){var a;if(!((a=n.taskCalendarSyncService)!=null&&a.isEnabled()))return;let t=bH(n,e.property,e.oldValue,e.newValue);(t&&!t.wasCompleted&&t.isCompleted?n.taskCalendarSyncService.completeTaskInCalendar(e.updatedTask):n.taskCalendarSyncService.updateTaskInCalendar(e.updatedTask,e.originalTask)).catch(i=>{Zv.warn("Failed to sync task update to Google Calendar:",{category:"provider",operation:"sync-task-update-google-calendar",error:i})})}async function Cqe(n,e){if(!(!n.autoArchiveService||e.property!=="status"||e.newValue===e.oldValue))try{let t=n.statusManager.getStatusConfig(e.newValue);if(!t)return;t.autoArchive?await n.autoArchiveService.scheduleAutoArchive(e.updatedTask,t):await n.autoArchiveService.cancelAutoArchive(e.updatedTask.path)}catch(t){Zv.warn("Failed to handle auto-archive for status property change:",{category:"persistence",operation:"handle-auto-archive-status-property-change",error:t})}}async function ffe(n,e){await Tqe(n,e),await bqe(n,e),await wqe(n,e),Sqe(n,e),await Cqe(n,e)}var Zv,hfe=y(()=>{Pr();q();Zv=M({tag:"Services/TaskService/TaskPropertyChangeSideEffects"})});function Eqe(n,e){return typeof n=="string"&&Object.prototype.hasOwnProperty.call(e,n)}function ih(n,e="frontmatter field"){if(typeof n!="string")throw new Error(`${e} resolved to a non-string frontmatter field name`);if(n.trim().length===0)throw new Error(`${e} resolved to an invalid frontmatter field name: ${n}`);return n}function gfe(n,e){let t=n.getMapping();if(Eqe(e,t))return ih(n.toUserField(e),`field mapping for ${String(e)}`);let r=xqe[e];return r?ih(n.toUserField(r),`field mapping for ${String(e)}`):ih(String(e),`task property ${String(e)}`)}var xqe,wH=y(()=>{xqe={recurrence_anchor:"recurrenceAnchor",complete_instances:"completeInstances",skipped_instances:"skippedInstances",recurrence_parent:"recurrenceParent",occurrence_date:"occurrenceDate",occurrence_materialization:"occurrenceMaterialization",occurrence_next_trigger:"occurrenceNextTrigger",occurrence_template:"occurrenceTemplate",occurrence_past_horizon:"occurrencePastHorizon",occurrence_future_horizon:"occurrenceFutureHorizon"}});function Dqe(n,e,t){return n==="status"?t(e):n==="blockedBy"?Pqe(e):e}function Pqe(n){if(n==null)return;let t=(Array.isArray(n)?n:[n]).map(r=>Ai(r)).filter(r=>!!r);return t.length>0?t:void 0}function yfe({freshTask:n,property:e,value:t,currentTimestamp:r,currentDateString:a,normalizeStatusValue:i,isCompletedStatus:s}){let o=Dqe(e,t,i),l={...n};if(l[e]=o,l.dateModified=r,e==="status"&&!n.recurrence){let c=i(o);s(c)?l.completedDate=a:l.completedDate=void 0}return{updatedTask:l,normalizedValue:o,dateModified:r}}function Aqe(n){let e=n.toLowerCase();return e==="true"||e==="false"?e==="true":n}function SH(n,e,t,r,a,i){if(!t){if(a(e)){n[r]=i;return}n[r]&&delete n[r]}}function vfe({frontmatter:n,property:e,fieldName:t,rawValue:r,normalizedValue:a,dateModified:i,dateModifiedField:s,completedDateField:o,isRecurring:l,normalizeStatusValue:c,isCompletedStatus:d,currentDateString:u}){let p=ih(t,`task property ${String(e)}`),m=ih(s,"dateModified field mapping"),f=ih(o,"completedDate field mapping");if(e==="status"){let h=c(a);n[p]=Aqe(h),SH(n,h,l,f,d,u)}else if((e==="due"||e==="scheduled")&&!r)delete n[p];else if(e==="blockedBy"){let h=Array.isArray(a)?a:[];h.length>0?n[p]=sre(h):delete n[p]}else n[p]=a;n[m]=i}var kfe=y(()=>{Zs();wH()});function Tfe(n,e,t){let r=!!n.archived,a={...n};a.archived=!r,a.dateModified=t;let i=Array.isArray(a.tags)?a.tags:[];return r?a.tags=i.filter(s=>s!==e):i.includes(e)?a.tags=[...i]:a.tags=[...i,e],{updatedTask:a,isCurrentlyArchived:r,operation:r?"unarchiving":"archiving",dateModified:t}}function bfe({frontmatter:n,archiveTag:e,isCurrentlyArchived:t,dateModified:r,dateModifiedField:a}){if(t){let i=n.tags;if(Array.isArray(i)){let s=i.filter(o=>o!==e);s.length===0?delete n.tags:n.tags=s}}else n.tags?Array.isArray(n.tags)||(n.tags=[n.tags]):n.tags=[],n.tags.includes(e)||n.tags.push(e);n[a]=r}function wfe({isCurrentlyArchived:n,moveArchivedTasks:e,archiveFolderTemplate:t,tasksFolderTemplate:r,fileName:a,taskData:i,processFolderTemplate:s}){if(!e)return null;let o=n?r==null?void 0:r.trim():t==null?void 0:t.trim();if(!o)return null;let l=n?"tasks":"archive",c=s(o,{title:i.title||"",priority:i.priority,status:i.status,contexts:i.contexts,projects:i.projects});return{operation:n?"unarchiving":"archiving",destinationKind:l,destinationFolder:c,newPath:`${c}/${a}`}}var Sfe=y(()=>{});function sN(n){let e={...n};return delete e.duration,e}function oN(n){return Array.isArray(n)?n.map(sN):[]}function CH(n,e,t=e,r="Work session"){let a={startTime:t,description:r};return{updatedTask:{...n,dateModified:e,timeEntries:[...oN(n.timeEntries),a]},newEntry:a,dateModified:e}}function xH(n,e,t,r=t){let a={...n,dateModified:t},i=oN(n.timeEntries),s=i.findIndex(o=>o.startTime===e.startTime&&!o.endTime);return s!==-1&&(i[s]={...i[s],endTime:r},a.timeEntries=i),{updatedTask:a,stopTimestamp:r,dateModified:t}}function EH(n,e,t){if(!Array.isArray(n.timeEntries))throw new Error("Task has no time entries");if(e<0||e>=n.timeEntries.length)throw new Error("Invalid time entry index");return{updatedTask:{...n,dateModified:t,timeEntries:oN(n.timeEntries).filter((r,a)=>a!==e)},timeEntryIndex:e,dateModified:t}}var Cfe=y(()=>{});function xfe({frontmatter:n,timeEntriesField:e,dateModifiedField:t,newEntry:r,dateModified:a}){n[e]||(n[e]=[]),Array.isArray(n[e])&&(n[e]=n[e].map(sN)),n[e].push(r),n[t]=a}function Efe({frontmatter:n,timeEntriesField:e,dateModifiedField:t,timeEntryIndex:r,dateModified:a}){n[e]&&Array.isArray(n[e])&&(n[e]=n[e].filter((i,s)=>s!==r)),n[t]=a}function Dfe({frontmatter:n,timeEntriesField:e,dateModifiedField:t,activeSession:r,stopTimestamp:a,dateModified:i}){if(n[e]&&Array.isArray(n[e])){let s=n[e].map(sN),o=s.findIndex(l=>l.startTime===r.startTime&&!l.endTime);o!==-1&&(s[o].endTime=a),n[e]=s}n[t]=i}var Pfe=y(()=>{Cfe()});function Afe(n,e){return{uniqueAdditions:Array.from(new Set(n)),uniqueRemovals:Array.from(new Set(e))}}function Mfe({blockedTask:n,blockingTaskPath:e,action:t,rawEntry:r,useFrontmatterMarkdownLinks:a,resolveDependencyPath:i,formatDependencyLink:s}){var u;let o=Array.isArray(n.blockedBy)?n.blockedBy.map(p=>Ai(p)).filter(p=>!!p):[];if(o.length===0&&t==="remove")return null;let l=!1,c=!1,d=[];for(let p of o){if(i(n.path,p)===e&&(c=!0,t==="remove")){l=!0;continue}d.push(p)}if(t==="add"&&!c){let p=r?Ai(r):null,m={uid:s(n.path,e,a),reltype:(u=p==null?void 0:p.reltype)!=null?u:Pi};p!=null&&p.gap&&(m.gap=p.gap),d.push(m),l=!0}return l?d:null}function DH(n){return n===null?null:{blockedBy:n.length>0?n:void 0}}var Ife=y(()=>{Zs()});var Ln,qt,lN,Nfe=y(()=>{Pr();TU();Ln=require("obsidian");JI();yt();Zs();Cn();xe();pf();kH();Qme();Oi();afe();sfe();mfe();hfe();kfe();Sfe();Pfe();p2();uM();Ife();wH();ya();q();qt=M({tag:"Services/TaskService"}),lN=class{constructor(e){this.plugin=e;this.occurrenceMaterializations=new Map;this.taskCreationService=new rN({runtime:this.plugin,webhookNotifier:this.webhookNotifier,applyTaskCreationDefaults:t=>Promise.resolve(ife(t,this.plugin.settings)),applyTemplate:t=>this.applyTemplate(t),processFolderTemplate:(t,r,a)=>{var s;if(!/\{\{currentNote(?:Path|Title)\}\}/.test(t))return this.processFolderTemplate(t,r,a);let i=this.plugin.app.workspace.getActiveFile();return this.processFolderTemplate(t,r,a,{path:((s=i==null?void 0:i.parent)==null?void 0:s.path)||"",title:(i==null?void 0:i.basename)||""})},sanitizeTitleForFilename:ufe,sanitizeTitleForStorage:pfe}),this.taskUpdateService=new iN({runtime:this.plugin,webhookNotifier:this.webhookNotifier,autoArchiveService:this.autoArchiveService,updateCompletedDateInFrontmatter:(t,r,a)=>this.updateCompletedDateInFrontmatter(t,r,a)})}hasGoogleCalendarLinks(e){return!!(e.googleCalendarEventId||e.googleCalendarExceptionEventId)}createArchiveCalendarDeletionTask(e,t){return{...t,googleCalendarEventId:e.googleCalendarEventId,googleCalendarExceptionEventId:e.googleCalendarExceptionEventId,googleCalendarExceptionOriginalScheduled:e.googleCalendarExceptionOriginalScheduled,googleCalendarMovedOriginalDates:e.googleCalendarMovedOriginalDates?[...e.googleCalendarMovedOriginalDates]:void 0}}clearGoogleCalendarMetadata(e){e.googleCalendarEventId=void 0,e.googleCalendarExceptionEventId=void 0,e.googleCalendarExceptionOriginalScheduled=void 0,e.googleCalendarMovedOriginalDates=void 0}writeOptionalFrontmatterField(e,t,r){if(r==null||Array.isArray(r)&&r.length===0){delete e[t];return}e[t]=r}async deleteArchivedTaskFromCalendar(e){return!this.plugin.taskCalendarSyncService||await this.plugin.taskCalendarSyncService.deleteTaskFromCalendar(e)?!0:(qt.warn("Failed to delete archived task from Google Calendar during archive:",{category:"provider",operation:"delete-archived-task-google-calendar-archive",details:{taskPath:e.path,eventId:e.googleCalendarEventId}}),!1)}translate(e,t){return this.plugin.i18n.translate(e,t)}setWebhookNotifier(e){this.webhookNotifier=e,this.taskCreationService.setWebhookNotifier(e),this.taskUpdateService.setWebhookNotifier(e)}setAutoArchiveService(e){this.autoArchiveService=e,this.taskUpdateService.setAutoArchiveService(e)}normalizeStatusValue(e){return typeof e=="boolean"?e?"true":"false":typeof e=="string"?e:typeof e=="number"?String(e):""}getCompletionDateForTask(e){return Yo()}processFolderTemplate(e,t,r=new Date,a){let i=t?{title:t.title,priority:t.priority,status:t.status,contexts:t.contexts,projects:t.projects,due:t.due,scheduled:t.scheduled}:void 0;return eN(e,{date:r,taskData:i,currentNote:a,extractProjectBasename:s=>this.extractProjectBasename(s),extractProjectFilePath:s=>this.extractProjectFilePath(s)})}async createTask(e,t={}){let r=await this.taskCreationService.createTask(e,t);return await this.seedInitialOccurrence(r.taskInfo),r}async applyTemplate(e){var r,a,i,s;let t=this.plugin.settings.taskCreationDefaults;if(!t.useBodyTemplate||!((r=t.bodyTemplate)!=null&&r.trim()))return{frontmatter:{},body:((a=e.details)==null?void 0:a.trim())||""};try{let o=(0,Ln.normalizePath)(t.bodyTemplate.trim());o.endsWith(".md")||(o+=".md");let l=this.plugin.app.vault.getAbstractFileByPath(o);if(l instanceof Ln.TFile){let c=await this.plugin.app.vault.read(l),d={title:e.title||"",priority:e.priority||"",status:e.status||"",contexts:Array.isArray(e.contexts)?e.contexts:[],tags:Array.isArray(e.tags)?e.tags:[],timeEstimate:e.timeEstimate||0,dueDate:e.due||"",scheduledDate:e.scheduled||"",details:e.details||"",parentNote:e.parentNote||""};return dx(c,d)}else return qt.warn(`Task body template not found: ${o}`,{category:"persistence",operation:"task-body-template-not-found"}),ve(this.plugin.emitter,this.translate("services.task.notices.templateNotFound",{path:o})),{frontmatter:{},body:((i=e.details)==null?void 0:i.trim())||""}}catch(o){return qt.error("Error reading task body template:",{category:"persistence",operation:"reading-task-body-template",error:o}),ve(this.plugin.emitter,this.translate("services.task.notices.templateReadError",{template:t.bodyTemplate})),{frontmatter:{},body:((s=e.details)==null?void 0:s.trim())||""}}}getOccurrenceTemplateReference(e){var a,i;let t=(a=e.occurrence_template)==null?void 0:a.trim();if(t)return t;let r=this.plugin.settings.taskCreationDefaults;return r.useOccurrenceBodyTemplate&&((i=r.occurrenceBodyTemplate)!=null&&i.trim())?r.occurrenceBodyTemplate.trim():null}resolveTemplateFile(e,t){var o,l,c,d,u,p,m,f;let r=vt(e).trim();if(!r)return null;let a=(f=(u=(l=(o=this.plugin.app.metadataCache).getFirstLinkpathDest)==null?void 0:l.call(o,r,t))!=null?u:(d=(c=this.plugin.app.metadataCache).getFirstLinkpathDest)==null?void 0:d.call(c,r.replace(/\.md$/i,""),t))!=null?f:(m=(p=this.plugin.app.metadataCache).getFirstLinkpathDest)==null?void 0:m.call(p,r,"");if(a instanceof Ln.TFile)return a;let i=(0,Ln.normalizePath)(r),s=/\.md$/i.test(i)?[i]:[`${i}.md`,i];for(let h of s){let g=this.plugin.app.vault.getAbstractFileByPath(h);if(g instanceof Ln.TFile)return g}return null}buildOccurrenceTemplateData(e,t){return{title:e.title||t.title||"",priority:e.priority||t.priority||"",status:e.status||"",contexts:Array.isArray(e.contexts)?e.contexts:[],tags:Array.isArray(e.tags)?e.tags:[],timeEstimate:e.timeEstimate||0,dueDate:e.due||"",scheduledDate:e.scheduled||"",details:e.details||"",parentNote:this.buildOccurrenceParentReference(t)}}extractTemplateCustomFrontmatter(e){let t=new Set(this.plugin.fieldMapper.getUserFields().map(a=>a.key)),r={};for(let[a,i]of Object.entries(e))a==="tags"||t.has(a)||this.plugin.fieldMapper.lookupMappingKey(a)||(r[a]=i);return Object.keys(r).length>0?r:void 0}buildOccurrenceTemplateTask(e){let t=this.plugin.fieldMapper.mapFromFrontmatter(e.frontmatter,"",!1),r=e.body.replace(/\r\n/g,` +`).trimEnd(),a={...t};return r.trim().length>0&&(a.details=r),{templateTask:a,customFrontmatter:this.extractTemplateCustomFrontmatter(e.frontmatter)}}async resolveOccurrenceTemplate(e,t){let r=this.getOccurrenceTemplateReference(e);if(!r)return{configured:!1};let a=this.resolveTemplateFile(r,e.path);if(!a)return qt.warn(`Occurrence note template not found: ${r}`,{category:"persistence",operation:"occurrence-template-not-found"}),ve(this.plugin.emitter,this.translate("services.task.notices.occurrenceTemplateNotFound",{path:r})),{configured:!0};try{let i=await this.plugin.app.vault.read(a),s=dx(i,this.buildOccurrenceTemplateData(t,e));return{configured:!0,...this.buildOccurrenceTemplateTask(s)}}catch(i){return qt.error("Error reading occurrence note template:",{category:"persistence",operation:"reading-occurrence-template",error:i}),ve(this.plugin.emitter,this.translate("services.task.notices.occurrenceTemplateReadError",{template:r})),{configured:!0}}}async toggleStatus(e){try{let r=this.plugin.statusManager.isCompletedStatus(e.status)?this.plugin.settings.defaultTaskStatus:this.plugin.statusManager.getCompletedStatuses()[0]||"done";return await this.updateProperty(e,"status",r)}catch(t){let r=t instanceof Error?t.message:String(t);throw qt.error("Error toggling task status:",{category:"persistence",operation:"toggling-task-status",details:{stack:t instanceof Error?t.stack:void 0,taskPath:e.path,currentStatus:e.status},error:r}),new Error(`Failed to toggle task status: ${r}`)}}async updateProperty(e,t,r,a={}){var i,s,o;try{let l=this.plugin.app.vault.getAbstractFileByPath(e.path);if(!(l instanceof Ln.TFile))throw new Error(`Cannot find task file: ${e.path}`);let c=await this.plugin.cacheManager.getTaskInfo(e.path)||e,d=(i=a.completionDate)!=null?i:this.getCompletionDateForTask(c),u=yfe({freshTask:c,property:t,value:r,currentTimestamp:qe(),currentDateString:d,normalizeStatusValue:m=>this.normalizeStatusValue(m),isCompletedStatus:m=>this.plugin.statusManager.isCompletedStatus(m)});t==="scheduled"&&dM(c,u.normalizedValue,u.updatedTask),(t==="recurrence"||t==="recurrence_anchor")&&Vf(u.updatedTask);let p=!1;if(t==="scheduled"&&c.recurrence&&typeof c.scheduled=="string"&&typeof u.normalizedValue=="string"&&u.normalizedValue.length>0){let m=re(c.scheduled),f=re(u.normalizedValue),h=m!==f,g=(s=c.complete_instances)!=null?s:[],v=(o=c.skipped_instances)!=null?o:[],k=g.filter(b=>b>=f),T=v.filter(b=>b>=f);if(h&&(k.length>0||T.length>0)){if(a.confirmClearInstances&&!await a.confirmClearInstances({complete:k,skipped:T}))return c;p=!0,u.updatedTask.complete_instances=g.filter(b=>bb{let f=gfe(this.plugin.fieldMapper,t),h=this.plugin.fieldMapper.toUserField("dateModified"),g=this.plugin.fieldMapper.toUserField("completedDate");vfe({frontmatter:m,property:t,fieldName:f,rawValue:r,normalizedValue:u.normalizedValue,dateModified:u.dateModified,dateModifiedField:h,completedDateField:g,isRecurring:!!c.recurrence,normalizeStatusValue:v=>this.normalizeStatusValue(v),isCompletedStatus:v=>this.plugin.statusManager.isCompletedStatus(v),currentDateString:d}),this.writeOptionalFrontmatterField(m,this.plugin.fieldMapper.toUserField("googleCalendarExceptionOriginalScheduled"),u.updatedTask.googleCalendarExceptionOriginalScheduled),this.writeOptionalFrontmatterField(m,this.plugin.fieldMapper.toUserField("googleCalendarMovedOriginalDates"),u.updatedTask.googleCalendarMovedOriginalDates),p&&(this.writeOptionalFrontmatterField(m,this.plugin.fieldMapper.toUserField("completeInstances"),u.updatedTask.complete_instances),this.writeOptionalFrontmatterField(m,this.plugin.fieldMapper.toUserField("skippedInstances"),u.updatedTask.skipped_instances))}),await this.applyPropertyChangeSideEffects(l,c,u.updatedTask,t,c[t],u.normalizedValue),u.updatedTask}catch(l){let c=l instanceof Error?l.message:String(l);throw qt.error("Error updating task property:",{category:"persistence",operation:"updating-task-property",details:{stack:l instanceof Error?l.stack:void 0,taskPath:e.path,property:t,value:r},error:c}),new Error(`Failed to update task property: ${c}`)}}async applyPropertyChangeSideEffects(e,t,r,a,i,s){await ffe({cacheManager:this.plugin.cacheManager,emitter:this.plugin.emitter,statusManager:this.plugin.statusManager,taskCalendarSyncService:this.plugin.taskCalendarSyncService,webhookNotifier:this.webhookNotifier,autoArchiveService:this.autoArchiveService,normalizeStatusValue:o=>this.normalizeStatusValue(o)},{file:e,originalTask:t,updatedTask:r,property:a,oldValue:i,newValue:s}),await this.seedInitialOccurrence(r,t),await this.reconcileMaterializedOccurrenceStatusChange(t,r,a,i,s)}async seedInitialOccurrence(e,t){if(!e.recurrence||e.recurrence_parent||e.archived||e.occurrence_materialization!=="on_completion"||t!=null&&t.recurrence&&t.occurrence_materialization==="on_completion")return;let r=Fb(e);if(r)try{await this.materializeOccurrence(e,r)}catch(a){qt.warn("Failed to create first occurrence:",{category:"persistence",operation:"seed-initial-occurrence",error:a}),ve(this.plugin.emitter,"Task saved, but its first occurrence could not be created. Use Create occurrence to retry.")}}async materializeOccurrence(e,t,r={}){let a=typeof t=="string"?t.slice(0,10):ae(t),i=JSON.stringify([e.path,a]),s=this.occurrenceMaterializations.get(i);if(s)return s;let o=this.materializeOccurrenceUnlocked(e,t,r);this.occurrenceMaterializations.set(i,o);try{return await o}finally{this.occurrenceMaterializations.delete(i)}}async materializeOccurrenceUnlocked(e,t,r={}){let a=await this.plugin.cacheManager.getTaskInfo(e.path)||e;if(!a.recurrence)throw new Error("Task is not recurring");let i=await this.plugin.cacheManager.getAllTasks(),s={parentTask:a,targetDate:t,currentTimestamp:qe(),existingOccurrences:i,parentLink:this.buildOccurrenceParentReference(a),defaultStatus:this.plugin.settings.defaultTaskStatus,defaultPriority:this.plugin.settings.defaultTaskPriority,overrides:r},o=vU(s);if(!o.created&&o.existingOccurrence)return o.existingOccurrence;let l=await this.resolveOccurrenceTemplate(a,o.occurrenceTask),d={...(l.templateTask||l.customFrontmatter?vU({...s,templateTask:l.templateTask}):o).occurrenceTask,creationContext:"api",customFrontmatter:l.customFrontmatter,occurrenceFilenameTemplate:this.resolveOccurrenceFilenameTemplate(a)},{taskInfo:u}=await this.createTask(d,{applyDefaults:!1,applyTemplate:!l.configured});return u}resolveOccurrenceFilenameTemplate(e){var t,r,a;try{let i=((t=this.plugin.settings.occurrenceFilenameTemplateProperty)==null?void 0:t.trim())||"occurrenceFilenameTemplate",s=this.plugin.app.vault.getAbstractFileByPath(e.path),o=s instanceof Ln.TFile?(r=this.plugin.app.metadataCache.getFileCache(s))==null?void 0:r.frontmatter:void 0,l=o==null?void 0:o[i],c=typeof l=="string"&&l.trim()?l:this.plugin.settings.occurrenceFilenameTemplate;return typeof c=="string"&&c.trim()?c:void 0}catch(i){return qt.warn("Failed to resolve occurrence filename template:",{category:"persistence",operation:"resolving-occurrence-filename-template",error:i}),((a=this.plugin.settings.occurrenceFilenameTemplate)==null?void 0:a.trim())||void 0}}async findMaterializedOccurrence(e,t){let r=await this.plugin.cacheManager.getTaskInfo(e.path)||e;if(!r.recurrence)return;let a=typeof t=="string"?t.slice(0,10):ae(t),i=await this.plugin.cacheManager.getAllTasks();return yU(i,r,a,this.buildOccurrenceParentReference(r))}async toggleRecurringTaskCompleteWithOccurrenceNotes(e,t){let r=await this.plugin.cacheManager.getTaskInfo(e.path)||e;if(!r.recurrence)throw new Error("Task is not recurring");let a=this.getRecurringTaskActionDate(r,t),i=ae(a),s=await this.findMaterializedOccurrence(r,a);if(s)return this.toggleStatus(s);let o=Array.isArray(r.complete_instances)?r.complete_instances.filter(l=>typeof l=="string"):[];if(r.occurrence_materialization==="on_completion"&&!o.includes(i)){let l=await this.materializeOccurrence(r,a);return this.toggleStatus(l)}return this.toggleRecurringTaskComplete(r,a)}async getMaterializedOccurrenceParent(e){let t=await this.plugin.cacheManager.getTaskInfo(e.path)||e;return this.resolveOccurrenceParentTask(t)}async skipMaterializedOccurrence(e,t=this.getDefaultSkippedOccurrenceStatus()){let r=await this.plugin.cacheManager.getTaskInfo(e.path)||e,a=await this.resolveOccurrenceParentTask(r);if(!a)throw new Error("Cannot resolve occurrence parent");let i=bpe({occurrenceTask:r,parentTask:a,skippedStatus:t,currentTimestamp:qe(),maintainDueDateOffsetInRecurring:this.plugin.settings.maintainDueDateOffsetInRecurring}),s=await this.persistTaskInfoUpdates(r,i.occurrenceUpdates,"skip-materialized-occurrence"),o=await this.persistTaskInfoUpdates(a,i.parentUpdates,"reconcile-skipped-materialized-occurrence-parent");if(i.materializeNextDate)try{await this.materializeOccurrence(o,i.materializeNextDate)}catch(l){qt.warn("Failed to materialize next occurrence after skip:",{category:"persistence",operation:"materialize-next-occurrence-after-skip",details:{parentPath:o.path,nextDate:i.materializeNextDate},error:l})}return s}async unskipMaterializedOccurrence(e){let t=await this.plugin.cacheManager.getTaskInfo(e.path)||e,r=await this.resolveOccurrenceParentTask(t);if(!r)throw new Error("Cannot resolve occurrence parent");let a=wpe({occurrenceTask:t,parentTask:r,activeStatus:this.plugin.settings.defaultTaskStatus,currentTimestamp:qe()}),i=await this.persistTaskInfoUpdates(t,a.occurrenceUpdates,"unskip-materialized-occurrence");return await this.persistTaskInfoUpdates(r,a.parentUpdates,"reconcile-unskipped-materialized-occurrence-parent"),i}getDefaultSkippedOccurrenceStatus(){var e;return(e=this.plugin.settings.customStatuses.find(t=>t.isSkipped))==null?void 0:e.value}async reconcileMaterializedOccurrenceStatusChange(e,t,r,a,i){if(r!=="status"||!FC(t))return;let s=this.plugin.statusManager.isCompletedStatus(this.normalizeStatusValue(a)),o=this.plugin.statusManager.isCompletedStatus(this.normalizeStatusValue(i));if(s===o)return;let l=await this.resolveOccurrenceParentTask(t);if(!l){qt.warn("Could not resolve materialized occurrence parent:",{category:"persistence",operation:"resolve-materialized-occurrence-parent",details:{taskPath:t.path,parent:t.recurrence_parent}});return}let c=qe(),d=o?kpe({occurrenceTask:t,parentTask:l,completedStatus:this.normalizeStatusValue(i),currentTimestamp:c,completionDate:t.completedDate||Yo(),maintainDueDateOffsetInRecurring:this.plugin.settings.maintainDueDateOffsetInRecurring}):Tpe({occurrenceTask:e,parentTask:l,activeStatus:this.normalizeStatusValue(i),currentTimestamp:c});o&&(d=this.adjustRescheduledOccurrenceCompletionProgression(d,t,l,c));let u=await this.persistTaskInfoUpdates(l,d.parentUpdates,"reconcile-materialized-occurrence-parent");if(o&&this.webhookNotifier)try{await this.webhookNotifier.triggerWebhook("recurring.instance.completed",{task:u,occurrence:t,date:d.targetDate})}catch(p){qt.warn("Failed to trigger materialized occurrence webhook:",{category:"provider",operation:"trigger-materialized-occurrence-webhook",error:p})}if(o&&d.materializeNextDate)try{await this.materializeOccurrence(u,d.materializeNextDate)}catch(p){qt.warn("Failed to materialize next occurrence after completion:",{category:"persistence",operation:"materialize-next-occurrence-after-completion",details:{parentPath:u.path,nextDate:d.materializeNextDate},error:p})}}adjustRescheduledOccurrenceCompletionProgression(e,t,r,a){var p;let i=this.getRescheduledOccurrenceProgressionDate(t);if(!i||typeof r.recurrence!="string")return e;let s=typeof e.updatedParentTask.recurrence=="string"?e.updatedParentTask.recurrence:r.recurrence;if((e.updatedParentTask.recurrence_anchor||"scheduled")==="completion")return e;let l=Cd({...e.updatedParentTask,recurrence:s,scheduled:t.scheduled||i,due:(p=t.due)!=null?p:r.due},this.plugin.settings.maintainDueDateOffsetInRecurring,{minOccurrenceDate:i}),c={...e.parentUpdates,recurrence:s,dateModified:a};l.scheduled?c.scheduled=l.scheduled:delete c.scheduled,l.due?c.due=l.due:delete c.due;let d={...r,...c},u=e.materializeNextDate?re(d.scheduled||""):void 0;return{...e,updatedParentTask:d,parentUpdates:c,parentFields:xv(c),materializeNextDate:u||void 0,changed:!0}}getRescheduledOccurrenceProgressionDate(e){let t=this.getSafeDatePart(e.occurrence_date),r=this.getSafeDatePart(e.scheduled);return!t||!r||r<=t?null:r}getSafeDatePart(e){if(!e)return"";try{return re(e)}catch(t){return""}}async resolveOccurrenceParentTask(e){var i,s;if(!e.recurrence_parent)return null;let t=vt(e.recurrence_parent),r=new Set([t]);t&&!t.endsWith(".md")&&r.add(`${t}.md`);for(let o of r){let l=await this.plugin.cacheManager.getTaskInfo(o);if(l)return l}let a=(s=(i=this.plugin.app.metadataCache).getFirstLinkpathDest)==null?void 0:s.call(i,t,e.path);return a instanceof Ln.TFile?await this.plugin.cacheManager.getTaskInfo(a.path):null}buildOccurrenceParentReference(e){return this.plugin.settings.useFrontmatterMarkdownLinks?`[${e.title}](<${encodeURI(e.path).replace(/\(/g,"%28").replace(/\)/g,"%29")}>)`:`[[${e.path.replace(/\.md$/i,"")}]]`}applyModelTaskUpdatesToFrontmatter(e,t){let r=Spe(t,this.plugin.fieldMapper.getMapping());for(let a of r)a.op==="delete"?delete e[a.field]:e[a.field]=a.value}async persistTaskInfoUpdates(e,t,r){var s;if(Object.keys(t).length===0)return e;let a=this.plugin.app.vault.getAbstractFileByPath(e.path);if(!(a instanceof Ln.TFile))throw new Error(`Cannot find task file: ${e.path}`);let i={...e,...t};await yr(this.plugin.app,a,o=>{this.applyModelTaskUpdatesToFrontmatter(o,t)});try{this.plugin.cacheManager.waitForFreshTaskData&&await this.plugin.cacheManager.waitForFreshTaskData(a),this.plugin.cacheManager.updateTaskInfoInCache(e.path,i)}catch(o){qt.error("Error updating cache for model task updates:",{category:"stale-data",operation:"persist-model-task-updates-cache",details:{taskPath:e.path,sourceOperation:r},error:o})}return this.plugin.emitter.trigger(rt,{path:e.path,originalTask:e,updatedTask:i}),(s=this.plugin.taskCalendarSyncService)!=null&&s.isEnabled()&&this.plugin.taskCalendarSyncService.updateTaskInCalendar(i,e).catch(o=>{qt.warn("Failed to sync model task update to Google Calendar:",{category:"provider",operation:"sync-model-task-update-google-calendar",details:{taskPath:e.path,sourceOperation:r},error:o})}),i}async toggleArchive(e){var u,p;let t=this.plugin.app.vault.getAbstractFileByPath(e.path);if(!(t instanceof Ln.TFile))throw new Error(`Cannot find task file: ${e.path}`);let r=this.plugin.fieldMapper.getMapping().archiveTag,a=Tfe(e,r,qe()),{updatedTask:i,isCurrentlyArchived:s,dateModified:o}=a;await yr(this.plugin.app,t,m=>{let f=this.plugin.fieldMapper.toUserField("dateModified");bfe({frontmatter:m,archiveTag:r,isCurrentlyArchived:s,dateModified:o,dateModifiedField:f})});let l=t,c=wfe({isCurrentlyArchived:s,moveArchivedTasks:this.plugin.settings.moveArchivedTasks,archiveFolderTemplate:this.plugin.settings.archiveFolder,tasksFolderTemplate:this.plugin.settings.tasksFolder,fileName:t.name,taskData:{title:i.title||"",priority:i.priority,status:i.status,contexts:i.contexts,projects:i.projects},processFolderTemplate:(m,f)=>this.processFolderTemplate(m,f)});if(c)try{if(await qu(this.plugin.app.vault,c.destinationFolder),this.plugin.app.vault.getAbstractFileByPath(c.newPath))throw new Error(`A file named "${t.name}" already exists in the ${c.destinationKind} folder "${c.destinationFolder}". Cannot move task to avoid overwriting existing file.`);await this.plugin.app.fileManager.renameFile(t,c.newPath);let f=this.plugin.app.vault.getAbstractFileByPath(c.newPath);if(!(f instanceof Ln.TFile))throw new Error(`Failed to resolve moved task file: ${c.newPath}`);l=f,i.path=c.newPath,this.plugin.cacheManager.clearCacheEntry(e.path)}catch(m){let f=m instanceof Error?m.message:String(m),h=c.operation;qt.error(`Error moving ${h} task:`,{category:"persistence",operation:"moving",details:{value:f}}),ve(this.plugin.emitter,this.translate("services.task.notices.moveTaskFailed",{operation:h,error:f}))}let d=!0;if((u=this.plugin.taskCalendarSyncService)!=null&&u.isEnabled()&&i.archived&&this.hasGoogleCalendarLinks(e)){let m=this.createArchiveCalendarDeletionTask(e,i);d=await this.deleteArchivedTaskFromCalendar(m),d&&this.clearGoogleCalendarMetadata(i)}try{l instanceof Ln.TFile&&this.plugin.cacheManager.waitForFreshTaskData&&await this.plugin.cacheManager.waitForFreshTaskData(l),this.plugin.cacheManager.updateTaskInfoInCache(i.path,i)}catch(m){qt.error("Error updating cache for archived task:",{category:"stale-data",operation:"updating-cache-archived-task",error:m})}if(this.plugin.emitter.trigger(rt,{path:i.path,originalTask:e,updatedTask:i}),this.webhookNotifier)try{i.archived?await this.webhookNotifier.triggerWebhook("task.archived",{task:i}):await this.webhookNotifier.triggerWebhook("task.unarchived",{task:i})}catch(m){qt.warn("Failed to trigger webhook for task archive/unarchive:",{category:"provider",operation:"trigger-webhook-task-archive-unarchive",error:m})}return(p=this.plugin.taskCalendarSyncService)!=null&&p.isEnabled()&&(i.archived?!d&&this.hasGoogleCalendarLinks(i)&&qt.warn("Archived task still has Google Calendar links and will need retry cleanup:",{category:"provider",operation:"archived-task-still-has-google-calendar-links-and-will-need-retry-cleanup",details:{value:i.path}}):this.plugin.taskCalendarSyncService.updateTaskInCalendar(i,e).catch(m=>{qt.warn("Failed to sync unarchived task to Google Calendar:",{category:"provider",operation:"sync-unarchived-task-google-calendar",error:m})})),i}async startTimeTracking(e){var o;let t=this.plugin.app.vault.getAbstractFileByPath(e.path);if(!(t instanceof Ln.TFile))throw new Error(`Cannot find task file: ${e.path}`);if(this.plugin.getActiveTimeSession(e))throw new Error("Time tracking is already active for this task");let a=CH(e,qe(),new Date().toISOString()),{updatedTask:i,newEntry:s}=a;await yr(this.plugin.app,t,l=>{let c=this.plugin.fieldMapper.toUserField("timeEntries"),d=this.plugin.fieldMapper.toUserField("dateModified");xfe({frontmatter:l,timeEntriesField:c,dateModifiedField:d,newEntry:s,dateModified:a.dateModified})});try{this.plugin.cacheManager.waitForFreshTaskData&&await this.plugin.cacheManager.waitForFreshTaskData(t),this.plugin.cacheManager.updateTaskInfoInCache(e.path,i)}catch(l){qt.error("Error updating cache for time tracking start:",{category:"stale-data",operation:"updating-cache-time-tracking-start",error:l})}if(this.plugin.emitter.trigger(rt,{path:e.path,originalTask:e,updatedTask:i}),this.webhookNotifier)try{await this.webhookNotifier.triggerWebhook("time.started",{task:i,session:(o=i.timeEntries)==null?void 0:o[i.timeEntries.length-1]})}catch(l){qt.warn("Failed to trigger webhook for time tracking start:",{category:"provider",operation:"trigger-webhook-time-tracking-start",error:l})}return i}async stopTimeTracking(e){var s;let t=this.plugin.app.vault.getAbstractFileByPath(e.path);if(!(t instanceof Ln.TFile))throw new Error(`Cannot find task file: ${e.path}`);let r=this.plugin.getActiveTimeSession(e);if(!r)throw new Error("No active time tracking session for this task");let a=xH(e,r,qe(),new Date().toISOString()),{updatedTask:i}=a;await yr(this.plugin.app,t,o=>{let l=this.plugin.fieldMapper.toUserField("timeEntries"),c=this.plugin.fieldMapper.toUserField("dateModified");Dfe({frontmatter:o,timeEntriesField:l,dateModifiedField:c,activeSession:r,stopTimestamp:a.stopTimestamp,dateModified:a.dateModified})});try{this.plugin.cacheManager.waitForFreshTaskData&&await this.plugin.cacheManager.waitForFreshTaskData(t),this.plugin.cacheManager.updateTaskInfoInCache(e.path,i)}catch(o){qt.error("Error updating cache for time tracking stop:",{category:"stale-data",operation:"updating-cache-time-tracking-stop",error:o})}if(this.plugin.emitter.trigger(rt,{path:e.path,originalTask:e,updatedTask:i}),this.webhookNotifier)try{await this.webhookNotifier.triggerWebhook("time.stopped",{task:i,session:(s=i.timeEntries)==null?void 0:s[i.timeEntries.length-1]})}catch(o){qt.warn("Failed to trigger webhook for time tracking stop:",{category:"provider",operation:"trigger-webhook-time-tracking-stop",error:o})}return i}async updateTask(e,t){let r=await this.taskUpdateService.updateTask(e,t);return await this.seedInitialOccurrence(r,e),r}async updateBlockingRelationships(e,t,r,a={}){let{uniqueAdditions:i,uniqueRemovals:s}=Afe(t,r);for(let o of s){let l=await this.plugin.cacheManager.getTaskInfo(o);if(!l)continue;let c=DH(this.computeBlockedByUpdate(l,e.path,"remove"));c&&await this.updateTask(l,c)}for(let o of i){let l=await this.plugin.cacheManager.getTaskInfo(o);if(!l)continue;let c=DH(this.computeBlockedByUpdate(l,e.path,"add",a[o]));c&&await this.updateTask(l,c)}}computeBlockedByUpdate(e,t,r,a){return Mfe({blockedTask:e,blockingTaskPath:t,action:r,rawEntry:a,useFrontmatterMarkdownLinks:this.plugin.settings.useFrontmatterMarkdownLinks,resolveDependencyPath:(i,s)=>{var o,l;return(l=(o=Jo(this.plugin.app,i,s))==null?void 0:o.path)!=null?l:null},formatDependencyLink:(i,s,o)=>Ks(this.plugin.app,i,s,o)})}async deleteTask(e){try{let t=this.plugin.app.vault.getAbstractFileByPath(e.path);if(!(t instanceof Ln.TFile))throw new Error(`Cannot find task file: ${e.path}`);if(this.plugin.taskCalendarSyncService&&this.hasGoogleCalendarLinks(e))try{await this.plugin.taskCalendarSyncService.deleteTaskFromCalendarByPath(e.path,e.googleCalendarEventId,e.googleCalendarExceptionEventId)}catch(r){qt.warn("Failed to delete task from Google Calendar:",{category:"provider",operation:"delete-task-google-calendar",error:r})}if(await this.plugin.app.fileManager.trashFile(t),this.plugin.cacheManager.clearCacheEntry(e.path),this.plugin.emitter.trigger(Di,{path:e.path,deletedTask:e}),this.webhookNotifier)try{await this.webhookNotifier.triggerWebhook("task.deleted",{task:e})}catch(r){qt.warn("Failed to trigger webhook for task deletion:",{category:"provider",operation:"trigger-webhook-task-deletion",error:r})}}catch(t){let r=t instanceof Error?t.message:String(t);throw qt.error("Error deleting task:",{category:"persistence",operation:"deleting-task",details:{stack:t instanceof Error?t.stack:void 0,taskPath:e.path},error:r}),new Error(`Failed to delete task: ${r}`)}}async resolveRecurringTaskActionDate(e,t){if(t)return t;let r=await this.plugin.cacheManager.getTaskInfo(e.path)||e;return this.getRecurringTaskActionDate(r)}getRecurringTaskActionDate(e,t){return mM(e,t)}async toggleRecurringTaskComplete(e,t){var d;let r=this.plugin.app.vault.getAbstractFileByPath(e.path);if(!(r instanceof Ln.TFile))throw new Error(`Cannot find task file: ${e.path}`);let a=await this.plugin.cacheManager.getTaskInfo(e.path)||e;if(!a.recurrence)throw new Error("Task is not recurring");let i=fce({freshTask:a,targetDate:this.getRecurringTaskActionDate(a,t),currentTimestamp:qe(),maintainDueDateOffsetInRecurring:this.plugin.settings.maintainDueDateOffsetInRecurring}),{updatedTask:s,dateStr:o,newComplete:l,targetDate:c}=i;if(await yr(this.plugin.app,r,u=>{let p=this.plugin.fieldMapper.toUserField("completeInstances"),m=this.plugin.fieldMapper.toUserField("skippedInstances"),f=this.plugin.fieldMapper.toUserField("dateModified"),h=this.plugin.fieldMapper.toUserField("scheduled"),g=this.plugin.fieldMapper.toUserField("due"),v=this.plugin.fieldMapper.toUserField("recurrence"),k=this.plugin.fieldMapper.toUserField("googleCalendarExceptionOriginalScheduled"),T=this.plugin.fieldMapper.toUserField("googleCalendarMovedOriginalDates");hce({frontmatter:u,completeInstancesField:p,skippedInstancesField:m,dateModifiedField:f,scheduledField:h,dueField:g,recurrenceField:v,googleCalendarExceptionOriginalScheduledField:k,googleCalendarMovedOriginalDatesField:T,plan:i})}),l&&this.plugin.settings.resetCheckboxesOnRecurrence){let u=null;await Ob(this.plugin.app,r,p=>{let{frontmatter:m,body:f}=Gu(p),{content:h,changed:g}=Vte(f);if(!g)return p;let v=m!==null?`--- +${m} +--- + +`:"",k=h.trimEnd();return u=h.replace(/\r\n/g,` +`).trimEnd(),k.length>0?`${v}${k} +`:v}),u!==null&&(s.details=u)}try{if(this.plugin.cacheManager.waitForFreshTaskData){let u={complete_instances:s.complete_instances};s.scheduled!==a.scheduled&&(u.scheduled=s.scheduled),s.due!==a.due&&(u.due=s.due),await this.plugin.cacheManager.waitForFreshTaskData(r)}this.plugin.cacheManager.updateTaskInfoInCache(a.path,s)}catch(u){qt.error("Error updating cache for recurring task:",{category:"stale-data",operation:"updating-cache-recurring-task",error:u})}if(this.plugin.emitter.trigger(rt,{path:a.path,originalTask:a,updatedTask:s}),l&&this.webhookNotifier)try{await this.webhookNotifier.triggerWebhook("recurring.instance.completed",{task:s,date:o,targetDate:c})}catch(u){qt.error("Error triggering recurring task completion webhook:",{category:"provider",operation:"triggering-recurring-task-completion-webhook",error:u})}return(d=this.plugin.taskCalendarSyncService)!=null&&d.isEnabled()&&this.plugin.taskCalendarSyncService.updateTaskInCalendar(s,a).catch(u=>{qt.warn("Failed to sync recurring task update to Google Calendar:",{category:"provider",operation:"sync-recurring-task-update-google-calendar",error:u})}),s}async toggleRecurringTaskSkipped(e,t){var d;let r=this.plugin.app.vault.getAbstractFileByPath(e.path);if(!(r instanceof Ln.TFile))throw new Error(`Cannot find task file: ${e.path}`);let a=await this.plugin.cacheManager.getTaskInfo(e.path)||e;if(!a.recurrence)throw new Error("Task is not recurring");let i=gce({freshTask:a,targetDate:this.getRecurringTaskActionDate(a,t),currentTimestamp:qe(),maintainDueDateOffsetInRecurring:this.plugin.settings.maintainDueDateOffsetInRecurring}),{updatedTask:s,dateStr:o,newSkipped:l,targetDate:c}=i;await yr(this.plugin.app,r,u=>{let p=this.plugin.fieldMapper.toUserField("skippedInstances"),m=this.plugin.fieldMapper.toUserField("completeInstances"),f=this.plugin.fieldMapper.toUserField("dateModified"),h=this.plugin.fieldMapper.toUserField("scheduled"),g=this.plugin.fieldMapper.toUserField("due"),v=this.plugin.fieldMapper.toUserField("googleCalendarExceptionOriginalScheduled"),k=this.plugin.fieldMapper.toUserField("googleCalendarMovedOriginalDates");yce({frontmatter:u,skippedField:p,completeField:m,dateModifiedField:f,scheduledField:h,dueField:g,googleCalendarExceptionOriginalScheduledField:v,googleCalendarMovedOriginalDatesField:k,plan:i})});try{this.plugin.cacheManager.waitForFreshTaskData&&await this.plugin.cacheManager.waitForFreshTaskData(r),this.plugin.cacheManager.updateTaskInfoInCache(a.path,s)}catch(u){qt.error("Error updating cache for skipped recurring task:",{category:"stale-data",operation:"updating-cache-skipped-recurring-task",error:u})}if(this.plugin.emitter.trigger(rt,{path:a.path,originalTask:a,updatedTask:s}),l&&this.webhookNotifier)try{await this.webhookNotifier.triggerWebhook("recurring.instance.skipped",{task:s,date:o,targetDate:c})}catch(u){qt.error("Error triggering recurring task skip webhook:",{category:"provider",operation:"triggering-recurring-task-skip-webhook",error:u})}return(d=this.plugin.taskCalendarSyncService)!=null&&d.isEnabled()&&this.plugin.taskCalendarSyncService.updateTaskInCalendar(s,a).catch(u=>{qt.warn("Failed to sync recurring task skip to Google Calendar:",{category:"provider",operation:"sync-recurring-task-skip-google-calendar",error:u})}),s}async deleteTimeEntry(e,t){let r=this.plugin.app.vault.getAbstractFileByPath(e.path);if(!(r instanceof Ln.TFile))throw new Error(`Cannot find task file: ${e.path}`);let a=EH(e,t,qe()),{updatedTask:i}=a;await yr(this.plugin.app,r,s=>{let o=this.plugin.fieldMapper.toUserField("timeEntries"),l=this.plugin.fieldMapper.toUserField("dateModified");Efe({frontmatter:s,timeEntriesField:o,dateModifiedField:l,timeEntryIndex:a.timeEntryIndex,dateModified:a.dateModified})});try{this.plugin.cacheManager.waitForFreshTaskData&&await this.plugin.cacheManager.waitForFreshTaskData(r),this.plugin.cacheManager.updateTaskInfoInCache(e.path,i)}catch(s){qt.error("Error updating cache for time entry deletion:",{category:"stale-data",operation:"updating-cache-time-entry-deletion",error:s})}return this.plugin.emitter.trigger(rt,{path:e.path,originalTask:e,updatedTask:i}),i}updateCompletedDateInFrontmatter(e,t,r){if(r)return;let a=this.plugin.fieldMapper.toUserField("completedDate");SH(e,t,r,a,i=>this.plugin.statusManager.isCompletedStatus(i),Yo())}extractProjectBasename(e){return Zo(e,this.plugin.app)}extractProjectFilePath(e){var a,i,s;let t=vt(e),r=(i=(a=this.plugin.app.metadataCache).getFirstLinkpathDest)==null?void 0:i.call(a,t,"");return((s=r==null?void 0:r.path)!=null?s:t).replace(/\.md$/i,"")}}});var fc,px=y(()=>{fc=class{constructor(){this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{let r=this.events[e];if(!r)return;let a=r.filter(i=>i!==t);a.length>0?this.events[e]=a:delete this.events[e]}}emit(e,...t){this.events[e]&&this.events[e].forEach(r=>{r(...t)})}removeAllListeners(e){e?delete this.events[e]:this.events={}}}});var cN,Rfe=y(()=>{dr();xe();cN=class{constructor(e){this.deps=e;this.indexQueryCache=new Map;this.cacheTimers=new Map;this.cacheTimeout=3e4}getIndexOptimizedTaskPaths(e){let t=this.analyzeQueryOptimizationSafety(e);if(!t.canOptimize)return this.deps.cacheManager.getAllTaskPaths();if(t.strategy==="intersect"){let r=this.getPathsForIndexableCondition(t.conditions[0]);for(let a=1;aa.type==="condition"&&this.isIndexableCondition(a)).length===t.length}hasIndexableConditionInOrGroup(e,t){return this.checkNodeForOrWithIndexable(e,t)}checkNodeForOrWithIndexable(e,t){if(e.type==="condition")return!1;if(e.type==="group"){if(e.conjunction==="or"&&e.children.some(a=>a.type==="condition"&&t.includes(a)))return!0;for(let r of e.children)if(this.checkNodeForOrWithIndexable(r,t))return!0}return!1}findIndexableConditions(e){let t=[];if(e.type==="condition")this.isIndexableCondition(e)&&t.push(e);else if(e.type==="group")for(let r of e.children)t.push(...this.findIndexableConditions(r));return t}isIndexableCondition(e){let{property:t,operator:r,value:a}=e;return!!(t==="status"&&r==="is"&&a||t==="priority"&&r==="is"&&a||t==="due"&&(r==="is"||r==="is-before"||r==="is-after")&&a||t==="scheduled"&&(r==="is"||r==="is-before"||r==="is-after")&&a)}getCachedIndexResult(e,t){let r=this.indexQueryCache.get(e);if(r)return new Set(r);let a=t();this.indexQueryCache.set(e,new Set(a));let i=this.cacheTimers.get(e);i&&this.deps.timer.clearTimeout(i);let s=this.deps.timer.setTimeout(()=>{this.indexQueryCache.delete(e),this.cacheTimers.delete(e)},this.cacheTimeout);return this.cacheTimers.set(e,s),a}getPathsForIndexableCondition(e){let{property:t,operator:r,value:a}=e,i=`${t}:${r}:${Y(a)}`;return this.getCachedIndexResult(i,()=>t==="status"&&r==="is"&&a&&typeof a=="string"?new Set(this.deps.cacheManager.getTaskPathsByStatus(a)):t==="priority"&&r==="is"&&a&&typeof a=="string"?new Set(this.deps.cacheManager.getTaskPathsByPriority(a)):(t==="due"||t==="scheduled")&&r==="is"&&a&&typeof a=="string"?new Set(this.deps.cacheManager.getTasksForDate(Fl(a))):(t==="due"||t==="scheduled")&&(r==="is-before"||r==="is-after")&&a&&typeof a=="string"?this.getTaskPathsForDateRange(t,r,Fl(a)):this.deps.cacheManager.getAllTaskPaths())}getTaskPathsForDateRange(e,t,r){return(e==="due"||e==="scheduled")&&(t==="is-before"||t==="is-after")?this.deps.cacheManager.getTaskPathsForDateRange(e,t,r):this.deps.cacheManager.getAllTaskPaths()}intersectPathSets(e,t){let r=new Set;for(let a of e)t.has(a)&&r.add(a);return r}}});function Ffe(n){return n.id||n.key}function dN(n,e){return n==null?1:e==null?-1:n.localeCompare(e)}function uN(n){if(typeof n=="boolean")return n;if(n==null)return;let e=Y(n).trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}function Lfe(n){if(typeof n=="number")return String(n);if(typeof n!="string")return;let e=n.match(/^(\d+(?:\.\d+)?)/);return e?e[1]:void 0}function _fe(n){if(Array.isArray(n))return Qv(n)[0];if(typeof n=="string")return n.trim().length===0?"":Qv(n)[0]}function Qv(n){let e=[],t=i=>{if(!i)return;let s=String(i).trim();if(!s)return;let o=s.match(/^\[\[([^|\]]+)(?:\|([^\]]+))?\]\]$/);if(o){let l=o[1]||"",d=o[2]||l.split("#")[0].split("/").pop()||l;d&&e.push(d),e.push(s);return}e.push(s)};if(Array.isArray(n))for(let i of n)t(Y(i));else if(typeof n=="string"){let i=ms(n);for(let s of i)t(s)}else n!=null&&t(Y(n));let r=new Set,a=[];for(let i of e)r.has(i)||(r.add(i),a.push(i));return a}function sh(n,e){return n==null?void 0:n.find(t=>Ffe(t)===e)}function Ofe(n,e){return n==null?void 0:n.find(t=>Ffe(t)===e||t.key===e)}function zfe(n,e){switch(n.type){case"boolean":return typeof e=="boolean"?e:Y(e).toLowerCase()==="true";case"number":return typeof e=="number"?e:e!=null?parseFloat(Y(e)):void 0;case"list":return Qv(e);case"date":case"text":default:return e!=null?Y(e):void 0}}function Bfe(n,e,t){switch(n.type){case"number":{let r=typeof e=="number"?e:e!=null?parseFloat(Y(e)):NaN,a=typeof t=="number"?t:t!=null?parseFloat(Y(t)):NaN,i=!isNaN(r),s=!isNaN(a);return i&&s?r-a:i&&!s?-1:!i&&s?1:0}case"boolean":{let r=uN(e),a=uN(t);return r===a?0:r===!0?-1:a===!0?1:r===!1?-1:a===!1?1:0}case"date":{let r=e?Date.parse(Y(e)):NaN,a=t?Date.parse(Y(t)):NaN,i=!isNaN(r),s=!isNaN(a);return i&&s?r-a:i&&!s?-1:!i&&s?1:0}case"list":{let r=_fe(e),a=_fe(t);return(r==null||r==="")&&(a==null||a==="")?0:r==null||r===""?1:a==null||a===""?-1:r.localeCompare(a)}case"text":default:{let r=e!=null?Y(e):"",a=t!=null?Y(t):"";return r.localeCompare(a)}}}function jfe(n,e,t=Mqe){var r;if(!n)return t.unknownField;try{switch(n.type){case"boolean":{let a=uN(e);return a==null?t.noValue:a?"true":"false"}case"number":return(r=Lfe(e))!=null?r:typeof e=="string"?t.nonNumeric:t.noValue;case"date":return e?Y(e):t.noDate;case"list":{if(Array.isArray(e)){let a=Qv(e);return a.length>0?a[0]:t.empty}if(typeof e=="string"){if(e.trim().length===0)return t.empty;let a=Qv(e);return a.length>0?a[0]:t.empty}return t.noValue}case"text":default:return e?Y(e).trim()||t.empty:t.noValue}}catch(a){return t.error}}function $fe(n,e,t){if(!n)return[t];switch(n.type){case"boolean":{let r=uN(e);return r==null?[t]:[r?"true":"false"]}case"number":{let r=Lfe(e);return r?[r]:[t]}case"date":return e?[Y(e)]:[t];case"list":{let r=Qv(e).filter(a=>!/^\[\[/.test(a));return r.length>0?r:[t]}case"text":default:{let r=Y(e).trim();return r?[r]:[t]}}}function Ufe(n,e){let t=[...n];if(!e)return t.sort();switch(e.type){case"number":return t.sort((r,a)=>{let i=parseFloat(r),s=parseFloat(a),o=!isNaN(i),l=!isNaN(s);return o&&l?s-i:o&&!l?-1:!o&&l?1:dN(r,a)});case"boolean":return t.sort((r,a)=>r==="true"&&a==="false"?-1:r==="false"&&a==="true"?1:dN(r,a));case"date":return t.sort((r,a)=>{let i=Date.parse(r),s=Date.parse(a),o=!isNaN(i),l=!isNaN(s);return o&&l?i-s:o&&!l?-1:!o&&l?1:dN(r,a)});case"text":case"list":default:return t.sort(dN)}}var Mqe,mx=y(()=>{Ku();dr();Mqe={unknownField:"unknown-field",noValue:"no-value",noDate:"no-date",empty:"empty",nonNumeric:"non-numeric",error:"error"}});function Hfe(n,e){return!!n&&re(n)!==e}function Jv(n,e,t){return!!n&&ps(n,e,t)}function Vfe(n,e){if(n.recurrence)return F0(n,st(e.dateStr));if(n.due&&re(n.due)===e.dateStr||n.scheduled&&re(n.scheduled)===e.dateStr)return!0;if(e.includeOverdue&&e.isViewingToday){let t=e.isCompletedStatus(n.status);if(Hfe(n.due,e.dateStr)&&Jv(n.due,t,e.hideCompletedFromOverdue)||Hfe(n.scheduled,e.dateStr)&&Jv(n.scheduled,t,e.hideCompletedFromOverdue))return!0}return!1}function Wfe(n,e){let t=e.isCompletedStatus(n.status);return n.recurrence&&!(t&&e.hideCompletedFromOverdue)&&Iqe(n,e.todayString)?!0:Jv(n.due,t,e.hideCompletedFromOverdue)||Jv(n.scheduled,t,e.hideCompletedFromOverdue)}function Iqe(n,e=zr()){if(!n.recurrence)return!1;let t=st(e),r=new Date(t);r.setUTCDate(r.getUTCDate()-1);let a=Nqe(n,t);if(a>r)return!1;let i=new Set(n.complete_instances||[]),s=new Set(n.skipped_instances||[]);return ly(n,a,r).some(l=>{let c=ae(l);return ca?re(a):"").filter(a=>a.length>0).map(a=>st(a)).reduce((a,i)=>i{yt();xe()});function pN(n,e,t,r){return n.type==="condition"?_qe(n,e,t,r):n.type==="group"?Rqe(n,e,t,r):!0}function Rqe(n,e,t,r){if(n.children.length===0)return!0;let a=n.children.filter(i=>i.type==="condition"?ir.isFilterNodeComplete(i):!0);return a.length===0?!0:n.conjunction==="and"?a.every(i=>pN(i,e,t,r)):n.conjunction==="or"?a.some(i=>pN(i,e,t,r)):!0}function _qe(n,e,t,r){let{property:a,operator:i,value:s}=n;if(typeof a=="string"&&a.startsWith("user:"))return Fqe(n,e,t);let o=ir.getTaskPropertyValue(e,a);if(a==="hasSubtasks"&&t.projectSubtasksService&&(o=t.projectSubtasksService.isTaskUsedAsProjectSync(e.path)),a==="status.isCompleted"){let l=oy(e,r||new Date,t.getCompletedStatuses()[0]);o=t.isCompletedStatus(l)}return a==="projects"&&(i==="contains"||i==="does-not-contain")?Lqe(o,i,s,t.app):ir.applyOperator(o,i,s,n.id,a)}function Fqe(n,e,t){let{property:r,operator:a,value:i}=n,s=r.slice(5),o=sh(t.userFields,s),l=o?zfe(o,t.getUserFieldRawValue(e,o.key)):void 0;if((o==null?void 0:o.type)==="list"&&(a==="contains"||a==="does-not-contain")){let d=Array.isArray(l)?l:l!=null?[String(l)]:[],p=(Array.isArray(i)?i:[String(i!=null?i:"")]).some(m=>typeof m=="string"&&d.some(f=>typeof f=="string"&&f.toLowerCase().includes(m.toLowerCase())));return a==="contains"?p:!p}let c=(o==null?void 0:o.type)==="date"?"due":r;return ir.applyOperator(l,a,i,n.id,c)}function Lqe(n,e,t,r){if(!Array.isArray(n)||typeof t!="string")return!1;let a=Gfe(t,r);if(!a)return!1;let i=n.some(s=>{if(!s||typeof s!="string")return!1;let o=Gfe(s,r);return o?o===a?!0:Oqe(s,t,r):!1});return e==="contains"?i:!i}function Gfe(n,e){if(!n||typeof n!="string")return null;let t=Zo(n,e);return t||null}function Oqe(n,e,t){if(!t)return!1;let r=Yfe(n),a=Yfe(e);if(!r||!a)return!1;let i=t.metadataCache.getFirstLinkpathDest(r,""),s=t.metadataCache.getFirstLinkpathDest(a,"");return i&&s?i.path===s.path:!1}function Yfe(n){return!n||typeof n!="string"?null:n.startsWith("[[")&&n.endsWith("]]")?n.slice(2,-2):n}var Kfe=y(()=>{Ad();yt();Cn();mx()});function MH(n,e,t,r){var i;if(e==="none")return new Map([["all",n]]);let a=new Map;for(let s of n){let o=$qe(s,e,t,r);for(let l of o)a.has(l)||a.set(l,[]),(i=a.get(l))==null||i.push(s)}return zqe(a,e,t)}function zqe(n,e,t){let r=new Map,a=Uqe(n,e,t);for(let i of a){let s=n.get(i);s&&r.set(i,s)}return r}function Bqe(n,e,t){var s;let r=t||new Date;r.setHours(0,0,0,0);let a=e.isCompletedStatus(n.status),i=(s=e.hideCompletedFromOverdue)!=null?s:!0;if(n.recurrence){if(F0(n,r)){let o=D(r,"yyyy-MM-dd");return PH(o,e,a,i)}return n.due?PH(n.due,e,a,i):_p("none",e)}return n.due?PH(n.due,e,a,i):_p("none",e)}function jqe(n,e){var t;return n.scheduled?Vqe(n.scheduled,e,e.isCompletedStatus(n.status),(t=e.hideCompletedFromOverdue)!=null?t:!0):oh("none",e)}function $qe(n,e,t,r){if(e==="project"){let a=Ko(n.projects||[]);return a.length===0?[Qfe(t)]:a.map(i=>t.resolveProjectToAbsolutePath(i))}if(e==="tags"){let a=n.tags||[];return a.length>0?a:[Jfe(t)]}if(typeof e=="string"&&e.startsWith("user:"))return[Hqe(n,e,t)];switch(e){case"status":return[n.status||"no-status"];case"priority":return[n.priority||"unknown"];case"context":return[n.contexts&&n.contexts.length>0?n.contexts[0]:"none"];case"due":return[Bqe(n,t,r)];case"scheduled":return[jqe(n,t)];case"completedDate":return[Wqe(n,t)];default:return["unknown"]}}function Uqe(n,e,t){if(typeof e=="string"&&e.startsWith("user:")){let r=qqe(Array.from(n.keys()),e,t);return t.currentSortKey===e&&t.currentSortDirection==="desc"&&r.reverse(),r}switch(e){case"priority":return Array.from(n.keys()).sort((r,a)=>t.getPriorityWeight(a)-t.getPriorityWeight(r));case"status":return Array.from(n.keys()).sort((r,a)=>t.getStatusOrder(r)-t.getStatusOrder(a));case"due":{let r=["overdue","today","tomorrow","nextSevenDays","later","none"],a=new Map(r.map((i,s)=>[_p(i,t),s]));return Array.from(n.keys()).sort((i,s)=>{var c,d;let o=(c=a.get(i))!=null?c:r.length,l=(d=a.get(s))!=null?d:r.length;return o-l})}case"scheduled":{let r=["past","today","tomorrow","nextSevenDays","later","none"],a=new Map(r.map((i,s)=>[oh(i,t),s]));return Array.from(n.keys()).sort((i,s)=>{var c,d;let o=(c=a.get(i))!=null?c:r.length,l=(d=a.get(s))!=null?d:r.length;return o-l})}case"project":return Array.from(n.keys()).sort((r,a)=>Zfe(r,a,Qfe(t),t.getLocale()));case"tags":return Array.from(n.keys()).sort((r,a)=>Zfe(r,a,Jfe(t),t.getLocale()));case"completedDate":return Array.from(n.keys()).sort((r,a)=>{if(r==="Not completed")return 1;if(a==="Not completed")return-1;if(r==="Invalid date")return 1;if(a==="Invalid date")return-1;if(r==null||a==null){if(r==null)return 1;if(a==null)return-1}return a.localeCompare(r)});default:return Array.from(n.keys()).sort((r,a)=>r==null?1:a==null?-1:r.localeCompare(a,t.getLocale()))}}function Hqe(n,e,t){let r=e.slice(5),a=sh(t.userFields||[],r),i=a?t.getUserFieldRawValue(n,a.key):void 0;return jfe(a,i)}function PH(n,e,t,r){let a=zr();if(ps(n,t,r))return _p("overdue",e);let i=re(n);if(qs(i,a))return _p("today",e);try{let s=new Date;s.setDate(s.getDate()+1);let o=D(s,"yyyy-MM-dd");if(qs(i,o))return _p("tomorrow",e);let l=new Date;l.setDate(l.getDate()+7);let c=D(l,"yyyy-MM-dd");return cf(i,c)||qs(i,c)?_p("nextSevenDays",e):_p("later",e)}catch(s){return AH.error(`Error categorizing date ${n}:`,{category:"validation",operation:"categorizing-date",error:s}),fx(e)}}function Vqe(n,e,t,r){let a=zr();if(ps(n,t,r))return oh("past",e);let i=re(n);if(qs(i,a))return oh("today",e);try{let s=new Date;s.setDate(s.getDate()+1);let o=D(s,"yyyy-MM-dd");if(qs(i,o))return oh("tomorrow",e);let l=new Date;l.setDate(l.getDate()+7);let c=D(l,"yyyy-MM-dd");return cf(i,c)||qs(i,c)?oh("nextSevenDays",e):oh("later",e)}catch(s){return AH.error(`Error categorizing scheduled date ${n}:`,{category:"validation",operation:"categorizing-scheduled-date",error:s}),fx(e)}}function Wqe(n,e){if(!n.completedDate)return"Not completed";try{return D(Na(n.completedDate),"yyyy-MM-dd")}catch(t){return AH.error(`Error formatting completed date ${n.completedDate}:`,{category:"validation",operation:"formatting-completed-date",error:t}),fx(e)}}function qqe(n,e,t){let r=e.slice(5),a=sh(t.userFields||[],r);return Ufe(n,a)}function Zfe(n,e,t,r){return n===t?1:e===t?-1:n==null?1:e==null?-1:n.localeCompare(e,r)}function _p(n,e){switch(n){case"overdue":return e.translate("services.filter.groupLabels.due.overdue","Overdue");case"today":return e.translate("services.filter.groupLabels.due.today","Today");case"tomorrow":return e.translate("services.filter.groupLabels.due.tomorrow","Tomorrow");case"nextSevenDays":return e.translate("services.filter.groupLabels.due.nextSevenDays","Next seven days");case"later":return e.translate("services.filter.groupLabels.due.later","Later");case"none":return e.translate("services.filter.groupLabels.due.none","No due date");case"invalid":default:return fx(e)}}function oh(n,e){switch(n){case"past":return e.translate("services.filter.groupLabels.scheduled.past","Past scheduled");case"today":return e.translate("services.filter.groupLabels.scheduled.today","Today");case"tomorrow":return e.translate("services.filter.groupLabels.scheduled.tomorrow","Tomorrow");case"nextSevenDays":return e.translate("services.filter.groupLabels.scheduled.nextSevenDays","Next seven days");case"later":return e.translate("services.filter.groupLabels.scheduled.later","Later");case"none":return e.translate("services.filter.groupLabels.scheduled.none","No scheduled date");case"invalid":default:return fx(e)}}function Qfe(n){return n.translate("services.filter.groupLabels.noProject","No project")}function Jfe(n){return n.translate("services.filter.groupLabels.noTags","No tags")}function fx(n){return n.translate("services.filter.groupLabels.invalidDate","Invalid date")}var AH,Xfe=y(()=>{Cr();xe();yt();mx();q();AH=M({tag:"Services/FilterService/FilterTaskGrouping"})});function ehe(n,e,t,r){return n.sort((a,i)=>{let s=Yqe(a,i,e,r);return s!==0?t==="desc"?-s:s:Xqe(a,i,e,r)})}function Xv(n,e){if(!n&&!e)return 0;if(!n)return 1;if(!e)return-1;try{return Sd(n,e)?-1:Sd(e,n)?1:0}catch(t){return Gqe.error("Error comparing dates time-aware:",{category:"validation",operation:"comparing-dates-time-aware",details:{dateA:n,dateB:e},error:t}),n.localeCompare(e)}}function Yqe(n,e,t,r){if(typeof t=="string"&&t.startsWith("user:"))return e4e(n,e,t,r);switch(t){case"due":return Xv(n.due,e.due);case"scheduled":return Xv(n.scheduled,e.scheduled);case"priority":return Zqe(n.priority,e.priority,r);case"status":return Qqe(n.status,e.status,r);case"title":return n.title.localeCompare(e.title);case"dateCreated":return Xv(n.dateCreated,e.dateCreated);case"completedDate":return Xv(n.completedDate,e.completedDate);case"tags":return Jqe(n.tags,e.tags);default:return 0}}function Kqe(n,e,t){let r=t.getPriorityWeight(n);return t.getPriorityWeight(e)-r}function Zqe(n,e,t){let r=t.getPriorityWeight(n),a=t.getPriorityWeight(e);return r-a}function Qqe(n,e,t){return t.getStatusOrder(n)-t.getStatusOrder(e)}function Jqe(n,e){let t=n&&n.length>0?n:[],r=e&&e.length>0?e:[];return t.length===0&&r.length===0?0:t.length===0?1:r.length===0?-1:t[0].toLowerCase().localeCompare(r[0].toLowerCase())}function Xqe(n,e,t,r){let i=["due","scheduled","priority","title"].filter(s=>s!==t);for(let s of i){let o=0;switch(s){case"scheduled":o=Xv(n.scheduled,e.scheduled);break;case"due":o=Xv(n.due,e.due);break;case"priority":o=Kqe(n.priority,e.priority,r);break;case"title":o=n.title.localeCompare(e.title);break}if(o!==0)return o}return 0}function e4e(n,e,t,r){let a=t.slice(5),i=sh(r.userFields||[],a);return i?Bfe(i,r.getUserFieldRawValue(n,i.key),r.getUserFieldRawValue(e,i.key)):0}var Gqe,the=y(()=>{xe();mx();q();Gqe=M({tag:"Services/FilterService/FilterTaskSorting"})});function rhe(n){return{statuses:n.statuses,priorities:n.priorities,contexts:n.contexts,projects:n.projects,tags:n.tags,folders:t4e(n.taskPaths,n.rootFolderLabel),userProperties:r4e(n.userFields||[])}}function t4e(n,e){let t=new Set;for(let r of n){let a=r.lastIndexOf("/");a>0?t.add(r.substring(0,a)):a===-1&&t.add("")}return Array.from(t).sort().map(r=>r===""?e:r)}function r4e(n){let e=[];for(let t of n)!t||!t.key||!t.displayName||e.push({id:`user:${t.id||t.key}`,label:t.displayName,category:n4e(t.type),supportedOperators:i4e(t.type),valueInputType:a4e(t.type)});return e}function n4e(n){switch(n){case"boolean":return"boolean";case"number":return"numeric";case"date":return"date";case"list":case"text":default:return"text"}}function a4e(n){switch(n){case"number":return"number";case"date":return"date";case"boolean":return"none";case"list":case"text":default:return"text"}}function i4e(n){switch(n){case"number":return["is","is-not","is-greater-than","is-less-than","is-greater-than-or-equal","is-less-than-or-equal","is-empty","is-not-empty"];case"date":return["is","is-not","is-before","is-after","is-on-or-before","is-on-or-after","is-empty","is-not-empty"];case"boolean":return["is-checked","is-not-checked"];case"list":return["contains","does-not-contain","is-empty","is-not-empty"];case"text":default:return["is","is-not","contains","does-not-contain","is-empty","is-not-empty"]}}var nhe=y(()=>{});function IH(n){return{type:"group",id:n(),conjunction:"and",children:[],sortKey:"due",sortDirection:"asc",groupKey:"none"}}function ihe(n,e,t,r){let a=o4e(n);if(s4e(a,e),!t){let i=ahe[e];a.children.push({type:"condition",id:r(),...i})}return a}function she(n,e){let t=IH(e);return{...t,...n,type:"group",id:n.id||t.id,conjunction:n.conjunction||t.conjunction,children:n.children||t.children,sortKey:n.sortKey||t.sortKey,sortDirection:n.sortDirection||t.sortDirection,groupKey:n.groupKey||t.groupKey}}function s4e(n,e){let t=ahe[e].property;n.children=n.children.filter(r=>r.type==="condition"?r.property!==t:!0)}function o4e(n){return JSON.parse(JSON.stringify(n))}var ahe,ohe=y(()=>{ahe={showCompleted:{property:"status.isCompleted",operator:"is-not-checked",value:null},showArchived:{property:"archived",operator:"is-not-checked",value:null},showRecurrent:{property:"recurrence",operator:"is-empty",value:null}}});var lhe={};Xe(lhe,{HierarchicalGroupingService:()=>RH});function NH(n){return n==null?"":typeof n=="string"?n.trim():typeof n=="number"||typeof n=="boolean"?String(n):""}var RH,che=y(()=>{RH=class{constructor(e){this.resolveUserFieldValues=e}group(e,t,r,a="asc",i=[]){let s=new Map,o=(c,d)=>{var p,m,f,h,g,v,k,T;if(!d||d==="none")return["all"];let u=b=>{let w=b.map(NH).filter(S=>S!=="");return w.length?w:[]};if(d.startsWith("user:")){let b=d.slice(5);if(this.resolveUserFieldValues){let C=this.resolveUserFieldValues(c,b)||[],x=u(C);return x.length?x:[`No ${b}`]}let w=(p=c.customProperties)==null?void 0:p[b];if(Array.isArray(w)){let C=u(w);return C.length?C:[`No ${b}`]}let S=NH(w);return S!==""?[S]:[`No ${b}`]}switch(d){case"status":return[((m=c.status)!=null?m:"").trim()||"No Status"];case"priority":return[((f=c.priority)!=null?f:"").trim()||"No Priority"];case"context":{let b=u((h=c.contexts)!=null?h:[]);return b.length?b:["No Context"]}case"project":{let b=u((g=c.projects)!=null?g:[]).map(C=>{let x=C.match(/^\[\[([^|\]]+)(?:\|([^\]]+))?\]\]$/);if(x){let E=x[1]||"";return x[2]||E.split("#")[0].split("/").pop()||E||C}return C}),w=[],S=new Set;for(let C of b)S.has(C)||(S.add(C),w.push(C));return w.length?w:["No Project"]}case"tags":{let b=u((v=c.tags)!=null?v:[]);return b.length?b:["No Tag"]}case"due":{let b=((k=c.due)!=null?k:"").trim();return b?[b.split("T")[0]]:["No Due Date"]}case"scheduled":{let b=((T=c.scheduled)!=null?T:"").trim();return b?[b.split("T")[0]]:["No Scheduled Date"]}default:{let w=c[d];if(Array.isArray(w)){let C=u(w);return C.length?C:[`No ${d}`]}let S=NH(w);return S!==""?[S]:[`No ${d}`]}}};for(let c of e){let d=o(c,t),u=o(c,r);for(let p of d){s.has(p)||s.set(p,new Map);let m=s.get(p);for(let f of u)m.has(f)||m.set(f,[]),m.get(f).push(c)}}let l=new Map;for(let[c,d]of s){let u=this.sortSubgroups(d,r,a,i);l.set(c,u)}return l}sortSubgroups(e,t,r,a){let i=Array.from(e.keys()),s=this.sortSubgroupKeys(i,t,r,a),o=new Map;for(let l of s)o.set(l,e.get(l));return o}sortSubgroupKeys(e,t,r,a){let i=o=>/^No\s/i.test(o);if(typeof t=="string"&&t.startsWith("user:")){let o=t.slice(5),l=a.find(u=>(u.id||u.key)===o),c=(u,p)=>{if(i(u)&&!i(p))return-1;if(!i(u)&&i(p))return 1;if((l==null?void 0:l.type)==="number"){let m=parseFloat(u),f=parseFloat(p),h=isNaN(m)?Number.POSITIVE_INFINITY:m,g=isNaN(f)?Number.POSITIVE_INFINITY:f;if(h!==g)return h-g}else if((l==null?void 0:l.type)==="boolean"){let m=u==="true"?0:u==="false"?1:2,f=p==="true"?0:p==="false"?1:2;if(m!==f)return m-f}else if((l==null?void 0:l.type)==="date"){let m=Date.parse(u),f=Date.parse(p),h=isNaN(m)?Number.POSITIVE_INFINITY:m,g=isNaN(f)?Number.POSITIVE_INFINITY:f;if(h!==g)return h-g}return u.localeCompare(p)},d=e.slice().sort(c);return r==="desc"?d.reverse():d}let s=e.slice().sort((o,l)=>i(o)&&!i(l)?-1:!i(o)&&i(l)?1:o.localeCompare(l));return r==="desc"?s.reverse():s}}});var dhe,mN,ek,fN,uhe=y(()=>{dhe=require("obsidian");Cn();px();Ad();Cr();xe();Rfe();mx();qfe();Kfe();Xfe();the();nhe();ohe();q();mN=M({tag:"Services/FilterService"}),ek=class ek extends fc{constructor(t,r,a,i){super();this.runtime=i;this.filterOptionsCache=null;this.filterOptionsCacheTimestamp=0;this.filterOptionsCacheTTL=3e5;this.filterOptionsComputeCount=0;this.filterOptionsCacheHits=0;this.cacheManager=t,this.statusManager=r,this.priorityManager=a,this.queryPlanner=new cN({cacheManager:t,timer:{setTimeout:(s,o)=>window.setTimeout(s,o),clearTimeout:s=>window.clearTimeout(s)}}),ek.lastInstance=this}translate(t,r,a){var i;try{if((i=this.runtime)!=null&&i.i18n)return this.runtime.i18n.translate(t,a)}catch(s){mN.error("FilterService translation error:",{category:"internal",operation:"filterservice-translation",error:s})}return r}static translateStatic(t,r){let a=ek.lastInstance;return a?a.translate(t,r):r}getLocale(){var t,r,a;try{let i=(a=(r=(t=this.runtime)==null?void 0:t.i18n)==null?void 0:r.getCurrentLocale)==null?void 0:a.call(r);if(i)return i}catch(i){mN.error("FilterService locale error:",{category:"internal",operation:"filterservice-locale",error:i})}return"en"}getNoProjectLabel(){return this.translate("services.filter.groupLabels.noProject","No project")}async getGroupedTasks(t,r){try{ir.validateFilterNode(t,!1);let a=this.queryPlanner.getIndexOptimizedTaskPaths(t),s=(await this.pathsToTaskInfos(Array.from(a))).filter(l=>this.evaluateFilterNode(t,l,r)),o=this.sortTasks(s,t.sortKey||"due",t.sortDirection||"asc");return this.currentSortKey=t.sortKey||"due",this.currentSortDirection=t.sortDirection||"asc",MH(o,t.groupKey||"none",this.createTaskGroupingContext(),r)}catch(a){if(a instanceof ga||a instanceof Pd)return mN.error("Filter error:",{category:"internal",operation:"filter",details:{values:[a.message,{nodeId:a.nodeId,field:a.field}]}}),new Map;throw a}}async getHierarchicalGroupedTasks(t,r){var a,i;try{ir.validateFilterNode(t,!1);let s=this.queryPlanner.getIndexOptimizedTaskPaths(t),l=(await this.pathsToTaskInfos(Array.from(s))).filter(p=>this.evaluateFilterNode(t,p,r)),c=this.sortTasks(l,t.sortKey||"due",t.sortDirection||"asc");this.currentSortKey=t.sortKey||"due",this.currentSortDirection=t.sortDirection||"asc";let d=MH(c,t.groupKey||"none",this.createTaskGroupingContext(),r),u=t.subgroupKey;if(u&&u!=="none"&&t.groupKey&&t.groupKey!=="none"){let{HierarchicalGroupingService:p}=await Promise.resolve().then(()=>(che(),lhe)),m=(k,T)=>{var x,E;let b=((E=(x=this.runtime)==null?void 0:x.settings)==null?void 0:E.userFields)||[],w=Ofe(b,T),S=`No ${(w==null?void 0:w.displayName)||(w==null?void 0:w.key)||T}`,C=w?this.getUserFieldRawValue(k,w.key):void 0;return $fe(w,C,S)},h=new p(m).group(c,t.groupKey,u,this.currentSortDirection,((i=(a=this.runtime)==null?void 0:a.settings)==null?void 0:i.userFields)||[]),g=Array.from(d.keys()),v=new Map;for(let k of g){let T=h.get(k);T&&v.set(k,T)}for(let[k,T]of h)v.has(k)||v.set(k,T);return{groups:d,hierarchicalGroups:v}}return{groups:d}}catch(s){if(s instanceof ga||s instanceof Pd)return mN.error("Filter error (hierarchical):",{category:"internal",operation:"filter-hierarchical",details:{values:[s.message,{nodeId:s.nodeId}]}}),{groups:new Map};throw s}}getCacheStats(){return this.queryPlanner.getCacheStats()}async pathsToTaskInfos(t){let r=[];for(let i=0;ithis.cacheManager.getCachedTaskInfo(l)));for(let l of o)l&&r.push(l)}return r}evaluateFilterNode(t,r,a){return pN(t,r,this.createPredicateEvaluationContext(),a)}createPredicateEvaluationContext(){var t,r,a,i;return{app:(t=this.runtime)==null?void 0:t.app,userFields:((a=(r=this.runtime)==null?void 0:r.settings)==null?void 0:a.userFields)||[],projectSubtasksService:(i=this.runtime)==null?void 0:i.projectSubtasksService,getUserFieldRawValue:(s,o)=>this.getUserFieldRawValue(s,o),getCompletedStatuses:()=>this.statusManager.getCompletedStatuses(),isCompletedStatus:s=>this.statusManager.isCompletedStatus(s)}}resolveProjectToAbsolutePath(t){var i;if(!t||typeof t!="string")return t||"";if(!((i=this.runtime)!=null&&i.app))return t;let r=this.parseLinkToPath(t),a=this.runtime.app.metadataCache.getFirstLinkpathDest(r,"");return a?a.path.replace(/\.md$/,""):r.replace(/\.md$/,"")}parseLinkToPath(t){return vt(t)}getPreferredProjectFormat(t){let r=this.getNoProjectLabel();return!t||t===r?t:t.includes("/")||t.endsWith(".md")?`[[${t}]]`:`[[${t}]]`}getOverdueTaskPaths(){return this.cacheManager.getOverdueTaskPaths()}sortTasks(t,r,a){return ehe(t,r,a,this.createTaskSortingContext())}createTaskGroupingContext(){var t,r,a,i;return{userFields:((r=(t=this.runtime)==null?void 0:t.settings)==null?void 0:r.userFields)||[],hideCompletedFromOverdue:(i=(a=this.runtime)==null?void 0:a.settings)==null?void 0:i.hideCompletedFromOverdue,currentSortKey:this.currentSortKey,currentSortDirection:this.currentSortDirection,isCompletedStatus:s=>this.statusManager.isCompletedStatus(s),getPriorityWeight:s=>this.priorityManager.getPriorityWeight(s),getStatusOrder:s=>this.statusManager.getStatusOrder(s),getUserFieldRawValue:(s,o)=>this.getUserFieldRawValue(s,o),resolveProjectToAbsolutePath:s=>this.resolveProjectToAbsolutePath(s),translate:(s,o,l)=>this.translate(s,o,l),getLocale:()=>this.getLocale()}}createTaskSortingContext(){var t,r;return{userFields:((r=(t=this.runtime)==null?void 0:t.settings)==null?void 0:r.userFields)||[],getPriorityWeight:a=>this.priorityManager.getPriorityWeight(a),getStatusOrder:a=>this.statusManager.getStatusOrder(a),getUserFieldRawValue:(a,i)=>this.getUserFieldRawValue(a,i)}}getUserFieldRawValue(t,r){var a;try{let i=this.cacheManager.getApp(),s=i.vault.getAbstractFileByPath(t.path),o=s instanceof dhe.TFile?(a=i.metadataCache.getFileCache(s))==null?void 0:a.frontmatter:void 0;return o?o[r]:void 0}catch(i){return}}async getFilterOptions(){var a,i;let t=Date.now();if(this.filterOptionsCache&&t-this.filterOptionsCacheTimestamp0?(this.filterOptionsCacheHits/i*100).toFixed(1)+"%":"0%";return{cacheHits:this.filterOptionsCacheHits,computeCount:this.filterOptionsComputeCount,hitRate:s,isCurrentlyCached:!!this.filterOptionsCache,cacheAge:r,ttlRemaining:a}}createDefaultQuery(){return IH(()=>ir.generateId())}addQuickToggleCondition(t,r,a){return ihe(t,r,a,()=>ir.generateId())}normalizeQuery(t){return she(t,()=>ir.generateId())}initialize(){this.cacheManager.on("file-updated",t=>{(t==null?void 0:t.filterIndexChanged)!==!1&&this.handleFilterIndexChanged(),this.emit("data-changed")}),this.cacheManager.on("file-added",()=>{this.handleFilterIndexChanged(),this.emit("data-changed")}),this.cacheManager.on("file-deleted",()=>{this.handleFilterIndexChanged(),this.emit("data-changed")}),this.cacheManager.on("file-renamed",()=>{this.handleFilterIndexChanged(),this.emit("data-changed")}),this.cacheManager.on("indexes-built",()=>{this.handleFilterIndexChanged(),this.emit("data-changed")})}cleanup(){this.queryPlanner.clearIndexQueryCache(),this.invalidateFilterOptionsCache(),this.removeAllListeners()}static createDateRangeFromDates(t){if(t.length===0)throw new Error(ek.translateStatic("services.filter.errors.noDatesProvided","No dates provided"));let r=t[0],a=t[t.length-1];return{start:D(r,"yyyy-MM-dd"),end:D(a,"yyyy-MM-dd")}}static shouldIncludeOverdueForRange(t,r){if(!r)return!1;let i=D(new Date,"yyyy-MM-dd");return t.some(s=>D(s,"yyyy-MM-dd")===i)}async getTasksForDate(t,r,a=!1){var p,m,f;let i=ae(t),s=_b(i),o=this.cacheManager.getAllTaskPaths(),c=(await this.pathsToTaskInfos(Array.from(o))).filter(h=>this.evaluateFilterNode(r,h)),d=(f=(m=(p=this.runtime)==null?void 0:p.settings)==null?void 0:m.hideCompletedFromOverdue)!=null?f:!0,u=c.filter(h=>Vfe(h,{dateStr:i,isViewingToday:s,includeOverdue:a,hideCompletedFromOverdue:d,isCompletedStatus:g=>this.statusManager.isCompletedStatus(g)}));return this.sortTasks(u,r.sortKey||"due",r.sortDirection||"asc")}async getOverdueTasks(t){var l,c,d;let r=this.cacheManager.getAllTaskPaths(),i=(await this.pathsToTaskInfos(Array.from(r))).filter(u=>this.evaluateFilterNode(t,u)),s=(d=(c=(l=this.runtime)==null?void 0:l.settings)==null?void 0:c.hideCompletedFromOverdue)!=null?d:!0,o=i.filter(u=>Wfe(u,{hideCompletedFromOverdue:s,isCompletedStatus:p=>this.statusManager.isCompletedStatus(p)}));return this.sortTasks(o,t.sortKey||"due",t.sortDirection||"asc")}async getAgendaDataWithOverdue(t,r,a=!1){let i=[];for(let o of t){let l=await this.getTasksForDate(o,r,!1);i.push({date:new Date(o),tasks:l})}let s=a?await this.getOverdueTasks(r):[];return{dailyData:i,overdueTasks:s}}async getAgendaData(t,r,a=!1){let i=[];for(let s of t){let o=await this.getTasksForDate(s,r,a&&Vz(s));i.push({date:new Date(s),tasks:o})}return i}async getFlatAgendaData(t,r,a=!1){let i=await this.getAgendaData(t,r,a),s=[];for(let o of i)for(let l of o.tasks)s.push({...l,agendaDate:o.date});return s}};ek.lastInstance=null;fN=ek});var tk,_H=y(()=>{tk=class{constructor(e,t){this.cache=e;this.statusManager=t}getStats(e){let t={},r={},a=0,i=0,s=0,o=0,l=0,c=0,d=new Date().toISOString().split("T")[0];for(let u of e){t[u.status]=(t[u.status]||0)+1,r[u.priority]=(r[u.priority]||0)+1;let p=this.statusManager.isCompletedStatus(u.status);u.archived&&o++,p&&a++,!p&&!u.archived&&i++,u.due&&u.due0&&(l++,c+=u.totalTrackedTime||0)}return{total:e.length,statusCounts:t,priorityCounts:r,completed:a,active:i,overdue:s,archived:o,withTimeEntries:l,totalTrackedMinutes:c,totalTrackedHours:Math.round(c/60*100)/100}}async getAggregatedTimeEstimate(e){let t=this.cache.getAllTimeEstimates();if(t.size===0)return 0;let{start:r,end:a}=this.getDateRange(e),i=0;for(let[s,o]of t.entries()){let l=await this.cache.getTaskInfo(s);l&&this.isTaskInRange(l,r,a)&&(i+=o)}return i}isTaskInRange(e,t,r){let a=e.due||e.scheduled;if(!a)return!1;let i=new Date(a);return i>=t&&i<=r}getDateRange(e){if(typeof e!="string")return e;let t=new Date,r=new Date(t),a=new Date(t);switch(e){case"daily":r.setHours(0,0,0,0),a.setHours(23,59,59,999);break;case"weekly":{let i=t.getDay(),s=t.getDate()-i+(i===0?-6:1);r.setDate(s),r.setHours(0,0,0,0),a.setDate(r.getDate()+6),a.setHours(23,59,59,999);break}case"monthly":r.setDate(1),r.setHours(0,0,0,0),a.setMonth(r.getMonth()+1),a.setDate(0),a.setHours(23,59,59,999);break;case"yearly":r.setMonth(0,1),r.setHours(0,0,0,0),a.setFullYear(r.getFullYear()+1),a.setDate(0),a.setHours(23,59,59,999);break}return{start:r,end:a}}}});var Fp,hN,phe=y(()=>{px();Ad();q();Fp=M({tag:"Services/ViewStateManager"}),hN=class extends fc{constructor(t,r){super();this.filterState={};this.viewPreferences={};this.savedViews=[];this.storageKey="tasknotes-view-filter-state";this.preferencesStorageKey="tasknotes-view-preferences";this.savedViewsStorageKey="tasknotes-saved-views";this.app=t,this.plugin=r,this.loadFromStorage(),this.loadPreferencesFromStorage(),this.savedViews=[...this.plugin.settings.savedViews]}async initializeSavedViews(){await this.migrateAndLoadSavedViews()}getFilterState(t){let r=this.filterState[t];if(r){if(typeof r!="object"||r.type!=="group"||!Array.isArray(r.children)||typeof r.conjunction!="string"){Fp.warn(`ViewStateManager: Ignoring old format filter state for ${t}, will use default`,{category:"validation",operation:"viewstatemanager-ignoring-old-format-filter-state"}),delete this.filterState[t],this.saveToStorage();return}return ir.deepCloneFilterQuery(r)}}setFilterState(t,r){this.filterState[t]=ir.deepCloneFilterQuery(r),this.saveToStorage(),this.emit("filter-state-changed",{viewType:t,query:ir.deepCloneFilterQuery(r)})}clearFilterState(t){delete this.filterState[t],this.saveToStorage(),this.emit("filter-state-cleared",{viewType:t})}clearAllFilterStates(){this.filterState={},this.saveToStorage(),this.emit("all-filter-states-cleared")}getViewPreferences(t){return this.viewPreferences[t]}setViewPreferences(t,r){this.viewPreferences[t]={...r},this.savePreferencesToStorage(),this.emit("view-preferences-changed",{viewType:t,preferences:r})}clearViewPreferences(t){delete this.viewPreferences[t],this.savePreferencesToStorage(),this.emit("view-preferences-cleared",{viewType:t})}clearAllViewPreferences(){this.viewPreferences={},this.savePreferencesToStorage(),this.emit("all-view-preferences-cleared")}loadFromStorage(){try{let t=this.app.loadLocalStorage(this.storageKey);t&&typeof t=="string"&&(this.filterState=JSON.parse(t))}catch(t){Fp.warn("Failed to load view filter state from storage:",{category:"persistence",operation:"load-view-filter-state-storage",error:t}),this.filterState={}}}saveToStorage(){try{this.app.saveLocalStorage(this.storageKey,JSON.stringify(this.filterState))}catch(t){Fp.warn("Failed to save view filter state to storage:",{category:"persistence",operation:"save-view-filter-state-storage",error:t})}}loadPreferencesFromStorage(){try{let t=this.app.loadLocalStorage(this.preferencesStorageKey);t&&typeof t=="string"&&(this.viewPreferences=JSON.parse(t))}catch(t){Fp.warn("Failed to load view preferences from storage:",{category:"configuration",operation:"load-view-preferences-storage",error:t}),this.viewPreferences={}}}savePreferencesToStorage(){try{this.app.saveLocalStorage(this.preferencesStorageKey,JSON.stringify(this.viewPreferences))}catch(t){Fp.warn("Failed to save view preferences to storage:",{category:"configuration",operation:"save-view-preferences-storage",error:t})}}getAllFilterStates(){return{...this.filterState}}getSavedViews(){return this.savedViews.map(t=>({...t,query:ir.deepCloneFilterQuery(t.query),viewOptions:t.viewOptions?{...t.viewOptions}:void 0}))}saveView(t,r,a,i){let s={id:this.generateId(),name:t,query:ir.deepCloneFilterQuery(r),viewOptions:a?{...a}:void 0,visibleProperties:i?[...i]:void 0};return this.savedViews.push(s),this.saveSavedViewsToPluginData(),this.emit("saved-views-changed",this.getSavedViews()),s}updateView(t,r){let a=this.savedViews.findIndex(s=>s.id===t);if(a===-1)throw new Error(`Saved view with ID ${t} not found`);let i={...r};i.query&&(i.query=ir.deepCloneFilterQuery(i.query)),i.viewOptions&&(i.viewOptions={...i.viewOptions}),this.savedViews[a]={...this.savedViews[a],...i},this.saveSavedViewsToPluginData(),this.emit("saved-views-changed",this.getSavedViews())}deleteView(t){let r=this.savedViews.findIndex(a=>a.id===t);if(r===-1)throw new Error(`Saved view with ID ${t} not found`);this.savedViews.splice(r,1),this.saveSavedViewsToPluginData(),this.emit("saved-views-changed",this.getSavedViews())}getSavedView(t){let r=this.savedViews.find(a=>a.id===t);if(r)return{...r,query:ir.deepCloneFilterQuery(r.query),viewOptions:r.viewOptions?{...r.viewOptions}:void 0,visibleProperties:r.visibleProperties?[...r.visibleProperties]:void 0}}clearAllSavedViews(){this.savedViews=[],this.saveSavedViewsToPluginData(),this.emit("saved-views-changed",this.getSavedViews())}updateSavedViewProperties(t,r){let a=this.savedViews.find(i=>i.id===t);a&&(a.visibleProperties=r,this.saveSavedViewsToPluginData(),this.emit("saved-views-changed",this.getSavedViews()))}getSavedViewProperties(t){let r=this.savedViews.find(a=>a.id===t);return r==null?void 0:r.visibleProperties}reorderSavedViews(t,r){if(t<0||t>=this.savedViews.length||r<0||r>this.savedViews.length||t===r)return;r=Math.min(r,this.savedViews.length-1);let[a]=this.savedViews.splice(t,1);this.savedViews.splice(r,0,a),this.saveSavedViewsToPluginData(),this.emit("saved-views-changed",this.getSavedViews())}generateId(){return Date.now().toString(36)+Math.random().toString(36).slice(2,11)}async migrateAndLoadSavedViews(){try{this.savedViews=[...this.plugin.settings.savedViews];let t=this.app.loadLocalStorage(this.savedViewsStorageKey);if(t&&typeof t=="string"&&this.savedViews.length===0){let r=JSON.parse(t);this.savedViews=[...r],await this.saveSavedViewsToPluginData(),this.app.saveLocalStorage(this.savedViewsStorageKey,null)}}catch(t){Fp.warn("Failed to load/migrate saved views:",{category:"persistence",operation:"load-migrate-saved-views",error:t}),this.savedViews=[]}}async saveSavedViewsToPluginData(){try{this.plugin.settings.savedViews=[...this.savedViews],await this.plugin.saveSettings()}catch(t){Fp.warn("Failed to save saved views to plugin data:",{category:"persistence",operation:"save-saved-views-plugin-data",error:t})}}needsMigration(){let r=!!this.app.loadLocalStorage(this.savedViewsStorageKey),a=this.plugin.settings.savedViews&&this.plugin.settings.savedViews.length>0;return r&&!a}async performMigration(){try{this.clearAllFilterStates(),await this.migrateAndLoadSavedViews(),this.emit("migration-complete")}catch(t){Fp.error("Error during ViewStateManager migration:",{category:"configuration",operation:"viewstatemanager-migration",error:t}),this.savedViews=[],await this.saveSavedViewsToPluginData()}}cleanup(){this.removeAllListeners()}}});var mhe,FH,gN,fhe=y(()=>{mhe=require("obsidian");Cn();q();FH=M({tag:"Services/ProjectSubtasksService"}),gN=class{constructor(e){this.cacheEventRefs=[];this.projectIndex=new Map;this.indexLastBuilt=0;this.INDEX_TTL=3e4;this.stats={indexBuilds:0,indexHits:0,indexMisses:0};this.plugin=e,this.registerCacheInvalidation()}registerCacheInvalidation(){var t;if(!((t=this.plugin.cacheManager)!=null&&t.on))return;let e=()=>this.invalidateIndex();this.cacheEventRefs=[this.plugin.cacheManager.on("file-updated",e),this.plugin.cacheManager.on("file-renamed",e),this.plugin.cacheManager.on("file-deleted",e)]}getFilesLinkingToProject(e){let t=this.plugin.app.metadataCache.resolvedLinks,r=[];for(let[a,i]of Object.entries(t))i&&i[e]>0&&r.push(a);return r}getUnresolvedProjectReferences(e){let r=this.plugin.app.metadataCache.unresolvedLinks[e];return r?Object.keys(r).filter(a=>!a.includes("#")&&!a.includes("|")):[]}async getTasksLinkedToProject(e){try{let t=this.getFilesLinkingToProject(e.path),r=[];for(let a of t){let i=await this.plugin.cacheManager.getTaskInfo(a);i&&await this.isLinkFromProjectsField(a,e.path)&&r.push(i)}return r}catch(t){return FH.error("Error getting tasks linked to project:",{category:"persistence",operation:"getting-tasks-linked-project",error:t}),[]}}async isTaskUsedAsProject(e){return this.isTaskUsedAsProjectSync(e)}async isLinkFromProjectsField(e,t){var r;try{let a=this.plugin.app.vault.getAbstractFileByPath(e);if(!(a instanceof mhe.TFile))return!1;let i=this.plugin.app.metadataCache.getFileCache(a),s=this.plugin.fieldMapper.toUserField("projects");if(!((r=i==null?void 0:i.frontmatter)!=null&&r[s]))return!1;let o=i.frontmatter[s];if(!Array.isArray(o))return!1;for(let l of o){if(!l||typeof l!="string")continue;let c=vt(l);if(c===l&&!l.startsWith("[["))continue;let d=this.plugin.app.metadataCache.getFirstLinkpathDest(c,e);if(d&&d.path===t)return!0}return!1}catch(a){return FH.error("Error checking if link is from projects field:",{category:"persistence",operation:"checking-if-link-projects-field",error:a}),!1}}isTaskUsedAsProjectSync(e){return this.ensureIndexBuilt(),this.projectIndex.has(e)?(this.stats.indexHits++,this.projectIndex.get(e)):(this.stats.indexMisses++,!1)}buildProjectIndex(){this.projectIndex.clear(),this.stats.indexBuilds++;try{let e=this.plugin.app.metadataCache.resolvedLinks,t=new Set;for(let[r,a]of Object.entries(e)){if(!a)continue;let i=this.plugin.app.metadataCache.getCache(r);if(!(i!=null&&i.frontmatter)||!this.plugin.cacheManager.isTaskFile(i.frontmatter))continue;let s=this.plugin.fieldMapper.toUserField("projects"),o=i.frontmatter[s];if(Array.isArray(o))for(let l of o){if(!l||typeof l!="string")continue;let c=vt(l);if(c===l&&!l.startsWith("[["))continue;let d=this.plugin.app.metadataCache.getFirstLinkpathDest(c,r);d&&t.add(d.path)}}for(let r of t)this.projectIndex.set(r,!0);this.indexLastBuilt=Date.now()}catch(e){FH.error("Error building project index:",{category:"persistence",operation:"building-project-index",error:e})}}ensureIndexBuilt(){Date.now()-this.indexLastBuilt>this.INDEX_TTL&&this.buildProjectIndex()}invalidateIndex(){this.projectIndex.clear(),this.indexLastBuilt=0}destroy(){for(let e of this.cacheEventRefs)this.plugin.cacheManager.offref(e);this.cacheEventRefs=[],this.invalidateIndex(),this.stats={indexBuilds:0,indexHits:0,indexMisses:0}}sortTasks(e){return e.sort((t,r)=>{let a=this.plugin.statusManager.isCompletedStatus(t.status),i=this.plugin.statusManager.isCompletedStatus(r.status);if(a!==i)return a?1:-1;let s=this.plugin.priorityManager.getPriorityWeight(t.priority),o=this.plugin.priorityManager.getPriorityWeight(r.priority);return s!==o?o-s:t.due&&r.due?new Date(t.due).getTime()-new Date(r.due).getTime():t.due?-1:r.due?1:t.title.localeCompare(r.title)})}}});var yN,hhe=y(()=>{yN=class{constructor(e){this.expandedProjects=new Set;this.collapsedDefaultExpandedProjects=new Set;this.plugin=e}isExpanded(e,t=!1){return t?!this.collapsedDefaultExpandedProjects.has(e):this.expandedProjects.has(e)}toggle(e,t=!1){return t?this.collapsedDefaultExpandedProjects.has(e)?(this.collapsedDefaultExpandedProjects.delete(e),!0):(this.collapsedDefaultExpandedProjects.add(e),this.expandedProjects.delete(e),!1):(this.collapsedDefaultExpandedProjects.delete(e),this.expandedProjects.has(e)?(this.expandedProjects.delete(e),!1):(this.expandedProjects.add(e),!0))}setExpanded(e,t,r=!1){if(r){t?this.collapsedDefaultExpandedProjects.delete(e):(this.collapsedDefaultExpandedProjects.add(e),this.expandedProjects.delete(e));return}this.collapsedDefaultExpandedProjects.delete(e),t?this.expandedProjects.add(e):this.expandedProjects.delete(e)}renamePath(e,t){e!==t&&(this.expandedProjects.delete(e)&&this.expandedProjects.add(t),this.collapsedDefaultExpandedProjects.delete(e)&&this.collapsedDefaultExpandedProjects.add(t))}getExpandedProjects(){return Array.from(this.expandedProjects)}clearAll(){this.expandedProjects.clear(),this.collapsedDefaultExpandedProjects.clear()}collapseAll(){this.clearAll()}}});var rk,vN,ghe=y(()=>{q();rk=M({tag:"Services/AutoArchiveService"}),vN=class{constructor(e){this.processorTimer=null;this.isRunning=!1;this.PROCESSOR_INTERVAL_MS=6e4;this.plugin=e}hasGoogleCalendarLink(e){return!!e.googleCalendarEventId}normalizeStatusValue(e){return typeof e=="boolean"?e?"true":"false":String(e)}getCalendarCleanupState(){let e=this.plugin.settings.googleCalendarExport;return!(e!=null&&e.enabled)||!(e!=null&&e.syncOnTaskDelete)?"skip":this.plugin.taskCalendarSyncService&&this.plugin.taskCalendarSyncService.isEnabled()?"ready":"retry"}async start(){this.stop(),this.isRunning=!0,await this.processQueue(),this.scheduleNextProcess()}stop(){this.isRunning=!1,this.processorTimer!==null&&(window.clearTimeout(this.processorTimer),this.processorTimer=null)}scheduleNextProcess(){this.isRunning&&(this.processorTimer=window.setTimeout(()=>{this.processorTimer=null,this.processQueue().catch(e=>{rk.error("Error processing auto-archive queue:",{category:"persistence",operation:"processing-auto-archive-queue",error:e})}).finally(()=>{this.isRunning&&this.scheduleNextProcess()})},this.PROCESSOR_INTERVAL_MS))}async scheduleAutoArchive(e,t){if(!t.autoArchive)return;if(e.recurrence){await this.cancelAutoArchive(e.path);return}let r=Date.now(),a=r+t.autoArchiveDelay*60*1e3,i={taskPath:e.path,statusChangeTimestamp:r,archiveAfterTimestamp:a,statusValue:t.value};await this.cancelAutoArchive(e.path);let s=await this.getQueue();s.push(i),await this.saveQueue(s)}async cancelAutoArchive(e){let t=await this.getQueue(),r=t.filter(a=>a.taskPath!==e);r.length!==t.length&&await this.saveQueue(r)}async processQueue(){let e=await this.getQueue();if(e.length===0)return;let t=Date.now(),r=[],a=[];for(let o of e)t>=o.archiveAfterTimestamp?r.push(o):a.push(o);if(r.length===0)return;let i=[];for(let o of r)try{await this.processItem(o)||i.push(o)}catch(l){rk.error(`Error processing auto-archive for ${o.taskPath}:`,{category:"persistence",operation:"processing-auto-archive",error:l}),i.push(o)}let s=[...i,...a];await this.saveQueue(s)}async processItem(e){let t=await this.plugin.cacheManager.getTaskByPath(e.taskPath);if(!t||this.normalizeStatusValue(t.status)!==this.normalizeStatusValue(e.statusValue))return!0;if(t.archived){if(this.hasGoogleCalendarLink(t)){let r=this.getCalendarCleanupState();if(r==="skip")return!0;if(r==="retry")return rk.warn(`Auto-archive Google cleanup deferred until calendar sync is ready for ${e.taskPath}`,{category:"provider",operation:"auto-archive-google-cleanup-deferred-until-calendar-sync-ready"}),!1;let a=await this.plugin.taskCalendarSyncService.deleteTaskFromCalendar(t);return a||rk.warn(`Auto-archive Google cleanup still pending for ${e.taskPath}`,{category:"provider",operation:"auto-archive-google-cleanup-still-pending"}),a}return!0}try{let r=await this.plugin.taskService.toggleArchive(t);if(r.archived&&this.hasGoogleCalendarLink(r)){e.taskPath=r.path;let a=this.getCalendarCleanupState();return a==="skip"?!0:(a==="retry"&&rk.warn(`Auto-archive Google cleanup deferred until calendar sync is ready for ${e.taskPath}`,{category:"provider",operation:"auto-archive-google-cleanup-deferred-until-calendar-sync-ready"}),!1)}return!0}catch(r){return rk.error(`Failed to archive task ${e.taskPath}:`,{category:"persistence",operation:"archive-task",error:r}),!1}}async getQueue(){let e=await this.plugin.loadData();return(e==null?void 0:e.autoArchiveQueue)||[]}async saveQueue(e){let t=await this.plugin.loadPluginDataForSafeWrite("save-auto-archive-queue");t&&(t.autoArchiveQueue=e,await this.plugin.saveData(t))}async clearQueue(){await this.saveQueue([])}async getQueueStatus(){let e=await this.getQueue();return{count:e.length,items:e}}}});function Lp(n,e){for(var t in e)n[t]=e[t];return n}function xhe(n){var e=n.parentNode;e&&e.removeChild(n)}function P(n,e,t){var r,a,i,s={};for(i in e)i=="key"?r=e[i]:i=="ref"?a=e[i]:s[i]=e[i];if(arguments.length>2&&(s.children=arguments.length>3?SN.call(arguments,2):t),typeof n=="function"&&n.defaultProps!=null)for(i in n.defaultProps)s[i]===void 0&&(s[i]=n.defaultProps[i]);return kN(n,s,r,a,null)}function kN(n,e,t,r,a){var i={type:n,props:e,key:t,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:a==null?++bhe:a};return a==null&&Be.vnode!=null&&Be.vnode(i),i}function sn(){return{current:null}}function Ot(n){return n.children}function c4e(n,e,t,r,a){var i;for(i in t)i==="children"||i==="key"||i in e||bN(n,i,null,t[i],r);for(i in e)a&&typeof e[i]!="function"||i==="children"||i==="key"||i==="value"||i==="checked"||t[i]===e[i]||bN(n,i,e[i],t[i],r)}function vhe(n,e,t){e[0]==="-"?n.setProperty(e,t==null?"":t):n[e]=t==null?"":typeof t!="number"||l4e.test(e)?t:t+"px"}function bN(n,e,t,r,a){var i;e:if(e==="style")if(typeof t=="string")n.style.cssText=t;else{if(typeof r=="string"&&(n.style.cssText=r=""),r)for(e in r)t&&e in t||vhe(n.style,e,"");if(t)for(e in t)r&&t[e]===r[e]||vhe(n.style,e,t[e])}else if(e[0]==="o"&&e[1]==="n")i=e!==(e=e.replace(/Capture$/,"")),e=e.toLowerCase()in n?e.toLowerCase().slice(2):e.slice(2),n.l||(n.l={}),n.l[e+i]=t,t?r||n.addEventListener(e,i?The:khe,i):n.removeEventListener(e,i?The:khe,i);else if(e!=="dangerouslySetInnerHTML"){if(a)e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!=="width"&&e!=="height"&&e!=="href"&&e!=="list"&&e!=="form"&&e!=="tabIndex"&&e!=="download"&&e in n)try{n[e]=t==null?"":t;break e}catch(s){}typeof t=="function"||(t==null||t===!1&&e.indexOf("-")==-1?n.removeAttribute(e):n.setAttribute(e,t))}}function khe(n){nk=!0;try{return this.l[n.type+!1](Be.event?Be.event(n):n)}finally{nk=!1}}function The(n){nk=!0;try{return this.l[n.type+!0](Be.event?Be.event(n):n)}finally{nk=!1}}function Ta(n,e){this.props=n,this.context=e}function hx(n,e){if(e==null)return n.__?hx(n.__,n.__.__k.indexOf(n)+1):null;for(var t;ee&&lh.sort(function(l,c){return l.__v.__b-c.__v.__b}));wN.__r=0}function Dhe(n,e,t,r,a,i,s,o,l,c){var d,u,p,m,f,h,g,v=r&&r.__k||Che,k=v.length;for(t.__k=[],d=0;d0?kN(m.type,m.props,m.key,m.ref?m.ref:null,m.__v):m)!=null){if(m.__=t,m.__b=t.__b+1,(p=v[d])===null||p&&m.key==p.key&&m.type===p.type)v[d]=void 0;else for(u=0;u=0;e--)if((t=n.__k[e])&&(r=Mhe(t)))return r}return null}function zH(n,e,t,r,a,i,s,o,l){var c,d,u,p,m,f,h,g,v,k,T,b,w,S,C,x=e.type;if(e.constructor!==void 0)return null;t.__h!=null&&(l=t.__h,o=e.__e=t.__e,e.__h=null,i=[o]),(c=Be.__b)&&c(e);try{e:if(typeof x=="function"){if(g=e.props,v=(c=x.contextType)&&r[c.__c],k=c?v?v.props.value:c.__:r,t.__c?h=(d=e.__c=t.__c).__=d.__E:("prototype"in x&&x.prototype.render?e.__c=d=new x(g,k):(e.__c=d=new Ta(g,k),d.constructor=x,d.render=p4e),v&&v.sub(d),d.props=g,d.state||(d.state={}),d.context=k,d.__n=r,u=d.__d=!0,d.__h=[],d._sb=[]),d.__s==null&&(d.__s=d.state),x.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=Lp({},d.__s)),Lp(d.__s,x.getDerivedStateFromProps(g,d.__s))),p=d.props,m=d.state,d.__v=e,u)x.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(x.getDerivedStateFromProps==null&&g!==p&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(g,k),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(g,d.__s,k)===!1||e.__v===t.__v){for(e.__v!==t.__v&&(d.props=g,d.state=d.__s,d.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.forEach(function(E){E&&(E.__=e)}),T=0;T{TN={},Che=[],l4e=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;SN=Che.slice,Be={__e:function(n,e,t,r){for(var a,i,s;e=e.__;)if((a=e.__c)&&!a.__)try{if((i=a.constructor)&&i.getDerivedStateFromError!=null&&(a.setState(i.getDerivedStateFromError(n)),s=a.__d),a.componentDidCatch!=null&&(a.componentDidCatch(n,r||{}),s=a.__d),s)return a.__E=a}catch(o){n=o}throw n}},bhe=0,OH=function(n){return n!=null&&n.constructor===void 0},nk=!1,Ta.prototype.setState=function(n,e){var t;t=this.__s!=null&&this.__s!==this.state?this.__s:this.__s=Lp({},this.state),typeof n=="function"&&(n=n(Lp({},t),this.props)),n&&Lp(t,n),n!=null&&this.__v&&(e&&this._sb.push(e),LH(this))},Ta.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),LH(this))},Ta.prototype.render=Ot,lh=[],whe=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,wN.__r=0,She=0});function h4e(){for(var n;n=$he.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(xN),n.__H.__h.forEach($H),n.__H.__h=[]}catch(e){n.__H.__h=[],Be.__e(e,n.__v)}}function g4e(n){var e,t=function(){clearTimeout(r),jhe&&cancelAnimationFrame(e),setTimeout(n)},r=setTimeout(t,100);jhe&&(e=requestAnimationFrame(t))}function xN(n){var e=hc,t=n.__c;typeof t=="function"&&(n.__c=void 0,t()),hc=e}function $H(n){var e=hc;n.__c=n.__(),hc=e}var f4e,hc,BH,_he,$he,jH,Fhe,Lhe,Ohe,zhe,Bhe,jhe,UH=y(()=>{Jd();$he=[],jH=[],Fhe=Be.__b,Lhe=Be.__r,Ohe=Be.diffed,zhe=Be.__c,Bhe=Be.unmount;Be.__b=function(n){hc=null,Fhe&&Fhe(n)},Be.__r=function(n){Lhe&&Lhe(n),f4e=0;var e=(hc=n.__c).__H;e&&(BH===hc?(e.__h=[],hc.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.__V=jH,t.__N=t.i=void 0})):(e.__h.forEach(xN),e.__h.forEach($H),e.__h=[])),BH=hc},Be.diffed=function(n){Ohe&&Ohe(n);var e=n.__c;e&&e.__H&&(e.__H.__h.length&&($he.push(e)!==1&&_he===Be.requestAnimationFrame||((_he=Be.requestAnimationFrame)||g4e)(h4e)),e.__H.__.forEach(function(t){t.i&&(t.__H=t.i),t.__V!==jH&&(t.__=t.__V),t.i=void 0,t.__V=jH})),BH=hc=null},Be.__c=function(n,e){e.some(function(t){try{t.__h.forEach(xN),t.__h=t.__h.filter(function(r){return!r.__||$H(r)})}catch(r){e.some(function(a){a.__h&&(a.__h=[])}),e=[],Be.__e(r,t.__v)}}),zhe&&zhe(n,e)},Be.unmount=function(n){Bhe&&Bhe(n);var e,t=n.__c;t&&t.__H&&(t.__H.__.forEach(function(r){try{xN(r)}catch(a){e=a}}),t.__H=void 0,e&&Be.__e(e,t.__v))};jhe=typeof requestAnimationFrame=="function"});function y4e(n,e){for(var t in e)n[t]=e[t];return n}function Uhe(n,e){for(var t in n)if(t!=="__source"&&!(t in e))return!0;for(var r in e)if(r!=="__source"&&n[r]!==e[r])return!0;return!1}function Hhe(n){this.props=n}function Qhe(n,e,t){return n&&(n.__c&&n.__c.__H&&(n.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),n.__c.__H=null),(n=y4e({},n)).__c!=null&&(n.__c.__P===t&&(n.__c.__P=e),n.__c=null),n.__k=n.__k&&n.__k.map(function(r){return Qhe(r,e,t)})),n}function Jhe(n,e,t){return n&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(r){return Jhe(r,e,t)}),n.__c&&n.__c.__P===e&&(n.__e&&t.insertBefore(n.__e,n.__d),n.__c.__e=!0,n.__c.__P=t)),n}function HH(){this.__u=0,this.t=null,this.__b=null}function Xhe(n){var e=n.__.__c;return e&&e.__a&&e.__a(n)}function EN(){this.u=null,this.o=null}function k4e(n){return this.getChildContext=function(){return n.context},n.children}function T4e(n){var e=this,t=n.i;e.componentWillUnmount=function(){Op(null,e.l),e.l=null,e.i=null},e.i&&e.i!==t&&e.componentWillUnmount(),n.__v?(e.l||(e.i=t,e.l={nodeType:1,parentNode:t,childNodes:[],appendChild:function(r){this.childNodes.push(r),e.i.appendChild(r)},insertBefore:function(r,a){this.childNodes.push(r),e.i.appendChild(r)},removeChild:function(r){this.childNodes.splice(this.childNodes.indexOf(r)>>>1,1),e.i.removeChild(r)}}),Op(P(k4e,{context:e.context},n.__v),e.l)):e.l&&e.componentWillUnmount()}function VH(n,e){var t=P(T4e,{__v:n,i:e});return t.containerInfo=e,t}function x4e(){}function E4e(){return this.cancelBubble}function D4e(){return this.defaultPrevented}var Vhe,hKt,v4e,Whe,qhe,b4e,w4e,S4e,C4e,Ghe,P4e,Yhe,Khe,Zhe,yx=y(()=>{Jd();Jd();UH();UH();(Hhe.prototype=new Ta).isPureReactComponent=!0,Hhe.prototype.shouldComponentUpdate=function(n,e){return Uhe(this.props,n)||Uhe(this.state,e)};Vhe=Be.__b;Be.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),Vhe&&Vhe(n)};hKt=typeof Symbol!="undefined"&&Symbol.for&&Symbol.for("react.forward_ref")||3911,v4e=Be.__e;Be.__e=function(n,e,t,r){if(n.then){for(var a,i=e;i=i.__;)if((a=i.__c)&&a.__c)return e.__e==null&&(e.__e=t.__e,e.__k=t.__k),a.__c(n,e)}v4e(n,e,t,r)};Whe=Be.unmount;Be.unmount=function(n){var e=n.__c;e&&e.__R&&e.__R(),e&&n.__h===!0&&(n.type=null),Whe&&Whe(n)},(HH.prototype=new Ta).__c=function(n,e){var t=e.__c,r=this;r.t==null&&(r.t=[]),r.t.push(t);var a=Xhe(r.__v),i=!1,s=function(){i||(i=!0,t.__R=null,a?a(o):o())};t.__R=s;var o=function(){if(!--r.__u){if(r.state.__a){var c=r.state.__a;r.__v.__k[0]=Jhe(c,c.__c.__P,c.__c.__O)}var d;for(r.setState({__a:r.__b=null});d=r.t.pop();)d.forceUpdate()}},l=e.__h===!0;r.__u++||l||r.setState({__a:r.__b=r.__v.__k[0]}),n.then(s,s)},HH.prototype.componentWillUnmount=function(){this.t=[]},HH.prototype.render=function(n,e){if(this.__b){if(this.__v.__k){var t=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=Qhe(this.__b,t,r.__O=r.__P)}this.__b=null}var a=e.__a&&P(Ot,null,n.fallback);return a&&(a.__h=null),[P(Ot,null,e.__a?null:n.children),a]};qhe=function(n,e,t){if(++t[1]===t[0]&&n.o.delete(e),n.props.revealOrder&&(n.props.revealOrder[0]!=="t"||!n.o.size))for(t=n.u;t;){for(;t.length>3;)t.pop()();if(t[1]{gge(e,n)})}function fge(n){n.isConnected&&n.getRootNode&&hge(n.getRootNode())}function hge(n){let e=tV.get(n);if(!e||!e.isConnected){if(e=n.querySelector("style[data-fullcalendar]"),!e){e=document.createElement("style"),e.setAttribute("data-fullcalendar","");let t=M4e();t&&(e.nonce=t);let r=n===document?document.head:n,a=n===document?r.querySelector("script,link[rel=stylesheet],link[as=style],style"):r.firstChild;r.insertBefore(e,a)}tV.set(n,e),A4e(e)}}function A4e(n){for(let e of mge)gge(n,e)}function gge(n,e){let{sheet:t}=n,r=t.cssRules.length;e.split("}").forEach((a,i)=>{a=a.trim(),a&&t.insertRule(a+"}",r+i)})}function M4e(){return WH===void 0&&(WH=I4e()),WH}function I4e(){let n=document.querySelector('meta[name="csp-nonce"]');if(n&&n.hasAttribute("content"))return n.getAttribute("content");let e=document.querySelector("script[nonce]");return e&&e.nonce||""}function Rx(n){n.parentNode&&n.parentNode.removeChild(n)}function Yn(n,e){if(n.closest)return n.closest(e);if(!document.documentElement.contains(n))return null;do{if(HN(n,e))return n;n=n.parentElement||n.parentNode}while(n!==null&&n.nodeType===1);return null}function HN(n,e){return(n.matches||n.matchesSelector||n.msMatchesSelector).call(n,e)}function yge(n,e){let t=n instanceof HTMLElement?[n]:n,r=[];for(let a=0;a{let r=Yn(t.target,n);r&&e.call(r,t,r)}}function pV(n,e,t,r){let a=_4e(t,r);return n.addEventListener(e,a),()=>{n.removeEventListener(e,a)}}function vge(n,e,t,r){let a;return pV(n,"mouseover",e,(i,s)=>{if(s!==a){a=s,t(i,s);let o=l=>{a=null,r(l,s),s.removeEventListener("mouseleave",o)};s.addEventListener("mouseleave",o)}})}function mV(n,e){let t=r=>{e(r),tge.forEach(a=>{n.removeEventListener(a,t)})};tge.forEach(r=>{n.addEventListener(r,t)})}function kge(n){return Object.assign({onClick:n},Tge(n))}function Tge(n){return{tabIndex:0,onKeyDown(e){(e.key==="Enter"||e.key===" ")&&(n(e),e.preventDefault())}}}function au(){return rge+=1,String(rge)}function ck(){document.body.classList.add("fc-not-allowed")}function dk(){document.body.classList.remove("fc-not-allowed")}function fV(n){n.style.userSelect="none",n.style.webkitUserSelect="none",n.addEventListener("selectstart",_x)}function hV(n){n.style.userSelect="",n.style.webkitUserSelect="",n.removeEventListener("selectstart",_x)}function gV(n){n.addEventListener("contextmenu",_x)}function yV(n){n.removeEventListener("contextmenu",_x)}function bge(n){let e=[],t=[],r,a;for(typeof n=="string"?t=n.split(/\s*,\s*/):typeof n=="function"?t=[n]:Array.isArray(n)&&(t=n),r=0;rr.replace("$"+i,a||""),n):t}function vV(n,e){return n-e}function vx(n){return n%1===0}function L4e(n){let e=n.querySelector(".fc-scrollgrid-shrink-frame"),t=n.querySelector(".fc-scrollgrid-shrink-cushion");if(!e)throw new Error("needs fc-scrollgrid-shrink-frame className");if(!t)throw new Error("needs fc-scrollgrid-shrink-cushion className");return n.getBoundingClientRect().width-e.getBoundingClientRect().width+t.getBoundingClientRect().width}function lt(n,e){return typeof n=="string"?z4e(n):typeof n=="object"&&n?age(n):typeof n=="number"?age({[e||"milliseconds"]:n}):null}function z4e(n){let e=O4e.exec(n);if(e){let t=e[1]?-1:1;return{years:0,months:0,days:t*(e[2]?parseInt(e[2],10):0),milliseconds:t*((e[3]?parseInt(e[3],10):0)*60*60*1e3+(e[4]?parseInt(e[4],10):0)*60*1e3+(e[5]?parseInt(e[5],10):0)*1e3+(e[6]?parseInt(e[6],10):0))}}return null}function age(n){let e={years:n.years||n.year||0,months:n.months||n.month||0,days:n.days||n.day||0,milliseconds:(n.hours||n.hour||0)*60*60*1e3+(n.minutes||n.minute||0)*60*1e3+(n.seconds||n.second||0)*1e3+(n.milliseconds||n.millisecond||n.ms||0)},t=n.weeks||n.week;return t&&(e.days+=t*7,e.specifiedWeeks=!0),e}function B4e(n,e){return n.years===e.years&&n.months===e.months&&n.days===e.days&&n.milliseconds===e.milliseconds}function Fx(n,e){return{years:n.years+e.years,months:n.months+e.months,days:n.days+e.days,milliseconds:n.milliseconds+e.milliseconds}}function Cge(n,e){return{years:n.years-e.years,months:n.months-e.months,days:n.days-e.days,milliseconds:n.milliseconds-e.milliseconds}}function kV(n,e){return{years:n.years*e,months:n.months*e,days:n.days*e,milliseconds:n.milliseconds*e}}function j4e(n){return ak(n)/365}function $4e(n){return ak(n)/30}function ak(n){return Ps(n)/864e5}function Ps(n){return n.years*(365*864e5)+n.months*(30*864e5)+n.days*864e5+n.milliseconds}function Lx(n,e){let t=null;for(let r=0;r=1?Math.min(a,i):a}function qH(n,e,t,r){let a=ji([e,0,1+Z4e(e,t,r)]),i=nr(n),s=Math.round(bc(a,i));return Math.floor(s/7)+1}function Z4e(n,e,t){let r=7+e-t;return-((7+ji([n,0,r]).getUTCDay()-e)%7)+r-1}function ige(n){return[n.getFullYear(),n.getMonth(),n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),n.getMilliseconds()]}function sge(n){return new Date(n[0],n[1]||0,n[2]==null?1:n[2],n[3]||0,n[4]||0,n[5]||0)}function Bp(n){return[n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()]}function ji(n){return n.length===1&&(n=n.concat([0])),new Date(Date.UTC(...n))}function bV(n){return!isNaN(n.valueOf())}function jp(n){return n.getUTCHours()*1e3*60*60+n.getUTCMinutes()*1e3*60+n.getUTCSeconds()*1e3+n.getUTCMilliseconds()}function qN(n,e,t=!1){let r=n.toISOString();return r=r.replace(".000",""),t&&(r=r.replace("T00:00:00Z","")),r.length>10&&(e==null?r=r.replace("Z",""):e!==0&&(r=r.replace("Z",SV(e,!0)))),r}function Wp(n){return n.toISOString().replace(/T.*$/,"")}function pk(n){return n.toISOString().match(/^\d{4}-\d{2}/)[0]}function wV(n){return dh(n.getUTCHours(),2)+":"+dh(n.getUTCMinutes(),2)+":"+dh(n.getUTCSeconds(),2)}function SV(n,e=!1){let t=n<0?"-":"+",r=Math.abs(n),a=Math.floor(r/60),i=Math.round(r%60);return e?`${t+dh(a,2)}:${dh(i,2)}`:`GMT${t}${a}${i?`:${dh(i,2)}`:""}`}function Ae(n,e,t){let r,a;return function(...i){if(!r)a=n.apply(this,i);else if(!Tc(r,i)){t&&t(a);let s=n.apply(this,i);(!e||!e(s,a))&&(a=s)}return r=i,a}}function mk(n,e,t){let r,a;return i=>{if(!r)a=n.call(this,i);else if(!Va(r,i)){t&&t(a);let s=n.call(this,i);(!e||!e(s,a))&&(a=s)}return r=i,a}}function oge(n,e,t){let r=Object.keys(n).length;return r===1&&n.timeZoneName==="short"?a=>SV(a.timeZoneOffset):r===0&&e.week?a=>i3e(t.computeWeekNumber(a.marker),t.weekText,t.weekTextLong,t.locale,e.week):t3e(n,e,t)}function t3e(n,e,t){n=Object.assign({},n),e=Object.assign({},e),r3e(n,e),n.timeZone="UTC";let r=new Intl.DateTimeFormat(t.locale.codes,n),a;if(e.omitZeroMinute){let i=Object.assign({},n);delete i.minute,a=new Intl.DateTimeFormat(t.locale.codes,i)}return i=>{let{marker:s}=i,o;a&&!s.getUTCMinutes()?o=a:o=r;let l=o.format(s);return n3e(l,i,n,e,t)}}function r3e(n,e){n.timeZoneName&&(n.hour||(n.hour="2-digit"),n.minute||(n.minute="2-digit")),n.timeZoneName==="long"&&(n.timeZoneName="short"),e.omitZeroMinute&&(n.second||n.millisecond)&&delete e.omitZeroMinute}function n3e(n,e,t,r,a){return n=n.replace(X4e,""),t.timeZoneName==="short"&&(n=a3e(n,a.timeZone==="UTC"||e.timeZoneOffset==null?"UTC":SV(e.timeZoneOffset))),r.omitCommas&&(n=n.replace(Q4e,"").trim()),r.omitZeroMinute&&(n=n.replace(":00","")),r.meridiem===!1?n=n.replace(DN,"").trim():r.meridiem==="narrow"?n=n.replace(DN,(i,s)=>s.toLocaleLowerCase()):r.meridiem==="short"?n=n.replace(DN,(i,s)=>`${s.toLocaleLowerCase()}m`):r.meridiem==="lowercase"&&(n=n.replace(DN,i=>i.toLocaleLowerCase())),n=n.replace(J4e," "),n=n.trim(),n}function a3e(n,e){let t=!1;return n=n.replace(e3e,()=>(t=!0,e)),t||(n+=` ${e}`),n}function i3e(n,e,t,r,a){let i=[];return a==="long"?i.push(t):(a==="short"||a==="narrow")&&i.push(e),(a==="long"||a==="short")&&i.push(" "),i.push(r.simpleNumberFormat.format(n)),r.options.direction==="rtl"&&i.reverse(),i.join("")}function s3e(n,e,t){return t.getMarkerYear(n)!==t.getMarkerYear(e)?5:t.getMarkerMonth(n)!==t.getMarkerMonth(e)?4:t.getMarkerDay(n)!==t.getMarkerDay(e)?2:jp(n)!==jp(e)?1:0}function o3e(n,e){let t={};for(let r in n)(!(r in _N)||_N[r]<=e)&&(t[r]=n[r]);return t}function l3e(n,e,t,r){let a=0;for(;a=0;i-=1){let s=n[i][r];if(typeof s=="object"&&s)a.unshift(s);else if(s!==void 0){t[r]=s;break}}a.length&&(t[r]=YN(a))}}for(let r=n.length-1;r>=0;r-=1){let a=n[r];for(let i in a)i in t||(t[i]=a[i])}return t}function Xd(n,e){let t={};for(let r in n)e(n[r],r)&&(t[r]=n[r]);return t}function To(n,e){let t={};for(let r in n)t[r]=e(n[r],r);return t}function DV(n){let e={};for(let t of n)e[t]=!0;return e}function KN(n){let e=[];for(let t in n)e.push(n[t]);return e}function Va(n,e){if(n===e)return!0;for(let t in n)if(LN.call(n,t)&&!(t in e))return!1;for(let t in e)if(LN.call(e,t)&&n[t]!==e[t])return!1;return!0}function d3e(n,e){let t=u3e(n,e);for(let r of t)if(!c3e.test(r))return!1;return!0}function u3e(n,e){let t=[];for(let r in n)LN.call(n,r)&&(r in e||t.push(r));for(let r in e)LN.call(e,r)&&n[r]!==e[r]&&t.push(r);return t}function NN(n,e,t={}){if(n===e)return!0;for(let r in e)if(!(r in n&&p3e(n[r],e[r],t[r])))return!1;for(let r in n)if(!(r in e))return!1;return!0}function p3e(n,e,t){return n===e||t===!0?!0:t?t(n,e):!1}function Pge(n,e=0,t,r=1){let a=[];t==null&&(t=Object.keys(n).length);for(let i=e;i{this.props.value!==s.value&&i.forEach(o=>{o.context=s.value,o.forceUpdate()})},this.sub=s=>{i.push(s);let o=s.componentWillUnmount;s.componentWillUnmount=()=>{i.splice(i.indexOf(s),1),o&&o.call(s)}}}return a},e}function Nge(n,e,t,r,a,i,s,o,l,c,d,u,p,m){return{dateEnv:a,nowManager:i,options:t,pluginHooks:o,emitter:d,dispatch:l,getCurrentData:c,calendarApi:u,viewSpec:n,viewApi:e,dateProfileGenerator:r,theme:s,isRtl:t.direction==="rtl",addResizeHandler(f){d.on("_resize",f)},removeResizeHandler(f){d.off("_resize",f)},createScrollResponder(f){return new ON(f,d,lt(t.scrollTime),t.scrollTimeReset)},registerInteractiveComponent:p,unregisterInteractiveComponent:m}}function g3e(n){let e=Object.create(this.prototype.propEquality);Object.assign(e,n),this.prototype.propEquality=e}function y3e(n){let e=Object.create(this.prototype.stateEquality);Object.assign(e,n),this.prototype.stateEquality=e}function Ms(n,e){typeof n=="function"?n(e):n&&(n.current=e)}function oV(n,e){var t;return!!(e.handleCustomRendering&&n&&(!((t=e.customRenderingMetaMap)===null||t===void 0)&&t[n]))}function PV(n,e,t){let r=Object.assign(Object.assign({},n.elAttrs),{ref:t});return(n.elClasses||e)&&(r.className=(n.elClasses||[]).concat(e||[]).concat(r.className||[]).filter(Boolean).join(" ")),n.elStyle&&(r.style=n.elStyle),r}function v3e(n){return!!n}function k3e(n,e){let t=n.props;return P(wx,Object.assign({renderProps:t.renderProps,generatorName:t.generatorName,customGenerator:t.customGenerator,defaultGenerator:t.defaultGenerator,renderId:n.context},e))}function T3e(n,e){let t=typeof n=="function"?n(e):n||[];return typeof t=="string"?[t]:t}function MV(n){return[`fc-${n.type}-view`,"fc-view"]}function b3e(n,e){let t=null,r=null;return n.start&&(t=e.createMarker(n.start)),n.end&&(r=e.createMarker(n.end)),!t&&!r||t&&r&&rr&&t.push({start:r,end:i.start}),i.end>r&&(r=i.end);return re.start)&&(n.start===null||e.end===null||n.start=n.start)&&(n.end===null||e.end!==null&&e.end<=n.end)}function ko(n,e){return(n.start===null||e>=n.start)&&(n.end===null||e=e.end?new Date(e.end.valueOf()-1):n}function _ge(n){let e=Math.floor(bc(n.start,n.end))||1,t=nr(n.start),r=Kr(t,e);return{start:t,end:r}}function QN(n,e=lt(0)){let t=null,r=null;if(n.end){r=nr(n.end);let a=n.end.valueOf()-r.valueOf();a&&a>=Ps(e)&&(r=Kr(r,1))}return n.start&&(t=nr(n.start),r&&r<=t&&(r=Kr(t,1))),{start:t,end:r}}function IV(n){let e=QN(n);return bc(e.start,e.end)>1}function $p(n,e,t,r){return r==="year"?lt(t.diffWholeYears(n,e),"year"):r==="month"?lt(t.diffWholeMonths(n,e),"month"):xge(n,e)}function hk(n,e,t,r){return{instanceId:au(),defId:n,range:e,forcedStartTzo:t==null?null:t,forcedEndTzo:r==null?null:r}}function C3e(n,e,t,r){for(let a=0;a!s[l.defId].recurringDef);for(let l in s){let c=s[l];if(c.recurringDef){let{duration:d}=c.recurringDef;d||(d=c.allDay?i.defaultAllDayEventDuration:i.defaultTimedEventDuration);let u=x3e(c,d,e,r,a.recurringTypes);for(let p of u){let m=hk(l,{start:p,end:r.add(p,d)});o[m.instanceId]=m}}}return{defs:s,instances:o}}function x3e(n,e,t,r,a){let s=a[n.recurringDef.typeId].expand(n.recurringDef.typeData,{start:r.subtract(t.start,e),end:t.end},r);return n.allDay&&(s=s.map(nr)),s}function Lge(n,e,t,r,a=NV(t),i,s){let{refined:o,extra:l}=zx(n,t,a),c=P3e(e,t),d=C3e(o,c,t.dateEnv,t.pluginHooks.recurringTypes);if(d){let p=sk(o,l,e?e.sourceId:"",d.allDay,!!d.duration,t,i);return p.recurringDef={typeId:d.typeId,typeData:d.typeData,duration:d.duration},{def:p,instance:null}}let u=D3e(o,c,t,r);if(u){let p=sk(o,l,e?e.sourceId:"",u.allDay,u.hasEnd,t,i),m=hk(p.defId,u.range,u.forcedStartTzo,u.forcedEndTzo);return s&&p.publicId&&s[p.publicId]&&(m.instanceId=s[p.publicId]),{def:p,instance:m}}return null}function zx(n,e,t=NV(e)){return Ox(n,t)}function NV(n){return Object.assign(Object.assign(Object.assign({},zN),E3e),n.pluginHooks.eventRefiners)}function sk(n,e,t,r,a,i,s){let o={title:n.title||"",groupId:n.groupId||"",publicId:n.id||"",url:n.url||"",recurringDef:null,defId:(s&&n.id?s[n.id]:"")||au(),sourceId:t,allDay:r,hasEnd:a,interactive:n.interactive,ui:gk(n,i),extendedProps:Object.assign(Object.assign({},n.extendedProps||{}),e)};for(let l of i.pluginHooks.eventDefMemberAdders)Object.assign(o,l(n));return Object.freeze(o.ui.classNames),Object.freeze(o.extendedProps),o}function D3e(n,e,t,r){let{allDay:a}=n,i,s=null,o=!1,l,c=null,d=n.start!=null?n.start:n.date;if(i=t.dateEnv.createMarkerMeta(d),i)s=i.marker;else if(!r)return null;return n.end!=null&&(l=t.dateEnv.createMarkerMeta(n.end)),a==null&&(e!=null?a=e:a=(!i||i.isTimeUnspecified)&&(!l||l.isTimeUnspecified)),a&&s&&(s=nr(s)),l&&(c=l.marker,a&&(c=nr(c)),s&&c<=s&&(c=null)),c?o=!0:r||(o=t.options.forceEventDuration||!1,c=t.dateEnv.add(s,a?t.options.defaultAllDayEventDuration:t.options.defaultTimedEventDuration)),{allDay:a,hasEnd:o,range:{start:s,end:c},forcedStartTzo:i?i.forcedTzo:null,forcedEndTzo:l?l.forcedTzo:null}}function P3e(n,e){let t=null;return n&&(t=n.defaultAllDay),t==null&&(t=e.options.defaultAllDay),t}function Sx(n,e,t,r,a,i){let s=Kn(),o=NV(t);for(let l of n){let c=Lge(l,e,t,r,o,a,i);c&&fh(c,s)}return s}function fh(n,e=Kn()){return e.defs[n.def.defId]=n.def,n.instance&&(e.instances[n.instance.instanceId]=n.instance),e}function Bx(n,e){let t=n.instances[e];if(t){let r=n.defs[t.defId],a=XN(n,i=>A3e(r,i));return a.defs[r.defId]=r,a.instances[t.instanceId]=t,a}return Kn()}function A3e(n,e){return!!(n.groupId&&n.groupId===e.groupId)}function Kn(){return{defs:{},instances:{}}}function JN(n,e){return{defs:Object.assign(Object.assign({},n.defs),e.defs),instances:Object.assign(Object.assign({},n.instances),e.instances)}}function XN(n,e){let t=Xd(n.defs,e),r=Xd(n.instances,a=>t[a.defId]);return{defs:t,instances:r}}function M3e(n,e){let{defs:t,instances:r}=n,a={},i={};for(let s in t)e.defs[s]||(a[s]=t[s]);for(let s in r)!e.instances[s]&&a[r[s].defId]&&(i[s]=r[s]);return{defs:a,instances:i}}function I3e(n,e){return Array.isArray(n)?Sx(n,null,e,!0):typeof n=="object"&&n?Sx([n],null,e,!0):n!=null?String(n):null}function lV(n){return Array.isArray(n)?n:typeof n=="string"?n.split(/\s+/):[]}function gk(n,e){let t=I3e(n.constraint,e);return{display:n.display||null,startEditable:n.startEditable!=null?n.startEditable:n.editable,durationEditable:n.durationEditable!=null?n.durationEditable:n.editable,constraints:t!=null?[t]:[],overlap:n.overlap!=null?n.overlap:null,allows:n.allow!=null?[n.allow]:[],backgroundColor:n.backgroundColor||n.color||"",borderColor:n.borderColor||n.color||"",textColor:n.textColor||"",classNames:(n.className||[]).concat(n.classNames||[])}}function RV(n){return n.reduce(R3e,N3e)}function R3e(n,e){return{display:e.display!=null?e.display:n.display,startEditable:e.startEditable!=null?e.startEditable:n.startEditable,durationEditable:e.durationEditable!=null?e.durationEditable:n.durationEditable,constraints:n.constraints.concat(e.constraints),overlap:typeof e.overlap=="boolean"?e.overlap:n.overlap,allows:n.allows.concat(e.allows),backgroundColor:e.backgroundColor||n.backgroundColor,borderColor:e.borderColor||n.borderColor,textColor:e.textColor||n.textColor,classNames:n.classNames.concat(e.classNames)}}function _V(n,e,t=FV(e)){let r;if(typeof n=="string"?r={url:n}:typeof n=="function"||Array.isArray(n)?r={events:n}:typeof n=="object"&&n&&(r=n),r){let{refined:a,extra:i}=Ox(r,t),s=F3e(a,e);if(s)return{_raw:n,isFetching:!1,latestFetchId:"",fetchRange:null,defaultAllDay:a.defaultAllDay,eventDataTransform:a.eventDataTransform,success:a.success,failure:a.failure,publicId:a.id||"",sourceId:au(),sourceDefId:s.sourceDefId,meta:s.meta,ui:gk(a,e),extendedProps:i}}return null}function FV(n){return Object.assign(Object.assign(Object.assign({},zN),_3e),n.pluginHooks.eventSourceRefiners)}function F3e(n,e){let t=e.pluginHooks.eventSourceDefs;for(let r=t.length-1;r>=0;r-=1){let i=t[r].parseMeta(n);if(i)return{sourceDefId:r,meta:i}}return null}function Oge(n,e,t,r,a){switch(e.type){case"RECEIVE_EVENTS":return L3e(n,t[e.sourceId],e.fetchId,e.fetchRange,e.rawEvents,a);case"RESET_RAW_EVENTS":return O3e(n,t[e.sourceId],e.rawEvents,r.activeRange,a);case"ADD_EVENTS":return z3e(n,e.eventStore,r?r.activeRange:null,a);case"RESET_EVENTS":return e.eventStore;case"MERGE_EVENTS":return JN(n,e.eventStore);case"PREV":case"NEXT":case"CHANGE_DATE":case"CHANGE_VIEW_TYPE":return r?mh(n,r.activeRange,a):n;case"REMOVE_EVENTS":return M3e(n,e.eventStore);case"REMOVE_EVENT_SOURCE":return Bge(n,e.sourceId);case"REMOVE_ALL_EVENT_SOURCES":return XN(n,i=>!i.sourceId);case"REMOVE_ALL_EVENTS":return Kn();default:return n}}function L3e(n,e,t,r,a,i){if(e&&t===e.latestFetchId){let s=Sx(zge(a,e,i),e,i);return r&&(s=mh(s,r,i)),JN(Bge(n,e.sourceId),s)}return n}function O3e(n,e,t,r,a){let{defIdMap:i,instanceIdMap:s}=j3e(n),o=Sx(zge(t,e,a),e,a,!1,i,s);return mh(o,r,a)}function zge(n,e,t){let r=t.options.eventDataTransform,a=e?e.eventDataTransform:null;return a&&(n=dge(n,a)),r&&(n=dge(n,r)),n}function dge(n,e){let t;if(!e)t=n;else{t=[];for(let r of n){let a=e(r);a?t.push(a):a==null&&t.push(r)}}return t}function z3e(n,e,t,r){return t&&(e=mh(e,t,r)),JN(n,e)}function LV(n,e,t){let{defs:r}=n,a=To(n.instances,i=>r[i.defId].allDay?i:Object.assign(Object.assign({},i),{range:{start:t.createMarker(e.toDate(i.range.start,i.forcedStartTzo)),end:t.createMarker(e.toDate(i.range.end,i.forcedEndTzo))},forcedStartTzo:t.canComputeOffset?null:i.forcedStartTzo,forcedEndTzo:t.canComputeOffset?null:i.forcedEndTzo}));return{defs:r,instances:a}}function Bge(n,e){return XN(n,t=>t.sourceId!==e)}function B3e(n,e){return{defs:n.defs,instances:Xd(n.instances,t=>!e[t.instanceId])}}function j3e(n){let{defs:e,instances:t}=n,r={},a={};for(let i in e){let s=e[i],{publicId:o}=s;o&&(r[o]=i)}for(let i in t){let s=t[i],o=e[s.defId],{publicId:l}=o;l&&(a[l]=i)}return{defIdMap:r,instanceIdMap:a}}function $3e(n,e,t){(n[e]||(n[e]=[])).push(t)}function U3e(n,e,t){t?n[e]&&(n[e]=n[e].filter(r=>r!==t)):delete n[e]}function OV(n,e){return Sx(V3e(n),null,e)}function V3e(n){let e;return n===!0?e=[{}]:Array.isArray(n)?e=n.filter(t=>t.daysOfWeek):typeof n=="object"&&n?e=[n]:e=[],e=e.map(t=>Object.assign(Object.assign({},H3e),t)),e}function eR(n,e,t){t.emitter.trigger("select",Object.assign(Object.assign({},zV(n,t)),{jsEvent:e?e.origEvent:null,view:t.viewApi||t.calendarApi.view}))}function W3e(n,e){e.emitter.trigger("unselect",{jsEvent:n?n.origEvent:null,view:e.viewApi||e.calendarApi.view})}function zV(n,e){let t={};for(let r of e.pluginHooks.dateSpanTransforms)Object.assign(t,r(n,e));return Object.assign(t,n6e(n,e.dateEnv)),t}function Cx(n,e,t){let{dateEnv:r,options:a}=t,i=e;return n?(i=nr(i),i=r.add(i,a.defaultAllDayEventDuration)):i=r.add(i,a.defaultTimedEventDuration),i}function jx(n,e,t,r){let a=BN(n.defs,e),i=Kn();for(let s in n.defs){let o=n.defs[s];i.defs[s]=q3e(o,a[s],t,r)}for(let s in n.instances){let o=n.instances[s],l=i.defs[o.defId];i.instances[s]=G3e(o,l,a[o.defId],t,r)}return i}function q3e(n,e,t,r){let a=t.standardProps||{};a.hasEnd==null&&e.durationEditable&&(t.startDelta||t.endDelta)&&(a.hasEnd=!0);let i=Object.assign(Object.assign(Object.assign({},n),a),{ui:Object.assign(Object.assign({},n.ui),a.ui)});t.extendedProps&&(i.extendedProps=Object.assign(Object.assign({},i.extendedProps),t.extendedProps));for(let s of r.pluginHooks.eventDefMutationAppliers)s(i,t,r);return!i.hasEnd&&r.options.forceEventDuration&&(i.hasEnd=!0),i}function G3e(n,e,t,r,a){let{dateEnv:i}=a,s=r.standardProps&&r.standardProps.allDay===!0,o=r.standardProps&&r.standardProps.hasEnd===!1,l=Object.assign({},n);return s&&(l.range=_ge(l.range)),r.datesDelta&&t.startEditable&&(l.range={start:i.add(l.range.start,r.datesDelta),end:i.add(l.range.end,r.datesDelta)}),r.startDelta&&t.durationEditable&&(l.range={start:i.add(l.range.start,r.startDelta),end:l.range.end}),r.endDelta&&t.durationEditable&&(l.range={start:l.range.start,end:i.add(l.range.end,r.endDelta)}),o&&(l.range={start:l.range.start,end:Cx(e.allDay,l.range.start,a)}),e.allDay&&(l.range={start:nr(l.range.start),end:nr(l.range.end)}),l.range.end$ge(t,e))}function $ge(n,e){let t=[];return e[""]&&t.push(e[""]),e[n.defId]&&t.push(e[n.defId]),t.push(n.ui),RV(t)}function Sh(n,e){let t=n.map(Y3e);return t.sort((r,a)=>wge(r,a,e)),t.map(r=>r._seg)}function Y3e(n){let{eventRange:e}=n,t=e.def,r=e.instance?e.instance.range:e.range,a=r.start?r.start.valueOf():0,i=r.end?r.end.valueOf():0;return Object.assign(Object.assign(Object.assign({},t.extendedProps),t),{id:t.publicId,start:a,end:i,duration:i-a,allDay:Number(t.allDay),_seg:n})}function K3e(n,e){let{pluginHooks:t}=e,r=t.isDraggableTransformers,{def:a,ui:i}=n.eventRange,s=i.startEditable;for(let o of r)s=o(s,a,i,e);return s}function Z3e(n,e){return n.isStart&&n.eventRange.ui.durationEditable&&e.options.eventResizableFromStart}function Q3e(n,e){return n.isEnd&&n.eventRange.ui.durationEditable}function Gp(n,e,t,r,a,i,s){let{dateEnv:o,options:l}=t,{displayEventTime:c,displayEventEnd:d}=l,u=n.eventRange.def,p=n.eventRange.instance;c==null&&(c=r!==!1),d==null&&(d=a!==!1);let m=p.range.start,f=p.range.end,h=i||n.start||n.eventRange.range.start,g=s||n.end||n.eventRange.range.end,v=nr(m).valueOf()===nr(h).valueOf(),k=nr(gc(f,-1)).valueOf()===nr(gc(g,-1)).valueOf();return c&&!u.allDay&&(v||k)?(h=v?m:h,g=k?f:g,d&&u.hasEnd?o.formatRange(h,g,e,{forcedStartTzo:i?null:p.forcedStartTzo,forcedEndTzo:s?null:p.forcedEndTzo}):o.format(h,e,{forcedTzo:i?null:p.forcedStartTzo})):""}function Is(n,e,t){let r=n.eventRange.range;return{isPast:r.end<=(t||e.start),isFuture:r.start>=(t||e.end),isToday:e&&ko(e,r.start)}}function J3e(n){let e=["fc-event"];return n.isMirror&&e.push("fc-event-mirror"),n.isDraggable&&e.push("fc-event-draggable"),(n.isStartResizable||n.isEndResizable)&&e.push("fc-event-resizable"),n.isDragging&&e.push("fc-event-dragging"),n.isResizing&&e.push("fc-event-resizing"),n.isSelected&&e.push("fc-event-selected"),n.isStart&&e.push("fc-event-start"),n.isEnd&&e.push("fc-event-end"),n.isPast&&e.push("fc-event-past"),n.isToday&&e.push("fc-event-today"),n.isFuture&&e.push("fc-event-future"),e}function $x(n){return n.instance?n.instance.instanceId:`${n.def.defId}:${n.range.start.toISOString()}`}function yk(n,e){let{def:t,instance:r}=n.eventRange,{url:a}=t;if(a)return{href:a};let{emitter:i,options:s}=e,{eventInteractive:o}=s;return o==null&&(o=t.interactive,o==null&&(o=!!i.hasHandlers("eventClick"))),o?Tge(l=>{i.trigger("eventClick",{el:l.target,event:new vr(e,t,r),jsEvent:l,view:e.viewApi})}):{}}function e6e(n,e,t){let r=t6e(n,e),{range:a}=r;if(!a.start)return null;if(!a.end){if(t==null)return null;a.end=e.add(a.start,t)}return r}function t6e(n,e){let{refined:t,extra:r}=Ox(n,X3e),a=t.start?e.createMarkerMeta(t.start):null,i=t.end?e.createMarkerMeta(t.end):null,{allDay:s}=t;return s==null&&(s=a&&a.isTimeUnspecified&&(!i||i.isTimeUnspecified)),Object.assign({range:{start:a?a.marker:null,end:i?i.marker:null},allDay:s},r)}function jV(n,e){return Rge(n.range,e.range)&&n.allDay===e.allDay&&r6e(n,e)}function r6e(n,e){for(let t in e)if(t!=="range"&&t!=="allDay"&&n[t]!==e[t])return!1;for(let t in n)if(!(t in e))return!1;return!0}function n6e(n,e){return Object.assign(Object.assign({},Uge(n.range,e,n.allDay)),{allDay:n.allDay})}function $V(n,e,t){return Object.assign(Object.assign({},Uge(n,e,t)),{timeZone:e.timeZone})}function Uge(n,e,t){return{start:e.toDate(n.start),end:e.toDate(n.end),startStr:e.formatIso(n.start,{omitTime:t}),endStr:e.formatIso(n.end,{omitTime:t})}}function a6e(n,e,t){let r=zx({editable:!1},t),a=sk(r.refined,r.extra,"",n.allDay,!0,t);return{def:a,ui:$ge(a,e),instance:hk(a.defId,n.range),range:n.range,isStart:!0,isEnd:!0}}function UV(n,e,t){let r=!1,a=function(o){r||(r=!0,e(o))},i=function(o){r||(r=!0,t(o))},s=n(a,i);s&&typeof s.then=="function"&&s.then(a,i)}function HV(n,e,t){n=n.toUpperCase();let r={method:n};return n==="GET"?e+=(e.indexOf("?")===-1?"?":"&")+new URLSearchParams(t):(r.body=new URLSearchParams(t),r.headers={"Content-Type":"application/x-www-form-urlencoded"}),fetch(e,r).then(a=>{if(a.ok)return a.json().then(i=>[i,a],()=>{throw new jN("Failure parsing JSON",a)});throw new jN("Request failed",a)})}function VV(){return YH==null&&(YH=i6e()),YH}function i6e(){if(typeof document=="undefined")return!0;let n=document.createElement("div");n.style.position="absolute",n.style.top="0px",n.style.left="0px",n.innerHTML="
",n.querySelector("table").style.height="100px",n.querySelector("div").style.height="100%",document.body.appendChild(n);let t=n.querySelector("div").offsetHeight>0;return document.body.removeChild(n),t}function Hge(n,e){return{component:n,el:e.el,useEventCenter:e.useEventCenter!=null?e.useEventCenter:!0,isHitComboAllowed:e.isHitComboAllowed||null}}function Ux(n){return{[n.component.uid]:n}}function s6e(n){let e=nr(n),t=Kr(e,1);return{start:e,end:t}}function WV(n,e){return n.left>=e.left&&n.left=e.top&&n.topt:e&&n>=e.end)}}function vk(n,e){let t=["fc-day",`fc-day-${U4e[n.dow]}`];return n.isDisabled?t.push("fc-day-disabled"):(n.isToday&&(t.push("fc-day-today"),t.push(e.getClass("today"))),n.isPast&&t.push("fc-day-past"),n.isFuture&&t.push("fc-day-future"),n.isOther&&t.push("fc-day-other")),t}function Cc(n,e,t="day",r=!0){let{dateEnv:a,options:i,calendarApi:s}=n,o=a.format(e,t==="week"?c6e:l6e);if(i.navLinks){let l=a.toDate(e),c=d=>{let u=t==="day"?i.navLinkDayClick:t==="week"?i.navLinkWeekClick:null;typeof u=="function"?u.call(s,a.toDate(e),d):(typeof u=="string"&&(t=u),s.zoomTo(e,t))};return Object.assign({title:uk(i.navLinkHint,[o,l],o),"data-navlink":""},r?kge(c):{onClick:c})}return{"aria-label":o}}function Vge(){return ZH===null&&(ZH=d6e()),ZH}function d6e(){let n=document.createElement("div");wh(n,{position:"absolute",top:-1e3,left:0,border:0,padding:0,overflow:"scroll",direction:"rtl"}),n.innerHTML="
",document.body.appendChild(n);let t=n.firstChild.getBoundingClientRect().left>n.getBoundingClientRect().left;return Rx(n),t}function Wge(){return QH||(QH=u6e()),QH}function u6e(){let n=document.createElement("div");n.style.overflow="scroll",n.style.position="absolute",n.style.top="-9999px",n.style.left="-9999px",document.body.appendChild(n);let e=qge(n);return document.body.removeChild(n),e}function qge(n){return{x:n.offsetHeight-n.clientHeight,y:n.offsetWidth-n.clientWidth}}function Gge(n,e=!1){let t=window.getComputedStyle(n),r=parseInt(t.borderLeftWidth,10)||0,a=parseInt(t.borderRightWidth,10)||0,i=parseInt(t.borderTopWidth,10)||0,s=parseInt(t.borderBottomWidth,10)||0,o=qge(n),l=o.y-r-a,c=o.x-i-s,d={borderLeft:r,borderRight:a,borderTop:i,borderBottom:s,scrollbarBottom:c,scrollbarLeft:0,scrollbarRight:0};return Vge()&&t.direction==="rtl"?d.scrollbarLeft=l:d.scrollbarRight=l,e&&(d.paddingLeft=parseInt(t.paddingLeft,10)||0,d.paddingRight=parseInt(t.paddingRight,10)||0,d.paddingTop=parseInt(t.paddingTop,10)||0,d.paddingBottom=parseInt(t.paddingBottom,10)||0),d}function KV(n,e=!1,t){let r=t?n.getBoundingClientRect():Vx(n),a=Gge(n,e),i={left:r.left+a.borderLeft+a.scrollbarLeft,right:r.right-a.borderRight-a.scrollbarRight,top:r.top+a.borderTop,bottom:r.bottom-a.borderBottom-a.scrollbarBottom};return e&&(i.left+=a.paddingLeft,i.right-=a.paddingRight,i.top+=a.paddingTop,i.bottom-=a.paddingBottom),i}function Vx(n){let e=n.getBoundingClientRect();return{left:e.left+window.scrollX,top:e.top+window.scrollY,right:e.right+window.scrollX,bottom:e.bottom+window.scrollY}}function p6e(n){let e=rR(n),t=n.getBoundingClientRect();for(let r of e){let a=tR(t,r.getBoundingClientRect());if(a)t=a;else return null}return t}function rR(n){let e=[];for(;n instanceof HTMLElement;){let t=window.getComputedStyle(n);if(t.position==="fixed")break;/(auto|scroll)/.test(t.overflow+t.overflowY+t.overflowX)&&e.push(n),n=n.parentNode}return e}function AN(n,e){let t=n.length;if(t!==e.length)return!1;for(let r=0;rt(n[a-1]))return[a,0];for(;rs)r=i+1;else return[i,1]}return[r,0]}function qx(n){let{refined:e,extra:t}=Ox(n,f6e);return{startTime:e.startTime||null,duration:e.duration||null,create:e.create!=null?e.create:!0,sourceId:e.sourceId,leftoverProps:t}}function Yge(n,e){return!n||e>10?zt({weekday:"short"}):e>1?zt({weekday:"short",month:"numeric",day:"numeric",omitCommas:!0}):zt({weekday:"long"})}function Zge(n){return n.text}function g6e(n,e,t){return n||Yge(e,t)}function MN(n,e){let t=n.activeRange;return e?t:{start:gc(t.start,n.slotMinTime.milliseconds),end:gc(t.end,n.slotMaxTime.milliseconds-864e5)}}function Gx(n,e,t){let{instances:r}=n.mutatedEvents;for(let a in r)if(!fk(e.validRange,r[a].range))return!1;return Qge({eventDrag:n},t)}function QV(n,e,t){return fk(e.validRange,n.range)?Qge({dateSelection:n},t):!1}function Qge(n,e){let t=e.getCurrentData(),r=Object.assign({businessHours:t.businessHours,dateSelection:"",eventStore:t.eventStore,eventUiBases:t.eventUiBases,eventSelection:"",eventDrag:null,eventResize:null},n);return(e.pluginHooks.isPropsValid||Jge)(r,e)}function Jge(n,e,t={},r){return!(n.eventDrag&&!y6e(n,e,t,r)||n.dateSelection&&!v6e(n,e,t,r))}function y6e(n,e,t,r){let a=e.getCurrentData(),i=n.eventDrag,s=i.mutatedEvents,o=s.defs,l=s.instances,c=BN(o,i.isEvent?n.eventUiBases:{"":a.selectionConfig});r&&(c=To(c,r));let d=B3e(n.eventStore,i.affectedEvents.instances),u=d.defs,p=d.instances,m=BN(u,n.eventUiBases);for(let f in l){let h=l[f],g=h.range,v=c[h.defId],k=o[h.defId];if(!Xge(v.constraints,g,d,n.businessHours,e))return!1;let{eventOverlap:T}=e.options,b=typeof T=="function"?T:null;for(let S in p){let C=p[S];if(ZN(g,C.range)&&(m[C.defId].overlap===!1&&i.isEvent||v.overlap===!1||b&&!b(new vr(e,u[C.defId],C),new vr(e,k,h))))return!1}let w=a.eventStore;for(let S of v.allows){let C=Object.assign(Object.assign({},t),{range:h.range,allDay:k.allDay}),x=w.defs[k.defId],E=w.instances[f],_;if(x?_=new vr(e,x,E):_=new vr(e,k),!S(zV(C,e),_))return!1}}return!0}function v6e(n,e,t,r){let a=n.eventStore,i=a.defs,s=a.instances,o=n.dateSelection,l=o.range,{selectionConfig:c}=e.getCurrentData();if(r&&(c=r(c)),!Xge(c.constraints,l,a,n.businessHours,e))return!1;let{selectOverlap:d}=e.options,u=typeof d=="function"?d:null;for(let p in s){let m=s[p];if(ZN(l,m.range)&&(c.overlap===!1||u&&!u(new vr(e,i[m.defId],m),null)))return!1}for(let p of c.allows){let m=Object.assign(Object.assign({},t),o);if(!p(zV(m,e),null))return!1}return!0}function Xge(n,e,t,r,a){for(let i of n)if(!T6e(k6e(i,e,t,r,a),e))return!1;return!0}function k6e(n,e,t,r,a){return n==="businessHours"?XH(mh(r,e,a)):typeof n=="string"?XH(XN(t,i=>i.groupId===n)):typeof n=="object"&&n?XH(mh(n,e,a)):[]}function XH(n){let{instances:e}=n,t=[];for(let r in e)t.push(e[r].range);return t}function T6e(n,e){for(let t of n)if(fk(t,e))return!0;return!1}function eye(n){let e=yge(n,".fc-scrollgrid-shrink"),t=0;for(let r of e)t=Math.max(t,L4e(r));return Math.ceil(t)}function JV(n,e){return n.liquid&&e.liquid}function tye(n,e){return e.maxHeight!=null||JV(n,e)}function rye(n,e,t,r){let{expandRows:a}=t;return typeof e.content=="function"?e.content(t):P("table",{role:"presentation",className:[e.tableClassName,n.syncRowHeights?"fc-scrollgrid-sync-table":""].join(" "),style:{minWidth:t.tableMinWidth,width:t.clientWidth,height:a?t.clientHeight:""}},t.tableColGroupNode,P(r?"thead":"tbody",{role:"presentation"},typeof e.rowContent=="function"?e.rowContent(t):e.rowContent))}function nye(n,e){return Tc(n,e,Va)}function aye(n,e){let t=[];for(let r of n){let a=r.span||1;for(let i=0;ie.eventRange.range.end?n:e}var mge,tV,WH,N4e,uh,R4e,ege,tge,rge,nge,O4e,U4e,GH,_N,DN,Q4e,J4e,X4e,e3e,rV,nV,aV,CV,wc,xV,EV,qp,Dge,LN,c3e,Age,iV,h3e,Tx,eu,sV,ON,bo,yc,Tt,wx,AV,gn,As,ph,RN,Fge,E3e,zN,N3e,_3e,tu,H3e,zp,vr,X3e,jN,YH,xx,hl,Ch,$i,Ex,KH,Dx,l6e,c6e,ZH,QH,gl,hh,Px,Ax,On,gh,Nx,kk,f6e,Kge,$N,h6e,UN,ru,yh,vh,kh,IN,lk,Ui,Up,nu,Hp,Kx,S6e,Vp,Th,Qx,eV,cV,dV,bh,XV=y(()=>{Jd();Jd();yx();mge=[],tV=new Map;typeof document!="undefined"&&hge(document);N4e=':root{--fc-small-font-size:.85em;--fc-page-bg-color:#fff;--fc-neutral-bg-color:hsla(0,0%,82%,.3);--fc-neutral-text-color:grey;--fc-border-color:#ddd;--fc-button-text-color:#fff;--fc-button-bg-color:#2c3e50;--fc-button-border-color:#2c3e50;--fc-button-hover-bg-color:#1e2b37;--fc-button-hover-border-color:#1a252f;--fc-button-active-bg-color:#1a252f;--fc-button-active-border-color:#151e27;--fc-event-bg-color:#3788d8;--fc-event-border-color:#3788d8;--fc-event-text-color:#fff;--fc-event-selected-overlay-color:rgba(0,0,0,.25);--fc-more-link-bg-color:#d0d0d0;--fc-more-link-text-color:inherit;--fc-event-resizer-thickness:8px;--fc-event-resizer-dot-total-width:8px;--fc-event-resizer-dot-border-width:1px;--fc-non-business-color:hsla(0,0%,84%,.3);--fc-bg-event-color:#8fdf82;--fc-bg-event-opacity:0.3;--fc-highlight-color:rgba(188,232,241,.3);--fc-today-bg-color:rgba(255,220,40,.15);--fc-now-indicator-color:red}.fc-not-allowed,.fc-not-allowed .fc-event{cursor:not-allowed}.fc{display:flex;flex-direction:column;font-size:1em}.fc,.fc *,.fc :after,.fc :before{box-sizing:border-box}.fc table{border-collapse:collapse;border-spacing:0;font-size:1em}.fc th{text-align:center}.fc td,.fc th{padding:0;vertical-align:top}.fc a[data-navlink]{cursor:pointer}.fc a[data-navlink]:hover{text-decoration:underline}.fc-direction-ltr{direction:ltr;text-align:left}.fc-direction-rtl{direction:rtl;text-align:right}.fc-theme-standard td,.fc-theme-standard th{border:1px solid var(--fc-border-color)}.fc-liquid-hack td,.fc-liquid-hack th{position:relative}@font-face{font-family:fcicons;font-style:normal;font-weight:400;src:url("data:application/x-font-ttf;charset=utf-8;base64,AAEAAAALAIAAAwAwT1MvMg8SBfAAAAC8AAAAYGNtYXAXVtKNAAABHAAAAFRnYXNwAAAAEAAAAXAAAAAIZ2x5ZgYydxIAAAF4AAAFNGhlYWQUJ7cIAAAGrAAAADZoaGVhB20DzAAABuQAAAAkaG10eCIABhQAAAcIAAAALGxvY2ED4AU6AAAHNAAAABhtYXhwAA8AjAAAB0wAAAAgbmFtZXsr690AAAdsAAABhnBvc3QAAwAAAAAI9AAAACAAAwPAAZAABQAAApkCzAAAAI8CmQLMAAAB6wAzAQkAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAABAAADpBgPA/8AAQAPAAEAAAAABAAAAAAAAAAAAAAAgAAAAAAADAAAAAwAAABwAAQADAAAAHAADAAEAAAAcAAQAOAAAAAoACAACAAIAAQAg6Qb//f//AAAAAAAg6QD//f//AAH/4xcEAAMAAQAAAAAAAAAAAAAAAQAB//8ADwABAAAAAAAAAAAAAgAANzkBAAAAAAEAAAAAAAAAAAACAAA3OQEAAAAAAQAAAAAAAAAAAAIAADc5AQAAAAABAWIAjQKeAskAEwAAJSc3NjQnJiIHAQYUFwEWMjc2NCcCnuLiDQ0MJAz/AA0NAQAMJAwNDcni4gwjDQwM/wANIwz/AA0NDCMNAAAAAQFiAI0CngLJABMAACUBNjQnASYiBwYUHwEHBhQXFjI3AZ4BAA0N/wAMJAwNDeLiDQ0MJAyNAQAMIw0BAAwMDSMM4uINIwwNDQAAAAIA4gC3Ax4CngATACcAACUnNzY0JyYiDwEGFB8BFjI3NjQnISc3NjQnJiIPAQYUHwEWMjc2NCcB87e3DQ0MIw3VDQ3VDSMMDQ0BK7e3DQ0MJAzVDQ3VDCQMDQ3zuLcMJAwNDdUNIwzWDAwNIwy4twwkDA0N1Q0jDNYMDA0jDAAAAgDiALcDHgKeABMAJwAAJTc2NC8BJiIHBhQfAQcGFBcWMjchNzY0LwEmIgcGFB8BBwYUFxYyNwJJ1Q0N1Q0jDA0Nt7cNDQwjDf7V1Q0N1QwkDA0Nt7cNDQwkDLfWDCMN1Q0NDCQMt7gMIw0MDNYMIw3VDQ0MJAy3uAwjDQwMAAADAFUAAAOrA1UAMwBoAHcAABMiBgcOAQcOAQcOARURFBYXHgEXHgEXHgEzITI2Nz4BNz4BNz4BNRE0JicuAScuAScuASMFITIWFx4BFx4BFx4BFREUBgcOAQcOAQcOASMhIiYnLgEnLgEnLgE1ETQ2Nz4BNz4BNz4BMxMhMjY1NCYjISIGFRQWM9UNGAwLFQkJDgUFBQUFBQ4JCRULDBgNAlYNGAwLFQkJDgUFBQUFBQ4JCRULDBgN/aoCVgQIBAQHAwMFAQIBAQIBBQMDBwQECAT9qgQIBAQHAwMFAQIBAQIBBQMDBwQECASAAVYRGRkR/qoRGRkRA1UFBAUOCQkVDAsZDf2rDRkLDBUJCA4FBQUFBQUOCQgVDAsZDQJVDRkLDBUJCQ4FBAVVAgECBQMCBwQECAX9qwQJAwQHAwMFAQICAgIBBQMDBwQDCQQCVQUIBAQHAgMFAgEC/oAZEhEZGRESGQAAAAADAFUAAAOrA1UAMwBoAIkAABMiBgcOAQcOAQcOARURFBYXHgEXHgEXHgEzITI2Nz4BNz4BNz4BNRE0JicuAScuAScuASMFITIWFx4BFx4BFx4BFREUBgcOAQcOAQcOASMhIiYnLgEnLgEnLgE1ETQ2Nz4BNz4BNz4BMxMzFRQWMzI2PQEzMjY1NCYrATU0JiMiBh0BIyIGFRQWM9UNGAwLFQkJDgUFBQUFBQ4JCRULDBgNAlYNGAwLFQkJDgUFBQUFBQ4JCRULDBgN/aoCVgQIBAQHAwMFAQIBAQIBBQMDBwQECAT9qgQIBAQHAwMFAQIBAQIBBQMDBwQECASAgBkSEhmAERkZEYAZEhIZgBEZGREDVQUEBQ4JCRUMCxkN/asNGQsMFQkIDgUFBQUFBQ4JCBUMCxkNAlUNGQsMFQkJDgUEBVUCAQIFAwIHBAQIBf2rBAkDBAcDAwUBAgICAgEFAwMHBAMJBAJVBQgEBAcCAwUCAQL+gIASGRkSgBkSERmAEhkZEoAZERIZAAABAOIAjQMeAskAIAAAExcHBhQXFjI/ARcWMjc2NC8BNzY0JyYiDwEnJiIHBhQX4uLiDQ0MJAzi4gwkDA0N4uINDQwkDOLiDCQMDQ0CjeLiDSMMDQ3h4Q0NDCMN4uIMIw0MDOLiDAwNIwwAAAABAAAAAQAAa5n0y18PPPUACwQAAAAAANivOVsAAAAA2K85WwAAAAADqwNVAAAACAACAAAAAAAAAAEAAAPA/8AAAAQAAAAAAAOrAAEAAAAAAAAAAAAAAAAAAAALBAAAAAAAAAAAAAAAAgAAAAQAAWIEAAFiBAAA4gQAAOIEAABVBAAAVQQAAOIAAAAAAAoAFAAeAEQAagCqAOoBngJkApoAAQAAAAsAigADAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAA4ArgABAAAAAAABAAcAAAABAAAAAAACAAcAYAABAAAAAAADAAcANgABAAAAAAAEAAcAdQABAAAAAAAFAAsAFQABAAAAAAAGAAcASwABAAAAAAAKABoAigADAAEECQABAA4ABwADAAEECQACAA4AZwADAAEECQADAA4APQADAAEECQAEAA4AfAADAAEECQAFABYAIAADAAEECQAGAA4AUgADAAEECQAKADQApGZjaWNvbnMAZgBjAGkAYwBvAG4Ac1ZlcnNpb24gMS4wAFYAZQByAHMAaQBvAG4AIAAxAC4AMGZjaWNvbnMAZgBjAGkAYwBvAG4Ac2ZjaWNvbnMAZgBjAGkAYwBvAG4Ac1JlZ3VsYXIAUgBlAGcAdQBsAGEAcmZjaWNvbnMAZgBjAGkAYwBvAG4Ac0ZvbnQgZ2VuZXJhdGVkIGJ5IEljb01vb24uAEYAbwBuAHQAIABnAGUAbgBlAHIAYQB0AGUAZAAgAGIAeQAgAEkAYwBvAE0AbwBvAG4ALgAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") format("truetype")}.fc-icon{speak:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;display:inline-block;font-family:fcicons!important;font-style:normal;font-variant:normal;font-weight:400;height:1em;line-height:1;text-align:center;text-transform:none;-webkit-user-select:none;-moz-user-select:none;user-select:none;width:1em}.fc-icon-chevron-left:before{content:"\\e900"}.fc-icon-chevron-right:before{content:"\\e901"}.fc-icon-chevrons-left:before{content:"\\e902"}.fc-icon-chevrons-right:before{content:"\\e903"}.fc-icon-minus-square:before{content:"\\e904"}.fc-icon-plus-square:before{content:"\\e905"}.fc-icon-x:before{content:"\\e906"}.fc .fc-button{border-radius:0;font-family:inherit;font-size:inherit;line-height:inherit;margin:0;overflow:visible;text-transform:none}.fc .fc-button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}.fc .fc-button{-webkit-appearance:button}.fc .fc-button:not(:disabled){cursor:pointer}.fc .fc-button{background-color:transparent;border:1px solid transparent;border-radius:.25em;display:inline-block;font-size:1em;font-weight:400;line-height:1.5;padding:.4em .65em;text-align:center;-webkit-user-select:none;-moz-user-select:none;user-select:none;vertical-align:middle}.fc .fc-button:hover{text-decoration:none}.fc .fc-button:focus{box-shadow:0 0 0 .2rem rgba(44,62,80,.25);outline:0}.fc .fc-button:disabled{opacity:.65}.fc .fc-button-primary{background-color:var(--fc-button-bg-color);border-color:var(--fc-button-border-color);color:var(--fc-button-text-color)}.fc .fc-button-primary:hover{background-color:var(--fc-button-hover-bg-color);border-color:var(--fc-button-hover-border-color);color:var(--fc-button-text-color)}.fc .fc-button-primary:disabled{background-color:var(--fc-button-bg-color);border-color:var(--fc-button-border-color);color:var(--fc-button-text-color)}.fc .fc-button-primary:focus{box-shadow:0 0 0 .2rem rgba(76,91,106,.5)}.fc .fc-button-primary:not(:disabled).fc-button-active,.fc .fc-button-primary:not(:disabled):active{background-color:var(--fc-button-active-bg-color);border-color:var(--fc-button-active-border-color);color:var(--fc-button-text-color)}.fc .fc-button-primary:not(:disabled).fc-button-active:focus,.fc .fc-button-primary:not(:disabled):active:focus{box-shadow:0 0 0 .2rem rgba(76,91,106,.5)}.fc .fc-button .fc-icon{font-size:1.5em;vertical-align:middle}.fc .fc-button-group{display:inline-flex;position:relative;vertical-align:middle}.fc .fc-button-group>.fc-button{flex:1 1 auto;position:relative}.fc .fc-button-group>.fc-button.fc-button-active,.fc .fc-button-group>.fc-button:active,.fc .fc-button-group>.fc-button:focus,.fc .fc-button-group>.fc-button:hover{z-index:1}.fc-direction-ltr .fc-button-group>.fc-button:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0;margin-left:-1px}.fc-direction-ltr .fc-button-group>.fc-button:not(:last-child){border-bottom-right-radius:0;border-top-right-radius:0}.fc-direction-rtl .fc-button-group>.fc-button:not(:first-child){border-bottom-right-radius:0;border-top-right-radius:0;margin-right:-1px}.fc-direction-rtl .fc-button-group>.fc-button:not(:last-child){border-bottom-left-radius:0;border-top-left-radius:0}.fc .fc-toolbar{align-items:center;display:flex;justify-content:space-between}.fc .fc-toolbar.fc-header-toolbar{margin-bottom:1.5em}.fc .fc-toolbar.fc-footer-toolbar{margin-top:1.5em}.fc .fc-toolbar-title{font-size:1.75em;margin:0}.fc-direction-ltr .fc-toolbar>*>:not(:first-child){margin-left:.75em}.fc-direction-rtl .fc-toolbar>*>:not(:first-child){margin-right:.75em}.fc-direction-rtl .fc-toolbar-ltr{flex-direction:row-reverse}.fc .fc-scroller{-webkit-overflow-scrolling:touch;position:relative}.fc .fc-scroller-liquid{height:100%}.fc .fc-scroller-liquid-absolute{bottom:0;left:0;position:absolute;right:0;top:0}.fc .fc-scroller-harness{direction:ltr;overflow:hidden;position:relative}.fc .fc-scroller-harness-liquid{height:100%}.fc-direction-rtl .fc-scroller-harness>.fc-scroller{direction:rtl}.fc-theme-standard .fc-scrollgrid{border:1px solid var(--fc-border-color)}.fc .fc-scrollgrid,.fc .fc-scrollgrid table{table-layout:fixed;width:100%}.fc .fc-scrollgrid table{border-left-style:hidden;border-right-style:hidden;border-top-style:hidden}.fc .fc-scrollgrid{border-bottom-width:0;border-collapse:separate;border-right-width:0}.fc .fc-scrollgrid-liquid{height:100%}.fc .fc-scrollgrid-section,.fc .fc-scrollgrid-section table,.fc .fc-scrollgrid-section>td{height:1px}.fc .fc-scrollgrid-section-liquid>td{height:100%}.fc .fc-scrollgrid-section>*{border-left-width:0;border-top-width:0}.fc .fc-scrollgrid-section-footer>*,.fc .fc-scrollgrid-section-header>*{border-bottom-width:0}.fc .fc-scrollgrid-section-body table,.fc .fc-scrollgrid-section-footer table{border-bottom-style:hidden}.fc .fc-scrollgrid-section-sticky>*{background:var(--fc-page-bg-color);position:sticky;z-index:3}.fc .fc-scrollgrid-section-header.fc-scrollgrid-section-sticky>*{top:0}.fc .fc-scrollgrid-section-footer.fc-scrollgrid-section-sticky>*{bottom:0}.fc .fc-scrollgrid-sticky-shim{height:1px;margin-bottom:-1px}.fc-sticky{position:sticky}.fc .fc-view-harness{flex-grow:1;position:relative}.fc .fc-view-harness-active>.fc-view{bottom:0;left:0;position:absolute;right:0;top:0}.fc .fc-col-header-cell-cushion{display:inline-block;padding:2px 4px}.fc .fc-bg-event,.fc .fc-highlight,.fc .fc-non-business{bottom:0;left:0;position:absolute;right:0;top:0}.fc .fc-non-business{background:var(--fc-non-business-color)}.fc .fc-bg-event{background:var(--fc-bg-event-color);opacity:var(--fc-bg-event-opacity)}.fc .fc-bg-event .fc-event-title{font-size:var(--fc-small-font-size);font-style:italic;margin:.5em}.fc .fc-highlight{background:var(--fc-highlight-color)}.fc .fc-cell-shaded,.fc .fc-day-disabled{background:var(--fc-neutral-bg-color)}a.fc-event,a.fc-event:hover{text-decoration:none}.fc-event.fc-event-draggable,.fc-event[href]{cursor:pointer}.fc-event .fc-event-main{position:relative;z-index:2}.fc-event-dragging:not(.fc-event-selected){opacity:.75}.fc-event-dragging.fc-event-selected{box-shadow:0 2px 7px rgba(0,0,0,.3)}.fc-event .fc-event-resizer{display:none;position:absolute;z-index:4}.fc-event-selected .fc-event-resizer,.fc-event:hover .fc-event-resizer{display:block}.fc-event-selected .fc-event-resizer{background:var(--fc-page-bg-color);border-color:inherit;border-radius:calc(var(--fc-event-resizer-dot-total-width)/2);border-style:solid;border-width:var(--fc-event-resizer-dot-border-width);height:var(--fc-event-resizer-dot-total-width);width:var(--fc-event-resizer-dot-total-width)}.fc-event-selected .fc-event-resizer:before{bottom:-20px;content:"";left:-20px;position:absolute;right:-20px;top:-20px}.fc-event-selected,.fc-event:focus{box-shadow:0 2px 5px rgba(0,0,0,.2)}.fc-event-selected:before,.fc-event:focus:before{bottom:0;content:"";left:0;position:absolute;right:0;top:0;z-index:3}.fc-event-selected:after,.fc-event:focus:after{background:var(--fc-event-selected-overlay-color);bottom:-1px;content:"";left:-1px;position:absolute;right:-1px;top:-1px;z-index:1}.fc-h-event{background-color:var(--fc-event-bg-color);border:1px solid var(--fc-event-border-color);display:block}.fc-h-event .fc-event-main{color:var(--fc-event-text-color)}.fc-h-event .fc-event-main-frame{display:flex}.fc-h-event .fc-event-time{max-width:100%;overflow:hidden}.fc-h-event .fc-event-title-container{flex-grow:1;flex-shrink:1;min-width:0}.fc-h-event .fc-event-title{display:inline-block;left:0;max-width:100%;overflow:hidden;right:0;vertical-align:top}.fc-h-event.fc-event-selected:before{bottom:-10px;top:-10px}.fc-direction-ltr .fc-daygrid-block-event:not(.fc-event-start),.fc-direction-rtl .fc-daygrid-block-event:not(.fc-event-end){border-bottom-left-radius:0;border-left-width:0;border-top-left-radius:0}.fc-direction-ltr .fc-daygrid-block-event:not(.fc-event-end),.fc-direction-rtl .fc-daygrid-block-event:not(.fc-event-start){border-bottom-right-radius:0;border-right-width:0;border-top-right-radius:0}.fc-h-event:not(.fc-event-selected) .fc-event-resizer{bottom:0;top:0;width:var(--fc-event-resizer-thickness)}.fc-direction-ltr .fc-h-event:not(.fc-event-selected) .fc-event-resizer-start,.fc-direction-rtl .fc-h-event:not(.fc-event-selected) .fc-event-resizer-end{cursor:w-resize;left:calc(var(--fc-event-resizer-thickness)*-.5)}.fc-direction-ltr .fc-h-event:not(.fc-event-selected) .fc-event-resizer-end,.fc-direction-rtl .fc-h-event:not(.fc-event-selected) .fc-event-resizer-start{cursor:e-resize;right:calc(var(--fc-event-resizer-thickness)*-.5)}.fc-h-event.fc-event-selected .fc-event-resizer{margin-top:calc(var(--fc-event-resizer-dot-total-width)*-.5);top:50%}.fc-direction-ltr .fc-h-event.fc-event-selected .fc-event-resizer-start,.fc-direction-rtl .fc-h-event.fc-event-selected .fc-event-resizer-end{left:calc(var(--fc-event-resizer-dot-total-width)*-.5)}.fc-direction-ltr .fc-h-event.fc-event-selected .fc-event-resizer-end,.fc-direction-rtl .fc-h-event.fc-event-selected .fc-event-resizer-start{right:calc(var(--fc-event-resizer-dot-total-width)*-.5)}.fc .fc-popover{box-shadow:0 2px 6px rgba(0,0,0,.15);position:absolute;z-index:9999}.fc .fc-popover-header{align-items:center;display:flex;flex-direction:row;justify-content:space-between;padding:3px 4px}.fc .fc-popover-title{margin:0 2px}.fc .fc-popover-close{cursor:pointer;font-size:1.1em;opacity:.65}.fc-theme-standard .fc-popover{background:var(--fc-page-bg-color);border:1px solid var(--fc-border-color)}.fc-theme-standard .fc-popover-header{background:var(--fc-neutral-bg-color)}';kc(N4e);uh=class{constructor(e){this.drainedOption=e,this.isRunning=!1,this.isDirty=!1,this.pauseDepths={},this.timeoutId=0}request(e){this.isDirty=!0,this.isPaused()||(this.clearTimeout(),e==null?this.tryDrain():this.timeoutId=setTimeout(this.tryDrain.bind(this),e))}pause(e=""){let{pauseDepths:t}=this;t[e]=(t[e]||0)+1,this.clearTimeout()}resume(e="",t){let{pauseDepths:r}=this;e in r&&(t?delete r[e]:(r[e]-=1,r[e]<=0&&delete r[e]),this.tryDrain())}isPaused(){return Object.keys(this.pauseDepths).length}tryDrain(){if(!this.isRunning&&!this.isPaused()){for(this.isRunning=!0;this.isDirty;)this.isDirty=!1,this.drained();this.isRunning=!1}}clear(){this.clearTimeout(),this.isDirty=!1,this.pauseDepths={}}clearTimeout(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=0)}drained(){this.drainedOption&&this.drainedOption()}};R4e=/(top|left|right|bottom|width|height)$/i;ege=0;tge=["webkitTransitionEnd","otransitionend","oTransitionEnd","msTransitionEnd","transitionend"];rge=0;nge=["years","months","days","milliseconds"],O4e=/^(-?)(?:(\d+)\.)?(\d+):(\d\d)(?::(\d\d)(?:\.(\d\d\d))?)?/;U4e=["sun","mon","tue","wed","thu","fri","sat"];GH={week:3,separator:9,omitZeroMinute:9,meridiem:9,omitCommas:9},_N={timeZoneName:7,era:6,year:5,month:4,day:2,weekday:2,hour:1,minute:1,second:1},DN=/\s*([ap])\.?m\.?/i,Q4e=/,/g,J4e=/\s+/g,X4e=/\u200e/g,e3e=/UTC|GMT/,rV=class{constructor(e){let t={},r={},a=9;for(let i in e)i in GH?(r[i]=e[i],GH[i]<9&&(a=Math.min(GH[i],a))):(t[i]=e[i],i in _N&&(a=Math.min(_N[i],a)));this.standardDateProps=t,this.extendedSettings=r,this.smallestUnitNum=a,this.buildFormattingFunc=Ae(oge)}format(e,t){return this.buildFormattingFunc(this.standardDateProps,this.extendedSettings,t)(e)}formatRange(e,t,r,a){let{standardDateProps:i,extendedSettings:s}=this,o=s3e(e.marker,t.marker,r.calendarSystem);if(!o)return this.format(e,r);let l=o;l>1&&(i.year==="numeric"||i.year==="2-digit")&&(i.month==="numeric"||i.month==="2-digit")&&(i.day==="numeric"||i.day==="2-digit")&&(l=1);let c=this.format(e,r),d=this.format(t,r);if(c===d)return c;let u=o3e(i,l),p=oge(u,s,r),m=p(e),f=p(t),h=l3e(c,m,d,f),g=s.separator||a||r.defaultSeparator||"";return h?h.before+m+g+f+h.after:c+g+d}getSmallestUnit(){switch(this.smallestUnitNum){case 7:case 6:case 5:return"year";case 4:return"month";case 3:return"week";case 2:return"day";default:return"time"}}};nV=class{constructor(e){this.cmdStr=e}format(e,t,r){return t.cmdFormatter(this.cmdStr,FN(e,null,t,r))}formatRange(e,t,r,a){return r.cmdFormatter(this.cmdStr,FN(e,t,r,a))}},aV=class{constructor(e){this.func=e}format(e,t,r){return this.func(FN(e,null,t,r))}formatRange(e,t,r,a){return this.func(FN(e,t,r,a))}};CV={navLinkDayClick:B,navLinkWeekClick:B,duration:lt,bootstrapFontAwesome:B,buttonIcons:B,customButtons:B,defaultAllDayEventDuration:lt,defaultTimedEventDuration:lt,nextDayThreshold:lt,scrollTime:lt,scrollTimeReset:Boolean,slotMinTime:lt,slotMaxTime:lt,dayPopoverFormat:zt,slotDuration:lt,snapDuration:lt,headerToolbar:B,footerToolbar:B,defaultRangeSeparator:String,titleRangeSeparator:String,forceEventDuration:Boolean,dayHeaders:Boolean,dayHeaderFormat:zt,dayHeaderClassNames:B,dayHeaderContent:B,dayHeaderDidMount:B,dayHeaderWillUnmount:B,dayCellClassNames:B,dayCellContent:B,dayCellDidMount:B,dayCellWillUnmount:B,initialView:String,aspectRatio:Number,weekends:Boolean,weekNumberCalculation:B,weekNumbers:Boolean,weekNumberClassNames:B,weekNumberContent:B,weekNumberDidMount:B,weekNumberWillUnmount:B,editable:Boolean,viewClassNames:B,viewDidMount:B,viewWillUnmount:B,nowIndicator:Boolean,nowIndicatorSnap:B,nowIndicatorClassNames:B,nowIndicatorContent:B,nowIndicatorDidMount:B,nowIndicatorWillUnmount:B,showNonCurrentDates:Boolean,lazyFetching:Boolean,startParam:String,endParam:String,timeZoneParam:String,timeZone:String,locales:B,locale:B,themeSystem:String,dragRevertDuration:Number,dragScroll:Boolean,allDayMaintainDuration:Boolean,unselectAuto:Boolean,dropAccept:B,eventOrder:bge,eventOrderStrict:Boolean,handleWindowResize:Boolean,windowResizeDelay:Number,longPressDelay:Number,eventDragMinDistance:Number,expandRows:Boolean,height:B,contentHeight:B,direction:String,weekNumberFormat:zt,eventResizableFromStart:Boolean,displayEventTime:Boolean,displayEventEnd:Boolean,weekText:String,weekTextLong:String,progressiveEventRendering:Boolean,businessHours:B,initialDate:B,now:B,eventDataTransform:B,stickyHeaderDates:B,stickyFooterScrollbar:B,viewHeight:B,defaultAllDay:Boolean,eventSourceFailure:B,eventSourceSuccess:B,eventDisplay:String,eventStartEditable:Boolean,eventDurationEditable:Boolean,eventOverlap:B,eventConstraint:B,eventAllow:B,eventBackgroundColor:String,eventBorderColor:String,eventTextColor:String,eventColor:String,eventClassNames:B,eventContent:B,eventDidMount:B,eventWillUnmount:B,selectConstraint:B,selectOverlap:B,selectAllow:B,droppable:Boolean,unselectCancel:String,slotLabelFormat:B,slotLaneClassNames:B,slotLaneContent:B,slotLaneDidMount:B,slotLaneWillUnmount:B,slotLabelClassNames:B,slotLabelContent:B,slotLabelDidMount:B,slotLabelWillUnmount:B,dayMaxEvents:B,dayMaxEventRows:B,dayMinWidth:Number,slotLabelInterval:lt,allDayText:String,allDayClassNames:B,allDayContent:B,allDayDidMount:B,allDayWillUnmount:B,slotMinWidth:Number,navLinks:Boolean,eventTimeFormat:zt,rerenderDelay:Number,moreLinkText:B,moreLinkHint:B,selectMinDistance:Number,selectable:Boolean,selectLongPressDelay:Number,eventLongPressDelay:Number,selectMirror:Boolean,eventMaxStack:Number,eventMinHeight:Number,eventMinWidth:Number,eventShortHeight:Number,slotEventOverlap:Boolean,plugins:B,firstDay:Number,dayCount:Number,dateAlignment:String,dateIncrement:lt,hiddenDays:B,fixedWeekCount:Boolean,validRange:B,visibleRange:B,titleFormat:B,eventInteractive:Boolean,noEventsText:String,viewHint:B,navLinkHint:B,closeHint:String,timeHint:String,eventHint:String,moreLinkClick:B,moreLinkClassNames:B,moreLinkContent:B,moreLinkDidMount:B,moreLinkWillUnmount:B,monthStartFormat:zt,handleCustomRendering:B,customRenderingMetaMap:B,customRenderingReplaces:Boolean},wc={eventDisplay:"auto",defaultRangeSeparator:" - ",titleRangeSeparator:" – ",defaultTimedEventDuration:"01:00:00",defaultAllDayEventDuration:{day:1},forceEventDuration:!1,nextDayThreshold:"00:00:00",dayHeaders:!0,initialView:"",aspectRatio:1.35,headerToolbar:{start:"title",center:"",end:"today prev,next"},weekends:!0,weekNumbers:!1,weekNumberCalculation:"local",editable:!1,nowIndicator:!1,scrollTime:"06:00:00",scrollTimeReset:!0,slotMinTime:"00:00:00",slotMaxTime:"24:00:00",showNonCurrentDates:!0,lazyFetching:!0,startParam:"start",endParam:"end",timeZoneParam:"timeZone",timeZone:"local",locales:[],locale:"",themeSystem:"standard",dragRevertDuration:500,dragScroll:!0,allDayMaintainDuration:!1,unselectAuto:!0,dropAccept:"*",eventOrder:"start,-duration,allDay,title",dayPopoverFormat:{month:"long",day:"numeric",year:"numeric"},handleWindowResize:!0,windowResizeDelay:100,longPressDelay:1e3,eventDragMinDistance:5,expandRows:!1,navLinks:!1,selectable:!1,eventMinHeight:15,eventMinWidth:30,eventShortHeight:30,monthStartFormat:{month:"long",day:"numeric"},nowIndicatorSnap:"auto"},xV={datesSet:B,eventsSet:B,eventAdd:B,eventChange:B,eventRemove:B,windowResize:B,eventClick:B,eventMouseEnter:B,eventMouseLeave:B,select:B,unselect:B,loading:B,_unmount:B,_beforeprint:B,_afterprint:B,_noEventDrop:B,_noEventResize:B,_resize:B,_scrollRequest:B},EV={buttonText:B,buttonHints:B,views:B,plugins:B,initialEvents:B,events:B,eventSources:B},qp={headerToolbar:ch,footerToolbar:ch,buttonText:ch,buttonHints:ch,buttonIcons:ch,dateIncrement:ch,plugins:PN,events:PN,eventSources:PN,resources:PN};Dge={type:String,component:B,buttonText:String,buttonTextKey:String,dateProfileGeneratorClass:B,usesMinMaxTime:Boolean,classNames:B,content:B,didMount:B,willUnmount:B};({hasOwnProperty:LN}=Object.prototype);c3e=/^on[A-Z]/;Age={};iV=class{getMarkerYear(e){return e.getUTCFullYear()}getMarkerMonth(e){return e.getUTCMonth()}getMarkerDay(e){return e.getUTCDate()}arrayToMarker(e){return ji(e)}markerToArray(e){return Bp(e)}};m3e("gregory",iV);h3e=/^\s*(\d{4})(-?(\d{2})(-?(\d{2})([T ](\d{2}):?(\d{2})(:?(\d{2})(\.(\d+))?)?(Z|(([-+])(\d{2})(:?(\d{2}))?))?)?)?)?$/;Tx=class{constructor(e){let t=this.timeZone=e.timeZone,r=t!=="local"&&t!=="UTC";e.namedTimeZoneImpl&&r&&(this.namedTimeZoneImpl=new e.namedTimeZoneImpl(t)),this.canComputeOffset=!!(!r||this.namedTimeZoneImpl),this.calendarSystem=f3e(e.calendarSystem),this.locale=e.locale,this.weekDow=e.locale.week.dow,this.weekDoy=e.locale.week.doy,e.weekNumberCalculation==="ISO"&&(this.weekDow=1,this.weekDoy=4),typeof e.firstDay=="number"&&(this.weekDow=e.firstDay),typeof e.weekNumberCalculation=="function"&&(this.weekNumberFunc=e.weekNumberCalculation),this.weekText=e.weekText!=null?e.weekText:e.locale.options.weekText,this.weekTextLong=(e.weekTextLong!=null?e.weekTextLong:e.locale.options.weekTextLong)||this.weekText,this.cmdFormatter=e.cmdFormatter,this.defaultSeparator=e.defaultSeparator}createMarker(e){let t=this.createMarkerMeta(e);return t===null?null:t.marker}createNowMarker(){return this.canComputeOffset?this.timestampToMarker(new Date().valueOf()):ji(ige(new Date))}createMarkerMeta(e){if(typeof e=="string")return this.parse(e);let t=null;return typeof e=="number"?t=this.timestampToMarker(e):e instanceof Date?(e=e.valueOf(),isNaN(e)||(t=this.timestampToMarker(e))):Array.isArray(e)&&(t=ji(e)),t===null||!bV(t)?null:{marker:t,isTimeUnspecified:!1,forcedTzo:null}}parse(e){let t=Mge(e);if(t===null)return null;let{marker:r}=t,a=null;return t.timeZoneOffset!==null&&(this.canComputeOffset?r=this.timestampToMarker(r.valueOf()-t.timeZoneOffset*60*1e3):a=t.timeZoneOffset),{marker:r,isTimeUnspecified:t.isTimeUnspecified,forcedTzo:a}}getYear(e){return this.calendarSystem.getMarkerYear(e)}getMonth(e){return this.calendarSystem.getMarkerMonth(e)}getDay(e){return this.calendarSystem.getMarkerDay(e)}add(e,t){let r=this.calendarSystem.markerToArray(e);return r[0]+=t.years,r[1]+=t.months,r[2]+=t.days,r[6]+=t.milliseconds,this.calendarSystem.arrayToMarker(r)}subtract(e,t){let r=this.calendarSystem.markerToArray(e);return r[0]-=t.years,r[1]-=t.months,r[2]-=t.days,r[6]-=t.milliseconds,this.calendarSystem.arrayToMarker(r)}addYears(e,t){let r=this.calendarSystem.markerToArray(e);return r[0]+=t,this.calendarSystem.arrayToMarker(r)}addMonths(e,t){let r=this.calendarSystem.markerToArray(e);return r[1]+=t,this.calendarSystem.arrayToMarker(r)}diffWholeYears(e,t){let{calendarSystem:r}=this;return jp(e)===jp(t)&&r.getMarkerDay(e)===r.getMarkerDay(t)&&r.getMarkerMonth(e)===r.getMarkerMonth(t)?r.getMarkerYear(t)-r.getMarkerYear(e):null}diffWholeMonths(e,t){let{calendarSystem:r}=this;return jp(e)===jp(t)&&r.getMarkerDay(e)===r.getMarkerDay(t)?r.getMarkerMonth(t)-r.getMarkerMonth(e)+(r.getMarkerYear(t)-r.getMarkerYear(e))*12:null}greatestWholeUnit(e,t){let r=this.diffWholeYears(e,t);return r!==null?{unit:"year",value:r}:(r=this.diffWholeMonths(e,t),r!==null?{unit:"month",value:r}:(r=Ege(e,t),r!==null?{unit:"week",value:r}:(r=ik(e,t),r!==null?{unit:"day",value:r}:(r=H4e(e,t),vx(r)?{unit:"hour",value:r}:(r=V4e(e,t),vx(r)?{unit:"minute",value:r}:(r=W4e(e,t),vx(r)?{unit:"second",value:r}:{unit:"millisecond",value:t.valueOf()-e.valueOf()}))))))}countDurationsBetween(e,t,r){let a;return r.years&&(a=this.diffWholeYears(e,t),a!==null)?a/j4e(r):r.months&&(a=this.diffWholeMonths(e,t),a!==null)?a/$4e(r):r.days&&(a=ik(e,t),a!==null)?a/ak(r):(t.valueOf()-e.valueOf())/Ps(r)}startOf(e,t){return t==="year"?this.startOfYear(e):t==="month"?this.startOfMonth(e):t==="week"?this.startOfWeek(e):t==="day"?nr(e):t==="hour"?q4e(e):t==="minute"?G4e(e):t==="second"?Y4e(e):null}startOfYear(e){return this.calendarSystem.arrayToMarker([this.calendarSystem.getMarkerYear(e)])}startOfMonth(e){return this.calendarSystem.arrayToMarker([this.calendarSystem.getMarkerYear(e),this.calendarSystem.getMarkerMonth(e)])}startOfWeek(e){return this.calendarSystem.arrayToMarker([this.calendarSystem.getMarkerYear(e),this.calendarSystem.getMarkerMonth(e),e.getUTCDate()-(e.getUTCDay()-this.weekDow+7)%7])}computeWeekNumber(e){return this.weekNumberFunc?this.weekNumberFunc(this.toDate(e)):K4e(e,this.weekDow,this.weekDoy)}format(e,t,r={}){return t.format({marker:e,timeZoneOffset:r.forcedTzo!=null?r.forcedTzo:this.offsetForMarker(e)},this)}formatRange(e,t,r,a={}){return a.isEndExclusive&&(t=gc(t,-1)),r.formatRange({marker:e,timeZoneOffset:a.forcedStartTzo!=null?a.forcedStartTzo:this.offsetForMarker(e)},{marker:t,timeZoneOffset:a.forcedEndTzo!=null?a.forcedEndTzo:this.offsetForMarker(t)},this,a.defaultSeparator)}formatIso(e,t={}){let r=null;return t.omitTimeZoneOffset||(t.forcedTzo!=null?r=t.forcedTzo:r=this.offsetForMarker(e)),qN(e,r,t.omitTime)}timestampToMarker(e){return this.timeZone==="local"?ji(ige(new Date(e))):this.timeZone==="UTC"||!this.namedTimeZoneImpl?new Date(e):ji(this.namedTimeZoneImpl.timestampToArray(e))}offsetForMarker(e){return this.timeZone==="local"?-sge(Bp(e)).getTimezoneOffset():this.timeZone==="UTC"?0:this.namedTimeZoneImpl?this.namedTimeZoneImpl.offsetForArray(Bp(e)):null}toDate(e,t){return this.timeZone==="local"?sge(Bp(e)):this.timeZone==="UTC"?new Date(e.valueOf()):this.namedTimeZoneImpl?new Date(e.valueOf()-this.namedTimeZoneImpl.offsetForArray(Bp(e))*1e3*60):new Date(e.valueOf()-(t||0))}},eu=class{constructor(e){this.iconOverrideOption&&this.setIconOverride(e[this.iconOverrideOption])}setIconOverride(e){let t,r;if(typeof e=="object"&&e){t=Object.assign({},this.iconClasses);for(r in e)t[r]=this.applyIconOverridePrefix(e[r]);this.iconClasses=t}else e===!1&&(this.iconClasses={})}applyIconOverridePrefix(e){let t=this.iconOverridePrefix;return t&&e.indexOf(t)!==0&&(e=t+e),e}getClass(e){return this.classes[e]||""}getIconClass(e,t){let r;return t&&this.rtlIconClasses?r=this.rtlIconClasses[e]||this.iconClasses[e]:r=this.iconClasses[e],r?`${this.baseIconClass} ${r}`:""}getCustomButtonIconClass(e){let t;return this.iconOverrideCustomButtonOption&&(t=e[this.iconOverrideCustomButtonOption],t)?`${this.baseIconClass} ${this.applyIconOverridePrefix(t)}`:""}};eu.prototype.classes={};eu.prototype.iconClasses={};eu.prototype.baseIconClass="";eu.prototype.iconOverridePrefix="";sV=class extends Ta{render(){return P("div",{})}componentDidMount(){this.setState({})}};ON=class{constructor(e,t,r,a){this.execFunc=e,this.emitter=t,this.scrollTime=r,this.scrollTimeReset=a,this.handleScrollRequest=i=>{this.queuedRequest=Object.assign({},this.queuedRequest||{},i),this.drain()},t.on("_scrollRequest",this.handleScrollRequest),this.fireInitialScroll()}detach(){this.emitter.off("_scrollRequest",this.handleScrollRequest)}update(e){e&&this.scrollTimeReset?this.fireInitialScroll():this.drain()}fireInitialScroll(){this.handleScrollRequest({time:this.scrollTime})}drain(){this.queuedRequest&&this.execFunc(this.queuedRequest)&&(this.queuedRequest=null)}},bo=Ige({});yc=class extends Ta{shouldComponentUpdate(e,t){return!NN(this.props,e,this.propEquality)||!NN(this.state,t,this.stateEquality)}safeSetState(e){NN(this.state,Object.assign(Object.assign({},this.state),e),this.stateEquality)||this.setState(e)}};yc.addPropsEquality=g3e;yc.addStateEquality=y3e;yc.contextType=bo;yc.prototype.propEquality={};yc.prototype.stateEquality={};Tt=class extends yc{};Tt.contextType=bo;wx=class extends Tt{constructor(){super(...arguments),this.id=au(),this.queuedDomNodes=[],this.currentDomNodes=[],this.handleEl=e=>{let{options:t}=this.context,{generatorName:r}=this.props;(!t.customRenderingReplaces||!oV(r,t))&&this.updateElRef(e)},this.updateElRef=e=>{this.props.elRef&&Ms(this.props.elRef,e)}}render(){let{props:e,context:t}=this,{options:r}=t,{customGenerator:a,defaultGenerator:i,renderProps:s}=e,o=PV(e,[],this.handleEl),l=!1,c,d=[],u;if(a!=null){let p=typeof a=="function"?a(s,P):a;if(p===!0)l=!0;else{let m=p&&typeof p=="object";m&&"html"in p?o.dangerouslySetInnerHTML={__html:p.html}:m&&"domNodes"in p?d=Array.prototype.slice.call(p.domNodes):(m?OH(p):typeof p!="function")?c=p:u=p}}else l=!oV(e.generatorName,r);return l&&i&&(c=i(s)),this.queuedDomNodes=d,this.currentGeneratorMeta=u,P(e.elTag,o,c)}componentDidMount(){this.applyQueueudDomNodes(),this.triggerCustomRendering(!0)}componentDidUpdate(){this.applyQueueudDomNodes(),this.triggerCustomRendering(!0)}componentWillUnmount(){this.triggerCustomRendering(!1)}triggerCustomRendering(e){var t;let{props:r,context:a}=this,{handleCustomRendering:i,customRenderingMetaMap:s}=a.options;if(i){let o=(t=this.currentGeneratorMeta)!==null&&t!==void 0?t:s==null?void 0:s[r.generatorName];o&&i(Object.assign(Object.assign({id:this.id,isActive:e,containerEl:this.base,reportNewContainerEl:this.updateElRef,generatorMeta:o},r),{elClasses:(r.elClasses||[]).filter(v3e)}))}}applyQueueudDomNodes(){let{queuedDomNodes:e,currentDomNodes:t}=this,r=this.base;if(!Tc(e,t)){t.forEach(Rx);for(let a of e)r.appendChild(a);this.currentDomNodes=e}}};wx.addPropsEquality({elClasses:Tc,elStyle:Va,elAttrs:d3e,renderProps:Va});AV=Ige(0),gn=class extends Ta{constructor(){super(...arguments),this.InnerContent=k3e.bind(void 0,this),this.handleEl=e=>{this.el=e,this.props.elRef&&(Ms(this.props.elRef,e),e&&this.didMountMisfire&&this.componentDidMount())}}render(){let{props:e}=this,t=T3e(e.classNameGenerator,e.renderProps);if(e.children){let r=PV(e,t,this.handleEl),a=e.children(this.InnerContent,e.renderProps,r);return e.elTag?P(e.elTag,r,a):a}else return P(wx,Object.assign(Object.assign({},e),{elRef:this.handleEl,elTag:e.elTag||"div",elClasses:(e.elClasses||[]).concat(t),renderId:this.context}))}componentDidMount(){var e,t;this.el?(t=(e=this.props).didMount)===null||t===void 0||t.call(e,Object.assign(Object.assign({},this.props.renderProps),{el:this.el})):this.didMountMisfire=!0}componentWillUnmount(){var e,t;(t=(e=this.props).willUnmount)===null||t===void 0||t.call(e,Object.assign(Object.assign({},this.props.renderProps),{el:this.el}))}};gn.contextType=AV;As=class extends Tt{render(){let{props:e,context:t}=this,{options:r}=t,a={view:t.viewApi};return P(gn,{elRef:e.elRef,elTag:e.elTag||"div",elAttrs:e.elAttrs,elClasses:[...MV(e.viewSpec),...e.elClasses||[]],elStyle:e.elStyle,renderProps:a,classNameGenerator:r.viewClassNames,generatorName:void 0,didMount:r.viewDidMount,willUnmount:r.viewWillUnmount},()=>e.children)}};ph=class{constructor(e){this.props=e,this.initHiddenDays()}buildPrev(e,t,r){let{dateEnv:a}=this.props,i=a.subtract(a.startOf(t,e.currentRangeUnit),e.dateIncrement);return this.build(i,-1,r)}buildNext(e,t,r){let{dateEnv:a}=this.props,i=a.add(a.startOf(t,e.currentRangeUnit),e.dateIncrement);return this.build(i,1,r)}build(e,t,r=!0){let{props:a}=this,i,s,o,l,c,d;return i=this.buildValidRange(),i=this.trimHiddenDays(i),r&&(e=S3e(e,i)),s=this.buildCurrentRangeInfo(e,t),o=/^(year|month|week|day)$/.test(s.unit),l=this.buildRenderRange(this.trimHiddenDays(s.range),s.unit,o),l=this.trimHiddenDays(l),c=l,a.showNonCurrentDates||(c=fi(c,s.range)),c=this.adjustActiveRange(c),c=fi(c,i),d=ZN(s.range,i),ko(l,e)||(e=l.start),{currentDate:e,validRange:i,currentRange:s.range,currentRangeUnit:s.unit,isRangeAllDay:o,activeRange:c,renderRange:l,slotMinTime:a.slotMinTime,slotMaxTime:a.slotMaxTime,isValid:d,dateIncrement:this.buildDateIncrement(s.duration)}}buildValidRange(){let e=this.props.validRangeInput,t=typeof e=="function"?e.call(this.props.calendarApi,this.props.dateEnv.toDate(this.props.nowManager.getDateMarker())):e;return this.refineRange(t)||{start:null,end:null}}buildCurrentRangeInfo(e,t){let{props:r}=this,a=null,i=null,s=null,o;return r.duration?(a=r.duration,i=r.durationUnit,s=this.buildRangeFromDuration(e,t,a,i)):(o=this.props.dayCount)?(i="day",s=this.buildRangeFromDayCount(e,t,o)):(s=this.buildCustomVisibleRange(e))?i=r.dateEnv.greatestWholeUnit(s.start,s.end).unit:(a=this.getFallbackDuration(),i=kx(a).unit,s=this.buildRangeFromDuration(e,t,a,i)),{duration:a,unit:i,range:s}}getFallbackDuration(){return lt({day:1})}adjustActiveRange(e){let{dateEnv:t,usesMinMaxTime:r,slotMinTime:a,slotMaxTime:i}=this.props,{start:s,end:o}=e;return r&&(ak(a)<0&&(s=nr(s),s=t.add(s,a)),ak(i)>1&&(o=nr(o),o=Kr(o,-1),o=t.add(o,i))),{start:s,end:o}}buildRangeFromDuration(e,t,r,a){let{dateEnv:i,dateAlignment:s}=this.props,o,l,c;if(!s){let{dateIncrement:u}=this.props;u&&Ps(u){bx(()=>{this.setState({forPrint:!0})})},this.handleAfterPrint=()=>{bx(()=>{this.setState({forPrint:!1})})}}render(){let{props:e}=this,{options:t}=e,{forPrint:r}=this.state,a=r||t.height==="auto"||t.contentHeight==="auto",i=!a&&t.height!=null?t.height:"",s=["fc",r?"fc-media-print":"fc-media-screen",`fc-direction-${t.direction}`,e.theme.getClass("root")];return VV()||s.push("fc-liquid-hack"),e.children(s,i,a,r)}componentDidMount(){let{emitter:e}=this.props;e.on("_beforeprint",this.handleBeforePrint),e.on("_afterprint",this.handleAfterPrint)}componentWillUnmount(){let{emitter:e}=this.props;e.off("_beforeprint",this.handleBeforePrint),e.off("_afterprint",this.handleAfterPrint)}},hl=class{constructor(e){this.component=e.component,this.isHitComboAllowed=e.isHitComboAllowed||null}destroy(){}};Ch={},$i=class extends Ta{constructor(e,t){super(e,t),this.handleRefresh=()=>{let r=this.computeTiming();r.state.nowDate.valueOf()!==this.state.nowDate.valueOf()&&this.setState(r.state),this.clearTimeout(),this.setTimeout(r.waitMs)},this.handleVisibilityChange=()=>{document.hidden||this.handleRefresh()},this.state=this.computeTiming().state}render(){let{props:e,state:t}=this;return e.children(t.nowDate,t.todayRange)}componentDidMount(){this.setTimeout(),this.context.nowManager.addResetListener(this.handleRefresh),document.addEventListener("visibilitychange",this.handleVisibilityChange)}componentDidUpdate(e){e.unit!==this.props.unit&&(this.clearTimeout(),this.setTimeout())}componentWillUnmount(){this.clearTimeout(),this.context.nowManager.removeResetListener(this.handleRefresh),document.removeEventListener("visibilitychange",this.handleVisibilityChange)}computeTiming(){let{props:e,context:t}=this,r=t.nowManager.getDateMarker(),{nowIndicatorSnap:a}=t.options;a==="auto"&&(a=/year|month|week|day/.test(e.unit)||(e.unitValue||1)===1);let i,s;return a?(i=t.dateEnv.startOf(r,e.unit),s=t.dateEnv.add(i,lt(1,e.unit)).valueOf()-r.valueOf()):(i=r,s=1e3*60),s=Math.min(1e3*60*60*24,s),{state:{nowDate:i,todayRange:s6e(i)},waitMs:s}}setTimeout(e=this.computeTiming().waitMs){this.timeoutId=setTimeout(()=>{let t=this.computeTiming();this.setState(t.state,()=>{this.setTimeout(t.waitMs)})},e)}clearTimeout(){this.timeoutId&&clearTimeout(this.timeoutId)}};$i.contextType=bo;Ex=class{getCurrentData(){return this.currentDataManager.getCurrentData()}dispatch(e){this.currentDataManager.dispatch(e)}get view(){return this.getCurrentData().viewApi}batchRendering(e){e()}updateSize(){this.trigger("_resize",!0)}setOption(e,t){this.dispatch({type:"SET_OPTION",optionName:e,rawOptionValue:t})}getOption(e){return this.currentDataManager.currentCalendarOptionsInput[e]}getAvailableLocaleCodes(){return Object.keys(this.getCurrentData().availableRawLocales)}on(e,t){let{currentDataManager:r}=this;r.currentCalendarOptionsRefiners[e]?r.emitter.on(e,t):console.warn(`Unknown listener name '${e}'`)}off(e,t){this.currentDataManager.emitter.off(e,t)}trigger(e,...t){this.currentDataManager.emitter.trigger(e,...t)}changeView(e,t){this.batchRendering(()=>{if(this.unselect(),t)if(t.start&&t.end)this.dispatch({type:"CHANGE_VIEW_TYPE",viewType:e}),this.dispatch({type:"SET_OPTION",optionName:"visibleRange",rawOptionValue:t});else{let{dateEnv:r}=this.getCurrentData();this.dispatch({type:"CHANGE_VIEW_TYPE",viewType:e,dateMarker:r.createMarker(t)})}else this.dispatch({type:"CHANGE_VIEW_TYPE",viewType:e})})}zoomTo(e,t){let r=this.getCurrentData(),a;t=t||"day",a=r.viewSpecs[t]||this.getUnitViewSpec(t),this.unselect(),a?this.dispatch({type:"CHANGE_VIEW_TYPE",viewType:a.type,dateMarker:e}):this.dispatch({type:"CHANGE_DATE",dateMarker:e})}getUnitViewSpec(e){let{viewSpecs:t,toolbarConfig:r}=this.getCurrentData(),a=[].concat(r.header?r.header.viewsWithButtons:[],r.footer?r.footer.viewsWithButtons:[]),i,s;for(let o in t)a.push(o);for(i=0;i{this.dispatch({type:"REMOVE_EVENTS",eventStore:jge(e)})}})}getEventById(e){let t=this.getCurrentData(),{defs:r,instances:a}=t.eventStore;e=String(e);for(let i in r){let s=r[i];if(s.publicId===e){if(s.recurringDef)return new vr(t,s,null);for(let o in a){let l=a[o];if(l.defId===s.defId)return new vr(t,s,l)}}}return null}getEvents(){let e=this.getCurrentData();return Sc(e.eventStore,e)}removeAllEvents(){this.dispatch({type:"REMOVE_ALL_EVENTS"})}getEventSources(){let e=this.getCurrentData(),t=e.eventSources,r=[];for(let a in t)r.push(new zp(e,t[a]));return r}getEventSourceById(e){let t=this.getCurrentData(),r=t.eventSources;e=String(e);for(let a in r)if(r[a].publicId===e)return new zp(t,r[a]);return null}addEventSource(e){let t=this.getCurrentData();if(e instanceof zp)return t.eventSources[e.internalEventSource.sourceId]||this.dispatch({type:"ADD_EVENT_SOURCES",sources:[e.internalEventSource]}),e;let r=_V(e,t);return r?(this.dispatch({type:"ADD_EVENT_SOURCES",sources:[r]}),new zp(t,r)):null}removeAllEventSources(){this.dispatch({type:"REMOVE_ALL_EVENT_SOURCES"})}refetchEvents(){this.dispatch({type:"FETCH_EVENT_SOURCES",isRefetch:!0})}scrollToTime(e){let t=lt(e);t&&this.trigger("_scrollRequest",{time:t})}};KH=Kn(),Dx=class{constructor(){this.getKeysForEventDefs=Ae(this._getKeysForEventDefs),this.splitDateSelection=Ae(this._splitDateSpan),this.splitEventStore=Ae(this._splitEventStore),this.splitIndividualUi=Ae(this._splitIndividualUi),this.splitEventDrag=Ae(this._splitInteraction),this.splitEventResize=Ae(this._splitInteraction),this.eventUiBuilders={}}splitProps(e){let t=this.getKeyInfo(e),r=this.getKeysForEventDefs(e.eventStore),a=this.splitDateSelection(e.dateSelection),i=this.splitIndividualUi(e.eventUiBases,r),s=this.splitEventStore(e.eventStore,r),o=this.splitEventDrag(e.eventDrag),l=this.splitEventResize(e.eventResize),c={};this.eventUiBuilders=To(t,(d,u)=>this.eventUiBuilders[u]||Ae(o6e));for(let d in t){let u=t[d],p=s[d]||KH,m=this.eventUiBuilders[d];c[d]={businessHours:u.businessHours||e.businessHours,dateSelection:a[d]||null,eventStore:p,eventUiBases:m(e.eventUiBases[""],u.ui,i[d]),eventSelection:p.instances[e.eventSelection]?e.eventSelection:"",eventDrag:o[d]||null,eventResize:l[d]||null}}return c}_splitDateSpan(e){let t={};if(e){let r=this.getKeysForDateSpan(e);for(let a of r)t[a]=e}return t}_getKeysForEventDefs(e){return To(e.defs,t=>this.getKeysForEventDef(t))}_splitEventStore(e,t){let{defs:r,instances:a}=e,i={};for(let s in r)for(let o of t[s])i[o]||(i[o]=Kn()),i[o].defs[s]=r[s];for(let s in a){let o=a[s];for(let l of t[o.defId])i[l]&&(i[l].instances[s]=o)}return i}_splitIndividualUi(e,t){let r={};for(let a in e)if(a)for(let i of t[a])r[i]||(r[i]={}),r[i][a]=e[a];return r}_splitInteraction(e){let t={};if(e){let r=this._splitEventStore(e.affectedEvents,this._getKeysForEventDefs(e.affectedEvents)),a=this._getKeysForEventDefs(e.mutatedEvents),i=this._splitEventStore(e.mutatedEvents,a),s=o=>{t[o]||(t[o]={affectedEvents:r[o]||KH,mutatedEvents:i[o]||KH,isEvent:e.isEvent})};for(let o in r)s(o);for(let o in i)s(o)}return t}};l6e=zt({year:"numeric",month:"long",day:"numeric"}),c6e=zt({week:"long"});ZH=null;gl=class{constructor(e,t,r,a){this.els=t;let i=this.originClientRect=e.getBoundingClientRect();r&&this.buildElHorizontals(i.left),a&&this.buildElVerticals(i.top)}buildElHorizontals(e){let t=[],r=[];for(let a of this.els){let i=a.getBoundingClientRect();t.push(i.left-e),r.push(i.right-e)}this.lefts=t,this.rights=r}buildElVerticals(e){let t=[],r=[];for(let a of this.els){let i=a.getBoundingClientRect();t.push(i.top-e),r.push(i.bottom-e)}this.tops=t,this.bottoms=r}leftToIndex(e){let{lefts:t,rights:r}=this,a=t.length,i;for(i=0;i=t[i]&&e=t[i]&&e0}canScrollHorizontally(){return this.getMaxScrollLeft()>0}canScrollUp(){return this.getScrollTop()>0}canScrollDown(){return this.getScrollTop()0}canScrollRight(){return this.getScrollLeft()t.thickness||1){this.getEntryThickness=e,this.strictOrder=!1,this.allowReslicing=!1,this.maxCoord=-1,this.maxStackCnt=-1,this.levelCoords=[],this.entriesByLevel=[],this.stackCnts={}}addSegs(e){let t=[];for(let r of e)this.insertEntry(r,t);return t}insertEntry(e,t){let r=this.findInsertion(e);this.isInsertionValid(r,e)?this.insertEntryAt(e,r):this.handleInvalidInsertion(r,e,t)}isInsertionValid(e,t){return(this.maxCoord===-1||e.levelCoord+this.getEntryThickness(t)<=this.maxCoord)&&(this.maxStackCnt===-1||e.stackCnti.end&&this.insertEntry({index:e.index,thickness:e.thickness,span:{start:i.end,end:a.end}},r)}insertEntryAt(e,t){let{entriesByLevel:r,levelCoords:a}=this;t.lateral===-1?(JH(a,t.level,t.levelCoord),JH(r,t.level,[e])):JH(r[t.level],t.lateral,e),this.stackCnts[vc(e)]=t.stackCnt}findInsertion(e){let{levelCoords:t,entriesByLevel:r,strictOrder:a,stackCnts:i}=this,s=t.length,o=0,l=-1,c=-1,d=null,u=0;for(let f=0;f=o+this.getEntryThickness(e))break;let g=r[f],v,k=Ix(g,e.span.start,Mx),T=k[0]+k[1];for(;(v=g[T])&&v.span.starto&&(o=b,d=v,l=f,c=T),b===o&&(u=Math.max(u,i[vc(v)]+1)),T+=1}}let p=0;if(d)for(p=l+1;p1?Cc(this.context,s):{},p=e.toDate(s);e.namedTimeZoneImpl&&(p=gc(p,36e5));let m=Object.assign(Object.assign(Object.assign({date:p,view:a},i.extraRenderProps),{text:d}),l);return P(gn,{elTag:"th",elClasses:c,elAttrs:Object.assign({role:"columnheader",colSpan:i.colSpan,"data-date":l.isDisabled?void 0:Wp(s)},i.extraDataAttrs),renderProps:m,generatorName:"dayHeaderContent",customGenerator:t.dayHeaderContent,defaultGenerator:Zge,classNameGenerator:t.dayHeaderClassNames,didMount:t.dayHeaderDidMount,willUnmount:t.dayHeaderWillUnmount},f=>P("div",{className:"fc-scrollgrid-sync-inner"},!l.isDisabled&&P(f,{elTag:"a",elAttrs:u,elClasses:["fc-col-header-cell-cushion",i.isSticky&&"fc-sticky"]})))}},h6e=zt({weekday:"long"}),UN=class extends Tt{render(){let{props:e}=this,{dateEnv:t,theme:r,viewApi:a,options:i}=this.context,s=Kr(new Date(2592e5),e.dow),o={dow:e.dow,isDisabled:!1,isFuture:!1,isPast:!1,isToday:!1,isOther:!1},l=t.format(s,e.dayHeaderFormat),c=Object.assign(Object.assign(Object.assign(Object.assign({date:s},o),{view:a}),e.extraRenderProps),{text:l});return P(gn,{elTag:"th",elClasses:[Kge,...vk(o,r),...e.extraClassNames||[]],elAttrs:Object.assign({role:"columnheader",colSpan:e.colSpan},e.extraDataAttrs),renderProps:c,generatorName:"dayHeaderContent",customGenerator:i.dayHeaderContent,defaultGenerator:Zge,classNameGenerator:i.dayHeaderClassNames,didMount:i.dayHeaderDidMount,willUnmount:i.dayHeaderWillUnmount},d=>P("div",{className:"fc-scrollgrid-sync-inner"},P(d,{elTag:"a",elClasses:["fc-col-header-cell-cushion",e.isSticky&&"fc-sticky"],elAttrs:{"aria-label":t.format(s,h6e)}})))}},ru=class extends Tt{constructor(){super(...arguments),this.createDayHeaderFormatter=Ae(g6e)}render(){let{context:e}=this,{dates:t,dateProfile:r,datesRepDistinctDays:a,renderIntro:i}=this.props,s=this.createDayHeaderFormatter(e.options.dayHeaderFormat,a,t.length);return P($i,{unit:"day"},(o,l)=>P("tr",{role:"row"},i&&i("day"),t.map(c=>a?P($N,{key:c.toISOString(),date:c,dateProfile:r,todayRange:l,colCnt:t.length,dayHeaderFormat:s}):P(UN,{key:c.getUTCDay(),dow:c.getUTCDay(),dayHeaderFormat:s}))))}};yh=class{constructor(e,t){let r=e.start,{end:a}=e,i=[],s=[],o=-1;for(;r=t.length?t[t.length-1]+1:t[r]}},vh=class{constructor(e,t){let{dates:r}=e,a,i,s;if(t){for(i=r[0].getUTCDay(),a=1;a{this.el=e,Ms(this.props.elRef,e)}}render(){let{props:e}=this,{liquid:t,liquidIsAbsolute:r}=e,a=t&&r,i=["fc-scroller"];return t&&(r?i.push("fc-scroller-liquid-absolute"):i.push("fc-scroller-liquid")),P("div",{ref:this.handleEl,className:i.join(" "),style:{overflowX:e.overflowX,overflowY:e.overflowY,left:a&&-(e.overcomeLeft||0)||"",right:a&&-(e.overcomeRight||0)||"",bottom:a&&-(e.overcomeBottom||0)||"",marginLeft:!a&&-(e.overcomeLeft||0)||"",marginRight:!a&&-(e.overcomeRight||0)||"",marginBottom:!a&&-(e.overcomeBottom||0)||"",maxHeight:e.maxHeight||""}},e.children)}needsXScrolling(){if(IN.test(this.props.overflowX))return!1;let{el:e}=this,t=this.el.getBoundingClientRect().width-this.getYScrollbarWidth(),{children:r}=e;for(let a=0;at)return!0;return!1}needsYScrolling(){if(IN.test(this.props.overflowY))return!1;let{el:e}=this,t=this.el.getBoundingClientRect().height-this.getXScrollbarWidth(),{children:r}=e;for(let a=0;at)return!0;return!1}getXScrollbarWidth(){return IN.test(this.props.overflowX)?0:this.el.offsetHeight-this.el.clientHeight}getYScrollbarWidth(){return IN.test(this.props.overflowY)?0:this.el.offsetWidth-this.el.clientWidth}},Ui=class{constructor(e){this.masterCallback=e,this.currentMap={},this.depths={},this.callbackMap={},this.handleValue=(t,r)=>{let{depths:a,currentMap:i}=this,s=!1,o=!1;t!==null?(s=r in i,i[r]=t,a[r]=(a[r]||0)+1,o=!0):(a[r]-=1,a[r]||(delete i[r],delete this.callbackMap[r],s=!0)),this.masterCallback&&(s&&this.masterCallback(null,String(r)),o&&this.masterCallback(t,String(r)))}}createRef(e){let t=this.callbackMap[e];return t||(t=this.callbackMap[e]=r=>{this.handleValue(r,String(e))}),t}collect(e,t,r){return Pge(this.currentMap,e,t,r)}getAll(){return KN(this.currentMap)}};Up=class extends Tt{constructor(){super(...arguments),this.processCols=Ae(e=>e,nye),this.renderMicroColGroup=Ae(aye),this.scrollerRefs=new Ui,this.scrollerElRefs=new Ui(this._handleScrollerEl.bind(this)),this.state={shrinkWidth:null,forceYScrollbars:!1,scrollerClientWidths:{},scrollerClientHeights:{}},this.handleSizing=()=>{this.safeSetState(Object.assign({shrinkWidth:this.computeShrinkWidth()},this.computeScrollerDims()))}}render(){let{props:e,state:t,context:r}=this,a=e.sections||[],i=this.processCols(e.cols),s=this.renderMicroColGroup(i,t.shrinkWidth),o=oye(e.liquid,r);e.collapsibleWidth&&o.push("fc-scrollgrid-collapsible");let l=a.length,c=0,d,u=[],p=[],m=[];for(;c{}},a);return P(a?"th":"td",{ref:r.elRef,role:"presentation"},P("div",{className:`fc-scroller-harness${d?" fc-scroller-harness-liquid":""}`},P(lk,{ref:this.scrollerRefs.createRef(p),elRef:this.scrollerElRefs.createRef(p),overflowY:u,overflowX:i.liquid?"hidden":"visible",maxHeight:e.maxHeight,liquid:d,liquidIsAbsolute:!0},m)))}_handleScrollerEl(e,t){let r=b6e(this.props.sections,t);r&&Ms(r.chunk.scrollerElRef,e)}componentDidMount(){this.handleSizing(),this.context.addResizeHandler(this.handleSizing)}componentDidUpdate(){this.handleSizing()}componentWillUnmount(){this.context.removeResizeHandler(this.handleSizing)}computeShrinkWidth(){return sye(this.props.cols)?eye(this.scrollerElRefs.getAll()):0}computeScrollerDims(){let e=Wge(),{scrollerRefs:t,scrollerElRefs:r}=this,a=!1,i={},s={};for(let o in t.currentMap){let l=t.currentMap[o];if(l&&l.needsYScrolling()){a=!0;break}}for(let o of this.props.sections){let l=o.key,c=r.currentMap[l];if(c){let d=c.parentNode;i[l]=Math.floor(d.getBoundingClientRect().width-(a?e.y:0)),s[l]=Math.floor(d.getBoundingClientRect().height)}}return{forceYScrollbars:a,scrollerClientWidths:i,scrollerClientHeights:s}}};Up.addStateEquality({scrollerClientWidths:Va,scrollerClientHeights:Va});nu=class extends Tt{constructor(){super(...arguments),this.buildPublicEvent=Ae((e,t,r)=>new vr(e,t,r)),this.handleEl=e=>{this.el=e,Ms(this.props.elRef,e),e&&uge(e,this.props.seg)}}render(){let{props:e,context:t}=this,{options:r}=t,{seg:a}=e,{eventRange:i}=a,{ui:s}=i,o={event:this.buildPublicEvent(t,i.def,i.instance),view:t.viewApi,timeText:e.timeText,textColor:s.textColor,backgroundColor:s.backgroundColor,borderColor:s.borderColor,isDraggable:!e.disableDragging&&K3e(a,t),isStartResizable:!e.disableResizing&&Z3e(a,t),isEndResizable:!e.disableResizing&&Q3e(a),isMirror:!!(e.isDragging||e.isResizing||e.isDateSelecting),isStart:!!a.isStart,isEnd:!!a.isEnd,isPast:!!e.isPast,isFuture:!!e.isFuture,isToday:!!e.isToday,isSelected:!!e.isSelected,isDragging:!!e.isDragging,isResizing:!!e.isResizing};return P(gn,{elRef:this.handleEl,elTag:e.elTag,elAttrs:e.elAttrs,elClasses:[...J3e(o),...a.eventRange.ui.classNames,...e.elClasses||[]],elStyle:e.elStyle,renderProps:o,generatorName:"eventContent",customGenerator:r.eventContent,defaultGenerator:e.defaultGenerator,classNameGenerator:r.eventClassNames,didMount:r.eventDidMount,willUnmount:r.eventWillUnmount},e.children)}componentDidUpdate(e){this.el&&this.props.seg!==e.seg&&uge(this.el,this.props.seg)}},Hp=class extends Tt{render(){let{props:e,context:t}=this,{options:r}=t,{seg:a}=e,{ui:i}=a.eventRange,s=r.eventTimeFormat||e.defaultTimeFormat,o=Gp(a,s,t,e.defaultDisplayEventTime,e.defaultDisplayEventEnd);return P(nu,Object.assign({},e,{elTag:"a",elStyle:{borderColor:i.borderColor,backgroundColor:i.backgroundColor},elAttrs:yk(a,t),defaultGenerator:w6e,timeText:o}),(l,c)=>P(Ot,null,P(l,{elTag:"div",elClasses:["fc-event-main"],elStyle:{color:c.textColor}}),!!c.isStartResizable&&P("div",{className:"fc-event-resizer fc-event-resizer-start"}),!!c.isEndResizable&&P("div",{className:"fc-event-resizer fc-event-resizer-end"})))}};Hp.addPropsEquality({seg:Va});Kx=n=>P(bo.Consumer,null,e=>{let{options:t}=e,r={isAxis:n.isAxis,date:e.dateEnv.toDate(n.date),view:e.viewApi};return P(gn,{elRef:n.elRef,elTag:n.elTag||"div",elAttrs:n.elAttrs,elClasses:n.elClasses,elStyle:n.elStyle,renderProps:r,generatorName:"nowIndicatorContent",customGenerator:t.nowIndicatorContent,classNameGenerator:t.nowIndicatorClassNames,didMount:t.nowIndicatorDidMount,willUnmount:t.nowIndicatorWillUnmount},n.children)}),S6e=zt({day:"numeric"}),Vp=class extends Tt{constructor(){super(...arguments),this.refineRenderProps=mk(C6e)}render(){let{props:e,context:t}=this,{options:r}=t,a=this.refineRenderProps({date:e.date,dateProfile:e.dateProfile,todayRange:e.todayRange,isMonthStart:e.isMonthStart||!1,showDayNumber:e.showDayNumber,extraRenderProps:e.extraRenderProps,viewApi:t.viewApi,dateEnv:t.dateEnv,monthStartFormat:r.monthStartFormat});return P(gn,{elRef:e.elRef,elTag:e.elTag,elAttrs:Object.assign(Object.assign({},e.elAttrs),a.isDisabled?{}:{"data-date":Wp(e.date)}),elClasses:[...vk(a,t.theme),...e.elClasses||[]],elStyle:e.elStyle,renderProps:a,generatorName:"dayCellContent",customGenerator:r.dayCellContent,defaultGenerator:e.defaultGenerator,classNameGenerator:a.isDisabled?void 0:r.dayCellClassNames,didMount:r.dayCellDidMount,willUnmount:r.dayCellWillUnmount},e.children)}};Th=class extends Tt{render(){let{props:e}=this,{seg:t}=e;return P(nu,{elTag:"div",elClasses:["fc-bg-event"],elStyle:{backgroundColor:t.eventRange.ui.backgroundColor},defaultGenerator:x6e,seg:t,timeText:"",isDragging:!1,isResizing:!1,isDateSelecting:!1,isSelected:!1,isPast:e.isPast,isFuture:e.isFuture,isToday:e.isToday,disableDragging:!0,disableResizing:!0})}};Qx=n=>P(bo.Consumer,null,e=>{let{dateEnv:t,options:r}=e,{date:a}=n,i=r.weekNumberFormat||n.defaultFormat,s=t.computeWeekNumber(a),o=t.format(a,i),l={num:s,text:o,date:a};return P(gn,{elRef:n.elRef,elTag:n.elTag,elAttrs:n.elAttrs,elClasses:n.elClasses,elStyle:n.elStyle,renderProps:l,generatorName:"weekNumberContent",customGenerator:r.weekNumberContent,defaultGenerator:E6e,classNameGenerator:r.weekNumberClassNames,didMount:r.weekNumberDidMount,willUnmount:r.weekNumberWillUnmount},n.children)});eV=10,cV=class extends Tt{constructor(){super(...arguments),this.state={titleId:Hi()},this.handleRootEl=e=>{this.rootEl=e,this.props.elRef&&Ms(this.props.elRef,e)},this.handleDocumentMouseDown=e=>{let t=VN(e);this.rootEl.contains(t)||this.handleCloseClick()},this.handleDocumentKeyDown=e=>{e.key==="Escape"&&this.handleCloseClick()},this.handleCloseClick=()=>{let{onClose:e}=this.props;e&&e()}}render(){let{theme:e,options:t}=this.context,{props:r,state:a}=this,i=["fc-popover",e.getClass("popover")].concat(r.extraClassNames||[]);return VH(P("div",Object.assign({},r.extraAttrs,{id:r.id,className:i.join(" "),"aria-labelledby":a.titleId,ref:this.handleRootEl}),P("div",{className:"fc-popover-header "+e.getClass("popoverHeader")},P("span",{className:"fc-popover-title",id:a.titleId},r.title),P("span",{className:"fc-popover-close "+e.getIconClass("close"),title:t.closeHint,onClick:this.handleCloseClick})),P("div",{className:"fc-popover-body "+e.getClass("popoverContent")},r.children)),r.parentEl)}componentDidMount(){document.addEventListener("mousedown",this.handleDocumentMouseDown),document.addEventListener("keydown",this.handleDocumentKeyDown),this.updateSize()}componentWillUnmount(){document.removeEventListener("mousedown",this.handleDocumentMouseDown),document.removeEventListener("keydown",this.handleDocumentKeyDown)}updateSize(){let{isRtl:e}=this.context,{alignmentEl:t,alignGridTop:r}=this.props,{rootEl:a}=this,i=p6e(t);if(i){let s=a.getBoundingClientRect(),o=r?Yn(t,".fc-scrollgrid").getBoundingClientRect().top:i.top,l=e?i.right-s.width:i.left;o=Math.max(o,eV),l=Math.min(l,document.documentElement.clientWidth-eV-s.width),l=Math.max(l,eV);let c=a.offsetParent.getBoundingClientRect();wh(a,{top:o-c.top,left:l-c.left})}}},dV=class extends On{constructor(){super(...arguments),this.handleRootEl=e=>{this.rootEl=e,e?this.context.registerInteractiveComponent(this,{el:e,useEventCenter:!1}):this.context.unregisterInteractiveComponent(this)}}render(){let{options:e,dateEnv:t}=this.context,{props:r}=this,{startDate:a,todayRange:i,dateProfile:s}=r,o=t.format(a,e.dayPopoverFormat);return P(Vp,{elRef:this.handleRootEl,date:a,dateProfile:s,todayRange:i},(l,c,d)=>P(cV,{elRef:d.ref,id:r.id,title:o,extraClassNames:["fc-more-popover"].concat(d.className||[]),extraAttrs:d,parentEl:r.parentEl,alignmentEl:r.alignmentEl,alignGridTop:r.alignGridTop,onClose:r.onClose},bk(e)&&P(l,{elTag:"div",elClasses:["fc-more-popover-misc"]}),r.children))}queryHit(e,t,r,a){let{rootEl:i,props:s}=this;return e>=0&&e=0&&t{this.linkEl=e,this.props.elRef&&Ms(this.props.elRef,e)},this.handleClick=e=>{let{props:t,context:r}=this,{moreLinkClick:a}=r.options,i=pge(t).start;function s(o){let{def:l,instance:c,range:d}=o.eventRange;return{event:new vr(r,l,c),start:r.dateEnv.toDate(d.start),end:r.dateEnv.toDate(d.end),isStart:o.isStart,isEnd:o.isEnd}}typeof a=="function"&&(a=a({date:i,allDay:!!t.allDayDate,allSegs:t.allSegs.map(s),hiddenSegs:t.hiddenSegs.map(s),jsEvent:e,view:r.viewApi})),!a||a==="popover"?this.setState({isPopoverOpen:!0}):typeof a=="string"&&r.calendarApi.zoomTo(i,a)},this.handlePopoverClose=()=>{this.setState({isPopoverOpen:!1})}}render(){let{props:e,state:t}=this;return P(bo.Consumer,null,r=>{let{viewApi:a,options:i,calendarApi:s}=r,{moreLinkText:o}=i,{moreCnt:l}=e,c=pge(e),d=typeof o=="function"?o.call(s,l):`+${l} ${o}`,u=uk(i.moreLinkHint,[l],d),p={num:l,shortText:`+${l}`,text:d,view:a};return P(Ot,null,!!e.moreCnt&&P(gn,{elTag:e.elTag||"a",elRef:this.handleLinkEl,elClasses:[...e.elClasses||[],"fc-more-link"],elStyle:e.elStyle,elAttrs:Object.assign(Object.assign(Object.assign({},e.elAttrs),kge(this.handleClick)),{title:u,"aria-expanded":t.isPopoverOpen,"aria-controls":t.isPopoverOpen?t.popoverId:""}),renderProps:p,generatorName:"moreLinkContent",customGenerator:i.moreLinkContent,defaultGenerator:e.defaultGenerator||D6e,classNameGenerator:i.moreLinkClassNames,didMount:i.moreLinkDidMount,willUnmount:i.moreLinkWillUnmount},e.children),t.isPopoverOpen&&P(dV,{id:t.popoverId,startDate:c.start,endDate:c.end,dateProfile:e.dateProfile,todayRange:e.todayRange,extraDateSpan:e.extraDateSpan,parentEl:this.parentEl,alignmentEl:e.alignmentElRef?e.alignmentElRef.current:this.linkEl,alignGridTop:e.alignGridTop,forceTimed:e.forceTimed,onClose:this.handlePopoverClose},e.popoverContent()))})}componentDidMount(){this.updateParentEl()}componentDidUpdate(){this.updateParentEl()}updateParentEl(){this.linkEl&&(this.parentEl=Yn(this.linkEl,".fc-view-harness"))}}});function N6e(n){let e=n.length>0?n[0].code:"en",t=I6e.concat(n),r={en:gye};for(let a of t)r[a.code]=a;return{map:r,defaultCode:e}}function yye(n,e){return typeof n=="object"&&!Array.isArray(n)?vye(n.code,[n.code],n):R6e(n,e)}function R6e(n,e){let t=[].concat(n||[]),r=_6e(t,e)||gye;return vye(n,t,r)}function _6e(n,e){for(let t=0;t0;a-=1){let i=r.slice(0,a).join("-");if(e[i])return e[i]}}return null}function vye(n,e,t){let r=YN([hye,t],["buttonText"]);delete r.code;let{week:a}=r;return delete r.week,{codeArg:n,codes:e,week:a,simpleNumberFormat:new Intl.NumberFormat(n),options:r}}function Wa(n){return{id:au(),name:n.name,premiumReleaseDate:n.premiumReleaseDate?new Date(n.premiumReleaseDate):void 0,deps:n.deps||[],reducers:n.reducers||[],isLoadingFuncs:n.isLoadingFuncs||[],contextInit:[].concat(n.contextInit||[]),eventRefiners:n.eventRefiners||{},eventDefMemberAdders:n.eventDefMemberAdders||[],eventSourceRefiners:n.eventSourceRefiners||{},isDraggableTransformers:n.isDraggableTransformers||[],eventDragMutationMassagers:n.eventDragMutationMassagers||[],eventDefMutationAppliers:n.eventDefMutationAppliers||[],dateSelectionTransformers:n.dateSelectionTransformers||[],datePointTransforms:n.datePointTransforms||[],dateSpanTransforms:n.dateSpanTransforms||[],views:n.views||{},viewPropsTransformers:n.viewPropsTransformers||[],isPropsValid:n.isPropsValid||null,externalDefTransforms:n.externalDefTransforms||[],viewContainerAppends:n.viewContainerAppends||[],eventDropTransformers:n.eventDropTransformers||[],componentInteractions:n.componentInteractions||[],calendarInteractions:n.calendarInteractions||[],themeClasses:n.themeClasses||{},eventSourceDefs:n.eventSourceDefs||[],cmdFormatter:n.cmdFormatter,recurringTypes:n.recurringTypes||[],namedTimeZonedImpl:n.namedTimeZonedImpl,initialView:n.initialView||"",elementDraggingImpl:n.elementDraggingImpl,optionChangeHandlers:n.optionChangeHandlers||{},scrollGridImpl:n.scrollGridImpl||null,listenerRefiners:n.listenerRefiners||{},optionRefiners:n.optionRefiners||{},propSetHandlers:n.propSetHandlers||{}}}function F6e(n,e){let t={},r={premiumReleaseDate:void 0,reducers:[],isLoadingFuncs:[],contextInit:[],eventRefiners:{},eventDefMemberAdders:[],eventSourceRefiners:{},isDraggableTransformers:[],eventDragMutationMassagers:[],eventDefMutationAppliers:[],dateSelectionTransformers:[],datePointTransforms:[],dateSpanTransforms:[],views:{},viewPropsTransformers:[],isPropsValid:null,externalDefTransforms:[],viewContainerAppends:[],eventDropTransformers:[],componentInteractions:[],calendarInteractions:[],themeClasses:{},eventSourceDefs:[],cmdFormatter:null,recurringTypes:[],namedTimeZonedImpl:null,initialView:"",elementDraggingImpl:null,optionChangeHandlers:{},scrollGridImpl:null,listenerRefiners:{},optionRefiners:{},propSetHandlers:{}};function a(i){for(let s of i){let o=s.name,l=t[o];l===void 0?(t[o]=s.id,a(s.deps),r=O6e(r,s)):l!==s.id&&console.warn(`Duplicate plugin '${o}'`)}}return n&&a(n),a(e),r}function L6e(){let n=[],e=[],t;return(r,a)=>((!t||!Tc(r,n)||!Tc(a,e))&&(t=F6e(r,a)),n=r,e=a,t)}function O6e(n,e){return{premiumReleaseDate:z6e(n.premiumReleaseDate,e.premiumReleaseDate),reducers:n.reducers.concat(e.reducers),isLoadingFuncs:n.isLoadingFuncs.concat(e.isLoadingFuncs),contextInit:n.contextInit.concat(e.contextInit),eventRefiners:Object.assign(Object.assign({},n.eventRefiners),e.eventRefiners),eventDefMemberAdders:n.eventDefMemberAdders.concat(e.eventDefMemberAdders),eventSourceRefiners:Object.assign(Object.assign({},n.eventSourceRefiners),e.eventSourceRefiners),isDraggableTransformers:n.isDraggableTransformers.concat(e.isDraggableTransformers),eventDragMutationMassagers:n.eventDragMutationMassagers.concat(e.eventDragMutationMassagers),eventDefMutationAppliers:n.eventDefMutationAppliers.concat(e.eventDefMutationAppliers),dateSelectionTransformers:n.dateSelectionTransformers.concat(e.dateSelectionTransformers),datePointTransforms:n.datePointTransforms.concat(e.datePointTransforms),dateSpanTransforms:n.dateSpanTransforms.concat(e.dateSpanTransforms),views:Object.assign(Object.assign({},n.views),e.views),viewPropsTransformers:n.viewPropsTransformers.concat(e.viewPropsTransformers),isPropsValid:e.isPropsValid||n.isPropsValid,externalDefTransforms:n.externalDefTransforms.concat(e.externalDefTransforms),viewContainerAppends:n.viewContainerAppends.concat(e.viewContainerAppends),eventDropTransformers:n.eventDropTransformers.concat(e.eventDropTransformers),calendarInteractions:n.calendarInteractions.concat(e.calendarInteractions),componentInteractions:n.componentInteractions.concat(e.componentInteractions),themeClasses:Object.assign(Object.assign({},n.themeClasses),e.themeClasses),eventSourceDefs:n.eventSourceDefs.concat(e.eventSourceDefs),cmdFormatter:e.cmdFormatter||n.cmdFormatter,recurringTypes:n.recurringTypes.concat(e.recurringTypes),namedTimeZonedImpl:e.namedTimeZonedImpl||n.namedTimeZonedImpl,initialView:n.initialView||e.initialView,elementDraggingImpl:n.elementDraggingImpl||e.elementDraggingImpl,optionChangeHandlers:Object.assign(Object.assign({},n.optionChangeHandlers),e.optionChangeHandlers),scrollGridImpl:e.scrollGridImpl||n.scrollGridImpl,listenerRefiners:Object.assign(Object.assign({},n.listenerRefiners),e.listenerRefiners),optionRefiners:Object.assign(Object.assign({},n.optionRefiners),e.optionRefiners),propSetHandlers:Object.assign(Object.assign({},n.propSetHandlers),e.propSetHandlers)}}function z6e(n,e){return n===void 0?e:e===void 0?n:new Date(Math.max(n.valueOf(),e.valueOf()))}function B6e(n,e){let t={},r;for(r in n)tW(r,t,n,e);for(r in e)tW(r,t,n,e);return t}function tW(n,e,t,r){if(e[n])return e[n];let a=j6e(n,e,t,r);return a&&(e[n]=a),a}function j6e(n,e,t,r){let a=t[n],i=r[n],s=d=>a&&a[d]!==null?a[d]:i&&i[d]!==null?i[d]:null,o=s("component"),l=s("superType"),c=null;if(l){if(l===n)throw new Error("Can't have a custom view type that references itself");c=tW(l,e,t,r)}return!o&&c&&(o=c.component),o?{type:n,component:o,defaults:Object.assign(Object.assign({},c?c.defaults:{}),a?a.rawOptions:{}),overrides:Object.assign(Object.assign({},c?c.overrides:{}),i?i.rawOptions:{})}:null}function cye(n){return To(n,$6e)}function $6e(n){let e=typeof n=="function"?{component:n}:n,{component:t}=e;return e.content?t=dye(e):t&&!(t.prototype instanceof Tt)&&(t=dye(Object.assign(Object.assign({},e),{content:t}))),{superType:e.type,component:t,rawOptions:e}}function dye(n){return e=>P(bo.Consumer,null,t=>P(gn,{elTag:"div",elClasses:MV(t.viewSpec),renderProps:Object.assign(Object.assign({},e),{nextDayThreshold:t.options.nextDayThreshold}),generatorName:void 0,customGenerator:n.content,classNameGenerator:n.classNames,didMount:n.didMount,willUnmount:n.willUnmount}))}function U6e(n,e,t,r){let a=cye(n),i=cye(e.views),s=B6e(a,i);return To(s,o=>H6e(o,i,e,t,r))}function H6e(n,e,t,r,a){let i=n.overrides.duration||n.defaults.duration||r.duration||t.duration,s=null,o="",l="",c={};if(i&&(s=V6e(i),s)){let p=kx(s);o=p.unit,p.value===1&&(l=o,c=e[o]?e[o].rawOptions:{})}let d=p=>{let m=p.buttonText||{},f=n.defaults.buttonTextKey;return f!=null&&m[f]!=null?m[f]:m[n.type]!=null?m[n.type]:m[l]!=null?m[l]:null},u=p=>{let m=p.buttonHints||{},f=n.defaults.buttonTextKey;return f!=null&&m[f]!=null?m[f]:m[n.type]!=null?m[n.type]:m[l]!=null?m[l]:null};return{type:n.type,component:n.component,duration:s,durationUnit:o,singleUnit:l,optionDefaults:n.defaults,optionOverrides:Object.assign(Object.assign({},c),n.overrides),buttonTextOverride:d(r)||d(t)||n.overrides.buttonText,buttonTextDefault:d(a)||n.defaults.buttonText||d(wc)||n.type,buttonTitleOverride:u(r)||u(t)||n.overrides.buttonHint,buttonTitleDefault:u(a)||n.defaults.buttonHint||u(wc)}}function V6e(n){let e=JSON.stringify(n),t=uye[e];return t===void 0&&(t=lt(n),uye[e]=t),t}function W6e(n,e){switch(e.type){case"CHANGE_VIEW_TYPE":n=e.viewType}return n}function q6e(n,e){switch(e.type){case"CHANGE_DATE":return e.dateMarker;default:return n}}function G6e(n,e,t){let r=n.initialDate;return r!=null?e.createMarker(r):t.getDateMarker()}function Y6e(n,e){switch(e.type){case"SET_OPTION":return Object.assign(Object.assign({},n),{[e.optionName]:e.rawOptionValue});default:return n}}function K6e(n,e,t,r){let a;switch(e.type){case"CHANGE_VIEW_TYPE":return r.build(e.dateMarker||t);case"CHANGE_DATE":return r.build(e.dateMarker);case"PREV":if(a=r.buildPrev(n,t),a.isValid)return a;break;case"NEXT":if(a=r.buildNext(n,t),a.isValid)return a;break}return n}function Z6e(n,e,t){let r=e?e.activeRange:null;return Tye({},n9e(n,t),r,t)}function Q6e(n,e,t,r){let a=t?t.activeRange:null;switch(e.type){case"ADD_EVENT_SOURCES":return Tye(n,e.sources,a,r);case"REMOVE_EVENT_SOURCE":return X6e(n,e.sourceId);case"PREV":case"NEXT":case"CHANGE_DATE":case"CHANGE_VIEW_TYPE":return t?bye(n,a,r):n;case"FETCH_EVENT_SOURCES":return dW(n,e.sourceIds?DV(e.sourceIds):wye(n,r),a,e.isRefetch||!1,r);case"RECEIVE_EVENTS":case"RECEIVE_EVENT_ERROR":return r9e(n,e.sourceId,e.fetchId,e.fetchRange);case"REMOVE_ALL_EVENT_SOURCES":return{};default:return n}}function J6e(n,e,t){let r=e?e.activeRange:null;return dW(n,wye(n,t),r,!0,t)}function kye(n){for(let e in n)if(n[e].isFetching)return!0;return!1}function Tye(n,e,t,r){let a={};for(let i of e)a[i.sourceId]=i;return t&&(a=bye(a,t,r)),Object.assign(Object.assign({},n),a)}function X6e(n,e){return Xd(n,t=>t.sourceId!==e)}function bye(n,e,t){return dW(n,Xd(n,r=>e9e(r,e,t)),e,!1,t)}function e9e(n,e,t){return Sye(n,t)?!t.options.lazyFetching||!n.fetchRange||n.isFetching||e.startn.fetchRange.end:!n.latestFetchId}function dW(n,e,t,r,a){let i={};for(let s in n){let o=n[s];e[s]?i[s]=t9e(o,t,r,a):i[s]=o}return i}function t9e(n,e,t,r){let{options:a,calendarApi:i}=r,s=r.pluginHooks.eventSourceDefs[n.sourceDefId],o=au();return s.fetch({eventSource:n,range:e,isRefetch:t,context:r},l=>{let{rawEvents:c}=l;a.eventSourceSuccess&&(c=a.eventSourceSuccess.call(i,c,l.response)||c),n.success&&(c=n.success.call(i,c,l.response)||c),r.dispatch({type:"RECEIVE_EVENTS",sourceId:n.sourceId,fetchId:o,fetchRange:e,rawEvents:c})},l=>{let c=!1;a.eventSourceFailure&&(a.eventSourceFailure.call(i,l),c=!0),n.failure&&(n.failure(l),c=!0),c||console.warn(l.message,l),r.dispatch({type:"RECEIVE_EVENT_ERROR",sourceId:n.sourceId,fetchId:o,fetchRange:e,error:l})}),Object.assign(Object.assign({},n),{isFetching:!0,latestFetchId:o})}function r9e(n,e,t,r){let a=n[e];return a&&t===a.latestFetchId?Object.assign(Object.assign({},n),{[e]:Object.assign(Object.assign({},a),{isFetching:!1,fetchRange:r})}):n}function wye(n,e){return Xd(n,t=>Sye(t,e))}function n9e(n,e){let t=FV(e),r=[].concat(n.eventSources||[]),a=[];n.initialEvents&&r.unshift(n.initialEvents),n.events&&r.unshift(n.events);for(let i of r){let s=_V(i,e,t);s&&a.push(s)}return a}function Sye(n,e){return!e.pluginHooks.eventSourceDefs[n.sourceDefId].ignoreRange}function a9e(n,e){switch(e.type){case"UNSELECT_DATES":return null;case"SELECT_DATES":return e.selection;default:return n}}function i9e(n,e){switch(e.type){case"UNSELECT_EVENT":return"";case"SELECT_EVENT":return e.eventInstanceId;default:return n}}function s9e(n,e){let t;switch(e.type){case"UNSET_EVENT_DRAG":return null;case"SET_EVENT_DRAG":return t=e.state,{affectedEvents:t.affectedEvents,mutatedEvents:t.mutatedEvents,isEvent:t.isEvent};default:return n}}function o9e(n,e){let t;switch(e.type){case"UNSET_EVENT_RESIZE":return null;case"SET_EVENT_RESIZE":return t=e.state,{affectedEvents:t.affectedEvents,mutatedEvents:t.mutatedEvents,isEvent:t.isEvent};default:return n}}function l9e(n,e,t,r,a){let i=n.headerToolbar?pye(n.headerToolbar,n,e,t,r,a):null,s=n.footerToolbar?pye(n.footerToolbar,n,e,t,r,a):null;return{header:i,footer:s}}function pye(n,e,t,r,a,i){let s={},o=[],l=!1;for(let c in n){let d=n[c],u=c9e(d,e,t,r,a,i);s[c]=u.widgets,o.push(...u.viewsWithButtons),l=l||u.hasTitle}return{sectionWidgets:s,viewsWithButtons:o,hasTitle:l}}function c9e(n,e,t,r,a,i){let s=e.direction==="rtl",o=e.customButtons||{},l=t.buttonText||{},c=e.buttonText||{},d=t.buttonHints||{},u=e.buttonHints||{},p=n?n.split(" "):[],m=[],f=!1;return{widgets:p.map(g=>g.split(",").map(v=>{if(v==="title")return f=!0,{buttonName:v};let k,T,b,w,S,C;if(k=o[v])b=x=>{k.click&&k.click.call(x.target,x,x.target)},(w=r.getCustomButtonIconClass(k))||(w=r.getIconClass(v,s))||(S=k.text),C=k.hint||k.text;else if(T=a[v]){m.push(v),b=()=>{i.changeView(v)},(S=T.buttonTextOverride)||(w=r.getIconClass(v,s))||(S=T.buttonTextDefault);let x=T.buttonTextOverride||T.buttonTextDefault;C=uk(T.buttonTitleOverride||T.buttonTitleDefault||e.viewHint,[x,v],x)}else if(i[v])if(b=()=>{i[v]()},(S=l[v])||(w=r.getIconClass(v,s))||(S=c[v]),v==="prevYear"||v==="nextYear"){let x=v==="prevYear"?"prev":"next";C=uk(d[x]||u[x],[c.year||"year","year"],c[v])}else C=x=>uk(d[v]||u[v],[c[x]||x,x],c[v]);return{buttonName:v,buttonClick:b,buttonIcon:w,buttonText:S,buttonHint:C}})),viewsWithButtons:m,hasTitle:f}}function y9e(n,e,t){let{dateEnv:r,options:a}=t,i,s,o,l,c={};return i=n.startParam,i==null&&(i=a.startParam),s=n.endParam,s==null&&(s=a.endParam),o=n.timeZoneParam,o==null&&(o=a.timeZoneParam),typeof n.extraParams=="function"?l=n.extraParams():l=n.extraParams||{},Object.assign(c,l),c[i]=r.formatIso(e.start),c[s]=r.formatIso(e.end),r.timeZone!=="local"&&(c[o]=r.timeZone),c}function b9e(n,e,t,r,a){let i=n?DV(n):null,s=nr(a.start),o=a.end,l=[];for(e&&(e.milliseconds<0?o=Kr(o,1):e.milliseconds>=1e3*60*60*24&&(s=Kr(s,-1)));s1?{year:"numeric",month:"short",day:"numeric"}:{year:"numeric",month:"long",day:"numeric"}}function P9e(n,e,t,r,a,i,s,o){let l=yye(e||s.defaultCode,s.map);return new Tx({calendarSystem:"gregory",timeZone:n,namedTimeZoneImpl:i.namedTimeZonedImpl,locale:l,weekNumberCalculation:t,firstDay:r,weekText:a,cmdFormatter:i.cmdFormatter,defaultSeparator:o})}function A9e(n,e){let t=e.themeClasses[n.themeSystem]||xc;return new t(n)}function M9e(n){let e=n.dateProfileGeneratorClass||ph;return new e(n)}function I9e(n,e,t){return new rW(n,e,t)}function N9e(n){return To(n,e=>e.ui)}function R9e(n,e,t){let r={"":e};for(let a in n){let i=n[a];i.sourceId&&t[i.sourceId]&&(r[a]=t[i.sourceId])}return r}function _9e(n){let{options:e}=n;return{eventUiSingleBase:gk({display:e.eventDisplay,editable:e.editable,startEditable:e.eventStartEditable,durationEditable:e.eventDurationEditable,constraint:e.eventConstraint,overlap:typeof e.eventOverlap=="boolean"?e.eventOverlap:void 0,allow:e.eventAllow,backgroundColor:e.eventBackgroundColor,borderColor:e.eventBorderColor,textColor:e.eventTextColor,color:e.eventColor},n),selectionConfig:gk({constraint:e.selectConstraint,overlap:typeof e.selectOverlap=="boolean"?e.selectOverlap:void 0,allow:e.selectAllow},n)}}function eW(n,e){for(let t of e.pluginHooks.isLoadingFuncs)if(t(n))return!0;return!1}function F9e(n){return OV(n.options.businessHours,n)}function fye(n,e){for(let t in n)console.warn(`Unknown option '${t}'`+(e?` for view '${e}'`:""))}function L9e(n,e,t,r,a,i){let s=t.build(a,void 0,!1),o=t.buildPrev(e,r,!1),l=t.buildNext(e,r,!1);return{title:i,activeButton:n.type,navUnit:n.singleUnit,isTodayEnabled:s.isValid&&!ko(e.currentRange,a),isPrevEnabled:o.isValid,isNextEnabled:l.isValid}}function O9e(n){return n.map(e=>new e)}var I6e,hye,gye,xc,uye,rW,d9e,u9e,p9e,m9e,f9e,h9e,g9e,v9e,k9e,T9e,w9e,x9e,nW,aR,aW,iW,iR,sW,oW,lW,cW,sR,Eh=y(()=>{XV();Jd();yx();I6e=[],hye={code:"en",week:{dow:0,doy:4},direction:"ltr",buttonText:{prev:"prev",next:"next",prevYear:"prev year",nextYear:"next year",year:"year",today:"today",month:"month",week:"week",day:"day",list:"list"},weekText:"W",weekTextLong:"Week",closeHint:"Close",timeHint:"Time",eventHint:"Event",allDayText:"all-day",moreLinkText:"more",noEventsText:"No events to display"},gye=Object.assign(Object.assign({},hye),{buttonHints:{prev:"Previous $0",next:"Next $0",today(n,e){return e==="day"?"Today":`This ${n}`}},viewHint:"$0 view",navLinkHint:"Go to $0",moreLinkHint(n){return`Show ${n} more event${n===1?"":"s"}`}});xc=class extends eu{};xc.prototype.classes={root:"fc-theme-standard",tableCellShaded:"fc-cell-shaded",buttonGroup:"fc-button-group",button:"fc-button fc-button-primary",buttonActive:"fc-button-active"};xc.prototype.baseIconClass="fc-icon";xc.prototype.iconClasses={close:"fc-icon-x",prev:"fc-icon-chevron-left",next:"fc-icon-chevron-right",prevYear:"fc-icon-chevrons-left",nextYear:"fc-icon-chevrons-right"};xc.prototype.rtlIconClasses={prev:"fc-icon-chevron-right",next:"fc-icon-chevron-left",prevYear:"fc-icon-chevrons-right",nextYear:"fc-icon-chevrons-left"};xc.prototype.iconOverrideOption="buttonIcons";xc.prototype.iconOverrideCustomButtonOption="icon";xc.prototype.iconOverridePrefix="fc-icon-";uye={};rW=class{constructor(e,t,r){this.type=e,this.getCurrentData=t,this.dateEnv=r}get calendar(){return this.getCurrentData().calendarApi}get title(){return this.getCurrentData().viewTitle}get activeStart(){return this.dateEnv.toDate(this.getCurrentData().dateProfile.activeRange.start)}get activeEnd(){return this.dateEnv.toDate(this.getCurrentData().dateProfile.activeRange.end)}get currentStart(){return this.dateEnv.toDate(this.getCurrentData().dateProfile.currentRange.start)}get currentEnd(){return this.dateEnv.toDate(this.getCurrentData().dateProfile.currentRange.end)}getOption(e){return this.getCurrentData().options[e]}},d9e={ignoreRange:!0,parseMeta(n){return Array.isArray(n.events)?n.events:null},fetch(n,e){e({rawEvents:n.eventSource.meta})}},u9e=Wa({name:"array-event-source",eventSourceDefs:[d9e]}),p9e={parseMeta(n){return typeof n.events=="function"?n.events:null},fetch(n,e,t){let{dateEnv:r}=n.context,a=n.eventSource.meta;UV(a.bind(null,$V(n.range,r)),i=>e({rawEvents:i}),t)}},m9e=Wa({name:"func-event-source",eventSourceDefs:[p9e]}),f9e={method:String,extraParams:B,startParam:String,endParam:String,timeZoneParam:String},h9e={parseMeta(n){return n.url&&(n.format==="json"||!n.format)?{url:n.url,format:"json",method:(n.method||"GET").toUpperCase(),extraParams:n.extraParams,startParam:n.startParam,endParam:n.endParam,timeZoneParam:n.timeZoneParam}:null},fetch(n,e,t){let{meta:r}=n.eventSource,a=y9e(r,n.range,n.context);HV(r.method,r.url,a).then(([i,s])=>{e({rawEvents:i,response:s})},t)}},g9e=Wa({name:"json-event-source",eventSourceRefiners:f9e,eventSourceDefs:[h9e]});v9e={daysOfWeek:B,startTime:lt,endTime:lt,duration:lt,startRecur:B,endRecur:B},k9e={parse(n,e){if(n.daysOfWeek||n.startTime||n.endTime||n.startRecur||n.endRecur){let t={daysOfWeek:n.daysOfWeek||null,startTime:n.startTime||null,endTime:n.endTime||null,startRecur:n.startRecur?e.createMarker(n.startRecur):null,endRecur:n.endRecur?e.createMarker(n.endRecur):null,dateEnv:e},r;return n.duration&&(r=n.duration),!r&&n.startTime&&n.endTime&&(r=Cge(n.endTime,n.startTime)),{allDayGuess:!n.startTime&&!n.endTime,duration:r,typeData:t}}return null},expand(n,e,t){let r=fi(e,{start:n.startRecur,end:n.endRecur});return r?b9e(n.daysOfWeek,n.startTime,n.dateEnv,t,r):[]}},T9e=Wa({name:"simple-recurring-event",recurringTypes:[k9e],eventRefiners:v9e});w9e=Wa({name:"change-handler",optionChangeHandlers:{events(n,e){mye([n],e)},eventSources:mye}});x9e=[u9e,m9e,g9e,T9e,w9e,Wa({name:"misc",isLoadingFuncs:[n=>kye(n.eventSources)],propSetHandlers:{dateProfile:S9e,eventStore:C9e}})],nW=class{constructor(e,t){this.runTaskOption=e,this.drainedOption=t,this.queue=[],this.delayedRunner=new uh(this.drain.bind(this))}request(e,t){this.queue.push(e),this.delayedRunner.request(t)}pause(e){this.delayedRunner.pause(e)}resume(e,t){this.delayedRunner.resume(e,t)}drain(){let{queue:e}=this;for(;e.length;){let t=[],r;for(;r=e.shift();)this.runTask(r),t.push(r);this.drained(t)}}runTask(e){this.runTaskOption&&this.runTaskOption(e)}drained(e){this.drainedOption&&this.drainedOption(e)}};aR=class{constructor(){this.resetListeners=new Set}handleInput(e,t){let r=this.dateEnv;if(e!==r&&(typeof t=="function"?this.nowFn=t:r||(this.nowAnchorDate=e.toDate(t?e.createMarker(t):e.createNowMarker()),this.nowAnchorQueried=Date.now()),this.dateEnv=e,r))for(let a of this.resetListeners.values())a()}getDateMarker(){return this.nowAnchorDate?this.dateEnv.timestampToMarker(this.nowAnchorDate.valueOf()+(Date.now()-this.nowAnchorQueried)):this.dateEnv.createMarker(this.nowFn())}addResetListener(e){this.resetListeners.add(e)}removeResetListener(e){this.resetListeners.delete(e)}},aW=class{constructor(e){this.computeCurrentViewData=Ae(this._computeCurrentViewData),this.organizeRawLocales=Ae(N6e),this.buildLocale=Ae(yye),this.buildPluginHooks=L6e(),this.buildDateEnv=Ae(P9e),this.buildTheme=Ae(A9e),this.parseToolbars=Ae(l9e),this.buildViewSpecs=Ae(U6e),this.buildDateProfileGenerator=mk(M9e),this.buildViewApi=Ae(I9e),this.buildViewUiProps=mk(_9e),this.buildEventUiBySource=Ae(N9e,Va),this.buildEventUiBases=Ae(R9e),this.parseContextBusinessHours=mk(F9e),this.buildTitle=Ae(E9e),this.nowManager=new aR,this.emitter=new tu,this.actionRunner=new nW(this._handleAction.bind(this),this.updateData.bind(this)),this.currentCalendarOptionsInput={},this.currentCalendarOptionsRefined={},this.currentViewOptionsInput={},this.currentViewOptionsRefined={},this.currentCalendarOptionsRefiners={},this.optionsForRefining=[],this.optionsForHandling=[],this.getCurrentData=()=>this.data,this.dispatch=p=>{this.actionRunner.request(p)},this.props=e,this.actionRunner.pause(),this.nowManager=new aR;let t={},r=this.computeOptionsData(e.optionOverrides,t,e.calendarApi),a=r.calendarOptions.initialView||r.pluginHooks.initialView,i=this.computeCurrentViewData(a,r,e.optionOverrides,t);e.calendarApi.currentDataManager=this,this.emitter.setThisContext(e.calendarApi),this.emitter.setOptions(i.options);let s={nowManager:this.nowManager,dateEnv:r.dateEnv,options:r.calendarOptions,pluginHooks:r.pluginHooks,calendarApi:e.calendarApi,dispatch:this.dispatch,emitter:this.emitter,getCurrentData:this.getCurrentData},o=G6e(r.calendarOptions,r.dateEnv,this.nowManager),l=i.dateProfileGenerator.build(o);ko(l.activeRange,o)||(o=l.currentRange.start);for(let p of r.pluginHooks.contextInit)p(s);let c=Z6e(r.calendarOptions,l,s),d={dynamicOptionOverrides:t,currentViewType:a,currentDate:o,dateProfile:l,businessHours:this.parseContextBusinessHours(s),eventSources:c,eventUiBases:{},eventStore:Kn(),renderableEventStore:Kn(),dateSelection:null,eventSelection:"",eventDrag:null,eventResize:null,selectionConfig:this.buildViewUiProps(s).selectionConfig},u=Object.assign(Object.assign({},s),d);for(let p of r.pluginHooks.reducers)Object.assign(d,p(null,null,u));eW(d,s)&&this.emitter.trigger("loading",!0),this.state=d,this.updateData(),this.actionRunner.resume()}resetOptions(e,t){let{props:r}=this;t===void 0?r.optionOverrides=e:(r.optionOverrides=Object.assign(Object.assign({},r.optionOverrides||{}),e),this.optionsForRefining.push(...t)),(t===void 0||t.length)&&this.actionRunner.request({type:"NOTHING"})}_handleAction(e){let{props:t,state:r,emitter:a}=this,i=Y6e(r.dynamicOptionOverrides,e),s=this.computeOptionsData(t.optionOverrides,i,t.calendarApi),o=W6e(r.currentViewType,e),l=this.computeCurrentViewData(o,s,t.optionOverrides,i);t.calendarApi.currentDataManager=this,a.setThisContext(t.calendarApi),a.setOptions(l.options);let c={nowManager:this.nowManager,dateEnv:s.dateEnv,options:s.calendarOptions,pluginHooks:s.pluginHooks,calendarApi:t.calendarApi,dispatch:this.dispatch,emitter:a,getCurrentData:this.getCurrentData},{currentDate:d,dateProfile:u}=r;this.data&&this.data.dateProfileGenerator!==l.dateProfileGenerator&&(u=l.dateProfileGenerator.build(d)),d=q6e(d,e),u=K6e(u,e,d,l.dateProfileGenerator),(e.type==="PREV"||e.type==="NEXT"||!ko(u.currentRange,d))&&(d=u.currentRange.start);let p=Q6e(r.eventSources,e,u,c),m=Oge(r.eventStore,e,p,u,c),h=kye(p)&&!l.options.progressiveEventRendering&&r.renderableEventStore||m,{eventUiSingleBase:g,selectionConfig:v}=this.buildViewUiProps(c),k=this.buildEventUiBySource(p),T=this.buildEventUiBases(h.defs,g,k),b={dynamicOptionOverrides:i,currentViewType:o,currentDate:d,dateProfile:u,eventSources:p,eventStore:m,renderableEventStore:h,selectionConfig:v,eventUiBases:T,businessHours:this.parseContextBusinessHours(c),dateSelection:a9e(r.dateSelection,e),eventSelection:i9e(r.eventSelection,e),eventDrag:s9e(r.eventDrag,e),eventResize:o9e(r.eventResize,e)},w=Object.assign(Object.assign({},c),b);for(let x of s.pluginHooks.reducers)Object.assign(b,x(r,e,w));let S=eW(r,c),C=eW(b,c);!S&&C?a.trigger("loading",!0):S&&!C&&a.trigger("loading",!1),this.state=b,t.onAction&&t.onAction(e)}updateData(){let{props:e,state:t}=this,r=this.data,a=this.computeOptionsData(e.optionOverrides,t.dynamicOptionOverrides,e.calendarApi),i=this.computeCurrentViewData(t.currentViewType,a,e.optionOverrides,t.dynamicOptionOverrides),s=this.data=Object.assign(Object.assign(Object.assign({nowManager:this.nowManager,viewTitle:this.buildTitle(t.dateProfile,i.options,a.dateEnv),calendarApi:e.calendarApi,dispatch:this.dispatch,emitter:this.emitter,getCurrentData:this.getCurrentData},a),i),t),o=a.pluginHooks.optionChangeHandlers,l=r&&r.calendarOptions,c=a.calendarOptions;if(l&&l!==c){l.timeZone!==c.timeZone&&(t.eventSources=s.eventSources=J6e(s.eventSources,t.dateProfile,s),t.eventStore=s.eventStore=LV(s.eventStore,r.dateEnv,s.dateEnv),t.renderableEventStore=s.renderableEventStore=LV(s.renderableEventStore,r.dateEnv,s.dateEnv));for(let d in o)(this.optionsForHandling.indexOf(d)!==-1||l[d]!==c[d])&&o[d](c[d],s)}this.optionsForHandling=[],e.onData&&e.onData(s)}computeOptionsData(e,t,r){if(!this.optionsForRefining.length&&e===this.stableOptionOverrides&&t===this.stableDynamicOptionOverrides)return this.stableCalendarOptionsData;let{refinedOptions:a,pluginHooks:i,localeDefaults:s,availableLocaleData:o,extra:l}=this.processRawCalendarOptions(e,t);fye(l);let c=this.buildDateEnv(a.timeZone,a.locale,a.weekNumberCalculation,a.firstDay,a.weekText,i,o,a.defaultRangeSeparator),d=this.buildViewSpecs(i.views,this.stableOptionOverrides,this.stableDynamicOptionOverrides,s),u=this.buildTheme(a,i),p=this.parseToolbars(a,this.stableOptionOverrides,u,d,r);return this.stableCalendarOptionsData={calendarOptions:a,pluginHooks:i,dateEnv:c,viewSpecs:d,theme:u,toolbarConfig:p,localeDefaults:s,availableRawLocales:o.map}}processRawCalendarOptions(e,t){let{locales:r,locale:a}=GN([wc,e,t]),i=this.organizeRawLocales(r),s=i.map,o=this.buildLocale(a||i.defaultCode,s).options,l=this.buildPluginHooks(e.plugins||[],x9e),c=this.currentCalendarOptionsRefiners=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},CV),xV),EV),l.listenerRefiners),l.optionRefiners),d={},u=GN([wc,o,e,t]),p={},m=this.currentCalendarOptionsInput,f=this.currentCalendarOptionsRefined,h=!1;for(let g in u)this.optionsForRefining.indexOf(g)===-1&&(u[g]===m[g]||qp[g]&&g in m&&qp[g](m[g],u[g]))?p[g]=f[g]:c[g]?(p[g]=c[g](u[g]),h=!0):d[g]=m[g];return h&&(this.currentCalendarOptionsInput=u,this.currentCalendarOptionsRefined=p,this.stableOptionOverrides=e,this.stableDynamicOptionOverrides=t),this.optionsForHandling.push(...this.optionsForRefining),this.optionsForRefining=[],{rawOptions:this.currentCalendarOptionsInput,refinedOptions:this.currentCalendarOptionsRefined,pluginHooks:l,availableLocaleData:i,localeDefaults:o,extra:d}}_computeCurrentViewData(e,t,r,a){let i=t.viewSpecs[e];if(!i)throw new Error(`viewType "${e}" is not available. Please make sure you've loaded all neccessary plugins`);let{refinedOptions:s,extra:o}=this.processRawViewOptions(i,t.pluginHooks,t.localeDefaults,r,a);fye(o),this.nowManager.handleInput(t.dateEnv,s.now);let l=this.buildDateProfileGenerator({dateProfileGeneratorClass:i.optionDefaults.dateProfileGeneratorClass,nowManager:this.nowManager,duration:i.duration,durationUnit:i.durationUnit,usesMinMaxTime:i.optionDefaults.usesMinMaxTime,dateEnv:t.dateEnv,calendarApi:this.props.calendarApi,slotMinTime:s.slotMinTime,slotMaxTime:s.slotMaxTime,showNonCurrentDates:s.showNonCurrentDates,dayCount:s.dayCount,dateAlignment:s.dateAlignment,dateIncrement:s.dateIncrement,hiddenDays:s.hiddenDays,weekends:s.weekends,validRangeInput:s.validRange,visibleRangeInput:s.visibleRange,fixedWeekCount:s.fixedWeekCount}),c=this.buildViewApi(e,this.getCurrentData,t.dateEnv);return{viewSpec:i,options:s,dateProfileGenerator:l,viewApi:c}}processRawViewOptions(e,t,r,a,i){let s=GN([wc,e.optionDefaults,r,a,e.optionOverrides,i]),o=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},CV),xV),EV),Dge),t.listenerRefiners),t.optionRefiners),l={},c=this.currentViewOptionsInput,d=this.currentViewOptionsRefined,u=!1,p={};for(let m in s)s[m]===c[m]||qp[m]&&qp[m](s[m],c[m])?l[m]=d[m]:(s[m]===this.currentCalendarOptionsInput[m]||qp[m]&&qp[m](s[m],this.currentCalendarOptionsInput[m])?m in this.currentCalendarOptionsRefined&&(l[m]=this.currentCalendarOptionsRefined[m]):o[m]?l[m]=o[m](s[m]):p[m]=s[m],u=!0);return u&&(this.currentViewOptionsInput=s,this.currentViewOptionsRefined=l),{rawOptions:this.currentViewOptionsInput,refinedOptions:this.currentViewOptionsRefined,extra:p}}};iW=class extends Tt{render(){let e=this.props.widgetGroups.map(t=>this.renderWidgetGroup(t));return P("div",{className:"fc-toolbar-chunk"},...e)}renderWidgetGroup(e){let{props:t}=this,{theme:r}=this.context,a=[],i=!0;for(let s of e){let{buttonName:o,buttonClick:l,buttonText:c,buttonIcon:d,buttonHint:u}=s;if(o==="title")i=!1,a.push(P("h2",{className:"fc-toolbar-title",id:t.titleId},t.title));else{let p=o===t.activeButton,m=!t.isTodayEnabled&&o==="today"||!t.isPrevEnabled&&o==="prev"||!t.isNextEnabled&&o==="next",f=[`fc-${o}-button`,r.getClass("button")];p&&f.push(r.getClass("buttonActive")),a.push(P("button",{type:"button",title:typeof u=="function"?u(t.navUnit):u,disabled:m,"aria-pressed":p,className:f.join(" "),onClick:l},c||(d?P("span",{className:d,role:"img"}):"")))}}if(a.length>1){let s=i&&r.getClass("buttonGroup")||"";return P("div",{className:s},...a)}return a[0]}},iR=class extends Tt{render(){let{model:e,extraClassName:t}=this.props,r=!1,a,i,s=e.sectionWidgets,o=s.center;return s.left?(r=!0,a=s.left):a=s.start,s.right?(r=!0,i=s.right):i=s.end,P("div",{className:[t||"","fc-toolbar",r?"fc-toolbar-ltr":""].join(" ")},this.renderSection("start",a||[]),this.renderSection("center",o||[]),this.renderSection("end",i||[]))}renderSection(e,t){let{props:r}=this;return P(iW,{key:e,widgetGroups:t,title:r.title,navUnit:r.navUnit,activeButton:r.activeButton,isTodayEnabled:r.isTodayEnabled,isPrevEnabled:r.isPrevEnabled,isNextEnabled:r.isNextEnabled,titleId:r.titleId})}},sW=class extends Tt{constructor(){super(...arguments),this.state={availableWidth:null},this.handleEl=e=>{this.el=e,Ms(this.props.elRef,e),this.updateAvailableWidth()},this.handleResize=()=>{this.updateAvailableWidth()}}render(){let{props:e,state:t}=this,{aspectRatio:r}=e,a=["fc-view-harness",r||e.liquid||e.height?"fc-view-harness-active":"fc-view-harness-passive"],i="",s="";return r?t.availableWidth!==null?i=t.availableWidth/r:s=`${1/r*100}%`:i=e.height||"",P("div",{"aria-labelledby":e.labeledById,ref:this.handleEl,className:a.join(" "),style:{height:i,paddingBottom:s}},e.children)}componentDidMount(){this.context.addResizeHandler(this.handleResize)}componentWillUnmount(){this.context.removeResizeHandler(this.handleResize)}updateAvailableWidth(){this.el&&this.props.aspectRatio&&this.setState({availableWidth:this.el.offsetWidth})}},oW=class extends hl{constructor(e){super(e),this.handleSegClick=(t,r)=>{let{component:a}=this,{context:i}=a,s=iu(r);if(s&&a.isValidSegDownEl(t.target)){let o=Yn(t.target,".fc-event-forced-url"),l=o?o.querySelector("a[href]").href:"";i.emitter.trigger("eventClick",{el:r,event:new vr(a.context,s.eventRange.def,s.eventRange.instance),jsEvent:t,view:i.viewApi}),l&&!t.defaultPrevented&&(window.location.href=l)}},this.destroy=pV(e.el,"click",".fc-event",this.handleSegClick)}},lW=class extends hl{constructor(e){super(e),this.handleEventElRemove=t=>{t===this.currentSegEl&&this.handleSegLeave(null,this.currentSegEl)},this.handleSegEnter=(t,r)=>{iu(r)&&(this.currentSegEl=r,this.triggerEvent("eventMouseEnter",t,r))},this.handleSegLeave=(t,r)=>{this.currentSegEl&&(this.currentSegEl=null,this.triggerEvent("eventMouseLeave",t,r))},this.removeHoverListeners=vge(e.el,".fc-event",this.handleSegEnter,this.handleSegLeave)}destroy(){this.removeHoverListeners()}triggerEvent(e,t,r){let{component:a}=this,{context:i}=a,s=iu(r);(!t||a.isValidSegDownEl(t.target))&&i.emitter.trigger(e,{el:r,event:new vr(i,s.eventRange.def,s.eventRange.instance),jsEvent:t,view:i.viewApi})}},cW=class extends yc{constructor(){super(...arguments),this.buildViewContext=Ae(Nge),this.buildViewPropTransformers=Ae(O9e),this.buildToolbarProps=Ae(L9e),this.headerRef=sn(),this.footerRef=sn(),this.interactionsStore={},this.state={viewLabelId:Hi()},this.registerInteractiveComponent=(e,t)=>{let r=Hge(e,t),s=[oW,lW].concat(this.props.pluginHooks.componentInteractions).map(o=>new o(r));this.interactionsStore[e.uid]=s,Ch[e.uid]=r},this.unregisterInteractiveComponent=e=>{let t=this.interactionsStore[e.uid];if(t){for(let r of t)r.destroy();delete this.interactionsStore[e.uid]}delete Ch[e.uid]},this.resizeRunner=new uh(()=>{this.props.emitter.trigger("_resize",!0),this.props.emitter.trigger("windowResize",{view:this.props.viewApi})}),this.handleWindowResize=e=>{let{options:t}=this.props;t.handleWindowResize&&e.target===window&&this.resizeRunner.request(t.windowResizeDelay)}}render(){let{props:e}=this,{toolbarConfig:t,options:r}=e,a=!1,i="",s;e.isHeightAuto||e.forPrint?i="":r.height!=null?a=!0:r.contentHeight!=null?i=r.contentHeight:s=Math.max(r.aspectRatio,.5);let o=this.buildViewContext(e.viewSpec,e.viewApi,e.options,e.dateProfileGenerator,e.dateEnv,e.nowManager,e.theme,e.pluginHooks,e.dispatch,e.getCurrentData,e.emitter,e.calendarApi,this.registerInteractiveComponent,this.unregisterInteractiveComponent),l=t.header&&t.header.hasTitle?this.state.viewLabelId:void 0;return P(bo.Provider,{value:o},P($i,{unit:"day"},c=>{let d=this.buildToolbarProps(e.viewSpec,e.dateProfile,e.dateProfileGenerator,e.currentDate,c,e.viewTitle);return P(Ot,null,t.header&&P(iR,Object.assign({ref:this.headerRef,extraClassName:"fc-header-toolbar",model:t.header,titleId:l},d)),P(sW,{liquid:a,height:i,aspectRatio:s,labeledById:l},this.renderView(e),this.buildAppendContent()),t.footer&&P(iR,Object.assign({ref:this.footerRef,extraClassName:"fc-footer-toolbar",model:t.footer,titleId:""},d)))}))}componentDidMount(){let{props:e}=this;this.calendarInteractions=e.pluginHooks.calendarInteractions.map(r=>new r(e)),window.addEventListener("resize",this.handleWindowResize);let{propSetHandlers:t}=e.pluginHooks;for(let r in t)t[r](e[r],e)}componentDidUpdate(e){let{props:t}=this,{propSetHandlers:r}=t.pluginHooks;for(let a in r)t[a]!==e[a]&&r[a](t[a],t)}componentWillUnmount(){window.removeEventListener("resize",this.handleWindowResize),this.resizeRunner.clear();for(let e of this.calendarInteractions)e.destroy();this.props.emitter.trigger("_unmount")}buildAppendContent(){let{props:e}=this,t=e.pluginHooks.viewContainerAppends.map(r=>r(e));return P(Ot,{},...t)}renderView(e){let{pluginHooks:t}=e,{viewSpec:r}=e,a={dateProfile:e.dateProfile,businessHours:e.businessHours,eventStore:e.renderableEventStore,eventUiBases:e.eventUiBases,dateSelection:e.dateSelection,eventSelection:e.eventSelection,eventDrag:e.eventDrag,eventResize:e.eventResize,isHeightAuto:e.isHeightAuto,forPrint:e.forPrint},i=this.buildViewPropTransformers(t.viewPropsTransformers);for(let o of i)Object.assign(a,o.transform(a,e));let s=r.component;return P(s,Object.assign({},a))}};sR=class extends Ex{constructor(e,t={}){super(),this.isRendering=!1,this.isRendered=!1,this.currentClassNames=[],this.customContentRenderId=0,this.handleAction=r=>{switch(r.type){case"SET_EVENT_DRAG":case"SET_EVENT_RESIZE":this.renderRunner.tryDrain()}},this.handleData=r=>{this.currentData=r,this.renderRunner.request(r.calendarOptions.rerenderDelay)},this.handleRenderRequest=()=>{if(this.isRendering){this.isRendered=!0;let{currentData:r}=this;bx(()=>{Op(P(xx,{options:r.calendarOptions,theme:r.theme,emitter:r.emitter},(a,i,s,o)=>(this.setClassNames(a),this.setHeight(i),P(AV.Provider,{value:this.customContentRenderId},P(cW,Object.assign({isHeightAuto:s,forPrint:o},r))))),this.el)})}else this.isRendered&&(this.isRendered=!1,Op(null,this.el),this.setClassNames([]),this.setHeight(""))},fge(e),this.el=e,this.renderRunner=new uh(this.handleRenderRequest),new aW({optionOverrides:t,calendarApi:this,onAction:this.handleAction,onData:this.handleData})}render(){let e=this.isRendering;e?this.customContentRenderId+=1:this.isRendering=!0,this.renderRunner.request(),e&&this.updateSize()}destroy(){this.isRendering&&(this.isRendering=!1,this.renderRunner.request())}updateSize(){bx(()=>{super.updateSize()})}batchRendering(e){this.renderRunner.pause("batchRendering"),e(),this.renderRunner.resume("batchRendering")}pauseRendering(){this.renderRunner.pause("pauseRendering")}resumeRendering(){this.renderRunner.resume("pauseRendering",!0)}resetOptions(e,t){this.currentDataManager.resetOptions(e,t)}setClassNames(e){if(!Tc(e,this.currentClassNames)){let{classList:t}=this.el;for(let r of this.currentClassNames)t.remove(r);for(let r of e)t.add(r);this.currentClassNames=e}}setHeight(e){uV(this.el,"height",e)}}});var Dh=y(()=>{XV();Jd();yx()});function z9e(n){return n.button===0&&!n.ctrlKey}function B9e(){uW+=1,setTimeout(()=>{uW-=1},kk.touchMouseIgnoreWait)}function j9e(){oR+=1,oR===1&&window.addEventListener("touchmove",xye,{passive:!1})}function $9e(){oR-=1,oR||window.removeEventListener("touchmove",xye,{passive:!1})}function xye(n){pW&&n.preventDefault()}function U9e(n){let e=n.tagName;return e==="HTML"||e==="BODY"}function pR(n,e){return!n&&!e?!0:!!n!=!!e?!1:jV(n.dateSpan,e.dateSpan)}function wW(n,e){let t={};for(let r of e.pluginHooks.datePointTransforms)Object.assign(t,r(n,e));return Object.assign(t,H9e(n,e.dateEnv)),t}function H9e(n,e){return{date:e.toDate(n.range.start),dateStr:e.formatIso(n.range.start,{omitTime:n.allDay}),allDay:n.allDay}}function V9e(n){let{options:e}=n.context,t=e.selectLongPressDelay;return t==null&&(t=e.longPressDelay),t}function W9e(n,e,t){let r=n.dateSpan,a=e.dateSpan,i=[r.range.start,r.range.end,a.range.start,a.range.end];i.sort(vV);let s={};for(let o of t){let l=o(n,e);if(l===!1)return null;l&&Object.assign(s,l)}return s.range={start:i[0],end:i[3]},s.allDay=r.allDay,s}function q9e(n,e,t,r){let a=n.dateSpan,i=e.dateSpan,s=a.range.start,o=i.range.start,l={};a.allDay!==i.allDay&&(l.allDay=i.allDay,l.hasEnd=e.context.options.allDayMaintainDuration,i.allDay?s=nr(t):s=t);let c=$p(s,o,n.context.dateEnv,n.componentId===e.componentId?n.largeUnit:null);c.milliseconds&&(l.allDay=!1);let d={datesDelta:c,standardProps:l};for(let u of r)u(d,n,e);return d}function G9e(n){let{options:e}=n.context,t=e.eventLongPressDelay;return t==null&&(t=e.longPressDelay),t}function Y9e(n,e,t,r){let a=n.context.dateEnv,i=n.dateSpan.range.start,s=e.dateSpan.range.start,o=$p(i,s,a,n.largeUnit);if(t){if(a.add(r.start,o)r.start)return{endDelta:o};return null}function Q9e(n,e,t){let r=Object.assign({},e.leftoverProps);for(let d of t.pluginHooks.externalDefTransforms)Object.assign(r,d(n,e));let{refined:a,extra:i}=zx(r,t),s=sk(a,i,e.sourceId,n.allDay,t.options.forceEventDuration||!!e.duration,t),o=n.range.start;n.allDay&&e.startTime&&(o=t.dateEnv.add(o,e.startTime));let l=e.duration?t.dateEnv.add(o,e.duration):Cx(n.allDay,o,t),c=hk(s.defId,{start:o,end:l});return{def:s,instance:c}}function J9e(n){let e=X9e(n,"event"),t=e?JSON.parse(e):{create:!1};return qx(t)}function X9e(n,e){let t=kk.dataAttrPrefix,r=(t?t+"-":"")+e;return n.getAttribute("data-"+r)||""}var uW,oR,pW,lR,mW,cR,dR,fW,Cye,hW,Yp,gW,Ph,yW,vW,Jx,kW,TW,K9e,Z9e,bW,uR,Eye,SW=y(()=>{Eh();Dh();kk.touchMouseIgnoreWait=500;uW=0,oR=0,pW=!1,lR=class{constructor(e){this.subjectEl=null,this.selector="",this.handleSelector="",this.shouldIgnoreMove=!1,this.shouldWatchScroll=!0,this.isDragging=!1,this.isTouchDragging=!1,this.wasTouchScroll=!1,this.handleMouseDown=t=>{if(!this.shouldIgnoreMouse()&&z9e(t)&&this.tryStart(t)){let r=this.createEventFromMouse(t,!0);this.emitter.trigger("pointerdown",r),this.initScrollWatch(r),this.shouldIgnoreMove||document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp)}},this.handleMouseMove=t=>{let r=this.createEventFromMouse(t);this.recordCoords(r),this.emitter.trigger("pointermove",r)},this.handleMouseUp=t=>{document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp),this.emitter.trigger("pointerup",this.createEventFromMouse(t)),this.cleanup()},this.handleTouchStart=t=>{if(this.tryStart(t)){this.isTouchDragging=!0;let r=this.createEventFromTouch(t,!0);this.emitter.trigger("pointerdown",r),this.initScrollWatch(r);let a=t.target;this.shouldIgnoreMove||a.addEventListener("touchmove",this.handleTouchMove),a.addEventListener("touchend",this.handleTouchEnd),a.addEventListener("touchcancel",this.handleTouchEnd),window.addEventListener("scroll",this.handleTouchScroll,!0)}},this.handleTouchMove=t=>{let r=this.createEventFromTouch(t);this.recordCoords(r),this.emitter.trigger("pointermove",r)},this.handleTouchEnd=t=>{if(this.isDragging){let r=t.target;r.removeEventListener("touchmove",this.handleTouchMove),r.removeEventListener("touchend",this.handleTouchEnd),r.removeEventListener("touchcancel",this.handleTouchEnd),window.removeEventListener("scroll",this.handleTouchScroll,!0),this.emitter.trigger("pointerup",this.createEventFromTouch(t)),this.cleanup(),this.isTouchDragging=!1,B9e()}},this.handleTouchScroll=()=>{this.wasTouchScroll=!0},this.handleScroll=t=>{if(!this.shouldIgnoreMove){let r=window.scrollX-this.prevScrollX+this.prevPageX,a=window.scrollY-this.prevScrollY+this.prevPageY;this.emitter.trigger("pointermove",{origEvent:t,isTouch:this.isTouchDragging,subjectEl:this.subjectEl,pageX:r,pageY:a,deltaX:r-this.origPageX,deltaY:a-this.origPageY})}},this.containerEl=e,this.emitter=new tu,e.addEventListener("mousedown",this.handleMouseDown),e.addEventListener("touchstart",this.handleTouchStart,{passive:!0}),j9e()}destroy(){this.containerEl.removeEventListener("mousedown",this.handleMouseDown),this.containerEl.removeEventListener("touchstart",this.handleTouchStart,{passive:!0}),$9e()}tryStart(e){let t=this.querySubjectEl(e),r=e.target;return t&&(!this.handleSelector||Yn(r,this.handleSelector))?(this.subjectEl=t,this.isDragging=!0,this.wasTouchScroll=!1,!0):!1}cleanup(){pW=!1,this.isDragging=!1,this.subjectEl=null,this.destroyScrollWatch()}querySubjectEl(e){return this.selector?Yn(e.target,this.selector):this.containerEl}shouldIgnoreMouse(){return uW||this.isTouchDragging}cancelTouchScroll(){this.isDragging&&(pW=!0)}initScrollWatch(e){this.shouldWatchScroll&&(this.recordCoords(e),window.addEventListener("scroll",this.handleScroll,!0))}recordCoords(e){this.shouldWatchScroll&&(this.prevPageX=e.pageX,this.prevPageY=e.pageY,this.prevScrollX=window.scrollX,this.prevScrollY=window.scrollY)}destroyScrollWatch(){this.shouldWatchScroll&&window.removeEventListener("scroll",this.handleScroll,!0)}createEventFromMouse(e,t){let r=0,a=0;return t?(this.origPageX=e.pageX,this.origPageY=e.pageY):(r=e.pageX-this.origPageX,a=e.pageY-this.origPageY),{origEvent:e,isTouch:!1,subjectEl:this.subjectEl,pageX:e.pageX,pageY:e.pageY,deltaX:r,deltaY:a}}createEventFromTouch(e,t){let r=e.touches,a,i,s=0,o=0;return r&&r.length?(a=r[0].pageX,i=r[0].pageY):(a=e.pageX,i=e.pageY),t?(this.origPageX=a,this.origPageY=i):(s=a-this.origPageX,o=i-this.origPageY),{origEvent:e,isTouch:!0,subjectEl:this.subjectEl,pageX:a,pageY:i,deltaX:s,deltaY:o}}};mW=class{constructor(){this.isVisible=!1,this.sourceEl=null,this.mirrorEl=null,this.sourceElRect=null,this.parentNode=document.body,this.zIndex=9999,this.revertDuration=0}start(e,t,r){this.sourceEl=e,this.sourceElRect=this.sourceEl.getBoundingClientRect(),this.origScreenX=t-window.scrollX,this.origScreenY=r-window.scrollY,this.deltaX=0,this.deltaY=0,this.updateElPosition()}handleMove(e,t){this.deltaX=e-window.scrollX-this.origScreenX,this.deltaY=t-window.scrollY-this.origScreenY,this.updateElPosition()}setIsVisible(e){e?this.isVisible||(this.mirrorEl&&(this.mirrorEl.style.display=""),this.isVisible=e,this.updateElPosition()):this.isVisible&&(this.mirrorEl&&(this.mirrorEl.style.display="none"),this.isVisible=e)}stop(e,t){let r=()=>{this.cleanup(),t()};e&&this.mirrorEl&&this.isVisible&&this.revertDuration&&(this.deltaX||this.deltaY)?this.doRevertAnimation(r,this.revertDuration):setTimeout(r,0)}doRevertAnimation(e,t){let r=this.mirrorEl,a=this.sourceEl.getBoundingClientRect();r.style.transition="top "+t+"ms,left "+t+"ms",wh(r,{left:a.left,top:a.top}),mV(r,()=>{r.style.transition="",e()})}cleanup(){this.mirrorEl&&(Rx(this.mirrorEl),this.mirrorEl=null),this.sourceEl=null}updateElPosition(){this.sourceEl&&this.isVisible&&wh(this.getMirrorEl(),{left:this.sourceElRect.left+this.deltaX,top:this.sourceElRect.top+this.deltaY})}getMirrorEl(){let e=this.sourceElRect,t=this.mirrorEl;return t||(t=this.mirrorEl=this.sourceEl.cloneNode(!0),t.style.userSelect="none",t.style.webkitUserSelect="none",t.style.pointerEvents="none",t.classList.add("fc-event-dragging"),wh(t,{position:"fixed",zIndex:this.zIndex,visibility:"",boxSizing:"border-box",width:e.right-e.left,height:e.bottom-e.top,right:"auto",bottom:"auto",margin:0}),this.parentNode.appendChild(t)),t}},cR=class extends hh{constructor(e,t){super(),this.handleScroll=()=>{this.scrollTop=this.scrollController.getScrollTop(),this.scrollLeft=this.scrollController.getScrollLeft(),this.handleScrollChange()},this.scrollController=e,this.doesListening=t,this.scrollTop=this.origScrollTop=e.getScrollTop(),this.scrollLeft=this.origScrollLeft=e.getScrollLeft(),this.scrollWidth=e.getScrollWidth(),this.scrollHeight=e.getScrollHeight(),this.clientWidth=e.getClientWidth(),this.clientHeight=e.getClientHeight(),this.clientRect=this.computeClientRect(),this.doesListening&&this.getEventTarget().addEventListener("scroll",this.handleScroll)}destroy(){this.doesListening&&this.getEventTarget().removeEventListener("scroll",this.handleScroll)}getScrollTop(){return this.scrollTop}getScrollLeft(){return this.scrollLeft}setScrollTop(e){this.scrollController.setScrollTop(e),this.doesListening||(this.scrollTop=Math.max(Math.min(e,this.getMaxScrollTop()),0),this.handleScrollChange())}setScrollLeft(e){this.scrollController.setScrollLeft(e),this.doesListening||(this.scrollLeft=Math.max(Math.min(e,this.getMaxScrollLeft()),0),this.handleScrollChange())}getClientWidth(){return this.clientWidth}getClientHeight(){return this.clientHeight}getScrollWidth(){return this.scrollWidth}getScrollHeight(){return this.scrollHeight}handleScrollChange(){}},dR=class extends cR{constructor(e,t){super(new Px(e),t)}getEventTarget(){return this.scrollController.el}computeClientRect(){return KV(this.scrollController.el)}},fW=class extends cR{constructor(e){super(new Ax,e)}getEventTarget(){return window}computeClientRect(){return{left:this.scrollLeft,right:this.scrollLeft+this.clientWidth,top:this.scrollTop,bottom:this.scrollTop+this.clientHeight}}handleScrollChange(){this.clientRect=this.computeClientRect()}},Cye=typeof performance=="function"?performance.now:Date.now,hW=class{constructor(){this.isEnabled=!0,this.scrollQuery=[window,".fc-scroller"],this.edgeThreshold=50,this.maxVelocity=300,this.pointerScreenX=null,this.pointerScreenY=null,this.isAnimating=!1,this.scrollCaches=null,this.everMovedUp=!1,this.everMovedDown=!1,this.everMovedLeft=!1,this.everMovedRight=!1,this.animate=()=>{if(this.isAnimating){let e=this.computeBestEdge(this.pointerScreenX+window.scrollX,this.pointerScreenY+window.scrollY);if(e){let t=Cye();this.handleSide(e,(t-this.msSinceRequest)/1e3),this.requestAnimation(t)}else this.isAnimating=!1}}}start(e,t,r){this.isEnabled&&(this.scrollCaches=this.buildCaches(r),this.pointerScreenX=null,this.pointerScreenY=null,this.everMovedUp=!1,this.everMovedDown=!1,this.everMovedLeft=!1,this.everMovedRight=!1,this.handleMove(e,t))}handleMove(e,t){if(this.isEnabled){let r=e-window.scrollX,a=t-window.scrollY,i=this.pointerScreenY===null?0:a-this.pointerScreenY,s=this.pointerScreenX===null?0:r-this.pointerScreenX;i<0?this.everMovedUp=!0:i>0&&(this.everMovedDown=!0),s<0?this.everMovedLeft=!0:s>0&&(this.everMovedRight=!0),this.pointerScreenX=r,this.pointerScreenY=a,this.isAnimating||(this.isAnimating=!0,this.requestAnimation(Cye()))}}stop(){if(this.isEnabled){this.isAnimating=!1;for(let e of this.scrollCaches)e.destroy();this.scrollCaches=null}}requestAnimation(e){this.msSinceRequest=e,requestAnimationFrame(this.animate)}handleSide(e,t){let{scrollCache:r}=e,{edgeThreshold:a}=this,i=a-e.distance,s=i*i/(a*a)*this.maxVelocity*t,o=1;switch(e.name){case"left":o=-1;case"right":r.setScrollLeft(r.getScrollLeft()+s*o);break;case"top":o=-1;case"bottom":r.setScrollTop(r.getScrollTop()+s*o);break}}computeBestEdge(e,t){let{edgeThreshold:r}=this,a=null,i=this.scrollCaches||[];for(let s of i){let o=s.clientRect,l=e-o.left,c=o.right-e,d=t-o.top,u=o.bottom-t;l>=0&&c>=0&&d>=0&&u>=0&&(d<=r&&this.everMovedUp&&s.canScrollUp()&&(!a||a.distance>d)&&(a={scrollCache:s,name:"top",distance:d}),u<=r&&this.everMovedDown&&s.canScrollDown()&&(!a||a.distance>u)&&(a={scrollCache:s,name:"bottom",distance:u}),l<=r&&this.everMovedLeft&&s.canScrollLeft()&&(!a||a.distance>l)&&(a={scrollCache:s,name:"left",distance:l}),c<=r&&this.everMovedRight&&s.canScrollRight()&&(!a||a.distance>c)&&(a={scrollCache:s,name:"right",distance:c}))}return a}buildCaches(e){return this.queryScrollEls(e).map(t=>t===window?new fW(!1):new dR(t,!1))}queryScrollEls(e){let t=[];for(let r of this.scrollQuery)typeof r=="object"?t.push(r):t.push(...Array.prototype.slice.call(e.getRootNode().querySelectorAll(r)));return t}},Yp=class extends Nx{constructor(e,t){super(e),this.containerEl=e,this.delay=null,this.minDistance=0,this.touchScrollAllowed=!0,this.mirrorNeedsRevert=!1,this.isInteracting=!1,this.isDragging=!1,this.isDelayEnded=!1,this.isDistanceSurpassed=!1,this.delayTimeoutId=null,this.onPointerDown=a=>{this.isDragging||(this.isInteracting=!0,this.isDelayEnded=!1,this.isDistanceSurpassed=!1,fV(document.body),gV(document.body),a.isTouch||a.origEvent.preventDefault(),this.emitter.trigger("pointerdown",a),this.isInteracting&&!this.pointer.shouldIgnoreMove&&(this.mirror.setIsVisible(!1),this.mirror.start(a.subjectEl,a.pageX,a.pageY),this.startDelay(a),this.minDistance||this.handleDistanceSurpassed(a)))},this.onPointerMove=a=>{if(this.isInteracting){if(this.emitter.trigger("pointermove",a),!this.isDistanceSurpassed){let i=this.minDistance,s,{deltaX:o,deltaY:l}=a;s=o*o+l*l,s>=i*i&&this.handleDistanceSurpassed(a)}this.isDragging&&(a.origEvent.type!=="scroll"&&(this.mirror.handleMove(a.pageX,a.pageY),this.autoScroller.handleMove(a.pageX,a.pageY)),this.emitter.trigger("dragmove",a))}},this.onPointerUp=a=>{this.isInteracting&&(this.isInteracting=!1,hV(document.body),yV(document.body),this.emitter.trigger("pointerup",a),this.isDragging&&(this.autoScroller.stop(),this.tryStopDrag(a)),this.delayTimeoutId&&(clearTimeout(this.delayTimeoutId),this.delayTimeoutId=null))};let r=this.pointer=new lR(e);r.emitter.on("pointerdown",this.onPointerDown),r.emitter.on("pointermove",this.onPointerMove),r.emitter.on("pointerup",this.onPointerUp),t&&(r.selector=t),this.mirror=new mW,this.autoScroller=new hW}destroy(){this.pointer.destroy(),this.onPointerUp({})}startDelay(e){typeof this.delay=="number"?this.delayTimeoutId=setTimeout(()=>{this.delayTimeoutId=null,this.handleDelayEnd(e)},this.delay):this.handleDelayEnd(e)}handleDelayEnd(e){this.isDelayEnded=!0,this.tryStartDrag(e)}handleDistanceSurpassed(e){this.isDistanceSurpassed=!0,this.tryStartDrag(e)}tryStartDrag(e){this.isDelayEnded&&this.isDistanceSurpassed&&(!this.pointer.wasTouchScroll||this.touchScrollAllowed)&&(this.isDragging=!0,this.mirrorNeedsRevert=!1,this.autoScroller.start(e.pageX,e.pageY,this.containerEl),this.emitter.trigger("dragstart",e),this.touchScrollAllowed===!1&&this.pointer.cancelTouchScroll())}tryStopDrag(e){this.mirror.stop(this.mirrorNeedsRevert,this.stopDrag.bind(this,e))}stopDrag(e){this.isDragging=!1,this.emitter.trigger("dragend",e)}setIgnoreMove(e){this.pointer.shouldIgnoreMove=e}setMirrorIsVisible(e){this.mirror.setIsVisible(e)}setMirrorNeedsRevert(e){this.mirrorNeedsRevert=e}setAutoScrollEnabled(e){this.autoScroller.isEnabled=e}},gW=class{constructor(e){this.el=e,this.origRect=Vx(e),this.scrollCaches=rR(e).map(t=>new dR(t,!0))}destroy(){for(let e of this.scrollCaches)e.destroy()}computeLeft(){let e=this.origRect.left;for(let t of this.scrollCaches)e+=t.origScrollLeft-t.getScrollLeft();return e}computeTop(){let e=this.origRect.top;for(let t of this.scrollCaches)e+=t.origScrollTop-t.getScrollTop();return e}isWithinClipping(e,t){let r={left:e,top:t};for(let a of this.scrollCaches)if(!U9e(a.getEventTarget())&&!WV(r,a.clientRect))return!1;return!0}};Ph=class{constructor(e,t){this.useSubjectCenter=!1,this.requireInitial=!0,this.disablePointCheck=!1,this.initialHit=null,this.movingHit=null,this.finalHit=null,this.handlePointerDown=r=>{let{dragging:a}=this;this.initialHit=null,this.movingHit=null,this.finalHit=null,this.prepareHits(),this.processFirstCoord(r),this.initialHit||!this.requireInitial?(a.setIgnoreMove(!1),this.emitter.trigger("pointerdown",r)):a.setIgnoreMove(!0)},this.handleDragStart=r=>{this.emitter.trigger("dragstart",r),this.handleMove(r,!0)},this.handleDragMove=r=>{this.emitter.trigger("dragmove",r),this.handleMove(r)},this.handlePointerUp=r=>{this.releaseHits(),this.emitter.trigger("pointerup",r)},this.handleDragEnd=r=>{this.movingHit&&this.emitter.trigger("hitupdate",null,!0,r),this.finalHit=this.movingHit,this.movingHit=null,this.emitter.trigger("dragend",r)},this.droppableStore=t,e.emitter.on("pointerdown",this.handlePointerDown),e.emitter.on("dragstart",this.handleDragStart),e.emitter.on("dragmove",this.handleDragMove),e.emitter.on("pointerup",this.handlePointerUp),e.emitter.on("dragend",this.handleDragEnd),this.dragging=e,this.emitter=new tu}processFirstCoord(e){let t={left:e.pageX,top:e.pageY},r=t,a=e.subjectEl,i;a instanceof HTMLElement&&(i=Vx(a),r=qV(r,i));let s=this.initialHit=this.queryHitForOffset(r.left,r.top);if(s){if(this.useSubjectCenter&&i){let o=tR(i,s.rect);o&&(r=GV(o))}this.coordAdjust=YV(r,t)}else this.coordAdjust={left:0,top:0}}handleMove(e,t){let r=this.queryHitForOffset(e.pageX+this.coordAdjust.left,e.pageY+this.coordAdjust.top);(t||!pR(this.movingHit,r))&&(this.movingHit=r,this.emitter.trigger("hitupdate",r,!1,e))}prepareHits(){this.offsetTrackers=To(this.droppableStore,e=>(e.component.prepareHits(),new gW(e.el)))}releaseHits(){let{offsetTrackers:e}=this;for(let t in e)e[t].destroy();this.offsetTrackers={}}queryHitForOffset(e,t){let{droppableStore:r,offsetTrackers:a}=this,i=null;for(let s in r){let o=r[s].component,l=a[s];if(l&&l.isWithinClipping(e,t)){let c=l.computeLeft(),d=l.computeTop(),u=e-c,p=t-d,{origRect:m}=l,f=m.right-m.left,h=m.bottom-m.top;if(u>=0&&u=0&&pi.layer)&&(g.componentId=s,g.context=o.context,g.rect.left+=c,g.rect.right+=c,g.rect.top+=d,g.rect.bottom+=d,i=g)}}}return i}};yW=class extends hl{constructor(e){super(e),this.handlePointerDown=r=>{let{dragging:a}=this,i=r.origEvent.target;a.setIgnoreMove(!this.component.isValidDateDownEl(i))},this.handleDragEnd=r=>{let{component:a}=this,{pointer:i}=this.dragging;if(!i.wasTouchScroll){let{initialHit:s,finalHit:o}=this.hitDragging;if(s&&o&&pR(s,o)){let{context:l}=a,c=Object.assign(Object.assign({},wW(s.dateSpan,l)),{dayEl:s.dayEl,jsEvent:r.origEvent,view:l.viewApi||l.calendarApi.view});l.emitter.trigger("dateClick",c)}}},this.dragging=new Yp(e.el),this.dragging.autoScroller.isEnabled=!1;let t=this.hitDragging=new Ph(this.dragging,Ux(e));t.emitter.on("pointerdown",this.handlePointerDown),t.emitter.on("dragend",this.handleDragEnd)}destroy(){this.dragging.destroy()}},vW=class extends hl{constructor(e){super(e),this.dragSelection=null,this.handlePointerDown=s=>{let{component:o,dragging:l}=this,{options:c}=o.context,d=c.selectable&&o.isValidDateDownEl(s.origEvent.target);l.setIgnoreMove(!d),l.delay=s.isTouch?V9e(o):null},this.handleDragStart=s=>{this.component.context.calendarApi.unselect(s)},this.handleHitUpdate=(s,o)=>{let{context:l}=this.component,c=null,d=!1;if(s){let u=this.hitDragging.initialHit;s.componentId===u.componentId&&this.isHitComboAllowed&&!this.isHitComboAllowed(u,s)||(c=W9e(u,s,l.pluginHooks.dateSelectionTransformers)),(!c||!QV(c,s.dateProfile,l))&&(d=!0,c=null)}c?l.dispatch({type:"SELECT_DATES",selection:c}):o||l.dispatch({type:"UNSELECT_DATES"}),d?ck():dk(),o||(this.dragSelection=c)},this.handlePointerUp=s=>{this.dragSelection&&(eR(this.dragSelection,s,this.component.context),this.dragSelection=null)};let{component:t}=e,{options:r}=t.context,a=this.dragging=new Yp(e.el);a.touchScrollAllowed=!1,a.minDistance=r.selectMinDistance||0,a.autoScroller.isEnabled=r.dragScroll;let i=this.hitDragging=new Ph(this.dragging,Ux(e));i.emitter.on("pointerdown",this.handlePointerDown),i.emitter.on("dragstart",this.handleDragStart),i.emitter.on("hitupdate",this.handleHitUpdate),i.emitter.on("pointerup",this.handlePointerUp)}destroy(){this.dragging.destroy()}};Jx=class n extends hl{constructor(e){super(e),this.subjectEl=null,this.subjectSeg=null,this.isDragging=!1,this.eventRange=null,this.relevantEvents=null,this.receivingContext=null,this.validMutation=null,this.mutatedRelevantEvents=null,this.handlePointerDown=s=>{let o=s.origEvent.target,{component:l,dragging:c}=this,{mirror:d}=c,{options:u}=l.context,p=l.context;this.subjectEl=s.subjectEl;let m=this.subjectSeg=iu(s.subjectEl),h=(this.eventRange=m.eventRange).instance.instanceId;this.relevantEvents=Bx(p.getCurrentData().eventStore,h),c.minDistance=s.isTouch?0:u.eventDragMinDistance,c.delay=s.isTouch&&h!==l.props.eventSelection?G9e(l):null,u.fixedMirrorParent?d.parentNode=u.fixedMirrorParent:d.parentNode=Yn(o,".fc"),d.revertDuration=u.dragRevertDuration;let g=l.isValidSegDownEl(o)&&!Yn(o,".fc-event-resizer");c.setIgnoreMove(!g),this.isDragging=g&&s.subjectEl.classList.contains("fc-event-draggable")},this.handleDragStart=s=>{let o=this.component.context,l=this.eventRange,c=l.instance.instanceId;s.isTouch?c!==this.component.props.eventSelection&&o.dispatch({type:"SELECT_EVENT",eventInstanceId:c}):o.dispatch({type:"UNSELECT_EVENT"}),this.isDragging&&(o.calendarApi.unselect(s),o.emitter.trigger("eventDragStart",{el:this.subjectEl,event:new vr(o,l.def,l.instance),jsEvent:s.origEvent,view:o.viewApi}))},this.handleHitUpdate=(s,o)=>{if(!this.isDragging)return;let l=this.relevantEvents,c=this.hitDragging.initialHit,d=this.component.context,u=null,p=null,m=null,f=!1,h={affectedEvents:l,mutatedEvents:Kn(),isEvent:!0};if(s){u=s.context;let g=u.options;d===u||g.editable&&g.droppable?(p=q9e(c,s,this.eventRange.instance.range.start,u.getCurrentData().pluginHooks.eventDragMutationMassagers),p&&(m=jx(l,u.getCurrentData().eventUiBases,p,u),h.mutatedEvents=m,Gx(h,s.dateProfile,u)||(f=!0,p=null,m=null,h.mutatedEvents=Kn()))):u=null}this.displayDrag(u,h),f?ck():dk(),o||(d===u&&pR(c,s)&&(p=null),this.dragging.setMirrorNeedsRevert(!p),this.dragging.setMirrorIsVisible(!s||!this.subjectEl.getRootNode().querySelector(".fc-event-mirror")),this.receivingContext=u,this.validMutation=p,this.mutatedRelevantEvents=m)},this.handlePointerUp=()=>{this.isDragging||this.cleanup()},this.handleDragEnd=s=>{if(this.isDragging){let o=this.component.context,l=o.viewApi,{receivingContext:c,validMutation:d}=this,u=this.eventRange.def,p=this.eventRange.instance,m=new vr(o,u,p),f=this.relevantEvents,h=this.mutatedRelevantEvents,{finalHit:g}=this.hitDragging;if(this.clearDrag(),o.emitter.trigger("eventDragStop",{el:this.subjectEl,event:m,jsEvent:s.origEvent,view:l}),d){if(c===o){let v=new vr(o,h.defs[u.defId],p?h.instances[p.instanceId]:null);o.dispatch({type:"MERGE_EVENTS",eventStore:h});let k={oldEvent:m,event:v,relatedEvents:Sc(h,o,p),revert(){o.dispatch({type:"MERGE_EVENTS",eventStore:f})}},T={};for(let b of o.getCurrentData().pluginHooks.eventDropTransformers)Object.assign(T,b(d,o));o.emitter.trigger("eventDrop",Object.assign(Object.assign(Object.assign({},k),T),{el:s.subjectEl,delta:d.datesDelta,jsEvent:s.origEvent,view:l})),o.emitter.trigger("eventChange",k)}else if(c){let v={event:m,relatedEvents:Sc(f,o,p),revert(){o.dispatch({type:"MERGE_EVENTS",eventStore:f})}};o.emitter.trigger("eventLeave",Object.assign(Object.assign({},v),{draggedEl:s.subjectEl,view:l})),o.dispatch({type:"REMOVE_EVENTS",eventStore:f}),o.emitter.trigger("eventRemove",v);let k=h.defs[u.defId],T=h.instances[p.instanceId],b=new vr(c,k,T);c.dispatch({type:"MERGE_EVENTS",eventStore:h});let w={event:b,relatedEvents:Sc(h,c,T),revert(){c.dispatch({type:"REMOVE_EVENTS",eventStore:h})}};c.emitter.trigger("eventAdd",w),s.isTouch&&c.dispatch({type:"SELECT_EVENT",eventInstanceId:p.instanceId}),c.emitter.trigger("drop",Object.assign(Object.assign({},wW(g.dateSpan,c)),{draggedEl:s.subjectEl,jsEvent:s.origEvent,view:g.context.viewApi})),c.emitter.trigger("eventReceive",Object.assign(Object.assign({},w),{draggedEl:s.subjectEl,view:g.context.viewApi}))}}else o.emitter.trigger("_noEventDrop")}this.cleanup()};let{component:t}=this,{options:r}=t.context,a=this.dragging=new Yp(e.el);a.pointer.selector=n.SELECTOR,a.touchScrollAllowed=!1,a.autoScroller.isEnabled=r.dragScroll;let i=this.hitDragging=new Ph(this.dragging,Ch);i.useSubjectCenter=e.useEventCenter,i.emitter.on("pointerdown",this.handlePointerDown),i.emitter.on("dragstart",this.handleDragStart),i.emitter.on("hitupdate",this.handleHitUpdate),i.emitter.on("pointerup",this.handlePointerUp),i.emitter.on("dragend",this.handleDragEnd)}destroy(){this.dragging.destroy()}displayDrag(e,t){let r=this.component.context,a=this.receivingContext;a&&a!==e&&(a===r?a.dispatch({type:"SET_EVENT_DRAG",state:{affectedEvents:t.affectedEvents,mutatedEvents:Kn(),isEvent:!0}}):a.dispatch({type:"UNSET_EVENT_DRAG"})),e&&e.dispatch({type:"SET_EVENT_DRAG",state:t})}clearDrag(){let e=this.component.context,{receivingContext:t}=this;t&&t.dispatch({type:"UNSET_EVENT_DRAG"}),e!==t&&e.dispatch({type:"UNSET_EVENT_DRAG"})}cleanup(){this.subjectSeg=null,this.isDragging=!1,this.eventRange=null,this.relevantEvents=null,this.receivingContext=null,this.validMutation=null,this.mutatedRelevantEvents=null}};Jx.SELECTOR=".fc-event-draggable, .fc-event-resizable";kW=class extends hl{constructor(e){super(e),this.draggingSegEl=null,this.draggingSeg=null,this.eventRange=null,this.relevantEvents=null,this.validMutation=null,this.mutatedRelevantEvents=null,this.handlePointerDown=i=>{let{component:s}=this,o=this.querySegEl(i),l=iu(o),c=this.eventRange=l.eventRange;this.dragging.minDistance=s.context.options.eventDragMinDistance,this.dragging.setIgnoreMove(!this.component.isValidSegDownEl(i.origEvent.target)||i.isTouch&&this.component.props.eventSelection!==c.instance.instanceId)},this.handleDragStart=i=>{let{context:s}=this.component,o=this.eventRange;this.relevantEvents=Bx(s.getCurrentData().eventStore,this.eventRange.instance.instanceId);let l=this.querySegEl(i);this.draggingSegEl=l,this.draggingSeg=iu(l),s.calendarApi.unselect(),s.emitter.trigger("eventResizeStart",{el:l,event:new vr(s,o.def,o.instance),jsEvent:i.origEvent,view:s.viewApi})},this.handleHitUpdate=(i,s,o)=>{let{context:l}=this.component,c=this.relevantEvents,d=this.hitDragging.initialHit,u=this.eventRange.instance,p=null,m=null,f=!1,h={affectedEvents:c,mutatedEvents:Kn(),isEvent:!0};i&&(i.componentId===d.componentId&&this.isHitComboAllowed&&!this.isHitComboAllowed(d,i)||(p=Y9e(d,i,o.subjectEl.classList.contains("fc-event-resizer-start"),u.range))),p&&(m=jx(c,l.getCurrentData().eventUiBases,p,l),h.mutatedEvents=m,Gx(h,i.dateProfile,l)||(f=!0,p=null,m=null,h.mutatedEvents=null)),m?l.dispatch({type:"SET_EVENT_RESIZE",state:h}):l.dispatch({type:"UNSET_EVENT_RESIZE"}),f?ck():dk(),s||(p&&pR(d,i)&&(p=null),this.validMutation=p,this.mutatedRelevantEvents=m)},this.handleDragEnd=i=>{let{context:s}=this.component,o=this.eventRange.def,l=this.eventRange.instance,c=new vr(s,o,l),d=this.relevantEvents,u=this.mutatedRelevantEvents;if(s.emitter.trigger("eventResizeStop",{el:this.draggingSegEl,event:c,jsEvent:i.origEvent,view:s.viewApi}),this.validMutation){let p=new vr(s,u.defs[o.defId],l?u.instances[l.instanceId]:null);s.dispatch({type:"MERGE_EVENTS",eventStore:u});let m={oldEvent:c,event:p,relatedEvents:Sc(u,s,l),revert(){s.dispatch({type:"MERGE_EVENTS",eventStore:d})}};s.emitter.trigger("eventResize",Object.assign(Object.assign({},m),{el:this.draggingSegEl,startDelta:this.validMutation.startDelta||lt(0),endDelta:this.validMutation.endDelta||lt(0),jsEvent:i.origEvent,view:s.viewApi})),s.emitter.trigger("eventChange",m)}else s.emitter.trigger("_noEventResize");this.draggingSeg=null,this.relevantEvents=null,this.validMutation=null};let{component:t}=e,r=this.dragging=new Yp(e.el);r.pointer.selector=".fc-event-resizer",r.touchScrollAllowed=!1,r.autoScroller.isEnabled=t.context.options.dragScroll;let a=this.hitDragging=new Ph(this.dragging,Ux(e));a.emitter.on("pointerdown",this.handlePointerDown),a.emitter.on("dragstart",this.handleDragStart),a.emitter.on("hitupdate",this.handleHitUpdate),a.emitter.on("dragend",this.handleDragEnd)}destroy(){this.dragging.destroy()}querySegEl(e){return Yn(e.subjectEl,".fc-event")}};TW=class{constructor(e){this.context=e,this.isRecentPointerDateSelect=!1,this.matchesCancel=!1,this.matchesEvent=!1,this.onSelect=r=>{r.jsEvent&&(this.isRecentPointerDateSelect=!0)},this.onDocumentPointerDown=r=>{let a=this.context.options.unselectCancel,i=VN(r.origEvent);this.matchesCancel=!!Yn(i,a),this.matchesEvent=!!Yn(i,Jx.SELECTOR)},this.onDocumentPointerUp=r=>{let{context:a}=this,{documentPointer:i}=this,s=a.getCurrentData();if(!i.wasTouchScroll){if(s.dateSelection&&!this.isRecentPointerDateSelect){let o=a.options.unselectAuto;o&&(!o||!this.matchesCancel)&&a.calendarApi.unselect(r)}s.eventSelection&&!this.matchesEvent&&a.dispatch({type:"UNSELECT_EVENT"})}this.isRecentPointerDateSelect=!1};let t=this.documentPointer=new lR(document);t.shouldIgnoreMove=!0,t.shouldWatchScroll=!1,t.emitter.on("pointerdown",this.onDocumentPointerDown),t.emitter.on("pointerup",this.onDocumentPointerUp),e.emitter.on("select",this.onSelect)}destroy(){this.context.emitter.off("select",this.onSelect),this.documentPointer.destroy()}},K9e={fixedMirrorParent:B},Z9e={dateClick:B,eventDragStart:B,eventDragStop:B,eventDrop:B,eventResizeStart:B,eventResizeStop:B,eventResize:B,drop:B,eventReceive:B,eventLeave:B},bW=class{constructor(e,t){this.receivingContext=null,this.droppableEvent=null,this.suppliedDragMeta=null,this.dragMeta=null,this.handleDragStart=a=>{this.dragMeta=this.buildDragMeta(a.subjectEl)},this.handleHitUpdate=(a,i,s)=>{let{dragging:o}=this.hitDragging,l=null,c=null,d=!1,u={affectedEvents:Kn(),mutatedEvents:Kn(),isEvent:this.dragMeta.create};a&&(l=a.context,this.canDropElOnCalendar(s.subjectEl,l)&&(c=Q9e(a.dateSpan,this.dragMeta,l),u.mutatedEvents=fh(c),d=!Gx(u,a.dateProfile,l),d&&(u.mutatedEvents=Kn(),c=null))),this.displayDrag(l,u),o.setMirrorIsVisible(i||!c||!document.querySelector(".fc-event-mirror")),d?ck():dk(),i||(o.setMirrorNeedsRevert(!c),this.receivingContext=l,this.droppableEvent=c)},this.handleDragEnd=a=>{let{receivingContext:i,droppableEvent:s}=this;if(this.clearDrag(),i&&s){let o=this.hitDragging.finalHit,l=o.context.viewApi,c=this.dragMeta;if(i.emitter.trigger("drop",Object.assign(Object.assign({},wW(o.dateSpan,i)),{draggedEl:a.subjectEl,jsEvent:a.origEvent,view:l})),c.create){let d=fh(s);i.dispatch({type:"MERGE_EVENTS",eventStore:d}),a.isTouch&&i.dispatch({type:"SELECT_EVENT",eventInstanceId:s.instance.instanceId}),i.emitter.trigger("eventReceive",{event:new vr(i,s.def,s.instance),relatedEvents:[],revert(){i.dispatch({type:"REMOVE_EVENTS",eventStore:d})},draggedEl:a.subjectEl,view:l})}}this.receivingContext=null,this.droppableEvent=null};let r=this.hitDragging=new Ph(e,Ch);r.requireInitial=!1,r.emitter.on("dragstart",this.handleDragStart),r.emitter.on("hitupdate",this.handleHitUpdate),r.emitter.on("dragend",this.handleDragEnd),this.suppliedDragMeta=t}buildDragMeta(e){return typeof this.suppliedDragMeta=="object"?qx(this.suppliedDragMeta):typeof this.suppliedDragMeta=="function"?qx(this.suppliedDragMeta(e)):J9e(e)}displayDrag(e,t){let r=this.receivingContext;r&&r!==e&&r.dispatch({type:"UNSET_EVENT_DRAG"}),e&&e.dispatch({type:"SET_EVENT_DRAG",state:t})}clearDrag(){this.receivingContext&&this.receivingContext.dispatch({type:"UNSET_EVENT_DRAG"})}canDropElOnCalendar(e,t){let r=t.options.dropAccept;return typeof r=="function"?r.call(t.calendarApi,e):typeof r=="string"&&r?!!HN(e,r):!0}};kk.dataAttrPrefix="";uR=class{constructor(e,t={}){this.handlePointerDown=a=>{let{dragging:i}=this,{minDistance:s,longPressDelay:o}=this.settings;i.minDistance=s!=null?s:a.isTouch?0:wc.eventDragMinDistance,i.delay=a.isTouch?o!=null?o:wc.longPressDelay:0},this.handleDragStart=a=>{a.isTouch&&this.dragging.delay&&a.subjectEl.classList.contains("fc-event")&&this.dragging.mirror.getMirrorEl().classList.add("fc-event-selected")},this.settings=t;let r=this.dragging=new Yp(e);r.touchScrollAllowed=!1,t.itemSelector!=null&&(r.pointer.selector=t.itemSelector),t.appendTo!=null&&(r.mirror.parentNode=t.appendTo),r.emitter.on("pointerdown",this.handlePointerDown),r.emitter.on("dragstart",this.handleDragStart),new bW(r,t.eventData)}destroy(){this.dragging.destroy()}},Eye=Wa({name:"@fullcalendar/interaction",componentInteractions:[yW,vW,Jx,kW],calendarInteractions:[TW],elementDraggingImpl:Yp,optionRefiners:K9e,listenerRefiners:Z9e})});var mR,Dye=y(()=>{SW();mR=class{constructor(e){this.draggableInstances=new Map;this.plugin=e}makeTaskCardDraggable(e,t){if(this.draggableInstances.has(e))return;e.dataset.taskPath=t;let r=new uR(e);this.draggableInstances.set(e,r),e.classList.remove("tn-static-cursor-pointer-2723efcc","tn-static-cursor-pointer-3b6a3a65"),e.classList.add("tn-static-cursor-grab-dad79857"),e.addEventListener("dragstart",a=>{e.classList.add("task-card--dragging"),a.dataTransfer&&(a.dataTransfer.setData("text/plain",t),a.dataTransfer.setData("application/x-task-path",t),a.dataTransfer.effectAllowed="copy")}),e.addEventListener("dragend",()=>{e.classList.remove("task-card--dragging")})}removeDraggable(e){let t=this.draggableInstances.get(e);t&&(t.destroy(),this.draggableInstances.delete(e))}destroy(){this.draggableInstances.forEach(e=>{e.destroy()}),this.draggableInstances.clear()}}});function fR(n){if(!n)return null;let e=Date.parse(n);return Number.isFinite(e)?e:null}function Kp(n){return Number.isFinite(n)?Math.max(1,Math.min(7200,Math.floor(n))):60}function hR(n){return Kp(n.plannedDuration*60)}function CW(n,e=Date.now()){var r;let t=((r=n.activePeriods)!=null?r:[]).reduce((a,i)=>{var c;let s=fR(i.startTime);if(s===null)return a;let o=(c=fR(i.endTime))!=null?c:e,l=Math.max(0,o-s);return a+l},0);return Math.floor(t/1e3)}function wk(n,e=Date.now()){let t=hR(n),r=CW(n,e);return Math.max(0,t-r)}function Pye(n,e=Date.now()){let t=Number.isFinite(n)?Math.max(0,Math.floor(n)):0;return e+t*1e3}function Aye(n,e=Date.now()){var r,a;let t=hR(n)*1e3;for(let i of(r=n.activePeriods)!=null?r:[]){let s=fR(i.startTime);if(s===null)continue;let o=(a=fR(i.endTime))!=null?a:e,l=Math.max(0,o-s);if(l>=t)return s+t;t-=l}return null}function Mye(n){let e=new Date(n),t=-e.getTimezoneOffset(),r=t>=0?"+":"-",a=(o,l=2)=>String(Math.abs(o)).padStart(l,"0"),i=a(Math.floor(Math.abs(t)/60)),s=a(Math.abs(t)%60);return`${e.getFullYear()}-${a(e.getMonth()+1)}-${a(e.getDate())}T${a(e.getHours())}:${a(e.getMinutes())}:${a(e.getSeconds())}.${a(e.getMilliseconds(),3)}${r}${i}:${s}`}function Sk(n,e={}){var c;let t=Math.max(0,Math.floor(n)),r=Math.floor(t/60),a=t%60,i=Math.floor(r/60),s=r%60,o=(c=e.padMinutes)!=null?c:!0;return i>0?`${i}:${s.toString().padStart(2,"0")}:${a.toString().padStart(2,"0")}`:`${o?r.toString().padStart(2,"0"):r.toString()}:${a.toString().padStart(2,"0")}`}function Iye(n){let e=n.trim();if(!e)return null;let t=e.split(":");if(t.length<1||t.length>3||!t.every(i=>/^\d+$/.test(i)))return null;let r=t.map(i=>Number(i));if(r.some(i=>!Number.isSafeInteger(i)))return null;let a;if(r.length===1)a=r[0]*60;else if(r.length===2){let[i,s]=r;if(s>59)return null;a=i*60+s}else{let[i,s,o]=r;if(s>59||o>59)return null;a=i*3600+s*60+o}return a<=0?null:Kp(a)}var gR=y(()=>{});var Ec,Nye,yR,Rye=y(()=>{Pr();uU();Ec=require("obsidian");co();gR();q();Nye=M({tag:"Services/StatusBarService"}),yR=class{constructor(e){this.statusBarElement=null;this.pomodoroStatusBarElement=null;this.updateTimeout=null;this.pomodoroUpdateTimeout=null;this.elapsedUpdateInterval=null;this.currentTrackedTasks=[];this.pomodoroEventRefs=[];this.plugin=e,this.requestDeduplicator=new wv}initialize(){this.ensureTrackedStatusBarElement(),this.ensurePomodoroStatusBarElement(),this.registerPomodoroEvents(),this.updateStatusBar(),this.updatePomodoroStatusBar()}ensureTrackedStatusBarElement(){this.statusBarElement||!this.plugin.settings.showTrackedTasksInStatusBar||(this.statusBarElement=this.plugin.addStatusBarItem(),this.statusBarElement.addClass("tasknotes-status-bar"),this.statusBarElement.classList.remove("tn-static-cursor-grab-dad79857","tn-static-cursor-pointer-2723efcc"),this.statusBarElement.classList.add("tn-static-cursor-pointer-3b6a3a65"),this.statusBarElement.addEventListener("click",()=>{this.handleStatusBarClick()}))}ensurePomodoroStatusBarElement(){this.pomodoroStatusBarElement||!this.plugin.settings.showPomodoroInStatusBar||(this.pomodoroStatusBarElement=this.plugin.addStatusBarItem(),this.pomodoroStatusBarElement.addClass("tasknotes-status-bar"),this.pomodoroStatusBarElement.addClass("tasknotes-pomodoro-status"),this.pomodoroStatusBarElement.classList.remove("tn-static-cursor-grab-dad79857","tn-static-cursor-pointer-2723efcc"),this.pomodoroStatusBarElement.classList.add("tn-static-cursor-pointer-3b6a3a65"),this.pomodoroStatusBarElement.addEventListener("click",()=>{this.plugin.activatePomodoroView()}))}registerPomodoroEvents(){var t;if(this.pomodoroEventRefs.length>0||!((t=this.plugin.emitter)!=null&&t.on))return;let e=()=>this.requestPomodoroUpdate();this.pomodoroEventRefs=[this.plugin.emitter.on(cd,e),this.plugin.emitter.on(ai,e),this.plugin.emitter.on(dd,e),this.plugin.emitter.on(ud,e)]}async updateStatusBar(){if(!this.statusBarElement){this.stopElapsedTicker();return}if(!this.plugin.settings.showTrackedTasksInStatusBar){this.hide();return}try{let e=await this.requestDeduplicator.execute("update-status-bar",()=>this.getTrackedTasks());this.renderStatusBar(e)}catch(e){Nye.error("Error updating status bar:",{category:"internal",operation:"updating-status-bar",error:e})}}updatePomodoroStatusBar(){if(!this.plugin.settings.showPomodoroInStatusBar){this.hidePomodoroStatusBar();return}if(this.ensurePomodoroStatusBarElement(),!this.pomodoroStatusBarElement||!this.plugin.pomodoroService)return;let e=this.plugin.pomodoroService.getState();if(!e.currentSession){this.hidePomodoroStatusBar();return}this.showElement(this.pomodoroStatusBarElement),this.renderPomodoroStatusBar(e)}async getTrackedTasks(){return this.plugin.cacheManager.getAllCachedTasks().filter(t=>t.archived?!1:this.plugin.getActiveTimeSession(t)!==null)}renderStatusBar(e){if(!this.statusBarElement)return;this.currentTrackedTasks=[...e];let t=e.length;if(t===0){this.stopElapsedTicker(),this.statusBarElement.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-min-height-800px-997b4c8c"),this.statusBarElement.classList.add("tn-static-display-none-6b99de8b");return}this.startElapsedTicker(),this.statusBarElement.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),this.statusBarElement.style.removeProperty("display"),this.statusBarElement.empty();let r=this.statusBarElement.createSpan({cls:"tasknotes-status-icon"});(0,Ec.setIcon)(r,"timer");let a=this.statusBarElement.createSpan({cls:"tasknotes-status-text"});if(t===1){let i=e[0],s=i.title.length>30?i.title.substring(0,30)+"...":i.title,o=this.formatElapsedDuration(this.getActiveElapsedMs(i));a.setText(`Tracking: ${s} (${o})`),(0,Ec.setTooltip)(this.statusBarElement,`Currently tracking: ${i.title} +Elapsed: ${o}`,{placement:"top"})}else{let i=this.formatElapsedDuration(e.reduce((l,c)=>l+this.getActiveElapsedMs(c),0));a.setText(`Tracking ${t} tasks (${i} total)`);let s=e.slice(0,5).map(l=>`${l.title} - ${this.formatElapsedDuration(this.getActiveElapsedMs(l))}`).join(` +`),o=t>5?`${s} +... and ${t-5} more`:s;(0,Ec.setTooltip)(this.statusBarElement,`Currently tracking: +${o}`,{placement:"top"})}}renderPomodoroStatusBar(e){if(!this.pomodoroStatusBarElement||!e.currentSession)return;this.pomodoroStatusBarElement.empty();let t=this.pomodoroStatusBarElement.createSpan({cls:"tasknotes-status-icon"});(0,Ec.setIcon)(t,e.currentSession.type==="work"?"timer":"coffee");let r=this.pomodoroStatusBarElement.createSpan({cls:"tasknotes-status-text"}),a=Sk(e.timeRemaining),i=this.getPomodoroSessionLabel(e.currentSession.type),s=e.isRunning?i:`${i} paused`;r.setText(`${s}: ${a}`),(0,Ec.setTooltip)(this.pomodoroStatusBarElement,`${s} +Remaining: ${a} +Click to open Pomodoro`,{placement:"top"})}getPomodoroSessionLabel(e){return e==="work"?"Focus":e==="short-break"?"Short break":"Long break"}showElement(e){e.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),e.style.removeProperty("display")}getActiveElapsedMs(e){let t=this.plugin.getActiveTimeSession(e);if(!(t!=null&&t.startTime))return 0;let r=Date.parse(t.startTime);return Number.isFinite(r)?Math.max(0,Date.now()-r):0}formatElapsedDuration(e){let t=Math.floor(e/1e3),r=t%60,a=Math.floor(t/60),i=a%60,s=Math.floor(a/60);return s>0?`${s}:${i.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`:`${i}:${r.toString().padStart(2,"0")}`}startElapsedTicker(){this.elapsedUpdateInterval===null&&(this.elapsedUpdateInterval=window.setInterval(()=>{if(this.currentTrackedTasks.length===0){this.stopElapsedTicker();return}this.renderStatusBar(this.currentTrackedTasks)},1e3))}stopElapsedTicker(){this.elapsedUpdateInterval!==null&&(window.clearInterval(this.elapsedUpdateInterval),this.elapsedUpdateInterval=null),this.currentTrackedTasks=[]}async handleStatusBarClick(){try{let e=await this.getTrackedTasks();if(e.length===0)return;if(e.length===1){let t=e[0],r=this.plugin.app.vault.getAbstractFileByPath(t.path);r instanceof Ec.TFile&&await this.plugin.app.workspace.getLeaf(!1).openFile(r)}else fn(this.plugin,e,t=>{(async()=>{if(t){let r=this.plugin.app.vault.getAbstractFileByPath(t.path);r instanceof Ec.TFile&&await this.plugin.app.workspace.getLeaf(!1).openFile(r)}})()})}catch(e){Nye.error("Error handling status bar click:",{category:"internal",operation:"handling-status-bar-click",error:e})}}requestUpdate(){this.updateTimeout&&window.clearTimeout(this.updateTimeout),this.updateTimeout=window.setTimeout(()=>{this.updateStatusBar()},100)}requestPomodoroUpdate(){this.pomodoroUpdateTimeout&&window.clearTimeout(this.pomodoroUpdateTimeout),this.pomodoroUpdateTimeout=window.setTimeout(()=>{this.updatePomodoroStatusBar()},100)}updateVisibility(){this.plugin.settings.showTrackedTasksInStatusBar?this.statusBarElement?this.updateStatusBar():this.ensureTrackedStatusBarElement():this.hide(),this.plugin.settings.showPomodoroInStatusBar?(this.ensurePomodoroStatusBarElement(),this.updatePomodoroStatusBar()):this.hidePomodoroStatusBar()}hide(){this.stopElapsedTicker(),this.statusBarElement&&(this.statusBarElement.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-min-height-800px-997b4c8c"),this.statusBarElement.classList.add("tn-static-display-none-6b99de8b"))}hidePomodoroStatusBar(){this.pomodoroStatusBarElement&&(this.pomodoroStatusBarElement.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-min-height-800px-997b4c8c"),this.pomodoroStatusBarElement.classList.add("tn-static-display-none-6b99de8b"))}destroy(){var e;this.updateTimeout&&(window.clearTimeout(this.updateTimeout),this.updateTimeout=null),this.pomodoroUpdateTimeout&&(window.clearTimeout(this.pomodoroUpdateTimeout),this.pomodoroUpdateTimeout=null),this.stopElapsedTicker(),(e=this.plugin.emitter)!=null&&e.offref&&this.pomodoroEventRefs.forEach(t=>this.plugin.emitter.offref(t)),this.pomodoroEventRefs=[],this.requestDeduplicator&&this.requestDeduplicator.cancelAll(),this.statusBarElement=null,this.pomodoroStatusBarElement=null}}});var _ye,xW,vR,Fye=y(()=>{_ye=require("obsidian");Pr();xe();q();Wd();xW=M({tag:"Services/NotificationService"}),vR=class{constructor(e){this.notificationQueue=[];this.processedReminders=new Set;this.activeAudioContexts=new Set;this.audioCleanupTimeouts=new Set;this.lastBroadScanTime=Date.now();this.lastQuickCheckTime=Date.now();this.BROAD_SCAN_INTERVAL=300*1e3;this.QUICK_CHECK_INTERVAL=30*1e3;this.QUEUE_WINDOW=300*1e3;this.plugin=e}async initialize(){this.plugin.settings.enableNotifications&&(this.plugin.settings.notificationType==="system"&&typeof Notification!="undefined"&&Notification.permission==="default"&&await Notification.requestPermission(),this.setupTaskUpdateListener(),this.setupFileUpdateListener(),this.startBroadScan(),this.startQuickCheck(),await this.scanTasksAndBuildQueue())}destroy(){this.broadScanInterval&&window.clearInterval(this.broadScanInterval),this.quickCheckInterval&&window.clearInterval(this.quickCheckInterval),this.taskUpdateListener&&this.plugin.emitter.offref(this.taskUpdateListener),this.fileUpdateListener&&this.plugin.emitter.offref(this.fileUpdateListener);for(let e of this.audioCleanupTimeouts)window.clearTimeout(e);this.audioCleanupTimeouts.clear();for(let e of this.activeAudioContexts)e.state!=="closed"&&e.close().catch(()=>{});this.activeAudioContexts.clear(),this.notificationQueue=[],this.processedReminders.clear()}startBroadScan(){this.broadScanInterval=window.setInterval(()=>{(async()=>{let e=Date.now();e-this.lastBroadScanTime>this.BROAD_SCAN_INTERVAL+6e4&&await this.handleSystemWakeUp(),await this.scanTasksAndBuildQueue(),this.lastBroadScanTime=e})()},this.BROAD_SCAN_INTERVAL)}startQuickCheck(){this.quickCheckInterval=window.setInterval(()=>{let e=Date.now();e-this.lastQuickCheckTime>this.QUICK_CHECK_INTERVAL+6e4,this.checkNotificationQueue(),this.lastQuickCheckTime=e},this.QUICK_CHECK_INTERVAL)}async scanTasksAndBuildQueue(){this.notificationQueue=[];let e=this.plugin.cacheManager.getAllCachedTasks(),t=Date.now(),r=t+this.QUEUE_WINDOW;for(let a of e)if(!(!a.reminders||a.reminders.length===0))for(let i of a.reminders){let s=`${a.path}-${i.id}`;if(this.processedReminders.has(s))continue;let o=this.calculateNotificationTime(a,i);o!==null&&o>t&&o<=r&&this.notificationQueue.push({taskPath:a.path,reminder:i,notifyAt:o})}this.notificationQueue.sort((a,i)=>a.notifyAt-i.notifyAt)}calculateNotificationTime(e,t){try{if(t.type==="absolute")return t.absoluteTime?et(t.absoluteTime).getTime():null;if(t.type==="relative"){if(!t.relatedTo||!t.offset)return null;let r=t.relatedTo==="due"?e.due:e.scheduled;if(!r)return null;let a=et(r),i=this.parseISO8601Duration(t.offset);return i===null?null:a.getTime()+i}}catch(r){return xW.error("Error calculating notification time:",{category:"provider",operation:"calculating-notification-time",error:r}),null}return null}parseISO8601Duration(e){let t=e.match(/^(-?)P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/);if(!t)return null;let[,r,a,i,s,o,l,c,d]=t,u=0;return a&&(u+=parseInt(a)*365*24*60*60*1e3),i&&(u+=parseInt(i)*30*24*60*60*1e3),s&&(u+=parseInt(s)*7*24*60*60*1e3),o&&(u+=parseInt(o)*24*60*60*1e3),l&&(u+=parseInt(l)*60*60*1e3),c&&(u+=parseInt(c)*60*1e3),d&&(u+=parseInt(d)*1e3),r==="-"?-u:u}checkNotificationQueue(){let e=Date.now(),t=[];for(let r=0;r=0;r--)this.notificationQueue.splice(t[r],1)}async triggerNotification(e){let t=this.plugin.app.vault.getAbstractFileByPath(e.taskPath);if(!(t instanceof _ye.TFile))return;let r=this.plugin.app.metadataCache.getFileCache(t);if(!r||!r.frontmatter)return;let a=this.plugin.fieldMapper.mapFromFrontmatter(r.frontmatter,e.taskPath,this.plugin.settings.storeTitleInFilename),i=e.reminder.description||this.generateDefaultMessage(a,e.reminder);if(this.playNotificationSound(),this.plugin.settings.notificationType==="system")if("Notification"in window&&Notification.permission==="granted"){let s=new Notification(a.title||"TaskNotes Reminder",{body:i,tag:`tasknotes-${e.taskPath}-${e.reminder.id}`});s.onclick=()=>{this.plugin.app.workspace.openLinkText(e.taskPath,"",!1),s.close()}}else this.showInAppNotice(i,e.taskPath);else this.showInAppNotice(i,e.taskPath);this.plugin.apiService&&await this.plugin.apiService.triggerWebhook("reminder.triggered",{task:a,reminder:e.reminder,notificationTime:new Date(e.notifyAt).toISOString(),message:i,notificationType:this.plugin.settings.notificationType})}playNotificationSound(){if(!this.plugin.settings.notificationSoundEnabled)return;let e=window.AudioContext||window.webkitAudioContext;if(e)try{let t=new e,r=t.createGain(),a=Math.max(0,Math.min(1,this.plugin.settings.notificationSoundVolume/100));r.gain.value=a*.3,r.connect(t.destination);let i=(l,c)=>{let d=t.createOscillator();d.connect(r),d.frequency.value=l,d.type="sine",d.start(),d.stop(t.currentTime+c)};i(880,.12),this.activeAudioContexts.add(t);let s=window.setTimeout(()=>{try{i(1175,.12)}catch(l){xW.error("Failed to play notification sound tone:",{category:"provider",operation:"play-notification-sound-tone",error:l})}},140);this.audioCleanupTimeouts.add(s);let o=window.setTimeout(()=>{this.activeAudioContexts.delete(t),this.audioCleanupTimeouts.delete(s),this.audioCleanupTimeouts.delete(o),t.close().catch(()=>{})},320);this.audioCleanupTimeouts.add(o)}catch(t){xW.error("Failed to play notification sound:",{category:"provider",operation:"play-notification-sound",error:t})}}async sendTestReminderNotification(){let e="TaskNotes Reminder",t="This is a test reminder from TaskNotes.";if(this.playNotificationSound(),this.plugin.settings.notificationType==="system"&&typeof Notification!="undefined"&&(Notification.permission==="default"&&await Notification.requestPermission(),Notification.permission==="granted")){new Notification(e,{body:t,tag:"tasknotes-test-reminder"});return}Ze(t,5e3)}showInAppNotice(e,t){let r=Ze(e,0),a=r.noticeEl;a.addEventListener("click",()=>{this.plugin.app.workspace.openLinkText(t,"",!1),r.hide()}),a.classList.remove("tn-static-cursor-grab-dad79857","tn-static-cursor-pointer-2723efcc"),a.classList.add("tn-static-cursor-pointer-3b6a3a65")}generateDefaultMessage(e,t){if(t.type==="absolute")return`Reminder: ${e.title}`;{let r=t.relatedTo==="due"?"due":"scheduled",a=this.formatDurationForDisplay(t.offset||"");return a.startsWith("-")?`${e.title} is ${r} in ${a.substring(1)}`:a==="PT0S"||a==="PT0M"?`${e.title} is ${r} now`:`${e.title} was ${r} ${a} ago`}}formatDurationForDisplay(e){let t=this.parseISO8601Duration(e);if(t===null)return e;let r=Math.abs(t),a=Math.floor(r/(60*1e3)),i=Math.floor(r/(3600*1e3)),s=Math.floor(r/(1440*60*1e3)),o="";return s>0?o=`${s} day${s>1?"s":""}`:i>0?o=`${i} hour${i>1?"s":""}`:a>0?o=`${a} minute${a>1?"s":""}`:o="now",t<0?`-${o}`:o}async refreshReminders(){await this.scanTasksAndBuildQueue()}queueRemindersForTask(e,t){let r=Date.now(),a=r+this.QUEUE_WINDOW;if(!(!t.reminders||t.reminders.length===0)){for(let i of t.reminders){let s=`${e}-${i.id}`;if(this.processedReminders.has(s))continue;let o=this.calculateNotificationTime(t,i);o!==null&&o>r&&o<=a&&this.notificationQueue.push({taskPath:e,reminder:i,notifyAt:o})}this.notificationQueue.sort((i,s)=>i.notifyAt-s.notifyAt)}}async refreshTaskReminders(e,t){this.removeNotificationsForTask(e),this.clearProcessedRemindersForTask(e);let r=t===void 0?await this.plugin.cacheManager.getTaskInfo(e):t;r&&this.queueRemindersForTask(e,r)}clearProcessedRemindersForTask(e){let t=[];for(let r of this.processedReminders)r.startsWith(`${e}-`)&&t.push(r);t.forEach(r=>this.processedReminders.delete(r))}setupTaskUpdateListener(){this.taskUpdateListener=this.plugin.emitter.on(rt,async({path:e,updatedTask:t})=>{!e||!t||await this.refreshTaskReminders(e,t)})}setupFileUpdateListener(){this.fileUpdateListener=this.plugin.emitter.on("file-updated",async({path:e})=>{e&&await this.refreshTaskReminders(e)})}removeNotificationsForTask(e){this.notificationQueue=this.notificationQueue.filter(t=>t.taskPath!==e)}async handleSystemWakeUp(){let e=Date.now(),t=[];for(let r of this.processedReminders){let[a,i]=r.split("-",2);if(!(!a||!i))try{let s=await this.plugin.cacheManager.getTaskInfo(a);if(s&&s.reminders){let o=s.reminders.find(l=>l.id===i);if(o){let l=this.calculateNotificationTime(s,o);l&&l<=e&&t.push(r)}}}catch(s){t.push(r)}}t.forEach(r=>this.processedReminders.delete(r)),await this.scanTasksAndBuildQueue()}}});var EW,kR,Lye=y(()=>{Pr();q();EW=M({tag:"Services/ViewPerformanceService"}),kR=class{constructor(e){this.globalTaskVersionCache=new Map;this.lastGlobalRefreshTime=0;this.globalTaskCount=0;this.viewHandlers=new Map;this.viewDebounceTimers=new Map;this.viewPendingUpdates=new Map;this.viewConfigs=new Map;this.updateInProgress=new Set;this.eventListener=null;this.plugin=e,this.setupGlobalEventListener()}registerView(e,t){this.viewConfigs.set(e.viewId,{debounceDelay:100,maxBatchSize:5,changeDetectionEnabled:!0,...e}),this.viewHandlers.set(e.viewId,t),this.viewPendingUpdates.set(e.viewId,new Set)}unregisterView(e){let t=this.viewDebounceTimers.get(e);t&&(window.clearTimeout(t),this.viewDebounceTimers.delete(e)),this.viewConfigs.delete(e),this.viewHandlers.delete(e),this.viewPendingUpdates.delete(e),this.updateInProgress.delete(e)}setupGlobalEventListener(){this.eventListener=this.plugin.emitter.on(rt,async({path:e,originalTask:t,updatedTask:r})=>{if(!e||!r){await this.triggerFullRefreshForAllViews();return}r.path||(r.path=e),this.hasTaskChanged(r)&&await this.handleTaskUpdateForAllViews(r,t)})}async handleTaskUpdateForAllViews(e,t){let r=[];for(let[a,i]of this.viewHandlers)i.shouldRefreshForTask&&!i.shouldRefreshForTask(t,e)||r.push(this.scheduleViewUpdate(a,e.path));await Promise.all(r),Math.random()<.1&&await this.cleanupTaskVersionCache()}async scheduleViewUpdate(e,t){let r=this.viewConfigs.get(e);if(!r)return;let a=this.viewPendingUpdates.get(e);a&&a.add(t);let i=this.viewDebounceTimers.get(e);i&&window.clearTimeout(i);let s=window.setTimeout(()=>{this.processPendingUpdatesForView(e)},r.debounceDelay);this.viewDebounceTimers.set(e,s)}async processPendingUpdatesForView(e){if(this.updateInProgress.has(e))return;let t=this.viewConfigs.get(e),r=this.viewHandlers.get(e),a=this.viewPendingUpdates.get(e);if(!(!t||!r||!a||a.size===0)){this.updateInProgress.add(e);try{let i=Array.from(a);if(a.clear(),i.length>t.maxBatchSize)await r.refresh();else{let s=i.map(o=>r.updateForTask(o,"update").catch(l=>{EW.error(`[ViewPerformanceService] Error updating task ${o} in ${e}:`,{category:"persistence",operation:"updating-task",error:l})}));await Promise.all(s)}}catch(i){EW.error(`[ViewPerformanceService] Error processing updates for ${e}:`,{category:"validation",operation:"processing-updates",error:i}),await r.refresh()}finally{this.updateInProgress.delete(e),this.viewDebounceTimers.delete(e)}}}async triggerFullRefreshForAllViews(){let e=[];for(let[t,r]of this.viewHandlers)this.updateInProgress.has(t)||e.push(r.refresh(!0));await Promise.all(e),this.lastGlobalRefreshTime=Date.now()}hasTaskChanged(e){let t=this.globalTaskVersionCache.get(e.path),r=e.dateModified||Date.now().toString();return t!==r?(this.globalTaskVersionCache.set(e.path,r),!0):!1}shouldDoFullRefresh(){let e=Date.now()-this.lastGlobalRefreshTime,t=this.globalTaskVersionCache.size;return e>600*1e3||Math.abs(t-this.globalTaskCount)>20||t===0}async cleanupTaskVersionCache(){try{let e=this.plugin.cacheManager.getAllTaskPaths(),t=new Set(e);for(let r of this.globalTaskVersionCache.keys())t.has(r)||this.globalTaskVersionCache.delete(r);this.globalTaskCount=t.size,this.globalTaskVersionCache.size>2e3&&(this.globalTaskVersionCache.clear(),this.lastGlobalRefreshTime=0)}catch(e){EW.error("[ViewPerformanceService] Error during cache cleanup:",{category:"stale-data",operation:"cache-cleanup",error:e})}}async forceRefreshAll(){this.globalTaskVersionCache.clear(),await this.triggerFullRefreshForAllViews()}getStats(){return{registeredViews:Array.from(this.viewConfigs.keys()),cacheSize:this.globalTaskVersionCache.size,activeUpdates:Array.from(this.updateInProgress),totalPendingUpdates:Array.from(this.viewPendingUpdates.values()).reduce((e,t)=>e+t.size,0),lastGlobalRefresh:new Date(this.lastGlobalRefreshTime).toISOString()}}destroy(){this.eventListener&&(this.plugin.emitter.offref(this.eventListener),this.eventListener=null);for(let e of this.viewDebounceTimers.values())window.clearTimeout(e);this.viewHandlers.clear(),this.viewDebounceTimers.clear(),this.viewPendingUpdates.clear(),this.viewConfigs.clear(),this.updateInProgress.clear(),this.globalTaskVersionCache.clear()}}});function eGe(n){return n.width>0&&n.height>0}function tGe(n){let e=n.cacheManager.getAllTaskPaths(),t=[];for(let r of e){let a=n.cacheManager.getCachedTaskInfoSync(r);a&&!a.archived&&t.push(a)}return t}function rGe(n,e){return eGe(n)?n:e}var Zp,Xx,TR,Oye=y(()=>{Zp=require("obsidian");Pr();co();Ua();Yl();hM();gR();xe();q();Xx=M({tag:"Views/PomodoroView"});TR=class extends Zp.ItemView{constructor(t,r){super(t);this.timerDisplay=null;this.timerInput=null;this.statusDisplay=null;this.sessionMetaDisplay=null;this.progressCircle=null;this.progressContainer=null;this.startButton=null;this.pauseButton=null;this.stopButton=null;this.taskDisplay=null;this.statsDisplay=null;this.taskSelectButton=null;this.taskClearButton=null;this.currentSelectedTask=null;this.taskCardContainer=null;this.addTimeButton=null;this.subtractTimeButton=null;this.skipBreakButton=null;this.isEditingTimer=!1;this.isTaskSelectorOpen=!1;this.todaysPomodoros=0;this.statElements={pomodoros:null};this.resizeObserver=null;this.resizeTimeout=null;this.resizeWindow=null;this.functionListeners=[];this.currentCircleSize=300;this.currentCircumference=0;this.lastLayoutSize=null;this.responsiveClass=null;this.workspaceListeners=[];this.visibilityObserver=null;this.wasVisible=!1;this.isClosed=!1;this.openGeneration=0;this.displayStateKey=null;this.taskCardDirty=!1;this.listeners=[];this.plugin=r,this.registerEvents()}refreshStats(){this.updateStats().catch(t=>{Xx.error("Failed to update stats:",{category:"validation",operation:"update-stats",error:t})})}getViewType(){return ld}getDisplayText(){return this.plugin.i18n.translate("views.pomodoro.title")}getIcon(){return"clock"}t(t,r){return this.plugin.i18n.translate(t,r)}registerEvents(){this.listeners.forEach(o=>this.plugin.emitter.offref(o)),this.listeners=[];let t=this.plugin.emitter.on(cd,({session:o,task:l})=>{this.updateDisplay(o,l)});this.listeners.push(t);let r=this.plugin.emitter.on(dd,({session:o,nextType:l})=>{this.onPomodoroComplete(o,l)});this.listeners.push(r);let a=this.plugin.emitter.on(ud,()=>{this.updateDisplay(void 0,void 0,{refreshStats:!0})});this.listeners.push(a);let i=this.plugin.emitter.on(ai,({session:o})=>{this.updateDisplay(o)});this.listeners.push(i);let s=this.plugin.emitter.on(rt,async({path:o,originalTask:l,updatedTask:c})=>{if(!o||!c)return;if(this.currentSelectedTask&&(this.currentSelectedTask.path===o||l&&this.currentSelectedTask.path===l.path)){this.currentSelectedTask=c,this.updateTaskCardDisplay(c);let u=this.plugin.pomodoroService.getState();u.currentSession&&l&&l.path!==c.path&&u.currentSession.taskPath===l.path&&await this.plugin.pomodoroService.assignTaskToCurrentSession(c)}});this.listeners.push(s)}async onOpen(){this.isClosed=!1;let t=++this.openGeneration;await this.plugin.onReady(),!(this.isClosed||t!==this.openGeneration)&&(this.registerEvents(),await this.render(),!(this.isClosed||t!==this.openGeneration)&&this.setupResizeHandling())}onResize(){if(this.resizeWindow&&this.resizeWindow!==this.contentEl.ownerDocument.defaultView){this.setupResizeHandling();return}this.handleVisibilityChange(),this.updateResponsiveLayout()}isViewVisible(){return!this.isClosed&&this.contentEl.ownerDocument.visibilityState!=="hidden"&&this.contentEl.isShown()}handleVisibilityChange(){var r;if(this.isClosed)return;let t=this.isViewVisible();t!==this.wasVisible&&(this.wasVisible=t,(r=this.contentEl.querySelector(".pomodoro-view"))==null||r.classList.toggle("pomodoro-view--rendering-paused",!t),t&&(this.displayStateKey=null,this.updateDisplay(),this.taskCardDirty&&this.updateTaskCardDisplay(this.currentSelectedTask)))}async onClose(){var t;this.isClosed=!0,this.openGeneration++,this.wasVisible=!1,this.displayStateKey=null,this.lastLayoutSize=null,this.responsiveClass=null,this.currentCircleSize=300,this.currentCircumference=0,this.taskCardDirty=!1,(t=this.visibilityObserver)==null||t.disconnect(),this.visibilityObserver=null,this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.resizeTimeout!==null&&((this.resizeWindow||window).clearTimeout(this.resizeTimeout),this.resizeTimeout=null),this.resizeWindow=null,this.listeners.forEach(r=>this.plugin.emitter.offref(r)),this.listeners=[],this.workspaceListeners.forEach(r=>this.plugin.app.workspace.offref(r)),this.workspaceListeners=[],this.functionListeners.forEach(r=>r()),this.functionListeners=[],this.timerDisplay=null,this.timerInput=null,this.statusDisplay=null,this.sessionMetaDisplay=null,this.progressCircle=null,this.progressContainer=null,this.startButton=null,this.pauseButton=null,this.stopButton=null,this.taskDisplay=null,this.statsDisplay=null,this.taskSelectButton=null,this.taskClearButton=null,this.currentSelectedTask=null,this.taskCardContainer=null,this.addTimeButton=null,this.subtractTimeButton=null,this.skipBreakButton=null,this.isEditingTimer=!1,this.statElements={pomodoros:null},this.contentEl.empty()}async render(){let t=this.contentEl.createDiv({cls:"tasknotes-plugin pomodoro-view"}),r=t.createDiv({cls:"pomodoro-view__timer-section"}),a=r.createDiv({cls:"pomodoro-view__timer-header"});this.statusDisplay=a.createDiv({cls:"pomodoro-view__status",text:this.t("views.pomodoro.status.ready")}),this.sessionMetaDisplay=a.createDiv({cls:"pomodoro-view__session-meta"}),this.progressContainer=r.createDiv({cls:"pomodoro-view__progress-container"});let i=activeWindow.createSvg("svg");i.setAttribute("class","pomodoro-view__progress-svg"),i.setAttribute("width","300"),i.setAttribute("height","300"),i.setAttribute("viewBox","0 0 300 300"),this.progressContainer.appendChild(i);let s=activeWindow.createSvg("circle");s.setAttributeNS(null,"cx","150"),s.setAttributeNS(null,"cy","150"),s.setAttributeNS(null,"r","140"),s.setAttributeNS(null,"fill","none"),s.setAttributeNS(null,"stroke","var(--tn-border-color)"),s.setAttributeNS(null,"stroke-width","2"),i.appendChild(s),this.progressCircle=activeWindow.createSvg("circle"),this.progressCircle.setAttributeNS(null,"cx","150"),this.progressCircle.setAttributeNS(null,"cy","150"),this.progressCircle.setAttributeNS(null,"r","140"),this.progressCircle.setAttributeNS(null,"fill","none"),this.progressCircle.setAttributeNS(null,"stroke","var(--tn-interactive-accent)"),this.progressCircle.setAttributeNS(null,"stroke-width","4"),this.progressCircle.setAttributeNS(null,"stroke-linecap","round");let l=2*Math.PI*140;this.progressCircle.setAttributeNS(null,"stroke-dasharray",l.toString()),this.progressCircle.setAttributeNS(null,"stroke-dashoffset",l.toString()),this.progressCircle.addClass("pomodoro-view__progress-circle"),i.appendChild(this.progressCircle);let c=this.progressContainer.createDiv({cls:"pomodoro-view__timer-overlay"}),u=`${this.plugin.settings.pomodoroWorkDuration.toString().padStart(2,"0")}:00`;this.timerDisplay=c.createDiv({cls:"pomodoro-view__timer-display",text:u}),this.timerDisplay.tabIndex=0,this.timerDisplay.setAttribute("role","button"),this.timerDisplay.setAttribute("aria-label",this.t("views.pomodoro.timer.editLabel")),this.timerInput=c.createEl("input",{cls:"pomodoro-view__timer-input pomodoro-view__timer-input--hidden",attr:{type:"text",inputmode:"numeric","aria-label":this.t("views.pomodoro.timer.inputLabel")}});let p=c.createDiv({cls:"pomodoro-view__time-controls"});this.subtractTimeButton=p.createEl("button",{cls:"pomodoro-view__time-adjust-button pomodoro-view__subtract-time",text:"-1m"}),this.subtractTimeButton.setAttribute("aria-label",this.t("views.pomodoro.buttons.subtractMinute")),this.addTimeButton=p.createEl("button",{cls:"pomodoro-view__time-adjust-button pomodoro-view__add-time",text:"+1m"}),this.addTimeButton.setAttribute("aria-label",this.t("views.pomodoro.buttons.addMinute")),this.taskDisplay=t.createDiv({cls:"pomodoro-view__task-display"});let m=t.createDiv({cls:"pomodoro-view__task-selector"}),f=m.createDiv({cls:"pomodoro-view__task-buttons"});this.taskSelectButton=f.createEl("button",{cls:"pomodoro-view__task-select-button",text:this.t("views.pomodoro.buttons.chooseTask")}),this.taskClearButton=f.createEl("button",{cls:"pomodoro-view__task-clear-button pomodoro-view__task-clear-button--hidden",text:this.t("views.pomodoro.buttons.clearTask")}),this.taskCardContainer=m.createDiv({cls:"pomodoro-view__task-card-container"});let h=t.createDiv({cls:"pomodoro-view__control-section"}),g=h.createDiv({cls:"pomodoro-view__primary-controls"});this.startButton=g.createEl("button",{text:this.t("views.pomodoro.buttons.startFocus"),cls:"pomodoro-view__start-button"}),this.pauseButton=g.createEl("button",{text:this.t("views.pomodoro.buttons.pause"),cls:"pomodoro-view__pause-button"}),this.pauseButton.addClass("pomodoro-view__pause-button--hidden"),this.stopButton=g.createEl("button",{text:this.t("views.pomodoro.buttons.stop"),cls:"pomodoro-view__stop-button"}),this.stopButton.addClass("pomodoro-view__stop-button--hidden"),this.skipBreakButton=h.createEl("button",{cls:"pomodoro-view__skip-break-button",text:this.t("views.pomodoro.buttons.skipBreak")}),this.skipBreakButton.addClass("pomodoro-view__skip-break-button--hidden");let v=t.createDiv({cls:"pomodoro-view__stats-section"});this.statsDisplay=v.createDiv({cls:"pomodoro-view__stats"});let k=this.statsDisplay.createDiv({cls:"pomodoro-view__stat pomodoro-view__stat--clickable"});this.statElements.pomodoros=k.createSpan({cls:"pomodoro-view__stat-value",text:"0"}),k.createSpan({cls:"pomodoro-view__stat-label",text:this.t("views.pomodoro.statsLabel")}),this.registerDomEvent(k,"click",()=>{this.plugin.activatePomodoroStatsView()}),this.registerDomEvent(this.startButton,"click",async()=>{var T,b,w;if(!((T=this.startButton)!=null&&T.hasClass("is-loading"))){(b=this.startButton)==null||b.addClass("pomodoro-view__start-button--loading");try{let S=this.plugin.pomodoroService.getState();S.currentSession&&!S.isRunning?await this.plugin.pomodoroService.resumePomodoro():S.nextSessionType==="short-break"?await this.plugin.pomodoroService.startBreak(!1):S.nextSessionType==="long-break"?await this.plugin.pomodoroService.startBreak(!0):await this.plugin.pomodoroService.startPomodoro(this.currentSelectedTask||void 0)}finally{(w=this.startButton)==null||w.removeClass("pomodoro-view__start-button--loading")}}}),this.registerDomEvent(this.pauseButton,"click",()=>{this.plugin.pomodoroService.pausePomodoro()}),this.registerDomEvent(this.stopButton,"click",()=>{this.plugin.pomodoroService.stopPomodoro()}),this.registerDomEvent(this.skipBreakButton,"click",()=>{let T=this.plugin.pomodoroService.getState();T.currentSession?this.plugin.pomodoroService.stopPomodoro():(T.nextSessionType==="short-break"||T.nextSessionType==="long-break")&&this.plugin.pomodoroService.skipBreak()}),this.registerDomEvent(this.addTimeButton,"click",()=>{this.adjustSessionTime(60)}),this.registerDomEvent(this.subtractTimeButton,"click",()=>{this.adjustSessionTime(-60)}),this.registerDomEvent(this.timerDisplay,"click",()=>{this.beginTimerEdit()}),this.registerDomEvent(this.timerDisplay,"keydown",T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),this.beginTimerEdit())}),this.registerDomEvent(this.timerInput,"keydown",T=>{T.key==="Enter"?(T.preventDefault(),this.commitTimerEdit()):T.key==="Escape"&&(T.preventDefault(),this.cancelTimerEdit())}),this.registerDomEvent(this.timerInput,"blur",()=>{this.commitTimerEdit()}),this.registerDomEvent(this.taskSelectButton,"click",async()=>{await this.openTaskSelector()}),this.registerDomEvent(this.taskClearButton,"click",async()=>{await this.selectTask(null)}),this.restoreLastSelectedTask(),this.updateDisplay(),this.refreshStats()}setupResizeHandling(){var i,s;if(this.isClosed)return;let t=this.contentEl.ownerDocument.defaultView||window;(i=this.resizeObserver)==null||i.disconnect(),(s=this.visibilityObserver)==null||s.disconnect(),this.resizeTimeout!==null&&((this.resizeWindow||t).clearTimeout(this.resizeTimeout),this.resizeTimeout=null),this.resizeWindow=t,this.lastLayoutSize=null,this.workspaceListeners.forEach(o=>this.plugin.app.workspace.offref(o)),this.workspaceListeners=[],this.functionListeners.forEach(o=>o()),this.functionListeners=[];let r=()=>{this.isClosed||this.resizeWindow!==t||(this.handleVisibilityChange(),this.resizeTimeout!==null&&t.clearTimeout(this.resizeTimeout),this.resizeTimeout=t.setTimeout(()=>{this.resizeTimeout=null,this.handleVisibilityChange(),this.updateResponsiveLayout()},150))};t.ResizeObserver&&(this.resizeObserver=new t.ResizeObserver(r),this.resizeObserver.observe(this.contentEl)),t.IntersectionObserver&&(this.visibilityObserver=new t.IntersectionObserver(r),this.visibilityObserver.observe(this.contentEl)),this.workspaceListeners.push(this.plugin.app.workspace.on("layout-change",r),this.plugin.app.workspace.on("active-leaf-change",r));let a=this.contentEl.ownerDocument;a.addEventListener("visibilitychange",r),t.addEventListener("resize",r),this.functionListeners.push(()=>a.removeEventListener("visibilitychange",r),()=>t.removeEventListener("resize",r)),this.handleVisibilityChange(),this.updateResponsiveLayout()}updateResponsiveLayout(){var m,f,h;if(!this.isViewVisible())return;let t=this.contentEl.querySelector(".pomodoro-view");if(!t)return;let r=t.getBoundingClientRect(),a=this.contentEl.getBoundingClientRect(),{width:i,height:s}=rGe({width:a.width,height:a.height},{width:r.width,height:r.height});if(i<=0||s<=0||((m=this.lastLayoutSize)==null?void 0:m.width)===i&&this.lastLayoutSize.height===s)return;this.lastLayoutSize={width:i,height:s};let o=Math.min(i/600,1),l=Math.min(s/800,1),c=Math.min(o*.7+l*.3,1),p=`pomodoro-view--${(h=(f=[[200,"tiny"],[250,"extra-narrow"],[300,"very-narrow"],[350,"narrow"],[400,"small"],[500,"medium-small"],[600,"medium"]].find(([g])=>i<=g))==null?void 0:f[1])!=null?h:"wide"}`;p!==this.responsiveClass&&(this.responsiveClass&&t.classList.remove(this.responsiveClass),t.classList.add(p),this.responsiveClass=p),t.style.setProperty("--pomodoro-scale",c.toString()),this.updateProgressCircleSize(i,s)}updateProgressCircleSize(t,r){if(!this.progressContainer)return;let a=this.progressContainer.querySelector(".pomodoro-view__progress-svg");if(!a)return;let i=Math.min(t*.8,r*.4),s;if(t<=200?s=Math.max(120,Math.min(i,t-40)):t<=250?s=Math.max(150,Math.min(i,t-50)):t<=300?s=Math.max(180,Math.min(i,t-60)):t<=350?s=Math.max(200,Math.min(i,t-70)):t<=400?s=Math.max(230,Math.min(i,t-80)):t<=500?s=Math.max(250,Math.min(i,t-100)):t<=600?s=Math.max(280,Math.min(i,300)):s=Math.max(300,Math.min(i,t*.5,400)),s===this.currentCircleSize)return;this.currentCircleSize=s,a.setAttribute("width",s.toString()),a.setAttribute("height",s.toString()),a.setAttribute("viewBox",`0 0 ${s} ${s}`),this.progressContainer.style.width=`${s}px`,this.progressContainer.style.height=`${s}px`;let o=s/2,l=o-20;if(a.querySelectorAll("circle").forEach(d=>{d.setAttribute("cx",o.toString()),d.setAttribute("cy",o.toString()),d.setAttribute("r",l.toString())}),this.progressCircle){let d=2*Math.PI*l;if(this.currentCircumference=d,this.progressCircle.setAttribute("stroke-dasharray",d.toString()),this.progressCircle.setAttribute("stroke-dashoffset",d.toString()),this.plugin.pomodoroService){let u=this.plugin.pomodoroService.getState();this.updateProgress(u)}}}async openTaskSelector(){if(!this.isTaskSelectorOpen){this.isTaskSelectorOpen=!0;try{let t=tGe(this.plugin),r=new Date;if(t.length===0){new Zp.Notice(this.t("views.pomodoro.notices.noTasks")),this.isTaskSelectorOpen=!1;return}fn(this.plugin,t,a=>{this.isTaskSelectorOpen=!1,this.selectTask(a)},{targetDate:r})}catch(t){this.isTaskSelectorOpen=!1,Xx.error("Error opening task selector:",{category:"persistence",operation:"opening-task-selector",error:t}),new Zp.Notice(this.t("views.pomodoro.notices.loadFailed"))}}}async selectTask(t){if(this.isClosed||(this.currentSelectedTask=t,this.updateTaskCardDisplay(t),await this.plugin.pomodoroService.saveLastSelectedTask(t==null?void 0:t.path),this.isClosed))return;let r=this.plugin.pomodoroService.getState();r.currentSession&&r.currentSession.type==="work"&&await this.plugin.pomodoroService.assignTaskToCurrentSession(t||void 0)}updateTaskCardDisplay(t){if(!this.isViewVisible()){this.taskCardDirty=!0;return}if(this.taskCardContainer)if(this.taskCardDirty=!1,this.taskSelectButton&&(t?(this.taskSelectButton.textContent=this.t("views.pomodoro.buttons.changeTask"),(0,Zp.setTooltip)(this.taskSelectButton,this.t("views.pomodoro.buttons.selectDifferentTask"),{placement:"top"}),this.taskSelectButton.removeClass("pomodoro-view__task-select-button--no-task")):(this.taskSelectButton.textContent=this.t("views.pomodoro.buttons.chooseTask"),this.taskSelectButton.removeAttribute("title"),this.taskSelectButton.addClass("pomodoro-view__task-select-button--no-task"))),this.taskClearButton&&(t?this.taskClearButton.removeClass("pomodoro-view__task-clear-button--hidden"):this.taskClearButton.addClass("pomodoro-view__task-clear-button--hidden")),this.taskCardContainer.empty(),t){let r=this.plugin.settings.defaultVisibleProperties?di(this.plugin.settings.defaultVisibleProperties,this.plugin):void 0,a=new Date,i=fM(t,a,this.plugin.statusManager,this.plugin.settings.defaultTaskStatus),s=pr(i,this.plugin,r,{targetDate:a});this.taskCardContainer.appendChild(s),this.taskCardContainer.removeClass("pomodoro-view__task-card-container--empty")}else this.taskCardContainer.addClass("pomodoro-view__task-card-container--empty")}async restoreLastSelectedTask(){let t=this.openGeneration;try{if(!this.plugin.pomodoroService)return;let r=await this.plugin.pomodoroService.getLastSelectedTaskPath();if(r&&!this.isClosed&&t===this.openGeneration){let a=await this.plugin.cacheManager.getTaskByPath(r);!this.isClosed&&t===this.openGeneration&&a&&!Wf(a,new Date,this.plugin.statusManager,this.plugin.settings.defaultTaskStatus)&&!a.archived&&await this.selectTask(a)}}catch(r){Xx.error("Error restoring last selected task:",{category:"persistence",operation:"restoring-last-selected-task",error:r})}}async updateTaskButtonFromPath(t){var a;let r=this.openGeneration;try{let i=await this.plugin.cacheManager.getTaskInfo(t);if(this.isClosed||r!==this.openGeneration||((a=this.plugin.pomodoroService.getState().currentSession)==null?void 0:a.taskPath)!==t)return;this.currentSelectedTask=i!=null?i:null,this.updateTaskCardDisplay(this.currentSelectedTask)}catch(i){Xx.error("Error updating task button from path:",{category:"persistence",operation:"updating-task-button-path",error:i})}}updateDisplay(t,r,a={}){var l,c,d,u,p,m,f;if(this.isClosed)return;if(a.refreshStats&&this.refreshStats(),!this.isViewVisible()){this.displayStateKey=null;return}if(!this.plugin.pomodoroService){this.statusDisplay&&(this.statusDisplay.textContent=this.t("views.pomodoro.status.ready"),this.statusDisplay.className="pomodoro-status pomodoro-view__status");return}let i=Date.now(),s=this.plugin.pomodoroService.getState();s.isRunning&&s.currentSession&&(s.timeRemaining=wk(s.currentSession,i)),this.updateTimer(s.timeRemaining),this.updateProgress(s),this.updateSessionMeta(s,i);let o=JSON.stringify([s.isRunning,(l=s.currentSession)==null?void 0:l.id,(c=s.currentSession)==null?void 0:c.type,(d=s.currentSession)==null?void 0:d.taskPath,s.nextSessionType]);if(o!==this.displayStateKey){if(this.displayStateKey=o,this.statElements.pomodoros&&this.statElements.pomodoros.textContent!==this.todaysPomodoros.toString()&&(this.statElements.pomodoros.textContent=this.todaysPomodoros.toString()),(u=this.contentEl.querySelector(".pomodoro-view"))==null||u.classList.toggle("pomodoro-view--rendering-paused",!s.isRunning),this.statusDisplay)if(s.isRunning&&s.currentSession){let h=s.currentSession.type==="work"?this.t("views.pomodoro.status.focus"):s.currentSession.type==="short-break"?this.t("views.pomodoro.status.shortBreak"):this.t("views.pomodoro.status.longBreak");this.statusDisplay.textContent=h,this.statusDisplay.className=`pomodoro-status pomodoro-view__status pomodoro-status-${s.currentSession.type} pomodoro-view__status--${s.currentSession.type}`}else s.currentSession&&!s.isRunning?(this.statusDisplay.textContent=this.t("views.pomodoro.status.paused"),this.statusDisplay.className="pomodoro-status pomodoro-view__status pomodoro-status-paused pomodoro-view__status--paused"):(this.statusDisplay.textContent=this.t("views.pomodoro.status.ready"),this.statusDisplay.className="pomodoro-status pomodoro-view__status");if(this.taskDisplay){let h=(p=s.currentSession)==null?void 0:p.taskPath,g=this.taskDisplay.dataset.currentTaskPath;h!==g&&(this.taskDisplay.empty(),this.taskDisplay.dataset.currentTaskPath=h||"")}if(this.taskSelectButton&&(m=s.currentSession)!=null&&m.taskPath&&s.currentSession.taskPath!==((f=this.currentSelectedTask)==null?void 0:f.path)&&this.updateTaskButtonFromPath(s.currentSession.taskPath),this.startButton&&this.pauseButton&&this.stopButton&&(s.isRunning?(this.startButton.addClass("pomodoro-view__start-button--hidden"),this.pauseButton.removeClass("pomodoro-view__pause-button--hidden"),this.stopButton.removeClass("pomodoro-view__stop-button--hidden")):s.currentSession?(this.startButton.removeClass("pomodoro-view__start-button--hidden"),this.startButton.textContent=this.t("views.pomodoro.buttons.resume"),this.pauseButton.addClass("pomodoro-view__pause-button--hidden"),this.stopButton.removeClass("pomodoro-view__stop-button--hidden")):(this.startButton.removeClass("pomodoro-view__start-button--hidden"),s.nextSessionType==="short-break"?this.startButton.textContent=this.t("views.pomodoro.buttons.startShortBreak"):s.nextSessionType==="long-break"?this.startButton.textContent=this.t("views.pomodoro.buttons.startLongBreak"):this.startButton.textContent=this.t("views.pomodoro.buttons.startFocus"),this.pauseButton.addClass("pomodoro-view__pause-button--hidden"),this.stopButton.addClass("pomodoro-view__stop-button--hidden"))),this.skipBreakButton){let h=s.currentSession&&(s.currentSession.type==="short-break"||s.currentSession.type==="long-break"),g=!s.currentSession&&(s.nextSessionType==="short-break"||s.nextSessionType==="long-break");h||g?(this.skipBreakButton.removeClass("pomodoro-view__skip-break-button--hidden"),this.skipBreakButton.textContent=this.t("views.pomodoro.buttons.skipBreak")):this.skipBreakButton.addClass("pomodoro-view__skip-break-button--hidden")}this.addTimeButton&&this.subtractTimeButton&&(this.addTimeButton.removeClass("pomodoro-view__time-adjust-button--hidden"),this.subtractTimeButton.removeClass("pomodoro-view__time-adjust-button--hidden")),this.timerDisplay&&(this.canEditTimer()?(this.timerDisplay.addClass("pomodoro-view__timer-display--editable"),this.timerDisplay.setAttribute("aria-disabled","false")):(this.timerDisplay.removeClass("pomodoro-view__timer-display--editable"),this.timerDisplay.setAttribute("aria-disabled","true")))}}updateSessionMeta(t,r=Date.now()){if(!this.sessionMetaDisplay)return;let a=Sk(t.timeRemaining,{padMinutes:!1}),i;if(t.currentSession){let s=this.getSessionTypeLabel(t.currentSession.type);if(t.isRunning){let o=Wu(new Date(Pye(t.timeRemaining,r)),this.plugin.settings.calendarViewSettings.timeFormat);i=this.t("views.pomodoro.meta.running",{time:a,endTime:o})}else i=this.t("views.pomodoro.meta.paused",{type:s,time:a})}else t.nextSessionType==="short-break"||t.nextSessionType==="long-break"?i=this.t("views.pomodoro.meta.breakReady",{type:this.getSessionTypeLabel(t.nextSessionType),time:a}):i=this.t("views.pomodoro.meta.ready",{time:a,count:this.todaysPomodoros});this.sessionMetaDisplay.textContent!==i&&(this.sessionMetaDisplay.textContent=i)}getSessionTypeLabel(t){return t==="work"?this.t("views.pomodoro.status.focus"):t==="short-break"?this.t("views.pomodoro.status.shortBreak"):this.t("views.pomodoro.status.longBreak")}canEditTimer(){var r;let t=(r=this.plugin.pomodoroService)==null?void 0:r.getState();return!!(t&&!t.isRunning)}beginTimerEdit(){if(!this.timerDisplay||!this.timerInput||!this.plugin.pomodoroService||!this.canEditTimer())return;let t=this.plugin.pomodoroService.getState();this.isEditingTimer=!0,this.timerInput.value=Sk(t.timeRemaining,{padMinutes:!1}),this.timerDisplay.addClass("pomodoro-view__timer-display--hidden"),this.timerInput.removeClass("pomodoro-view__timer-input--hidden"),this.timerInput.focus(),this.timerInput.select()}commitTimerEdit(){var a,i;if(!this.isEditingTimer||!this.timerInput||!this.timerDisplay)return;let t=Iye(this.timerInput.value);if(this.isEditingTimer=!1,this.timerInput.addClass("pomodoro-view__timer-input--hidden"),this.timerDisplay.removeClass("pomodoro-view__timer-display--hidden"),t===null){new Zp.Notice(this.t("views.pomodoro.notices.invalidDuration"));let s=(a=this.plugin.pomodoroService)==null?void 0:a.getState();s&&this.isViewVisible()&&this.updateTimer(s.timeRemaining);return}let r=(i=this.plugin.pomodoroService)==null?void 0:i.getState();r&&(r.currentSession?this.plugin.pomodoroService.setCurrentSessionRemainingTime(t):this.plugin.pomodoroService.adjustPreparedTimer(t),this.updateDisplay())}cancelTimerEdit(){var r;if(!this.timerInput||!this.timerDisplay)return;this.isEditingTimer=!1,this.timerInput.addClass("pomodoro-view__timer-input--hidden"),this.timerDisplay.removeClass("pomodoro-view__timer-display--hidden");let t=(r=this.plugin.pomodoroService)==null?void 0:r.getState();t&&this.isViewVisible()&&this.updateTimer(t.timeRemaining)}updateTimer(t){if(this.timerDisplay){if(this.isEditingTimer)return;let r=Math.max(0,Math.floor(t)),a=Sk(r);this.timerDisplay.textContent!==a&&(this.timerDisplay.textContent=a),this.timerDisplay.classList.toggle("pomodoro-view__timer-display--warning",r<=60&&r>0)}}updateProgress(t){var s;if(!this.progressCircle)return;let r=this.currentCircumference;if(r===0){let o=this.progressCircle.getAttribute("r"),l=o?parseInt(o):140;r=2*Math.PI*l,this.currentCircumference=r}let a=t.currentSession?Math.max(0,Math.min(1,1-t.timeRemaining/hR(t.currentSession))):0,i=r-a*r;this.progressCircle.getAttribute("stroke-dashoffset")!==i.toString()&&this.progressCircle.setAttributeNS(null,"stroke-dashoffset",i.toString());for(let o of["work","short-break","long-break"])this.progressCircle.classList.toggle(`pomodoro-view__progress-circle--${o}`,o===((s=t.currentSession)==null?void 0:s.type));this.progressCircle.classList.toggle("pomodoro-view__progress-circle--warning",!!t.currentSession&&t.timeRemaining<=60&&t.timeRemaining>0)}async updateStats(){let t=this.openGeneration;try{if(!this.plugin.pomodoroService){this.isViewVisible()&&this.statElements.pomodoros&&(this.statElements.pomodoros.textContent="0");return}let r=await this.plugin.pomodoroService.getTodayStats();if(this.isClosed||t!==this.openGeneration)return;this.todaysPomodoros=r.pomodorosCompleted,this.isViewVisible()&&this.statElements.pomodoros&&this.statElements.pomodoros.textContent!==r.pomodorosCompleted.toString()&&(this.statElements.pomodoros.textContent=r.pomodorosCompleted.toString()),this.updateDisplay()}catch(r){Xx.error("Failed to update stats:",{category:"validation",operation:"update-stats",error:r}),this.isViewVisible()&&this.statElements.pomodoros&&(this.statElements.pomodoros.textContent="0")}}adjustSessionTime(t){if(!this.plugin.pomodoroService)return;let r=this.plugin.pomodoroService.getState();if(r.currentSession)this.plugin.pomodoroService.adjustSessionTime(t);else{let a=Math.max(60,r.timeRemaining+t);this.plugin.pomodoroService.adjustPreparedTimer(a)}this.updateDisplay()}onPomodoroComplete(t,r){if(this.updateDisplay(void 0,void 0,{refreshStats:!0}),this.statusDisplay)if(t.type==="work"){let a=r==="long-break",i=this.t(a?"views.pomodoro.status.breakLength.long":"views.pomodoro.status.breakLength.short");this.statusDisplay.textContent=this.t("views.pomodoro.status.breakPrompt",{length:i})}else this.statusDisplay.textContent=this.t("views.pomodoro.status.breakComplete")}}});function bR(n){if(n.activePeriods&&Array.isArray(n.activePeriods))return n.activePeriods.filter(e=>e.endTime).reduce((e,t)=>{let r=new Date(t.startTime),i=new Date(t.endTime).getTime()-r.getTime();return e+Math.round(i/(1e3*60))},0);if(n.duration!==void 0)return n.duration;if(n.startTime&&n.endTime){let e=new Date(n.startTime),r=new Date(n.endTime).getTime()-e.getTime();return Math.round(r/(1e3*60))}return 0}var DW=y(()=>{});function eE(n){return[...n].sort((e,t)=>new Date(e.startTime).getTime()-new Date(t.startTime).getTime())}function nGe(n){var r;let e=(r=n.match(/^(\d{4}-\d{2}-\d{2})(?:[T\s]|$)/))==null?void 0:r[1];if(e)return e;let t=new Date(n);return isNaN(t.getTime())?"":ae(t)}function Ck(n){return nGe(n.startTime)}function zye(n,e){return e?n.filter(t=>Ck(t)===e):[]}function Bye(n,e,t){let r=ae(e),a=ae(t);if(!r||!a)return[];let[i,s]=r<=a?[r,a]:[a,r];return n.filter(o=>{let l=Ck(o);return l>=i&&l<=s})}function jye(n,e){let t=ae(n),r=ae(e);if(!t||!r)return[];let[a,i]=t<=r?[t,r]:[r,t],[s,o,l]=a.split("-").map(Number),[c,d,u]=i.split("-").map(Number),p=new Date(Date.UTC(s,o-1,l)),m=new Date(Date.UTC(c,d-1,u)),f=[];for(;p<=m;)f.push(ae(p)),p.setUTCDate(p.getUTCDate()+1);return f}function xk(n){let e=eE(n).filter(o=>o.type==="work"),t=e.filter(o=>o.completed),r=0;for(let o=e.length-1;o>=0&&e[o].completed;o--)r++;let a=t.reduce((o,l)=>o+bR(l),0),i=t.length>0?a/t.length:0,s=e.length>0?t.length/e.length*100:0;return{pomodorosCompleted:t.length,currentStreak:r,totalMinutes:a,averageSessionLength:Math.round(i),completionRate:Math.round(s)}}var PW=y(()=>{xe();DW()});function iGe(n){return Number.isInteger(n)&&n>=0&&n<=6}var Zn,aGe,wR,$ye=y(()=>{Zn=require("obsidian");Cr();Pr();Fi();xe();DW();PW();q();aGe=M({tag:"Views/PomodoroStatsView"});wR=class extends Zn.ItemView{constructor(t,r){super(t);this.overviewStatsEl=null;this.todayStatsEl=null;this.weekStatsEl=null;this.recentSessionsEl=null;this.overallStatsEl=null;this.plugin=r}getViewType(){return Kg}getDisplayText(){return this.plugin.i18n.translate("views.pomodoroStats.title")}getIcon(){return"bar-chart"}t(t,r){return this.plugin.i18n.translate(t,r)}async onOpen(){await this.plugin.onReady(),await this.waitForPomodoroService(),await this.render()}async onClose(){this.contentEl.empty()}async render(){this.contentEl.empty();let t=this.contentEl.createDiv({cls:"tasknotes-plugin tasknotes-container pomodoro-stats-container pomodoro-stats-view"}),r=t.createDiv({cls:"pomodoro-stats-header pomodoro-stats-view__header"});new Zn.Setting(r).setName(this.t("views.pomodoroStats.heading")).setHeading();let a=r.createDiv({cls:"pomodoro-stats-view__header-actions"});this.renderBasesMigrationHelp(a);let i=a.createEl("button",{cls:"pomodoro-stats-refresh-button pomodoro-stats-view__refresh-button",text:this.t("views.pomodoroStats.refresh")});this.registerDomEvent(i,"click",()=>{this.refreshStats()});let s=t.createDiv({cls:"pomodoro-stats-section pomodoro-stats-view__section"});new Zn.Setting(s).setName(this.t("views.pomodoroStats.sections.overview")).setHeading(),this.overviewStatsEl=s.createDiv({cls:"pomodoro-overview-grid pomodoro-stats-view__overview-grid"});let o=t.createDiv({cls:"pomodoro-stats-section pomodoro-stats-view__section"});new Zn.Setting(o).setName(this.t("views.pomodoroStats.sections.today")).setHeading(),this.todayStatsEl=o.createDiv({cls:"pomodoro-stats-grid pomodoro-stats-view__stats-grid"});let l=t.createDiv({cls:"pomodoro-stats-section pomodoro-stats-view__section"});new Zn.Setting(l).setName(this.t("views.pomodoroStats.sections.week")).setHeading(),this.weekStatsEl=l.createDiv({cls:"pomodoro-stats-grid pomodoro-stats-view__stats-grid"});let c=t.createDiv({cls:"pomodoro-stats-section pomodoro-stats-view__section"});new Zn.Setting(c).setName(this.t("views.pomodoroStats.sections.allTime")).setHeading(),this.overallStatsEl=c.createDiv({cls:"pomodoro-stats-grid pomodoro-stats-view__stats-grid"});let d=t.createDiv({cls:"pomodoro-stats-section pomodoro-stats-view__section"});new Zn.Setting(d).setName(this.t("views.pomodoroStats.sections.recent")).setHeading(),this.recentSessionsEl=d.createDiv({cls:"pomodoro-recent-sessions pomodoro-stats-view__recent-sessions"}),await this.refreshStats()}renderBasesMigrationHelp(t){if(this.plugin.settings.pomodoroStorageLocation==="daily-notes")return;let r=t.createEl("button",{cls:"pomodoro-stats-view__bases-help"}),a=this.t("views.pomodoroStats.basesMigration.title"),i=this.t("views.pomodoroStats.basesMigration.description");(0,Zn.setIcon)(r,"help-circle"),r.setAttr("aria-label",`${a}: ${i}`),(0,Zn.setTooltip)(r,i,{placement:"bottom"})}async waitForPomodoroService(){let t=Date.now();for(;!this.plugin.pomodoroService&&Date.now()-t<5e3;)await new Promise(r=>window.setTimeout(r,50))}async refreshStats(){try{if(!this.plugin.pomodoroService)return;let t=Xt(),r=Br(t),a=new Date(t);a.setDate(a.getDate()-1);let i=Br(a),s=this.plugin.settings.calendarViewSettings.firstDay||0,l={weekStartsOn:iGe(s)?s:0},c=ni(r,l),d=Bg(r,l),[u,p,m,f]=await Promise.all([this.plugin.pomodoroService.getTodayStats(),this.plugin.pomodoroService.getStatsForDate(i),this.plugin.pomodoroService.getStatsForDateRange(c,d),this.plugin.pomodoroService.getSessionHistory()]),h=xk(f);this.overviewStatsEl&&this.renderOverviewStats(this.overviewStatsEl,u,h,p),this.todayStatsEl&&this.renderStatsGrid(this.todayStatsEl,u),this.weekStatsEl&&this.renderStatsGrid(this.weekStatsEl,m),this.overallStatsEl&&this.renderStatsGrid(this.overallStatsEl,h),this.recentSessionsEl&&this.renderRecentSessions(this.recentSessionsEl,f)}catch(t){aGe.error("Failed to refresh stats:",{category:"stale-data",operation:"refresh-stats",error:t})}}renderRecentSessions(t,r){var i;let a=r.filter(s=>s.type==="work").slice(-10).reverse();if(t.empty(),a.length===0){t.createDiv({cls:"pomodoro-no-sessions pomodoro-stats-view__no-sessions",text:this.t("views.pomodoroStats.recents.empty")});return}for(let s of a){let o=t.createDiv({cls:"pomodoro-session-item pomodoro-stats-view__session-item"});this.registerDomEvent(o,"contextmenu",f=>{f.preventDefault(),this.showSessionContextMenu(f,s)});let l=o.createSpan({cls:"session-date pomodoro-stats-view__session-date"}),c=this.plugin.settings.calendarViewSettings.timeFormat;l.textContent=D(new Date(s.startTime),c==="12"?"MMM d, h:mm a":"MMM d, HH:mm");let d=o.createSpan({cls:"session-duration pomodoro-stats-view__session-duration"}),u=bR(s);d.textContent=this.t("views.pomodoroStats.recents.duration",{minutes:u});let p=o.createSpan({cls:"session-status pomodoro-stats-view__session-status"});if(p.textContent=this.t(s.completed?"views.pomodoroStats.recents.status.completed":"views.pomodoroStats.recents.status.interrupted"),p.addClass(s.completed?"status-completed":"status-interrupted"),p.addClass(s.completed?"pomodoro-stats-view__session-status--completed":"pomodoro-stats-view__session-status--interrupted"),s.taskPath){let f=o.createSpan({cls:"session-task pomodoro-stats-view__session-task"}),h=((i=s.taskPath.split("/").pop())==null?void 0:i.replace(".md",""))||"";f.textContent=h}let m=o.createEl("button",{cls:"pomodoro-stats-view__session-delete-button",attr:{type:"button","aria-label":this.t("views.pomodoroStats.recents.deleteAria")}});(0,Zn.setIcon)(m,"trash-2"),(0,Zn.setTooltip)(m,this.t("views.pomodoroStats.recents.delete"),{placement:"top"}),this.registerDomEvent(m,"click",f=>{f.preventDefault(),f.stopPropagation(),this.confirmDeleteSession(s)})}}showSessionContextMenu(t,r){let a=new Zn.Menu;a.addItem(i=>{i.setTitle(this.t("views.pomodoroStats.recents.delete")),i.setIcon("trash"),i.onClick(()=>{this.confirmDeleteSession(r)})}),a.showAtMouseEvent(t)}async confirmDeleteSession(t){if(!await ur(this.plugin.app,{title:this.t("views.pomodoroStats.recents.deleteConfirmTitle"),message:this.t("views.pomodoroStats.recents.deleteConfirmMessage"),confirmText:this.t("views.pomodoroStats.recents.deleteConfirmButton"),cancelText:this.t("common.cancel"),isDestructive:!0})||!this.plugin.pomodoroService)return;let a=await this.plugin.pomodoroService.deleteSessionFromHistory(t);new Zn.Notice(this.t(a?"views.pomodoroStats.recents.deleteSuccess":"views.pomodoroStats.recents.deleteNotFound")),a&&await this.refreshStats()}renderOverviewStats(t,r,a,i){t.empty();let s=v=>{if(v<60)return`${v}m`;let k=Math.floor(v/60),T=v%60;return T>0?`${k}h${T}m`:`${k}h`},o=r.pomodorosCompleted-i.pomodorosCompleted,l=r.totalMinutes-i.totalMinutes,c=t.createDiv({cls:"pomodoro-overview-card pomodoro-stats-view__overview-card"}),d=c.createDiv({cls:"overview-value pomodoro-stats-view__overview-value"});if(d.textContent=r.pomodorosCompleted.toString(),c.createDiv({cls:"overview-label pomodoro-stats-view__overview-label",text:this.t("views.pomodoroStats.overviewCards.todayPomos.label")}),o!==0){let v=c.createDiv({cls:"overview-change pomodoro-stats-view__overview-change"});v.textContent=o>0?this.t("views.pomodoroStats.overviewCards.todayPomos.change.more",{count:o}):this.t("views.pomodoroStats.overviewCards.todayPomos.change.less",{count:Math.abs(o)}),v.addClass(o>0?"positive":"negative")}let u=t.createDiv({cls:"pomodoro-overview-card pomodoro-stats-view__overview-card"}),p=u.createDiv({cls:"overview-value pomodoro-stats-view__overview-value"});p.textContent=a.pomodorosCompleted.toString(),u.createDiv({cls:"overview-label pomodoro-stats-view__overview-label",text:this.t("views.pomodoroStats.overviewCards.totalPomos.label")});let m=t.createDiv({cls:"pomodoro-overview-card pomodoro-stats-view__overview-card"}),f=m.createDiv({cls:"overview-value pomodoro-stats-view__overview-value"});if(f.textContent=s(r.totalMinutes),m.createDiv({cls:"overview-label pomodoro-stats-view__overview-label",text:this.t("views.pomodoroStats.overviewCards.todayFocus.label")}),l!==0){let v=m.createDiv({cls:"overview-change pomodoro-stats-view__overview-change"});v.textContent=l>0?this.t("views.pomodoroStats.overviewCards.todayFocus.change.more",{duration:s(Math.abs(l))}):this.t("views.pomodoroStats.overviewCards.todayFocus.change.less",{duration:s(Math.abs(l))}),v.addClass(l>0?"positive":"negative")}let h=t.createDiv({cls:"pomodoro-overview-card pomodoro-stats-view__overview-card"}),g=h.createDiv({cls:"overview-value pomodoro-stats-view__overview-value"});g.textContent=s(a.totalMinutes),h.createDiv({cls:"overview-label pomodoro-stats-view__overview-label",text:this.t("views.pomodoroStats.overviewCards.totalFocus.label")})}renderStatsGrid(t,r){t.empty();let a=t.createDiv({cls:"pomodoro-stat-card pomodoro-stats-view__stat-card"});a.createDiv({cls:"stat-value pomodoro-stats-view__stat-value",text:r.pomodorosCompleted.toString()}),a.createDiv({cls:"stat-label pomodoro-stats-view__stat-label",text:this.t("views.pomodoroStats.stats.pomodoros")});let i=t.createDiv({cls:"pomodoro-stat-card pomodoro-stats-view__stat-card"});i.createDiv({cls:"stat-value pomodoro-stats-view__stat-value",text:r.currentStreak.toString()}),i.createDiv({cls:"stat-label pomodoro-stats-view__stat-label",text:this.t("views.pomodoroStats.stats.streak")});let s=t.createDiv({cls:"pomodoro-stat-card pomodoro-stats-view__stat-card"});s.createDiv({cls:"stat-value pomodoro-stats-view__stat-value",text:r.totalMinutes.toString()}),s.createDiv({cls:"stat-label pomodoro-stats-view__stat-label",text:this.t("views.pomodoroStats.stats.minutes")});let o=t.createDiv({cls:"pomodoro-stat-card pomodoro-stats-view__stat-card"});o.createDiv({cls:"stat-value pomodoro-stats-view__stat-value",text:r.averageSessionLength.toString()}),o.createDiv({cls:"stat-label pomodoro-stats-view__stat-label",text:this.t("views.pomodoroStats.stats.average")});let l=t.createDiv({cls:"pomodoro-stat-card pomodoro-stats-view__stat-card"});l.createDiv({cls:"stat-value pomodoro-stats-view__stat-value",text:`${r.completionRate}%`}),l.createDiv({cls:"stat-label pomodoro-stats-view__stat-label",text:this.t("views.pomodoroStats.stats.completion")})}}});function sGe(n){return Number.isInteger(n)&&n>=0&&n<=6}function Ek(){return{dateRange:"all",selectedProjects:[],minTimeSpent:0}}function lGe(n){return typeof n=="string"&&oGe.has(n)}function Hye(n){return typeof n=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(n)}function cGe(n){if(!n||typeof n!="object")return Ek();let e=n,t=Ek();lGe(e.dateRange)&&(t.dateRange=e.dateRange),Hye(e.customStartDate)&&(t.customStartDate=e.customStartDate),Hye(e.customEndDate)&&(t.customEndDate=e.customEndDate),Array.isArray(e.selectedProjects)&&(t.selectedProjects=e.selectedProjects.filter(a=>typeof a=="string"));let r=typeof e.minTimeSpent=="number"?e.minTimeSpent:Number(e.minTimeSpent);return Number.isFinite(r)&&r>0&&(t.minTimeSpent=Math.floor(r)),t}function dGe(n){return n.filter(e=>!e.archived)}function uGe(n,e){if(!Array.isArray(n))return[e.noProjectLabel];let t=Ko(n);return t.length===0?[e.noProjectLabel]:t.filter(r=>{var a;return!((a=e.isArchivedProjectReference)!=null&&a.call(e,r))}).map(r=>e.consolidateProjectName(r)).filter(r=>typeof r=="string"&&r.length>0)}var wo,tE,Uye,oGe,SR,Vye=y(()=>{wo=require("obsidian");Cr();Pr();yt();xe();Ua();Yl();Cn();q();tE=M({tag:"Views/StatsView"});Uye="tasknotes-stats-view-filters",oGe=new Set(["all","7days","30days","90days","custom"]);SR=class extends wo.ItemView{constructor(t,r){super(t);this.overviewStatsEl=null;this.todayStatsEl=null;this.weekStatsEl=null;this.monthStatsEl=null;this.projectsStatsEl=null;this.filtersEl=null;this.currentFilters=Ek();this.drilldownModal=null;this.currentDrilldownData=null;this.listeners=[];this.statsCache=new Map;this.lastCacheTime=0;this.CACHE_DURATION=6e4;this.debounceTimeout=null;this.plugin=r}getViewType(){return Zg}getDisplayText(){return this.plugin.i18n.translate("views.stats.title")}getIcon(){return"bar-chart-4"}async onOpen(){await this.plugin.onReady(),this.currentFilters=this.loadPersistedFilters();let t=this.plugin.emitter.on(rt,async({path:r,originalTask:a,updatedTask:i})=>{if(!r||!i||!this.drilldownModal||!this.currentDrilldownData)return;this.currentDrilldownData.tasks.some(o=>o.path===r||a&&o.path===a.path)&&await this.refreshDrilldownModal()});this.listeners.push(t),await this.render()}async onClose(){this.contentEl.empty(),this.listeners.forEach(t=>this.plugin.emitter.offref(t)),this.listeners=[]}loadPersistedFilters(){try{let t=this.plugin.app.loadLocalStorage(Uye);return typeof t!="string"||t.length===0?Ek():cGe(JSON.parse(t))}catch(t){return tE.warn("[TaskNotes] Failed to load Stats view filters:",{category:"persistence",operation:"load-stats-view-filters",error:t}),Ek()}}savePersistedFilters(){try{this.plugin.app.saveLocalStorage(Uye,JSON.stringify(this.currentFilters))}catch(t){tE.warn("[TaskNotes] Failed to save Stats view filters:",{category:"persistence",operation:"save-stats-view-filters",error:t})}}async render(){let t=this.contentEl.createDiv({cls:"tasknotes-plugin tasknotes-container stats-container stats-view"}),r=t.createDiv({cls:"stats-header stats-view__header"});new wo.Setting(r).setName(this.plugin.i18n.translate("views.stats.taskProjectStats")).setHeading();let a=r.createEl("button",{cls:"stats-refresh-button stats-view__refresh-button",text:this.plugin.i18n.translate("views.stats.refreshButton")});this.registerDomEvent(a,"click",()=>{this.refreshStats()});let i=t.createDiv({cls:"stats-section stats-view__section"});new wo.Setting(i).setName(this.plugin.i18n.translate("views.stats.sections.filters")).setHeading(),this.filtersEl=i.createDiv({cls:"stats-filters stats-view__filters"}),this.renderFilters();let s=t.createDiv({cls:"stats-section stats-view__section"});new wo.Setting(s).setName(this.plugin.i18n.translate("views.stats.sections.overview")).setHeading(),this.overviewStatsEl=s.createDiv({cls:"stats-overview-grid stats-view__overview-grid"});let o=t.createDiv({cls:"stats-section stats-view__section"});new wo.Setting(o).setName(this.plugin.i18n.translate("views.stats.sections.today")).setHeading(),this.todayStatsEl=o.createDiv({cls:"stats-grid stats-view__stats-grid"});let l=t.createDiv({cls:"stats-section stats-view__section"});new wo.Setting(l).setName(this.plugin.i18n.translate("views.stats.sections.thisWeek")).setHeading(),this.weekStatsEl=l.createDiv({cls:"stats-grid stats-view__stats-grid"});let c=t.createDiv({cls:"stats-section stats-view__section"});new wo.Setting(c).setName(this.plugin.i18n.translate("views.stats.sections.thisMonth")).setHeading(),this.monthStatsEl=c.createDiv({cls:"stats-grid stats-view__stats-grid"});let d=t.createDiv({cls:"stats-section stats-view__section"});new wo.Setting(d).setName(this.plugin.i18n.translate("views.stats.sections.projectBreakdown")).setHeading(),this.projectsStatsEl=d.createDiv({cls:"stats-projects stats-view__projects"}),await this.refreshStats()}async refreshStats(){try{this.clearCache();let t=await Promise.allSettled([this.updateOverviewStats(),this.updateTodayStats(),this.updateWeekStats(),this.updateMonthStats(),this.updateProjectStats()])}catch(t){}}async getAllTasks(){let t=`all-tasks-${JSON.stringify(this.currentFilters)}`;if(this.isCacheValid()&&this.statsCache.has(t)){let i=this.statsCache.get(t);if(i)return i}let r=this.plugin.cacheManager.getAllTaskPaths(),a=[];for(let i of r)try{let s=await this.plugin.cacheManager.getTaskInfo(i);s&&a.push(s)}catch(s){}return a=dGe(a),a=this.applyTaskFilters(a),this.statsCache.set(t,a),this.lastCacheTime=Date.now(),a}applyTaskFilters(t){let r=t,a=this.getFilterDateRange();return(a.start||a.end)&&(r=r.filter(i=>{if(i.timeEntries&&i.timeEntries.length>0)return i.timeEntries.some(s=>{if(!s.startTime)return!1;let o=new Date(s.startTime);return!(a.start&&oa.end)});if(i.completedDate){let s=new Date(i.completedDate);return!(a.start&&sa.end)}if(i.dateCreated){let s=new Date(i.dateCreated);return!(a.start&&sa.end)}return!(a.start||a.end)})),this.currentFilters.minTimeSpent>0&&(r=r.filter(i=>oi(i.timeEntries||[])>=this.currentFilters.minTimeSpent)),r}async updateOverviewStats(){if(!this.overviewStatsEl)return;let t=await this.getAllTasks(),r=this.calculateOverallStats(t);this.renderOverviewStats(this.overviewStatsEl,r)}async updateTodayStats(){if(!this.todayStatsEl)return;let t=Xt(),r=await this.calculateStatsForRange(Vo(t),sb(t));this.renderTimeRangeStats(this.todayStatsEl,r)}async updateWeekStats(){if(!this.weekStatsEl)return;let t=Xt(),r=this.plugin.settings.calendarViewSettings.firstDay||0,i={weekStartsOn:sGe(r)?r:0},s=ni(t,i),o=Bg(t,i),l=await this.calculateStatsForRange(s,o);this.renderTimeRangeStats(this.weekStatsEl,l)}async updateMonthStats(){if(!this.monthStatsEl)return;let t=Xt(),r=YP(t),a=GP(t),i=await this.calculateStatsForRange(r,a);this.renderTimeRangeStats(this.monthStatsEl,i)}async updateProjectStats(){if(!this.projectsStatsEl)return;let t=await this.getAllTasks(),r=this.calculateProjectStats(t);await this.renderProjectStats(this.projectsStatsEl,r)}consolidateProjectName(t){var a,i;if(!t||typeof t!="string")return t;let r=Zo(t,(a=this.plugin)==null?void 0:a.app);if(r&&r!==t)return r;if(t.startsWith("[[")&&t.endsWith("]]")){let s=this.extractWikilinkPath(t);if(s&&((i=this.plugin)!=null&&i.app)){let o=this.plugin.app.metadataCache.getFirstLinkpathDest(s,"");if(o)return o.basename;let l=this.extractProjectName(t);if(l)return l}}if(t.includes("|")){let s=t.split("|");return s[s.length-1]||t}if(t.includes("/")){let s=t.split("/");return s[s.length-1]||t}return t}extractWikilinkPath(t){if(!t||typeof t!="string"||!t.startsWith("[[")||!t.endsWith("]]"))return null;let r=t.slice(2,-2);return(0,wo.parseLinktext)(r).path}extractProjectName(t){var a;return t&&Zo(t,(a=this.plugin)==null?void 0:a.app)||null}isArchivedProjectReference(t){var r;return((r=this.getProjectReferenceTask(t))==null?void 0:r.archived)===!0}getProjectReferenceTask(t){let r=t.trim();if(!this.isProjectNoteReference(r))return null;let a=vt(r);if(!a)return null;let i=a.replace(/\.md$/i,""),s=this.plugin.app.metadataCache.getFirstLinkpathDest(i,"");if(s){let l=this.plugin.cacheManager.getCachedTaskInfoSync(s.path);if(l)return l}let o=/\.md$/i.test(a)?[a]:[a,`${a}.md`];for(let l of o){let c=this.plugin.cacheManager.getCachedTaskInfoSync(l);if(c)return c}return null}isProjectNoteReference(t){return t.startsWith("[[")&&t.endsWith("]]")||/^\[[^\]]*\]\(.+\)$/.test(t)||t.startsWith("<")&&t.endsWith(">")||t.includes("/")||/\.md$/i.test(t)}calculateOverallStats(t){let r=0,a=0,i=0,s=new Set;for(let o of t){r+=oi(o.timeEntries||[]),a+=o.timeEstimate||0,this.plugin.statusManager.isCompletedStatus(o.status)&&i++;let l=this.getTaskProjects(o);for(let c of l)s.add(c)}return{totalTimeSpent:r,totalTimeEstimate:a,totalTasks:t.length,completedTasks:i,activeProjects:s.size,completionRate:t.length>0?i/t.length*100:0,avgTimePerTask:t.length>0?r/t.length:0}}async calculateStatsForRange(t,r){let i=(await this.getAllTasks()).filter(l=>{if(l.timeEntries&&l.timeEntries.length>0)return l.timeEntries.some(c=>{if(!c.startTime)return!1;let d=new Date(c.startTime);return d>=t&&d<=r});if(l.completedDate){let c=new Date(l.completedDate);return c>=t&&c<=r}if(l.dateCreated){let c=new Date(l.dateCreated);return c>=t&&c<=r}return!1}),s=this.calculateOverallStats(i),o=this.calculateProjectStats(i);return{overall:s,projects:o}}calculateProjectStats(t){let r=new Map;for(let s of t){let o=oi(s.timeEntries||[]),l=s.timeEstimate||0,c=this.plugin.statusManager.isCompletedStatus(s.status),d;s.timeEntries&&s.timeEntries.length>0?d=[...s.timeEntries].sort((m,f)=>new Date(f.startTime).getTime()-new Date(m.startTime).getTime())[0].startTime:s.completedDate?d=s.completedDate:s.dateModified&&(d=s.dateModified);let u=this.getTaskProjects(s);for(let p of u){r.has(p)||r.set(p,{tasks:[],totalTime:0,totalTimeEstimate:0,completedCount:0,lastActivity:void 0});let m=r.get(p);m&&(m.tasks.push(s),m.totalTime+=o,m.totalTimeEstimate+=l,c&&m.completedCount++,d&&(!m.lastActivity||new Date(d)>new Date(m.lastActivity))&&(m.lastActivity=d))}}let a=[];for(let[s,o]of r.entries())a.push({projectName:s,totalTimeSpent:o.totalTime,totalTimeEstimate:o.totalTimeEstimate,taskCount:o.tasks.length,completedTaskCount:o.completedCount,avgTimePerTask:o.tasks.length>0?o.totalTime/o.tasks.length:0,lastActivity:o.lastActivity});let i=this.plugin.i18n.translate("views.stats.noProject");return a.sort((s,o)=>s.projectName===i?1:o.projectName===i?-1:o.totalTimeSpent-s.totalTimeSpent),a}renderFilters(){if(!this.filtersEl)return;this.filtersEl.empty();let t=this.filtersEl.createDiv({cls:"stats-view__filter-grid"}),r=t.createDiv({cls:"stats-view__filter-item"}),a=r.createDiv({cls:"stats-view__filter-label"});a.textContent=this.plugin.i18n.translate("views.stats.sections.dateRange");let i=r.createEl("select",{cls:"stats-view__filter-select"}),s=[{value:"all",text:this.plugin.i18n.translate("views.stats.timeRanges.allTime")},{value:"7days",text:this.plugin.i18n.translate("views.stats.timeRanges.last7Days")},{value:"30days",text:this.plugin.i18n.translate("views.stats.timeRanges.last30Days")},{value:"90days",text:this.plugin.i18n.translate("views.stats.timeRanges.last90Days")},{value:"custom",text:this.plugin.i18n.translate("views.stats.timeRanges.customRange")}];for(let m of s){let f=i.createEl("option",{value:m.value,text:m.text});m.value===this.currentFilters.dateRange&&(f.selected=!0)}this.registerDomEvent(i,"change",()=>{this.currentFilters.dateRange=i.value,this.renderCustomDateInputs(),this.applyFilters()});let o=t.createDiv({cls:"stats-view__custom-dates"});this.currentFilters.dateRange==="custom"&&this.renderCustomDateInputs(o);let l=t.createDiv({cls:"stats-view__filter-item"}),c=l.createDiv({cls:"stats-view__filter-label"});c.textContent=this.plugin.i18n.translate("views.stats.filters.minTime");let d=l.createEl("input",{cls:"stats-view__filter-input",type:"number",value:this.currentFilters.minTimeSpent.toString(),placeholder:"0"});this.registerDomEvent(d,"input",()=>{this.currentFilters.minTimeSpent=parseInt(d.value)||0,this.applyFilters()});let p=t.createDiv({cls:"stats-view__filter-buttons"}).createEl("button",{cls:"stats-view__filter-button stats-view__filter-button--reset",text:this.plugin.i18n.translate("views.stats.resetFiltersButton")});this.registerDomEvent(p,"click",()=>{this.currentFilters=Ek(),this.renderFilters(),this.applyFilters()})}renderCustomDateInputs(t){var a;let r=t||((a=this.filtersEl)==null?void 0:a.querySelector(".stats-view__custom-dates"));if(r&&(r.empty(),this.currentFilters.dateRange==="custom")){let i=r.createDiv({cls:"stats-view__date-input-container"});i.createDiv({cls:"stats-view__date-label",text:this.plugin.i18n.translate("views.stats.dateRangeFrom")});let s=i.createEl("input",{cls:"stats-view__date-input",type:"date",value:this.currentFilters.customStartDate||""}),o=r.createDiv({cls:"stats-view__date-input-container"});o.createDiv({cls:"stats-view__date-label",text:this.plugin.i18n.translate("views.stats.dateRangeTo")});let l=o.createEl("input",{cls:"stats-view__date-input",type:"date",value:this.currentFilters.customEndDate||""});this.registerDomEvent(s,"change",()=>{this.currentFilters.customStartDate=s.value,this.applyFilters()}),this.registerDomEvent(l,"change",()=>{this.currentFilters.customEndDate=l.value,this.applyFilters()})}}async applyFilters(){this.savePersistedFilters(),this.debounceTimeout&&window.clearTimeout(this.debounceTimeout),this.debounceTimeout=window.setTimeout(()=>{(async()=>(await this.refreshStats(),this.debounceTimeout=null))()},300)}isCacheValid(){return Date.now()-this.lastCacheTimethis.consolidateProjectName(r),isArchivedProjectReference:r=>this.isArchivedProjectReference(r)})}catch(r){return[this.plugin.i18n.translate("views.stats.noProject")]}}getFilterDateRange(){let t=Xt();switch(this.currentFilters.dateRange){case"7days":return{start:Vo(Hg(t,7)),end:sb(t)};case"30days":return{start:Vo(Hg(t,30)),end:sb(t)};case"90days":return{start:Vo(Hg(t,90)),end:sb(t)};case"custom":return{start:this.currentFilters.customStartDate?new Date(`${this.currentFilters.customStartDate}T00:00:00`):void 0,end:this.currentFilters.customEndDate?new Date(`${this.currentFilters.customEndDate}T23:59:59.999`):void 0};case"all":default:return{}}}renderOverviewStats(t,r){t.empty();let a=h=>{if(h<60)return`${Math.round(h)}m`;let g=Math.floor(h/60),v=Math.round(h%60);return v>0?`${g}h ${v}m`:`${g}h`},i=t.createDiv({cls:"stats-overview-card stats-view__overview-card"}),s=i.createDiv({cls:"overview-value stats-view__overview-value"});s.textContent=`${a(r.totalTimeSpent)} / ${a(r.totalTimeEstimate)}`,i.createDiv({cls:"overview-label stats-view__overview-label",text:this.plugin.i18n.translate("views.stats.cards.timeTrackedEstimated")});let o=t.createDiv({cls:"stats-overview-card stats-view__overview-card"}),l=o.createDiv({cls:"overview-value stats-view__overview-value"});l.textContent=r.totalTasks.toString(),o.createDiv({cls:"overview-label stats-view__overview-label",text:this.plugin.i18n.translate("views.stats.cards.totalTasks")});let c=t.createDiv({cls:"stats-overview-card stats-view__overview-card"}),d=c.createDiv({cls:"overview-value stats-view__overview-value"});d.textContent=`${Math.round(r.completionRate)}%`,c.createDiv({cls:"overview-label stats-view__overview-label",text:this.plugin.i18n.translate("views.stats.cards.completionRate")});let u=t.createDiv({cls:"stats-overview-card stats-view__overview-card"}),p=u.createDiv({cls:"overview-value stats-view__overview-value"});p.textContent=r.activeProjects.toString(),u.createDiv({cls:"overview-label stats-view__overview-label",text:this.plugin.i18n.translate("views.stats.cards.activeProjects")});let m=t.createDiv({cls:"stats-overview-card stats-view__overview-card"}),f=m.createDiv({cls:"overview-value stats-view__overview-value"});f.textContent=a(r.avgTimePerTask),m.createDiv({cls:"overview-label stats-view__overview-label",text:this.plugin.i18n.translate("views.stats.cards.avgTimePerTask")})}renderTimeRangeStats(t,r){t.empty();let a=c=>{if(c<60)return`${Math.round(c)}m`;let d=Math.floor(c/60),u=Math.round(c%60);return u>0?`${d}h ${u}m`:`${d}h`},i=t.createDiv({cls:"stats-stat-card stats-view__stat-card"});i.createDiv({cls:"stat-value stats-view__stat-value",text:`${a(r.overall.totalTimeSpent)} / ${a(r.overall.totalTimeEstimate)}`}),i.createDiv({cls:"stat-label stats-view__stat-label",text:this.plugin.i18n.translate("views.stats.cards.timeTrackedEstimated")});let s=t.createDiv({cls:"stats-stat-card stats-view__stat-card"});s.createDiv({cls:"stat-value stats-view__stat-value",text:r.overall.totalTasks.toString()}),s.createDiv({cls:"stat-label stats-view__stat-label",text:this.plugin.i18n.translate("views.stats.labels.tasks")});let o=t.createDiv({cls:"stats-stat-card stats-view__stat-card"});o.createDiv({cls:"stat-value stats-view__stat-value",text:r.overall.completedTasks.toString()}),o.createDiv({cls:"stat-label stats-view__stat-label",text:this.plugin.i18n.translate("views.stats.labels.completed")});let l=t.createDiv({cls:"stats-stat-card stats-view__stat-card"});l.createDiv({cls:"stat-value stats-view__stat-value",text:r.overall.activeProjects.toString()}),l.createDiv({cls:"stat-label stats-view__stat-label",text:this.plugin.i18n.translate("views.stats.labels.projects")})}async renderProjectStats(t,r){if(t.empty(),r.length===0){t.createDiv({cls:"stats-no-data stats-view__no-data",text:this.plugin.i18n.translate("views.stats.noProjectData")});return}let a=s=>{if(s<60)return`${Math.round(s)}m`;let o=Math.floor(s/60),l=Math.round(s%60);return l>0?`${o}h ${l}m`:`${o}h`},i=s=>{if(!s)return this.plugin.i18n.translate("views.stats.notAvailable");try{let o=new Date(s);return D(o,"MMM d, yyyy")}catch(o){return this.plugin.i18n.translate("views.stats.notAvailable")}};for(let s of r){let o=["stats-project-item","stats-view__project-item","stats-view__project-item--clickable"];s.projectName===this.plugin.i18n.translate("views.stats.noProject")&&o.push("stats-view__project-item--no-project");let l=t.createDiv({cls:o.join(" ")});this.registerDomEvent(l,"click",()=>{this.openProjectDrilldown(s.projectName)});let c=l.createDiv({cls:"stats-view__project-header"}),d=c.createDiv({cls:"project-name stats-view__project-name"});d.textContent=s.projectName,c.createDiv({cls:"stats-view__click-indicator",text:"→"});let u=s.taskCount>0?s.completedTaskCount/s.taskCount*100:0,p=l.createDiv({cls:"stats-view__project-content-grid"}),m=p.createDiv({cls:"stats-view__progress-container"});this.renderProgressCircle(m,u,s.completedTaskCount,s.taskCount);let f=p.createDiv({cls:"stats-view__stats-container"});if(s.totalTimeSpent>0||s.totalTimeEstimate>0){let k=f.createDiv({cls:"stats-view__time-bar"}),b=k.createDiv({cls:"stats-view__time-bar-visual"}).createDiv({cls:"stats-view__time-bar-fill"}),w=0;s.totalTimeEstimate>0?w=s.totalTimeSpent/s.totalTimeEstimate*100:s.totalTimeSpent>0&&(w=100,b.classList.remove("tn-static-background-color-var-background-mo-94b219f0","tn-static-background-color-var-background-se-9087a23e","tn-static-background-color-var-color-red-134bc721","tn-static-background-color-var-text-accent-a954c70f"),b.classList.add("tn-static-background-color-var-color-base-40-ef5f175e")),b.style.width=`${Math.min(w,100)}%`,w>100&&(b.classList.remove("tn-static-background-color-var-background-mo-94b219f0","tn-static-background-color-var-background-se-9087a23e","tn-static-background-color-var-color-base-40-ef5f175e","tn-static-background-color-var-text-accent-a954c70f"),b.classList.add("tn-static-background-color-var-color-red-134bc721"));let S=k.createDiv({cls:"stats-view__time-bar-label"});S.textContent=`${a(s.totalTimeSpent)} / ${a(s.totalTimeEstimate)}`}let h=f.createDiv({cls:"project-stats stats-view__project-stats"});if(s.lastActivity){let k=h.createDiv({cls:"project-stat stats-view__project-stat"});k.textContent=`Last activity: ${i(s.lastActivity)}`}if(s.avgTimePerTask>0){let k=h.createDiv({cls:"project-stat stats-view__project-stat"});k.textContent=`Avg: ${a(s.avgTimePerTask)}/task`}let g=f.createDiv({cls:"stats-view__trend-container"}),v=g.createDiv({cls:"stats-view__sparkline"});try{let k=await this.calculateProjectTrend(s.projectName);k.length>0&&k.some(T=>T.value>0)?this.renderSparkline(v,k):g.remove()}catch(k){g.remove()}}}renderProgressCircle(t,r,a,i){let c=2*Math.PI*27.5,d=c-r/100*c,u=activeWindow.createSvg("svg");u.setAttribute("width","60"),u.setAttribute("height","60"),u.setAttribute("viewBox","0 0 60 60"),u.classList.add("stats-view__progress-circle-svg");let p=activeWindow.createSvg("circle");p.setAttribute("cx",(60/2).toString()),p.setAttribute("cy",(60/2).toString()),p.setAttribute("r",27.5.toString()),p.classList.add("stats-view__progress-circle-bg");let m=activeWindow.createSvg("circle");m.setAttribute("cx",(60/2).toString()),m.setAttribute("cy",(60/2).toString()),m.setAttribute("r",27.5.toString()),m.setAttribute("stroke-dasharray",`${c} ${c}`),m.setAttribute("stroke-dashoffset",d.toString()),m.classList.add("stats-view__progress-circle-fg");let f=activeWindow.createSvg("text");f.setAttribute("x","50%"),f.setAttribute("y","50%"),f.setAttribute("dy","0.3em"),f.setAttribute("text-anchor","middle"),f.classList.add("stats-view__progress-circle-text"),f.textContent=`${Math.round(r)}%`,u.appendChild(p),u.appendChild(m),u.appendChild(f),t.appendChild(u);let h=t.createDiv({cls:"stats-view__progress-label"});h.textContent=`${a}/${i} tasks`}async calculateProjectTrend(t){try{let r=this.plugin.cacheManager.getAllTaskPaths(),a=[];for(let o of r)try{let l=await this.plugin.cacheManager.getTaskInfo(o);l&&!l.archived&&this.getTaskProjects(l).includes(t)&&a.push(l)}catch(l){}let i=[],s=Xt();for(let o=29;o>=0;o--){let l=Hg(s,o),c=D(l,"yyyy-MM-dd"),d=0;for(let u of a)if(u.timeEntries)for(let p of u.timeEntries)p.startTime&&D(new Date(p.startTime),"yyyy-MM-dd")===c&&(d+=oi([p]));i.push({date:c,value:d})}return i}catch(r){return[]}}renderSparkline(t,r){if(t.empty(),r.length===0)return;let a=100,i=20,s=Math.max(...r.map(d=>d.value));if(s===0)return;let o=activeWindow.createSvg("svg");o.setAttribute("width",a.toString()),o.setAttribute("height",i.toString()),o.setAttribute("viewBox",`0 0 ${a} ${i}`),o.classList.add("stats-view__sparkline-svg");let l=activeWindow.createSvg("path"),c="";r.forEach((d,u)=>{let p=u/(r.length-1)*a,m=i-d.value/s*i;u===0?c+=`M ${p} ${m}`:c+=` L ${p} ${m}`}),l.setAttribute("d",c),l.setAttribute("fill","none"),l.setAttribute("stroke","currentColor"),l.setAttribute("stroke-width","1.5"),l.setAttribute("opacity","0.7"),o.appendChild(l),t.appendChild(o)}async openProjectDrilldown(t){this.closeDrilldownModal();let r=this.contentEl.ownerDocument,a=r.body.createDiv({cls:"stats-view__modal-backdrop"});this.drilldownModal=a;let i=a.createDiv({cls:"stats-view__modal tasknotes-plugin"}),s=i.createDiv({cls:"stats-view__modal-header"}),o=s.createDiv({cls:"stats-view__modal-title"});o.textContent=`${t} - Detailed View`;let l=s.createEl("button",{cls:"stats-view__modal-close",text:"×"}),c=i.createDiv({cls:"stats-view__modal-content"});c.textContent=this.plugin.i18n.translate("views.stats.loading"),this.registerDomEvent(l,"click",()=>this.closeDrilldownModal()),this.registerDomEvent(a,"click",u=>{u.target===a&&this.closeDrilldownModal()});let d=u=>{u.key==="Escape"&&(this.closeDrilldownModal(),r.removeEventListener("keydown",d))};r.addEventListener("keydown",d);try{let u=await this.getProjectDrilldownData(t);this.currentDrilldownData=u,this.renderDrilldownContent(c,u)}catch(u){tE.error("Error loading drill-down data:",{category:"persistence",operation:"loading-drill-down-data",error:u}),c.textContent=this.plugin.i18n.translate("notices.statsLoadingFailed")}}closeDrilldownModal(){this.drilldownModal&&(this.drilldownModal.remove(),this.drilldownModal=null,this.currentDrilldownData=null)}async refreshDrilldownModal(){if(!this.drilldownModal||!this.currentDrilldownData)return;let t=this.drilldownModal.querySelector(".stats-view__modal-content");if(t)try{let r=await this.getProjectDrilldownData(this.currentDrilldownData.projectName);this.currentDrilldownData=r,this.renderDrilldownContent(t,r)}catch(r){tE.error("Error refreshing drill-down modal:",{category:"stale-data",operation:"refreshing-drill-down-modal",error:r})}}async getProjectDrilldownData(t){var p;let r=this.plugin.cacheManager.getAllTaskPaths(),a=[];for(let m of r)try{let f=await this.plugin.cacheManager.getTaskInfo(m);f&&!f.archived&&this.getTaskProjects(f).includes(t)&&a.push(f)}catch(f){tE.error(`Failed to get task for drill-down: ${m}`,{category:"persistence",operation:"get-task-drill-down",error:f})}let i=a.reduce((m,f)=>m+oi(f.timeEntries||[]),0),s=a.reduce((m,f)=>m+(f.timeEstimate||0),0),o=a.filter(m=>this.plugin.statusManager.isCompletedStatus(m.status)).length,l=a.length>0?o/a.length*100:0,c=a.filter(m=>{var f;return((f=m.timeEntries)==null?void 0:f.length)||m.completedDate}).sort((m,f)=>{var v,k;let h=(v=m.timeEntries)!=null&&v.length?Math.max(...m.timeEntries.map(T=>new Date(T.startTime).getTime())):m.completedDate?new Date(m.completedDate).getTime():0;return((k=f.timeEntries)!=null&&k.length?Math.max(...f.timeEntries.map(T=>new Date(T.startTime).getTime())):f.completedDate?new Date(f.completedDate).getTime():0)-h}).slice(0,10),d=[],u=Xt();for(let m=29;m>=0;m--){let f=Hg(u,m),h=D(f,"yyyy-MM-dd"),g=0,v=0,k=0;for(let T of a){if(T.timeEntries){let b=T.timeEntries.filter(w=>D(new Date(w.startTime),"yyyy-MM-dd")===h);b.length>0&&(g+=oi(b),v++)}T.completedDate&&D(new Date(T.completedDate),"yyyy-MM-dd")===h&&(k++,(p=T.timeEntries)!=null&&p.some(b=>D(new Date(b.startTime),"yyyy-MM-dd")===h)||v++)}d.push({date:h,timeSpent:g,taskCount:v,completedTasks:k})}return{projectName:t,tasks:a,totalTimeSpent:i,totalTimeEstimate:s,completionRate:l,timeByDay:d,recentActivity:c}}renderDrilldownContent(t,r){t.empty();let a=w=>{if(w<60)return`${Math.round(w)}m`;let S=Math.floor(w/60),C=Math.round(w%60);return C>0?`${S}h ${C}m`:`${S}h`},s=t.createDiv({cls:"stats-view__drilldown-overview"}).createDiv({cls:"stats-view__drilldown-stats"}),o=s.createDiv({cls:"stats-view__drilldown-card"});o.createDiv({cls:"stats-view__drilldown-value",text:`${a(r.totalTimeSpent)} / ${a(r.totalTimeEstimate)}`}),o.createDiv({cls:"stats-view__drilldown-label",text:"Total Time"});let l=s.createDiv({cls:"stats-view__drilldown-card"});l.createDiv({cls:"stats-view__drilldown-value",text:r.tasks.length.toString()}),l.createDiv({cls:"stats-view__drilldown-label",text:"Total Tasks"});let c=s.createDiv({cls:"stats-view__drilldown-card"});c.createDiv({cls:"stats-view__drilldown-value",text:`${Math.round(r.completionRate)}%`}),c.createDiv({cls:"stats-view__drilldown-label",text:"Completed"});let d=s.createDiv({cls:"stats-view__drilldown-card"}),u=r.tasks.length>0?r.totalTimeSpent/r.tasks.length:0,p=r.tasks.length>0?r.totalTimeEstimate/r.tasks.length:0;d.createDiv({cls:"stats-view__drilldown-value",text:`${a(u)} / ${a(p)}`}),d.createDiv({cls:"stats-view__drilldown-label",text:"Avg per Task"});let m=t.createDiv({cls:"stats-view__drilldown-section"});m.createDiv({cls:"stats-view__drilldown-heading",text:"Activity Over Time (Last 30 Days)"});let f=m.createDiv({cls:"stats-view__activity-chart"});this.renderActivityChart(f,r.timeByDay);let h=t.createDiv({cls:"stats-view__drilldown-section"}),g=h.createDiv({cls:"stats-view__section-header"});g.createDiv({cls:"stats-view__drilldown-heading",text:"All Project Tasks"});let k=g.createDiv({cls:"stats-view__task-filters"}).createEl("select",{cls:"stats-view__filter-select"});k.createEl("option",{value:"all",text:this.plugin.i18n.translate("views.stats.filters.allTasks")}),k.createEl("option",{value:"active",text:this.plugin.i18n.translate("views.stats.filters.activeOnly")}),k.createEl("option",{value:"completed",text:this.plugin.i18n.translate("views.stats.filters.completedOnly")});let T=h.createDiv({cls:"stats-view__task-list"}),b=(w="all")=>{T.empty();let S=r.tasks;if(w==="active"?S=r.tasks.filter(x=>!this.plugin.statusManager.isCompletedStatus(x.status)):w==="completed"&&(S=r.tasks.filter(x=>this.plugin.statusManager.isCompletedStatus(x.status))),S.sort((x,E)=>{let _=this.plugin.statusManager.isCompletedStatus(x.status),F=this.plugin.statusManager.isCompletedStatus(E.status);if(_!==F)return _?1:-1;let I=A=>{var R;return(R=A.timeEntries)!=null&&R.length?Math.max(...A.timeEntries.map(O=>new Date(O.startTime).getTime())):A.dateModified?new Date(A.dateModified).getTime():0};return I(E)-I(x)}),S.length===0){T.createDiv({cls:"stats-view__no-data",text:this.plugin.i18n.translate("views.stats.noTasks")});return}let C=T.createDiv({cls:"stats-view__task-count"});C.textContent=`Showing ${S.length} task${S.length!==1?"s":""}`;for(let x of S){let E=this.plugin.settings.defaultVisibleProperties?di(this.plugin.settings.defaultVisibleProperties,this.plugin):void 0,_=pr(x,this.plugin,E);T.appendChild(_)}};b("all"),this.registerDomEvent(k,"change",()=>{b(k.value)})}renderActivityChart(t,r){if(t.empty(),r.length===0)return;let a=Math.max(...r.map(s=>s.timeSpent));if(a===0){t.createDiv({cls:"stats-view__no-data",text:"No time tracking data"});return}let i=t.createDiv({cls:"stats-view__bar-chart"});for(let s of r){let l=i.createDiv({cls:"stats-view__bar-container"}).createDiv({cls:"stats-view__bar"}),c=s.timeSpent/a*40;l.style.height=`${c}px`;let d=`${D(new Date(s.date),"MMM d")}: ${Math.round(s.timeSpent)}m`;l.setAttribute("title",d)}}}});var Wye,qye=y(()=>{Wye=`## TaskNotes v5 and the TaskNotes app — join the beta + +**TaskNotes v5** introduces portable collections that you can use in both Obsidian and the new **TaskNotes app**. Your tasks remain ordinary Markdown files in your vault, with [mdbase Connect](https://mdbase.dev/connect/) providing access from the app. + +Available to try now: +- **[Try the TaskNotes v5 plugin beta](https://github.com/callumalpass/tasknotes/releases/tag/5.0.0-beta.2)** +- **[Try the TaskNotes web app](https://app.tasknotes.dev/)** +- **[Download TaskNotes for iOS](https://apps.apple.com/app/tasknotes/id6797168033)** + +These are early releases under active development. Please back up your vault before trying them and [report any problems](https://github.com/callumalpass/tasknotes/issues). TaskNotes 4.13 remains the recommended stable plugin release. + +### Help bring TaskNotes to Android + +**We need at least 12 testers for the TaskNotes Android app before we can apply for a public Google Play release.** + +If you have an Android device and would like to help: + +1. **[Join the tester Google Group](https://groups.google.com/g/tasknotes-android-testers)** using the Google account you use for Google Play. +2. **[Opt in to the Google Play test](https://play.google.com/apps/testing/dev.tasknotes.app)** with that same account and install TaskNotes. +3. Stay opted in for **at least 14 consecutive days**, use the app regularly during that time, and let us know how it goes. + +You don’t need to be a developer—using TaskNotes for your everyday tasks and sharing anything confusing or broken is valuable feedback. Your participation will help make the Android release possible. +`});function pGe(n,e=AW){return n.replace(/\(((?:#\d+\s*)(?:,\s*#\d+\s*)*)\)/g,(t,r)=>`(${r.split(",").map(i=>i.trim()).filter(Boolean).map(i=>{let s=i.slice(1);return`[#${s}](${e}/issues/${s})`}).join(", ")})`)}var rE,nE,Gye,AW,CR,MW=y(()=>{rE=require("obsidian");Cr();qye();nE="tasknotes-release-notes",Gye="https://github.com/callumalpass/tasknotes/releases",AW="https://github.com/callumalpass/tasknotes";CR=class extends rE.ItemView{constructor(e,t,r,a){super(e),this.plugin=t,this.releaseNotesBundle=r,this.version=a}getViewType(){return nE}getDisplayText(){return this.plugin.i18n.translate("views.releaseNotes.title",{version:this.version})}getIcon(){return"book-open"}transformIssueLinks(e){return pGe(e)}formatDate(e){if(!e)return"";try{let t=Na(e);return D(t,"MMMM d, yyyy")}catch(t){return""}}async renderVersionContent(e,t){let r=t.content.replace(/^> \[!info\] TaskNotes v5 beta\r?\n(?:>[^\n]*(?:\n|$))*/gm,""),a=this.transformIssueLinks(r),i=t.isCurrent?`${this.plugin.i18n.translate("views.releaseNotes.baseFilesNotice")} + +${a}`:a;await rE.MarkdownRenderer.render(this.plugin.app,i,e,"",this)}async createVersionSection(e,t,r){let a=e.createDiv({cls:"release-notes-version-section"});a.classList.remove("tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-bottom-0-75rem-c05a3c6e","tn-static-margin-bottom-8px-fdf33f23"),a.classList.add("tn-static-margin-bottom-20px-49f14f8f"),a.classList.remove("tn-static-border-none-2eda1daa","tn-static-padding-12px-43bef435"),a.classList.add("tn-static-border-1px-solid-var-background-mo-b65b5121"),a.classList.remove("tn-static-border-radius-4px-c290c56e","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-padding-12px-43bef435","tn-static-padding-20px-ebe8e48c"),a.classList.add("tn-static-border-radius-6px-0dc8408c"),a.classList.remove("tn-static-flex-1-14e3b769"),a.classList.add("tn-static-overflow-hidden-69824400");let i=a.createDiv({cls:"release-notes-version-header"});i.classList.remove("tn-static-margin-8px-0-0-0-a2eb8382","tn-static-padding-0-16px-16px-16px-f1aa998c","tn-static-padding-0-41d7d7e2","tn-static-padding-12px-43bef435","tn-static-padding-20px-769fed37","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c","tn-static-padding-2px-8px-c8eea84a","tn-static-padding-2rem-42aa6d9c"),i.classList.add("tn-static-padding-16px-287f770e"),i.classList.remove("tn-static-cursor-grab-dad79857","tn-static-cursor-pointer-2723efcc"),i.classList.add("tn-static-cursor-pointer-3b6a3a65"),i.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),i.classList.add("tn-static-display-flex-75816cae"),i.classList.remove("tn-static-justify-content-center-03c4bb6f","tn-static-justify-content-flex-end-455f8cca"),i.classList.add("tn-static-justify-content-space-between-a562f4fd"),i.classList.remove("tn-static-align-items-baseline-4b95b5c7","tn-static-align-items-flex-start-0486f781"),i.classList.add("tn-static-align-items-center-7c619740"),i.style.backgroundColor=t.isCurrent?"var(--background-secondary)":"var(--background-primary)",i.classList.add("tn-static-transition-background-color-0-2s-8142f01e"),i.addEventListener("mouseenter",()=>{i.classList.remove("tn-static-background-color-var-background-mo-94b219f0","tn-static-background-color-var-color-base-40-ef5f175e","tn-static-background-color-var-color-red-134bc721","tn-static-background-color-var-text-accent-a954c70f"),i.classList.add("tn-static-background-color-var-background-se-9087a23e")}),i.addEventListener("mouseleave",()=>{i.style.backgroundColor=t.isCurrent?"var(--background-secondary)":"var(--background-primary)"});let s=i.createDiv({cls:"release-notes-version-info"});s.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),s.classList.add("tn-static-display-flex-75816cae"),s.classList.remove("tn-static-align-items-center-7c619740","tn-static-align-items-flex-start-0486f781"),s.classList.add("tn-static-align-items-baseline-4b95b5c7"),s.classList.remove("tn-static-display-flex-8bb39979","tn-static-gap-0-5rem-ce2fca4d","tn-static-gap-10px-f3d7ce77","tn-static-gap-6px-f0abc1db","tn-static-gap-8px-33fcd4c3"),s.classList.add("tn-static-gap-12px-ed7b3d87");let o=s.createEl("h2",{text:t.version});if(o.classList.remove("tn-static-margin-0-auto-266e9b04","tn-static-margin-0-db0d5f36","tn-static-margin-0-var-size-4-2-77f7dc08","tn-static-margin-2px-0-edce9b14","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-padding-12px-43bef435","tn-static-padding-20px-ebe8e48c"),o.classList.add("tn-static-margin-0-11696618"),o.classList.remove("tn-static-font-size-0-75em-948e16e5","tn-static-font-size-0-8em-19dc7c13","tn-static-font-size-0-9em-65025e95","tn-static-font-size-12px-65574819","tn-static-font-size-12px-b0cc7e05","tn-static-font-size-var-tn-font-size-sm-0274a31d","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-margin-top-8px-f4f01e68"),o.classList.add("tn-static-font-size-1-2em-3a352995"),o.classList.remove("tn-static-cursor-pointer-2723efcc","tn-static-font-weight-500-02a2d333","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd"),o.classList.add("tn-static-font-weight-600-eed0f8fb"),t.isCurrent){let p=s.createSpan({text:"Current"});p.classList.remove("tn-static-font-size-0-8em-19dc7c13","tn-static-font-size-0-9em-65025e95","tn-static-font-size-1-2em-3a352995","tn-static-font-size-12px-65574819","tn-static-font-size-12px-b0cc7e05","tn-static-font-size-var-tn-font-size-sm-0274a31d","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-margin-top-8px-f4f01e68"),p.classList.add("tn-static-font-size-0-75em-948e16e5"),p.classList.remove("tn-static-margin-8px-0-0-0-a2eb8382","tn-static-padding-0-16px-16px-16px-f1aa998c","tn-static-padding-0-41d7d7e2","tn-static-padding-12px-43bef435","tn-static-padding-16px-287f770e","tn-static-padding-20px-769fed37","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c","tn-static-padding-2rem-42aa6d9c"),p.classList.add("tn-static-padding-2px-8px-c8eea84a"),p.classList.remove("tn-static-border-radius-6px-0dc8408c","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-padding-12px-43bef435","tn-static-padding-20px-ebe8e48c"),p.classList.add("tn-static-border-radius-4px-c290c56e"),p.classList.remove("tn-static-background-color-var-background-mo-94b219f0","tn-static-background-color-var-background-se-9087a23e","tn-static-background-color-var-color-base-40-ef5f175e","tn-static-background-color-var-color-red-134bc721"),p.classList.add("tn-static-background-color-var-text-accent-a954c70f"),p.classList.remove("tn-static-color-var-color-accent-d2cad743","tn-static-color-var-text-accent-65b47ee3","tn-static-color-var-text-muted-5872de20","tn-static-color-var-text-warning-783d5f03","tn-static-color-var-tn-text-muted-a90fb6f3","tn-static-color-white-0a43e56a","tn-static-cursor-pointer-2723efcc","tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-2px-0-edce9b14","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c"),p.classList.add("tn-static-color-var-text-on-accent-f3e1679d"),p.classList.remove("tn-static-cursor-pointer-2723efcc","tn-static-font-weight-600-eed0f8fb","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd"),p.classList.add("tn-static-font-weight-500-02a2d333")}if(t.date){let p=s.createSpan({text:this.formatDate(t.date)});p.classList.remove("tn-static-color-var-color-accent-d2cad743","tn-static-color-var-text-accent-65b47ee3","tn-static-color-var-text-on-accent-f3e1679d","tn-static-color-var-text-warning-783d5f03","tn-static-color-var-tn-text-muted-a90fb6f3","tn-static-color-white-0a43e56a","tn-static-cursor-pointer-2723efcc","tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-2px-0-edce9b14","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c"),p.classList.add("tn-static-color-var-text-muted-5872de20"),p.classList.remove("tn-static-font-size-0-75em-948e16e5","tn-static-font-size-0-8em-19dc7c13","tn-static-font-size-1-2em-3a352995","tn-static-font-size-12px-65574819","tn-static-font-size-12px-b0cc7e05","tn-static-font-size-var-tn-font-size-sm-0274a31d","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-margin-top-8px-f4f01e68"),p.classList.add("tn-static-font-size-0-9em-65025e95")}let l=i.createSpan({text:r?"▼":"▶"});l.classList.remove("tn-static-font-size-0-75em-948e16e5","tn-static-font-size-0-9em-65025e95","tn-static-font-size-1-2em-3a352995","tn-static-font-size-12px-65574819","tn-static-font-size-12px-b0cc7e05","tn-static-font-size-var-tn-font-size-sm-0274a31d","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-margin-top-8px-f4f01e68"),l.classList.add("tn-static-font-size-0-8em-19dc7c13"),l.classList.remove("tn-static-color-var-color-accent-d2cad743","tn-static-color-var-text-accent-65b47ee3","tn-static-color-var-text-on-accent-f3e1679d","tn-static-color-var-text-warning-783d5f03","tn-static-color-var-tn-text-muted-a90fb6f3","tn-static-color-white-0a43e56a","tn-static-cursor-pointer-2723efcc","tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-2px-0-edce9b14","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c"),l.classList.add("tn-static-color-var-text-muted-5872de20");let c=a.createDiv({cls:"release-notes-version-content"});c.classList.remove("tn-static-margin-8px-0-0-0-a2eb8382","tn-static-padding-0-41d7d7e2","tn-static-padding-12px-43bef435","tn-static-padding-16px-287f770e","tn-static-padding-20px-769fed37","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c","tn-static-padding-2px-8px-c8eea84a","tn-static-padding-2rem-42aa6d9c"),c.classList.add("tn-static-padding-0-16px-16px-16px-f1aa998c"),c.style.display=r?"block":"none";let d=null,u=()=>(d||(d=this.renderVersionContent(c,t)),d);r&&await u(),i.addEventListener("click",()=>{let p=c.style.display!=="none";c.style.display=p?"none":"block",l.textContent=p?"▶":"▼",p||u()})}async onOpen(){let{contentEl:e}=this;e.empty(),e.addClass("tasknotes-release-notes-view");let t=e.createDiv({cls:"tasknotes-release-notes-container"});t.classList.remove("tn-static-margin-8px-0-0-0-a2eb8382","tn-static-padding-0-16px-16px-16px-f1aa998c","tn-static-padding-0-41d7d7e2","tn-static-padding-12px-43bef435","tn-static-padding-16px-287f770e","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c","tn-static-padding-2px-8px-c8eea84a","tn-static-padding-2rem-42aa6d9c"),t.classList.add("tn-static-padding-20px-769fed37"),t.classList.add("tn-static-max-width-900px-1d34c094"),t.classList.remove("tn-static-margin-0-11696618","tn-static-margin-0-db0d5f36","tn-static-margin-0-var-size-4-2-77f7dc08","tn-static-margin-2px-0-edce9b14","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-padding-12px-43bef435","tn-static-padding-20px-ebe8e48c"),t.classList.add("tn-static-margin-0-auto-266e9b04");let r=t.createDiv({cls:"release-notes-header"});r.classList.remove("tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-bottom-0-75rem-c05a3c6e","tn-static-margin-bottom-8px-fdf33f23"),r.classList.add("tn-static-margin-bottom-20px-49f14f8f"),r.createEl("h1",{text:this.plugin.i18n.translate("views.releaseNotes.header",{version:this.version})});let a=t.createEl("p");a.classList.remove("tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-bottom-0-75rem-c05a3c6e","tn-static-margin-bottom-8px-fdf33f23"),a.classList.add("tn-static-margin-bottom-20px-49f14f8f"),a.classList.remove("tn-static-font-size-0-75em-948e16e5","tn-static-font-size-0-8em-19dc7c13","tn-static-font-size-1-2em-3a352995","tn-static-font-size-12px-65574819","tn-static-font-size-12px-b0cc7e05","tn-static-font-size-var-tn-font-size-sm-0274a31d","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-margin-top-8px-f4f01e68"),a.classList.add("tn-static-font-size-0-9em-65025e95"),a.classList.remove("tn-static-color-var-color-accent-d2cad743","tn-static-color-var-text-accent-65b47ee3","tn-static-color-var-text-on-accent-f3e1679d","tn-static-color-var-text-warning-783d5f03","tn-static-color-var-tn-text-muted-a90fb6f3","tn-static-color-white-0a43e56a","tn-static-cursor-pointer-2723efcc","tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-2px-0-edce9b14","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c"),a.classList.add("tn-static-color-var-text-muted-5872de20");let i=this.plugin.i18n.translate("views.releaseNotes.starMessage"),s=i.toLowerCase().lastIndexOf("github");if(s!==-1){a.appendText(i.substring(0,s));let u=a.createEl("a",{text:i.substring(s,s+6),href:AW});u.classList.remove("tn-static-color-var-color-accent-d2cad743","tn-static-color-var-text-muted-5872de20","tn-static-color-var-text-on-accent-f3e1679d","tn-static-color-var-text-warning-783d5f03","tn-static-color-var-tn-text-muted-a90fb6f3","tn-static-color-white-0a43e56a","tn-static-cursor-pointer-2723efcc","tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-2px-0-edce9b14","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c"),u.classList.add("tn-static-color-var-text-accent-65b47ee3"),u.addEventListener("click",p=>{p.preventDefault(),window.open(AW,"_blank")}),a.appendText(i.substring(s+6))}else a.appendText(i);let o=t.createEl("section",{cls:"release-notes-announcement"});await rE.MarkdownRenderer.render(this.plugin.app,Wye,o,"",this);let l=t.createDiv({cls:"release-notes-versions"});for(let u=0;u{u.preventDefault(),window.open(Gye,"_blank")})}async onClose(){let{contentEl:e}=this;e.empty()}}});var Yye,Kye=y(()=>{Yye=`# TaskNotes 4.13.5 + +## Fixed + +- (#2360) Preserve expanded and collapsed settings cards when the settings interface is rebuilt. Thanks to @pankevely for reporting the loss of expanded sections. + +- (#2364) Fixed the calendar creation menu opening off-screen after selecting a time range by touch. Thanks to @saschaobsidian for reporting the iPad issue. +- (#2361) Fixed Kanban formula swimlanes showing **None** when first opening a view. Thanks to @iantierney for reporting and recording the issue. +- (#2362) Show every configured priority swimlane when empty swimlanes are visible, including priorities assigned only to hidden subtasks. Thanks to @iantierney for reporting. See [Kanban View](https://tasknotes.dev/views/kanban-view/). +- (#2359) Fixed task list cards retaining outdated metadata after property changes, including contexts, tags, and displayed Bases formula values. Thanks to @maks-io for reporting and investigating. + +## Changed + +- Clarified that dependencies store \`blockedBy\` and derive “Blocking”, separately from project/subtask membership. Thanks to @Dual1r for raising this in [discussion #2357](https://github.com/callumalpass/tasknotes/discussions/2357), and @Dani-8 for confirming the clarification. See [Dependencies](https://tasknotes.dev/features/task-management/#dependencies). +`});var Zye,Qye=y(()=>{Zye=`# TaskNotes 4.13.4 + +## Fixed + +- ([Discussion #2355](https://github.com/callumalpass/tasknotes/discussions/2355)) Fixed Live Preview task links remaining as task widgets after removing a note's task-identifying tag or property, and links to the same task incorrectly sharing a heading label during cache refreshes. Inline task links now retain heading and block targets when opening the note. Thanks to @ZedLeb for reporting and providing the reproduction, and @identity-wael for helping investigate. + +- (#2356) Reduced unnecessary Pomodoro timer rendering by removing progress-ring animation and redundant display updates. Hidden timers skip rendering, and warning pulses stop while paused. Improved view cleanup and timing accuracy across repeated pauses. Thanks to @akseliekseli for reporting the CPU usage issue. +- Corrected the desktop calendar sign-in dependency declaration. Electron remains provided by Obsidian and is not bundled with TaskNotes. +`});var Jye,Xye=y(()=>{Jye=`# TaskNotes 4.13.3 + +## Fixed + +- (#2352) Fixed the task description editor being obscured by the mobile keyboard when creating a task. Thanks to @kmalakoff for reporting. +- (#2210, #2207) Fixed Task List manual drag-to-reorder failing to start or save the new order. Thanks to @dong-jichen and @mgrecar for reporting, and @kemalguvenc, @MatthiasSoell, and @bravely for confirming and helping narrow down the issue. +`});var eve,tve=y(()=>{eve=`# TaskNotes 4.13.2 + +## Added + +- (#2349, #2127) Recurring tasks now create their first available occurrence note when “Create next after completion” is enabled. Completing the parent in the UI also uses occurrence notes, and new occurrence notes use unambiguous parent links across folders. Thanks to @raphaelfaouakhiri for the requests and investigation. See [Recurring Tasks](https://tasknotes.dev/features/recurring-tasks/#materialized-occurrence-notes). +- (#296) Added commands to start and stop time tracking for the current task note, usable from the Command Palette, hotkeys, and plugins such as Buttons. Thanks to @schosch-iteratec for the request and for sharing the Quick Actions workaround. See [Time Management](https://tasknotes.dev/features/time-management/). + +## Security + +- Updated dependencies to address reported security vulnerabilities. + +## Fixed + +- Fixed task dialogs falling back to plain text inputs when opened without an active note, including from release notes or in an empty vault. +- (#2347) Fixed subtasks created from the edit task modal ignoring the parent project when choosing their folder. Thanks to @iantierney for reporting. +`});var rve,nve=y(()=>{rve=`# TaskNotes 4.13.1 + +## Added + +- (#2223, #2224) Added \`task-card__metadata-date--today\` and \`task-card__metadata-date--future\` CSS classes for due and scheduled dates. Completed past dates are not classified as future when overdue styling is hidden. Thanks to @chmac for the suggestion and contribution. + +## Fixed + +- (#2313) Fixed ICS meetings disappearing when another guest declined. Declined meetings are hidden only when the feed identifies the calendar owner's response; otherwise they remain visible. Refresh subscriptions after updating. See [Calendar Integration](https://tasknotes.dev/features/calendar-integration/#ics-calendar-subscriptions). Thanks to @benschifman for reporting and providing the reproduction. +- (#2203) Completing or skipping a recurring instance in the edit modal no longer creates a duplicate Google Calendar event when the scheduled date advances. Manual rescheduling still creates the appropriate moved occurrence. Thanks to @christenbc for the fix. +- (#2336) Reduced the plugin bundle below Obsidian Sync Standard's 5 MB per-file limit so it can sync between devices again, and removed duplicate bundled dependencies to leave more room for future updates. Thanks to @kmalakoff for reporting and @CyberBlaed for confirming. +- (#2335) Fixed date-like text in the current note’s folder or title being replaced when choosing a task folder with \`{{currentNotePath}}\` or \`{{currentNoteTitle}}\`. Date tokens written in the folder template still work. Thanks to @hikatamika for reporting. +- (#2301) Fixed clicking the Pomodoro timer display to edit its duration. Thanks to @minnyee for reporting and identifying the cause. +- (#2328) Fixed direct status edits on occurrence notes not updating the recurring parent’s completion history or creating the next occurrence when configured. Thanks to @mudnug for reporting this. + +## Changed + +- (#2329) Clarified how to generate a TaskNotes API token and configure Claude Desktop's MCP bearer authentication, including restart and token replacement instructions. See [HTTP API](https://tasknotes.dev/HTTP_API/#connecting-claude-desktop-with-mcp). Thanks to @kmaustral for reporting the setup confusion and confirming the solution. +`});var ave,ive=y(()=>{ave=`# TaskNotes 4.13.0 + +## Before updating + +**HTTP API and MCP clients now require authentication.** If you previously connected without a token, copy the API token from **Settings → TaskNotes → Integrations** into your client's authentication settings. Requests must include \`Authorization: Bearer \`. If the token is empty when the server starts, TaskNotes generates and saves one; leaving it empty no longer disables authentication. See [HTTP API](https://tasknotes.dev/HTTP_API/). + +## Security + +- (#2292) Required authentication for local API/MCP listeners. OAuth callbacks now use an OS-assigned loopback port, accept each authorization state only once, and return fixed pages without reflecting callback text. Thanks to @martin-forge for the hardening. + +## Added + +- Added a dedicated TaskNotes v5 and app beta section to the plugin's release notes, including instructions for joining the Android test. The announcement appears once rather than repeating inside individual versions. +- (#2147) Added context-menu actions for recording task completion today, on the scheduled date, on the due date, or on a chosen date. The actions can be grouped in a submenu from Appearance settings. See [Completing Tasks](https://tasknotes.dev/features/task-management/#completing-tasks). + - Rescheduling a recurring task can reactivate affected completed or skipped instances after confirmation. See [Recurring Tasks](https://tasknotes.dev/features/recurring-tasks/). + - Completion-date actions, submenu settings, and rescheduling confirmations are translated into all supported languages. + - Thanks to @renatomen for the contribution. + +## Fixed + +- (#2291) Preserved background task updates when saving an older task edit window, including recurring completion history and properties changed or removed elsewhere. Thanks to @martin-forge for the fix. +- (#2294) Stopped plugin startup when an existing settings file cannot be read, preserving it for recovery instead of starting services with default settings. Thanks to @GGlider for reporting settings loss in #1591 and @martin-forge for the fix. +- (#2322) Fixed metadata edits deleting the saved title when a filename cannot represent it, such as for long titles. Existing title properties are preserved on unrelated edits; this does not recover previously deleted titles. Thanks to @1dezer1 for reporting. +- (#2255, #2300) Fixed task cards repeatedly disappearing and being restored while scrolling in Reading mode, which could pull the note down to the bottom. Thanks to @logicelf for the diagnosis and @nelsonlove for the fix. +- (#2318) Kept calendar events chronological when a Base sort is configured, using Base order for tasks at the same time. Thanks to @ky1ejs for reporting #1411 and @martin-forge for the fix. +- (#2319) Avoided duplicate recurring-task projections when TaskNotes has recorded the original occurrence date of a calendar move. Completion and skip history remain visible when requested. Other move cases are unchanged. Thanks to @martin-forge for the fix. +- (#2309) Fixed Google calendars enabled through the \`primary\` alias using the wrong color, ignoring visibility toggles, or losing their calendar name on event cards and linked notes. Thanks to @martin-forge for the fix. +- (#2279) Fixed Google Calendar authorization stalling when the system browser opens but does not report back that it launched. Authorization now completes or times out independently, and overlapping attempts cannot stop the active connection attempt. Thanks to @DamienDLR for the diagnosis. +- (#2298, #2299) Kept timed recurrence anchors when saving custom recurrence or completing a completion-anchored instance. Timed anchors are written with \`Z\` and retain their time, including seconds, without a device-timezone conversion. Date-only rules and scheduled-anchor completion are unchanged. See [Recurring Tasks](https://tasknotes.dev/features/recurring-tasks/). Thanks to @wellsbk1 for reporting. +- (#2043, #2055) Fixed tasks created with the default Subtasks view's **+** button missing their project and immediately disappearing from the view. Thanks to @kudrmax for reporting and @ther12k for the initial fix. +- (#2284) Prevented repeated activation of instant checkbox conversion from creating duplicate TaskNotes while the first conversion is still in progress. Thanks to @doyoonear for reporting. +- (#2314) Fixed rescheduled ICS recurring events appearing at their original time and cancelled occurrences remaining visible. Thanks to @benschifman for reporting. +- (#1849) Fixed context menus stacking on top of each other. Only one menu stays open at a time, and clicking the same indicator again closes its menu. This previously applied to date fields only, and now covers priority, status, recurrence, reminders, task, ICS event, and batch menus. Thanks to @3zra47 for reporting and @YBKF for the contribution. +- (#2303) Removed the extra space after inline task links on desktop while retaining the task menu on touch devices. Thanks to @nelsonlove for the fix. + +## Changed + +- (#2316) Clarified the Google OAuth Desktop app setup and redirect-mismatch troubleshooting, including why fixed Web application redirect URLs are not reliable with dynamic callback ports. See [Calendar Setup](https://tasknotes.dev/calendar-setup/). Thanks to @TomaszGaweda for reporting and following up. +`});var sve,ove=y(()=>{sve=`# TaskNotes 4.12.5 + +## Fixed + +- (#2255) Notes with an in-note task card no longer jump while scrolling in reading mode. The card is now restored only after scrolling settles instead of being re-injected every frame against Obsidian's virtualised reading view. Thanks to @logicelf for the detailed diagnosis. +- (#2256) Kanban swimlane order now follows the view's sort configuration again: with a formula or property sort applied, the swimlane holding the top-sorted task floats to the top of the board as it did before the swimlane ordering option was introduced. Thanks to @tsweezy for reporting this. +- (#2222) The TaskNotes settings tab bar now wraps to a second line instead of clipping the Integrations tab beside the documentation link on narrow settings panes. Thanks to @nextstitch and @YongcaiHuang for reporting this. +`});var lve,cve=y(()=>{lve=`# TaskNotes 4.12.4 + +> [!info] TaskNotes v5 beta +> +> [TaskNotes v5](https://github.com/callumalpass/tasknotes/releases/tag/5.0.0-beta.0) is available as an opt-in beta alongside TaskNotes 4.12. TaskNotes 4.12 remains the recommended stable release. +> +> The major change in v5 is support for portable TaskNotes collections. These collections can be used in both Obsidian and the [TaskNotes app](https://app.tasknotes.dev/), which is also available in beta, so the same tasks can be managed through either interface. +> +> TaskNotes collections are built on [mdbase](https://mdbase.dev/), a Markdown-native collection format. [mdbase Connect](https://mdbase.dev/connect/) provides the permissioned bridge that makes those collections available to the TaskNotes app. Your tasks remain ordinary Markdown files in your vault; mdbase adds a shared structure that compatible tools can understand. +> +> TaskNotes v5, mdbase Connect, and the TaskNotes app are all under active development. Please use a backed-up vault, expect some rough edges, and [report any problems you encounter](https://github.com/callumalpass/tasknotes/issues). + +## Changed + +- (#2187) Improved TaskNotes startup performance by allowing Bases registration to finish asynchronously. Thanks to @tgrosinger for the contribution. + +## Fixed + +- (#2232) Opening an occurrence note from a completion-anchored recurring task now + uses the task's scheduled occurrence date instead of defaulting to today. Thanks + to @chmac for reporting this. +- (#2247) Creating a new inline task now removes nested wikilink and Markdown-link + markup from the inserted task link's display text. Thanks to @bgk0018 for + reporting this. +- (#2231) Fixed Agenda views with \`showOverdueOnToday\` showing the same task twice + when both its scheduled and due dates were overdue. Thanks to @takashit16833 for + reporting this. +- (#2206) The time entry editor now opens much faster for tasks with many tracked + sessions by delaying the heavier description editor setup until a description + field is focused. Thanks to @Sapere-Kyle for reporting this. +- (#2239) Fixed Task List Bases embedded in mobile notes leaving a large blank gap + after the final task card. Thanks to @same774 for reporting this and @prethrive + for sharing a workaround. +- (#2238) The Relationships widget now stays below long Live Preview Dataview + tables and no longer appears twice after switching to Reading mode. Thanks to + @Romek1769 for reporting this. +- (#2250) Hardened Google Calendar task metadata updates: duplicate Google + Calendar fields are now repaired atomically without replacing concurrent task + edits, and synchronization finishing after a disconnect no longer writes stale + event metadata. Thanks to @3zra47 for reporting the corrupted task data that + prompted this review. +- (#2229) Google Calendar OAuth authorization now opens in the system browser + instead of Obsidian's Web Viewer, avoiding Google's 401 malformed-request + page in the in-app browser. Thanks to @prethrive for reporting this and + confirming the workaround. +- Skipping a recurring task instance from Task List or Kanban now records the + task's occurrence date instead of the view's current date. Thanks to + @renatomen for the contribution. +- (#2130) Tasks added by external sync while Obsidian is closed are now exported + to Google Calendar after TaskNotes starts. Thanks to @seththepeacock for + reporting this and @raphaelfaouakhiri for the contribution. +- (#2246) Fixed materialized recurring occurrences hiding occurrence-template filename suffixes in TaskNotes views. Thanks to @raphaelfaouakhiri for reporting and fixing this issue. +- (#2221) Fixed \`PUT /api/tasks/:id\` ignoring empty arrays for \`contexts\` and \`blockedBy\`: sending \`{"contexts": []}\` or \`{"blockedBy": []}\` now clears the corresponding frontmatter field instead of silently leaving the previous value in place. The deletion pass previously fired only on a literal \`undefined\`, which JSON cannot express, so HTTP clients had no way to clear these fields. Thanks to @tgrosinger for the contribution. +- (#2191) Completing or skipping a recurring occurrence that was moved earlier + than its original date no longer schedules that original date again. Thanks to + @martin-forge for the contribution. +- (#2193) Google Calendar event descriptions written with formatting now read as + plain text in event details, copied text, and generated notes, instead of + showing raw HTML tags. Paragraph breaks, list structure, and link addresses are + kept. Thanks to @martin-forge for the contribution. +- (#2192) Agenda and list cards for Google and Microsoft calendar events now + show the name of the calendar the event belongs to, instead of the generic + "Calendar" label. Thanks to @martin-forge for the contribution. +`});var dve,uve=y(()=>{dve=`# TaskNotes 4.12.3 + +> [!info] TaskNotes v5 beta +> +> [TaskNotes v5](https://github.com/callumalpass/tasknotes/releases/tag/5.0.0-beta.0) is available as an opt-in beta alongside TaskNotes 4.12. TaskNotes 4.12 remains the recommended stable release. +> +> The major change in v5 is support for portable TaskNotes collections. These collections can be used in both Obsidian and the [TaskNotes app](https://app.tasknotes.dev/), which is also available in beta, so the same tasks can be managed through either interface. +> +> TaskNotes collections are built on [mdbase](https://mdbase.dev/), a Markdown-native collection format. [mdbase Connect](https://mdbase.dev/connect/) provides the permissioned bridge that makes those collections available to the TaskNotes app. Your tasks remain ordinary Markdown files in your vault; mdbase adds a shared structure that compatible tools can understand. +> +> TaskNotes v5, mdbase Connect, and the TaskNotes app are all under active development. Please use a backed-up vault, expect some rough edges, and [report any problems you encounter](https://github.com/callumalpass/tasknotes/issues). + +## Fixed + +- (#2212) Fixed TaskNotes settings sections appearing offscreen or blank on + Obsidian 1.13 desktop. Thanks to @RafaQNunes for reporting this, and to + @m4to-3pe and @matthewrishii for confirming it remained in 4.12.2. +- (#2213) Runtime plugin-data updates now avoid writing when Obsidian cannot + safely read an existing TaskNotes \`data.json\`, preventing calendar sync, + Pomodoro, ICS, or auto-archive state writes from replacing saved settings. + Thanks to @3zra47 for the follow-up details and file-history evidence. +- (#2216) Fixed updated default Kanban Bases grouping every task into the + \`None\` column when grouping by status. The generated Kanban templates now use + the real status property, and existing Kanban files using \`task.status\` keep + grouping from TaskNotes task data. Thanks to @Esvorst for reporting this. +- (#2120, #2135) Long all-day event titles in Calendar week and day views now + truncate in the all-day row instead of stretching it vertically. Thanks to + @same774 and @ks-studio-net for reporting this, and to @Admorei for confirming + it remained in 4.12.2. +`});var pve,mve=y(()=>{pve=`# TaskNotes 4.12.2 + +> [!info] TaskNotes v5 beta +> +> [TaskNotes v5](https://github.com/callumalpass/tasknotes/releases/tag/5.0.0-beta.0) is available as an opt-in beta alongside TaskNotes 4.12. TaskNotes 4.12 remains the recommended stable release. +> +> The major change in v5 is support for portable TaskNotes collections. These collections can be used in both Obsidian and the [TaskNotes app](https://app.tasknotes.dev/), which is also available in beta, so the same tasks can be managed through either interface. +> +> TaskNotes collections are built on [mdbase](https://mdbase.dev/), a Markdown-native collection format. [mdbase Connect](https://mdbase.dev/connect/) provides the permissioned bridge that makes those collections available to the TaskNotes app. Your tasks remain ordinary Markdown files in your vault; mdbase adds a shared structure that compatible tools can understand. +> +> TaskNotes v5, mdbase Connect, and the TaskNotes app are all under active development. Please use a backed-up vault, expect some rough edges, and [report any problems you encounter](https://github.com/callumalpass/tasknotes/issues). + +## Fixed + +- (#2212) Fixed TaskNotes settings sections appearing pushed across the Obsidian settings pane on desktop. Thanks to @RafaQNunes for reporting this. +`});var fve,hve=y(()=>{fve=`# TaskNotes 4.12.1 + +> [!info] TaskNotes v5 beta +> +> [TaskNotes v5](https://github.com/callumalpass/tasknotes/releases/tag/5.0.0-beta.0) is available as an opt-in beta alongside TaskNotes 4.12. TaskNotes 4.12 remains the recommended stable release. +> +> The major change in v5 is support for portable TaskNotes collections. These collections can be used in both Obsidian and the [TaskNotes app](https://app.tasknotes.dev/), which is also available in beta, so the same tasks can be managed through either interface. +> +> TaskNotes collections are built on [mdbase](https://mdbase.dev/), a Markdown-native collection format. [mdbase Connect](https://mdbase.dev/connect/) provides the permissioned bridge that makes those collections available to the TaskNotes app. Your tasks remain ordinary Markdown files in your vault; mdbase adds a shared structure that compatible tools can understand. +> +> TaskNotes v5, mdbase Connect, and the TaskNotes app are all under active development. Please use a backed-up vault, expect some rough edges, and [report any problems you encounter](https://github.com/callumalpass/tasknotes/issues). + +## Changed + +- (#2204) Public documentation is now published from the dedicated \`tasknotes.dev\` repository. Plugin release notes and internal documentation remain in this repository. +- Updated compatibility with Obsidian's current plugin review and settings search. + +## Fixed + +- Fixed TaskNotes interface elements sometimes appearing in the wrong window when using Obsidian pop-out windows. +- Improved confirmation dialogs, icons, and modal styling to use Obsidian's current interface APIs. +`});var gve,yve=y(()=>{gve=`# TaskNotes 4.12.0 + +> [!info] TaskNotes v5 beta +> +> [TaskNotes v5](https://github.com/callumalpass/tasknotes/releases/tag/5.0.0-beta.0) is available as an opt-in beta alongside TaskNotes 4.12. TaskNotes 4.12 remains the recommended stable release. +> +> The major change in v5 is support for portable TaskNotes collections. These collections can be used in both Obsidian and the [TaskNotes app](https://app.tasknotes.dev/), which is also available in beta, so the same tasks can be managed through either interface. +> +> TaskNotes collections are built on [mdbase](https://mdbase.dev/), a Markdown-native collection format. [mdbase Connect](https://mdbase.dev/connect/) provides the permissioned bridge that makes those collections available to the TaskNotes app. Your tasks remain ordinary Markdown files in your vault; mdbase adds a shared structure that compatible tools can understand. +> +> TaskNotes v5, mdbase Connect, and the TaskNotes app are all under active development. Please use a backed-up vault, expect some rough edges, and [report any problems you encounter](https://github.com/callumalpass/tasknotes/issues). + +## Security + +- Calendar OAuth credentials and account tokens are now stored in Obsidian Secret Storage instead of TaskNotes' \`data.json\`, with automatic migration for existing connections. See [Calendar Integration](https://tasknotes.dev/features/calendar-integration/). + - Thanks to @mcuste for the contribution +- Updated bundled HTTP, address parsing, and schema validation dependencies to + versions containing their current security fixes. + +## Added + +- Added portable task attachment references. Attachments now round-trip as an + ordered \`attachments\` link list in task frontmatter and are exposed through + the TaskNotes model and runtime API. These are collection-file references + only; attachment bytes and binary metadata remain owned by the host. +- (#2142) MCP \`tasknotes_create_task\` and \`tasknotes_update_task\` now accept + \`customProperties\` for configured TaskNotes user fields. Thanks to + @phillipadsmith for suggesting this. +- (#2126, #2134) Added optional filename templates for materialized recurring + occurrence notes, with explicit date, ISO week, month, year, and month-name + variables plus per-parent overrides. Existing naming remains unchanged until a + template is configured. See [Recurring Tasks](https://tasknotes.dev/features/recurring-tasks/#occurrence-filenames). + Thanks to @raphaelfaouakhiri for reporting and implementing this. +- (#2105) Added \`{{projectFolder}}\` and \`{{projectFolders}}\` folder template + variables for storing tasks alongside linked project notes. See + [Template Variables](https://tasknotes.dev/features/template-variables/). + Thanks to @carypruitt for this contribution. + +## Changed + +- Generated TaskNotes type contracts now include configured natural-language + capture triggers, allowing compatible clients to offer the same field + suggestions. +- Rebuilt the TaskNotes documentation with + reorganized navigation, full-text search, mobile and accessibility + improvements, and references generated from the current commands, settings, + compatibility metadata, HTTP routes, and default Bases. Added practical + guides for adopting TaskNotes in an existing vault, mobile use, custom Bases, + and backup and recovery. See the + [TaskNotes documentation](https://tasknotes.dev/). +- (#2088) Convert current note to task now uses your default scheduled date when + the note does not already have \`scheduled\` frontmatter, while the **None** + default still leaves converted notes unscheduled. See + [Task Properties](https://tasknotes.dev/settings/task-properties/#scheduled-date). + Thanks to @e-zz for suggesting this. + +## Fixed + +- Plugin settings now recover when Obsidian briefly returns no data while + reloading an externally changed settings file, preventing a post-reload error + without overwriting the existing settings. +- (#2194) Pomodoro task selection suggestions now keep rich task cards at the + menu width, preventing task titles from wrapping one letter per line. Thanks + to @Evilgenee for reporting this. +- (#2196) Drag-to-reorder now works for Task List Bases embedded in Live Preview + notes, matching the behavior of directly opened Bases and Reading mode embeds. + Thanks to @jimbo108108 for reporting this. +- (#2198) Agenda Bases can now show overdue scheduled or due tasks on today's + row with \`showOverdueOnToday\`, and regenerated default Agenda files enable + that behavior by default. Thanks to @vicrdguez for reporting this. +- (#2182) Checklist progress on task cards now excludes cancelled markdown + checklist items such as \`[-]\` from the completed/total count. Thanks to + @ctrl-q for reporting this. +- (#2180) Inline task cards in Live Preview now keep their click and context menu + handlers active on Obsidian 1.13, so clicking a rendered task link opens the + edit modal instead of revealing the raw wikilink. Thanks to @npondel for the + detailed diagnosis and @minchinweb for confirming the issue. +- (#2171) Stopped recurring + notification and status-bar scans from reading unindexed notes directly from + disk while preserving the fallback for direct task lookups. Thanks to + @tgrosinger for identifying and diagnosing the excessive vault reads. +- (#2174) **Open or create occurrence note** from Quick Actions now uses the + recurring task's scheduled occurrence date, preventing duplicate occurrence + notes keyed to the day the action was run. Thanks to @chmac for reporting + this. +- (#2169) Regenerated default Base views now include tasks whose identifying + property is stored as a list containing the configured task value. Thanks to + @GlebYavorski for reporting this. +- (#2166) Fixed Task List views configured to start collapsed so the first + chevron click expands only the selected group instead of expanding every + other group. Thanks to @renatomen for reporting and fixing this. +- (#2165) **Convert current note to task** now reads configured field mappings, + including list-valued title fields such as \`aliases\`, and preserves an + existing aliases list when the title is unchanged. Thanks to @jkuball for + reporting this. +- (#2164) Flat Kanban boards now clear stale swimlane layout state when they + rerender, preventing columns from occasionally stacking into one vertical + strip after switching tabs. Thanks to @brienna for reporting this. +- (#2160, #2161) Generated Kanban Bases now use the correct TaskNotes status + property and configuration block. Rich Bases status values render as their + configured labels, while pinned columns and saved column order are honored. + Thanks to @kevin-4c for the detailed reports and diagnosis. +- (#2111, #2159) Recurring task instances now remain visible through the final + day of Calendar and Agenda ranges in positive-offset time zones, regardless + of the configured first day of the week. Thanks to @Arachnidai and @odxn0803 + for reporting this. +- (#2155) Regenerated default Calendar Bases now inherit the app-level time slot + duration instead of hardcoding 30 minutes. Existing per-Base time settings + remain intentional overrides. Thanks to @SZZ504232 for reporting this. +- (#2154) Timed ICS events without a \`TZID\` now preserve their floating wall + time in the user's local timezone instead of being interpreted as UTC. Thanks + to @cloesophia for the reproducible calendar sample. +- (#2152) Fixed paginated Google Calendar refreshes for calendars with many + events so secondary calendars do not disappear after Google returns a second + page. Thanks to @wobafett for reporting and diagnosing this. +- (#2141) Fixed Task List groups for tasks without scheduled or due dates showing + a raw Bases icon object instead of **None**. Thanks to @ks-studio-net for + reporting this. +- (#2140) The edit task modal now shows saved task-identification tags when + hiding identification tags is disabled. Thanks to @3zra47 for reporting this. +- (#2148) Empty list-like frontmatter values no longer become literal \`"null"\` + entries when tasks are edited. Thanks to @minchinweb for reporting this. +- (#2120, #2135) Long all-day event titles in Calendar week and day views now + truncate instead of stretching the all-day row. Thanks to @same774 and + @ks-studio-net for reporting this. +- (#2124) Fixed a Kanban crash when opening or closing the edit modal immediately + after moving a task between list-valued swimlanes such as contexts. Thanks to + @Decia-C for reporting this. +- (#2114) Completing a rescheduled occurrence for a scheduled-anchored recurring + task now advances the parent from the moved occurrence date instead of an + earlier original occurrence date. Thanks to @chrabia for reporting this. +- (#2113) Failed Google Calendar manual refreshes no longer make the next + immediate refresh show a misleading success notice. Thanks to @JohWQ for + reporting this. +- (#2109) TaskNotes no longer injects instant-conversion controls into embedded + or detached Markdown editors, preventing checkbox notes opened from unrelated + Bases from freezing Obsidian on mobile. Thanks to @jmartinmcfly for the clear + reproduction and recording. +- (#2107, #2108) Creating tasks with **Store title in filename** enabled now + handles duplicate or case-variant titles without failing or replacing the task + title with a suffixed filename. Thanks to @AdmiralClackington for reporting and + diagnosing this. +- (#2106) Regenerated default Calendar Base files now use your configured first + day of the week instead of forcing Sunday. Thanks to @atos2212-blip, @cweekly, + @idontcode34, and @hikatamika for reporting this. +- (#2100) Tags added while creating a task now keep the same frontmatter order as + tags added later from the task context menu. Thanks to @mgrecar for reporting + this. +- (#2092) New non-recurring tasks created directly in a completed status now get + a completed date, so completed-date views can find them immediately. Thanks + to @Crell for reporting this. +- (#2096) Fixed TaskNotes Kanban swimlanes falling back to **None** when the + swimlane used a Bases formula that was not already cached by Bases. Thanks to + @ddevaal for reporting this. +- (#2093) TaskNotes now retries custom Bases view registration when the Bases + core plugin is enabled after TaskNotes, preventing default views from showing + **Unknown view type** until TaskNotes is reloaded. Thanks to @yaye-work for + reporting this. +- (#2084) The Relationships widget no longer prevents editor text selection from + autoscrolling when dragging below the bottom edge of a task note. Thanks to + @lostwildland for reporting this. +- (#2081, #2103) Kept task card and relationships widgets visible in reading mode + when Obsidian scroll or preview updates remove their DOM, and refreshed visible + widgets promptly after metadata changes. Thanks to @mukhozhuk for reporting and + debugging this and @martin-forge for fixing it. +- (#2064, #2066) Recurring tasks now advance correctly after their next + scheduled date is manually adjusted, preserving due-date offsets and times + without jumping back to an earlier occurrence. Thanks to @chmac for reporting + and fixing this. +- (#2018) Fixed **Hide empty columns** in Kanban views with swimlanes so columns + with no visible tasks are hidden while pinned columns remain. Thanks to + @scottTomaszewski for reporting and fixing this. +- Fixed recurring all-day ICS subscription events keeping the original end date + on later instances, which could cause calendar list views to show events under + the wrong day. Thanks to @abbiefalls90. +- (#2033) Fixed the project folder badge on task cards so, when expandable + subtasks are enabled, it expands or collapses inline subtasks instead of + showing an unavailable-action notice. Thanks to @abbiefalls90 for the fix and + @scottkodai for the follow-up feedback. +- (#2040, #2041) Stopped newly created tasks from filling the Google Calendar + retry queue when calendar export is disabled. Thanks to @chmac for reporting + and fixing this. +- (#2046, #2051) The date and time picker now focuses the natural-language input + when it is enabled, making keyboard-driven quick actions ready for immediate + typing. Thanks to @DevOps-Toast for reporting this and @ther12k for fixing it. +- (#2125, #2129) Materialized recurring occurrence notes now record the date + they were actually completed, while the parent recurring task continues to + track the occurrence date. Thanks to @raphaelfaouakhiri for reporting and + fixing this. +- (#2173, #2175) Completion-anchored recurring tasks with materialized + occurrence notes now schedule the next occurrence from the day the occurrence + was actually completed. Thanks to @chmac for reporting and fixing this. +- (#1982) Preserved the Task List's own scroll position during Bases refreshes so + long mobile lists do not jump back to the top after task updates. Thanks to + @3zra47 for the follow-up report. +- (#1863) Microsoft Calendar event updates now accept opaque Exchange calendar + IDs instead of failing local validation before contacting Microsoft Graph. + Thanks to @fmacondray for reporting this and providing the follow-up stack + trace. +`});var vve,kve=y(()=>{vve=`# TaskNotes 4.11.1 + +## Added + +- (#2024) Added materialized occurrence notes to the Relationships widget, so recurring parent task notes can show their occurrence notes in an **Occurrences** tab. See [Relationships Widget](https://tasknotes.dev/features/inline-tasks/#relationships-widget). Thanks to @3zra47 for requesting this. +- (#2022) Added a **Skip instance** / **Unskip instance** action to the recurring task edit modal's completion calendar, so skipped dates can be adjusted from the same date menu as completions. See [Recurring Tasks](https://tasknotes.dev/features/recurring-tasks/#completion-tracking). Thanks to @AmonAmarthFTW for requesting this. +- (#2048) Added current due and scheduled dates to the edit modal's task information. Thanks to @1activegeek for requesting this. +- (#2058, #2059) Added natural-language parsing and the full date picker to date-type custom fields. Thanks to @chmac for requesting this. +- (#2060) Added date-type custom fields to the task right-click menu under **Custom dates**. Thanks to @chmac for requesting this. +- (#2067) Added an **Edit task** action to the task card context menu, including inline task cards. Thanks to @DarkCellar for requesting this. +- (#2068) Added \`reminders\` input support to the MCP \`tasknotes_create_task\` and \`tasknotes_update_task\` tools. Thanks to @Spirit597 for requesting this. +- (#2069) Added an **Add project** action to the Quick Actions palette. Thanks to @chmac for requesting this. + +## Fixed + +- (#2007) Fixed a remaining task creation autocomplete case where a status value containing another status label could leave status fragments in the task title. Thanks to @prepare4robots for the follow-up report. +- (#2031) Fixed quick task creation failing when natural language input created a recurring task with a scheduled time. Thanks to @rdefaccio for reporting this. +- (#2034) Fixed Advanced Calendar timed events switching to a high-contrast mobile fill when Obsidian is narrowed or split on desktop. Thanks to @RumiaKitinari for reporting this. +- (#2039) Fixed broken images on the Workflows and Calendar Setup documentation pages. Thanks to @chmac for reporting this. +- (#2045) Fixed custom modal fields assigned to Basic Information not appearing in task creation or edit modals. Thanks to @chmac for reporting this. +- (#2063) Fixed project autocomplete storing ambiguous project links without the selected note's folder path. Thanks to @chmac for reporting this. +- (#2072) Fixed inline task links to headings so they show both the task title and heading instead of only the heading. Thanks to @spasche for reporting this. +- (#2075) Fixed multiday Calendar events being clipped to one day when a Base is embedded in Reading view. Thanks to @ddevaal for reporting this. +- (#2079) Fixed the reminder modal's **Absolute** tab so it switches from relative fields to absolute date and time fields. Thanks to @JunwonYoon for reporting this and identifying the CSS specificity issue. + +## Changed + +- Improved local review checks so unsafe direct \`Object.prototype\` method access is caught before submission. +`});var Tve,bve=y(()=>{Tve=`# TaskNotes 4.11.0 + +## Added + +- (#730, #1897, #1942, #1998) Added [Canvas Bases](https://github.com/callumalpass/canvas-bases), an optional companion plugin that turns Obsidian Bases views into canvas-style boards and reusable JSON Canvas snapshots, with TaskNotes badges, task menus, dependency and subtask edges, and assignment zones for supported TaskNotes actions. See [Canvas Bases](https://tasknotes.dev/companion-plugins/canvas-bases/) for setup details. Thanks to @DillPickle80, @BradGaddis, @Hyadhuad, and @AlinaWithAFace for the visual planning requests, and to @renatomen, @prayidae, and @maranqz for the related discussion. +- Added a TaskNotes starter note that is created and opened automatically on first install to introduce task creation, inline conversion, and embedded Bases views. +- Added a runtime API surface for companion plugins to show or populate the standard TaskNotes task context menu. +- (#2000) Added separate settings for using the active note as a project during normal task creation and during inline task creation or instant conversion. Thanks to @BlueScreen32 for suggesting the split. +- (#1303, #2001) Added separate templates for materialized occurrence notes, including parent-level \`occurrence_template\` support and a global fallback setting. Thanks to @BrucePlumb for suggesting a separate occurrence-note template and @ak-42 for the related per-recurrence template request. +- (#2006) Added the projected local finish time beside the remaining duration while a Pomodoro is running. See [Pomodoro View](https://tasknotes.dev/views/pomodoro-view/) for the timer behavior. Thanks to @abbiefalls90 for suggesting this. +- (#2016) Added a setting for recurring external calendar event related notes, so Google, Microsoft, and ICS recurrences can either share notes across the series or keep notes limited to the selected instance. See [Integrations Settings](https://tasknotes.dev/settings/integrations/#calendar-subscriptions-ics) for the setting. Thanks to @akhtsang for reporting this, and to @cathywu and @mdbraber for the earlier series-linking discussion. + +## Changed + +- (#1737) Clarified that changing the task tag does not automatically update existing Base view filters. Thanks to @goldorak00 for reporting this, and to @Domcoppinger and @imsuck for the first-time setup feedback. +- (#2005) Excluded archived task notes and archived project-note references from Task & Project Statistics. Thanks to @Xiarno for suggesting this. +- Added a local review-type lint check that catches dependency-resolution warnings from Obsidian's online review before submission. +- Improved dependency and project relationship cache updates so ordinary note edits avoid unnecessary relationship recalculation, while blocked and blocking state stays current when dependency status changes. +- Improved filter and view query caching so filter options update immediately after relevant task-field changes while large Task List, Kanban, and Calendar queries avoid repeated vault scans. +- Extended the in-app release notes bundle to include the current major release, with collapsed versions rendered only when opened. + +## Fixed + +- (#2015) Fixed Google Calendar events from the previous six months disappearing from Calendar and Mini Calendar views after a fresh sync. Thanks to @akhtsang for reporting this. +- (#2013) Fixed task-card status and priority dots becoming oversized on touch-capable desktop devices. Thanks to @RumiaKitinari for reporting this. +- (#2009) Restored Tab and Shift+Tab focus movement in the Create new task modal's natural language input instead of letting the markdown editor indent the title. Thanks to @prepare4robots for reporting this. +- (#2007) Fixed status autocomplete in the task creation modal leaving status value fragments in the task title when the editor auto-paired the status trigger. Thanks to @prepare4robots for reporting this. +- (#2004) Fixed the Pomodoro start command forgetting the selected task after it was completed, so reopening the task lets it be picked up again. Thanks to @MPourjam for reporting this. +- (#1996) Made Kanban card drag-and-drop show a clear drop slot marker while cards are being repositioned, so the landing position remains visible during sorting. Thanks to @phillipadsmith for reporting this. +- Fixed runtime API dependency removal so removing the last dependency from a task also clears the mapped \`blockedBy\` property from the note. +`});var wve,Sve=y(()=>{wve=`# TaskNotes 4.10.2 + +## Fixed + +- (#1995) Fixed Bases Calendar views showing both a materialized occurrence note and its matching virtual recurring task instance. Thanks to @rdefaccio for reporting this. +- (Discussion #1994) Fixed timed recurring tasks failing to advance their due dates when due-date offset preservation is enabled. Thanks to @mgrecar for raising this. +`});var Cve,xve=y(()=>{Cve=`# TaskNotes 4.10.1 + +## Added + +- Added a startup check for new compatible TaskNotes releases. When a new release is available, TaskNotes shows a notice that opens the TaskNotes entry in Obsidian's Community Plugins browser. +- (#1989) Added a command-palette action plus runtime and HTTP API actions for updating configured default \`.base\` files from the current TaskNotes templates. Thanks to @businessBoris for the request. +- (#1115) Added API and MCP support for creating materialized occurrence notes from recurring tasks, and made headless recurring-instance completion respect occurrence notes when the parent uses Create next after completion. Thanks to @gsssr for the original request, @slipstyle for the follow-up, and @martin-forge for identifying the API/MCP gap. + +## Fixed + +- (#1985) Fixed embedded Calendar and Agenda time-grid views drifting out of alignment inside callouts and Reading mode. Thanks to @matesvecenik for reporting and sharing screenshots. +- (#1986) Fixed the local HTTP API rejecting requests from the TaskNotes browser extension's Chrome extension origin. Thanks to @n1njaznutz for reporting this. +- (#1980) Added mobile bottom spacing to Agenda Calendar views so the last visible tasks can scroll above Obsidian's bottom navigation bar. Thanks to @Jomo94 for reporting and sharing the screenshot. +- (#1984) Fixed mobile task link overlays hiding configured inline task card properties such as scheduled date, due date, contexts, and projects. Thanks to @stil-sudo for reporting. +- (#1979) Kept the left-positioned subtask chevron from overlapping the task status control on mobile task cards. Thanks to @Jomo94 for reporting and sharing the screenshot. +- (#1903) Reduced the Edit Task modal's mobile action-button footer so Open note, Archive, Delete, Save, and Cancel take two rows instead of three on iPhone-sized screens. Thanks to @3zra47 for the original report and @krzyfu for the follow-up about the button area crowding the editor. +- (#1982) Preserved scroll position in TaskNotes Bases after task edits and data refreshes, avoiding jumps back to the top on mobile. Thanks to @3zra47 for reporting. +- (#1978) Restored Obsidian editor shortcuts such as insert link, headings, and list toggles inside the Edit Task modal's Details editor. Thanks to @krzyfu for reporting this. +`});var Eve,Dve=y(()=>{Eve=`# TaskNotes 4.10.0 + +## Added + +- **New companion plugin:** TaskNotes Workflows adds Markdown-defined automation for TaskNotes tasks, events, schedules, and manual commands. It keeps automation workflows outside TaskNotes core while using the runtime API for safe task reads, writes, queries, events, and relationship resolution. See [TaskNotes Workflows](https://tasknotes.dev/companion-plugins/tasknotes-workflows/). + - (#1530) \`Auto-start time tracking\` starts a timer when a task moves into active work. Thanks to @Jendrik0 and @benmartinek for the request and follow-up. + - (#222, #184) \`Stop time tracking on complete\` stops active timers when a task is completed. Thanks to @bcohen44 and @cathywu for the requests, and @amarjt for the follow-up. + - (#265) \`Stamp started timestamp\` records a custom started timestamp when a task first moves into active work. Thanks to @cathywu, @digitaldoctors, and @Leo310 for the request and discussion. + - (#1703) \`Clear scheduled when started\` clears the scheduled date when a task moves into active work. Thanks to @kmaustral for the request. + - (#1293) \`Rollover overdue scheduled tasks\` moves incomplete tasks with past scheduled dates back to today. Thanks to @grosserfrank for the request. + - (#1896) \`Escalate upcoming due tasks\` raises priority as due dates approach. Thanks to @Neptune-Illusion for the request. + - (#214, #518, #1785, #1855) The subtask inheritance workflows can copy parent contexts, tags, priority, planning dates, and dependencies into new subtasks. Thanks to @timfidd, @bepolymathe, @AndyEveritt, @lindsaylearns, @tomsymonds, @wedgen, @poulpoulsen, and @misolex for the related requests and discussion. + - (#1166) \`Blocked task review\` provides a reminder-style review for blocked tasks without automatically deleting dependency links. Thanks to @jpmoo and @jortscity for the request and follow-up. +- Added a versioned TaskNotes JavaScript runtime API for companion plugins, with namespaced model validation, canonical task query validation/normalization/explain helpers, catalogs, query/support helpers, lifecycle events, typed errors/results, task, time-tracking, Pomodoro, recurring-task, settings, NLP, event, and extension-registry surfaces. Runtime API mutations carry source and correlation metadata so companion plugins can debug and coordinate workflow runs. See [JavaScript API](https://tasknotes.dev/javascript-api/). +- Added documentation for the companion-plugin model. See [Companion Plugins](https://tasknotes.dev/companion-plugins/). +- (#288, #345, #361, #523, #573, #703, #925, #929, #1115, #1137, #1260, #1303, #1324, #1394, #1445, #1509, #1735, #1736, #1743, #1780, #1874, #1951, #1974) Added support for TaskNotes spec 0.2.0 materialized occurrences, including recurrence parent/date fields, generated mdbase schema roles, parent reconciliation when occurrence notes are completed, occurrence notes that inherit parent planning metadata without copying history, occurrence note controls in task, calendar, and edit-modal completion menus, and visible occurrence identity on task cards. This gives recurring tasks a concrete occurrence-note path for per-instance state, related notes, subtasks, templates, scheduling changes, completion history, and calendar behavior without forcing every recurring task to create files. See [Recurring Tasks](https://tasknotes.dev/features/recurring-tasks/#materialized-occurrence-notes) and [Property Types Reference](https://tasknotes.dev/settings/property-types-reference/#materialized-occurrence-properties). Thanks to @LuxBetancourt, @jerzy-dudzic, @luciolebrillante, @BryanWall, @jhedlund, @kazerniel, @nschenone, @realJohnDoe, @cathywu, @Lorite, @EllenGYY, @JcMinarro, @gsssr, @slipstyle, @3zra47, @Leonard-44, @ak-42, @RumiaKitinari, @atos2212-blip, @kmaustral, @eugenedefox, @notDavid, @zitongcharliedeng, and @Jomo94 for the related recurrence, occurrence, completion, and calendar requests. +- (#1951) Added Calendar support for recurring tasks stretched between scheduled and due dates when the existing stretch option is enabled. Date-only ranges stay as all-day spans, and timed ranges render once per day in the range. Thanks to @atos2212-blip for the request. +- (#1751, #1792, #1969) Added a Task List and Kanban view option to hide top-level subtasks when their parent task is also in the filtered view, while still allowing inherited expanded relationships to show the subtasks under the parent. Thanks to @Glint-Eye and @Proxybat for the request and follow-up, and @stanley-910 and @Spencerduran for the earlier PRs. + +## Changed + +- Moved core TaskNotes model behavior for field mapping, dates, recurrence, time-tracking, and adapter operation planning into a shared package used by the plugin and companion tooling. +- Calendar views now coalesce materialized occurrence notes with their matching virtual recurring instances. Dragging a materialized occurrence reschedules that occurrence note without changing the parent recurrence rule or the note's \`occurrence_date\` identity. See [Recurring Tasks](https://tasknotes.dev/features/recurring-tasks/#calendar-drag-and-drop). +- Improved the Calendar Bases View Options menu by splitting settings into clearer groups and hiding view-specific controls until they apply to the selected calendar mode. + +## Fixed + +- (#1976) Fixed embedded Calendar and Agenda Bases so "Navigate to date from property" can use the containing note's date property when the Base rows do not have that property. Thanks to @matesvecenik for reporting this. +- (#1977) Fixed Calendar and Agenda views showing duplicate all-day entries when a task's scheduled date and due date are the same day. Timed due dates on the same day still show as separate deadline markers. Thanks to @pdgBC for reporting this. +- Fixed the release notes view using cramped interface typography instead of regular reading typography. +- (#216) Improved inline conversion for Tasks plugin task lines, including Dataview-style fields, priority markers, recurrence text, date aliases, block links, and safer trailing-field parsing. Thanks to @ksdavidc for the request, @natleahh for the Dataview example, and @hangryscribe3 and @nayatiuh for the discussion. +- (#1974) Stopped Calendar and Agenda property-based events from logging date parse errors for entries that do not have the selected date property. Thanks to @Jomo94 for suggesting completed-date Agenda events. +- (#1973) Reduced unnecessary Calendar view recreations when external calendar providers are reported in a different order, and preserved Calendar scroll position when a config-driven refresh has to recreate the view. Thanks to @e-zz for reporting this. +- (#1972) Fixed ICS calendar event related notes so standalone events with similar numeric IDs no longer show unrelated notes or tasks on every event. Thanks to @ks-studio-net for reporting this. +- (#1970) Fixed generated default Base filters so updating default files applies configured excluded folders to TaskNotes task views. Thanks to @henrim01 for reporting that templates could still appear in regenerated views. +- (#1968) Fixed inline task link overlays collapsing on Obsidian mobile, which could hide the task title and leave a tall empty gap after the widget. Thanks to @renatomen for reporting and diagnosing the containment issue. +`});var Pve,Ave=y(()=>{Pve=`# TaskNotes 4.9.2 + +## Added + +- (#1791) Added collapse and expand controls for grouped Bases Task List views, including a default collapsed state option. + - Thanks to @renatomen for the contribution. + +## Fixed + +- Fixed Pomodoro storage migration so existing plugin-data history is written to daily notes before switching storage, and clarified that daily notes can come from either the core Daily Notes plugin or Periodic Notes. +- (#1964) Fixed Microsoft Calendar OAuth so connecting no longer forces a fresh consent prompt every time, and clarified the Microsoft desktop app setup steps. + - Thanks to @thechonta for reporting. +- (#1966) Fixed custom priority icons so they render as icons instead of filled squares on task cards. + - Thanks to @sruiz-savia for reporting. +- (#1963) Fixed Google Calendar sync so duplicate event ID fields are repaired when saving task calendar metadata. + - Thanks to @christenbc for reporting. +- (#1961) Fixed the default custom filename template so it uses the recommended double-brace syntax and no longer warns on first use. + - Thanks to @chmac for reporting. +- (#1962) Fixed task tag normalization so tags entered with spaces are saved with hyphens for Obsidian tag compatibility. + - Thanks to @christenbc for reporting. +- (#1959) Fixed the MCP \`tasknotes_list_tasks\` tool so circular internal task data and live Obsidian object references no longer break task-list responses. + - Thanks to @kmaustral for reporting. +- (#1957) Fixed the Pomodoro timer layout in vertically split panes so the timer header and progress circle remain reachable when the pane is short. + - Thanks to @sumiyalairu03 for reporting. +- (#1956) Fixed Google Calendar sync so completing a recurring task updates the linked event title with the completion checkmark. + - Thanks to @jacksoluke for reporting. +- (#1953) Fixed inline task conversion so source-line wikilinks no longer create nested wikilinks in the replacement link text. + - Thanks to @bgk0018 for reporting. +- (#1952) Fixed Pomodoro task picker search results so matching task titles are ranked and sorted ahead of due-date ordering. + - Thanks to @KFrancoD for reporting. +- (#1392, #1949) Fixed due and scheduled date picker fields so typed or pasted date edits stay open until you choose Select, including compact \`YYYYMMDD\` entry when a date is already set. + - Thanks to @kazerniel for reporting and following up. +- (#982, #1947) Restored larger mobile task-card typography and let secondary card icons wrap below the task details when they no longer fit comfortably on mobile. + - Thanks to @3zra47 for reporting the font-size regression, @chrsdk and @scottaltham-payroc for confirming the mobile font-size issue, and @Jomo94 for reporting the mobile card layout problem. +`});var Mve,Ive=y(()=>{Mve=`# TaskNotes 4.9.1 + +## Added + +- (#1885) Added Shift+arrow keyboard range selection while bulk task selection mode is active. + - Thanks to @chrabia for suggesting bulk selection improvements and @sumiyalairu03 for the keyboard selection idea. + +## Fixed + +- (#781, #1085) Fixed Outlook-published ICS calendar events appearing at the wrong time when their feed used Windows timezone names without matching timezone definitions. + - Thanks to @chrlaney for reporting and @mjkrasny for confirming the Outlook timezone case. +- (#1696) Fixed Google Calendar export for scheduled recurring tasks when a single occurrence is moved to a different date. + - Keeps the recurring master event on its original rule, excludes the original occurrence date, and syncs the moved occurrence as a detached event. + - Thanks to @martin-forge for reporting and contributing the fix. +- (#1912) Fixed "Create subtask" inserting the full path of the parent task in the Projects field instead of using the normal Obsidian link text. + - Thanks to @pkuehne for reporting and @benmartinek for confirming. +- (#1921) Fixed Google Calendar and auto-archive updates not running after direct task file edits. + - TaskNotes now picks up status, completion, and date changes made directly in a task file without triggering a large one-time Google Calendar rewrite at startup. + - Recovery also removes stale Google Calendar links when task files were deleted or replaced outside TaskNotes. + - Thanks to @martin-forge for reporting and contributing the fix. +- (#1938) Fixed partial HTTP API task updates rewriting native tags with \`#\` prefixes or duplicate task tags. + - Thanks to @joseluisgonzalezdelgado-ctrl for reporting. +- (#1939) Fixed the task Details field rendering as a small nested textarea when the embedded editor falls back. + - Thanks to @g-arthurvanderbilt for reporting and @cookbr for confirming the desktop impact. +- Fixed tag and modal preview edge cases found during validation: double-hash tags no longer match the task tag, empty tag lists stay empty when read back, and natural-language previews remain visible when enabled. +- (#1941) Fixed mobile Kanban boards scrolling the whole board vertically instead of keeping each list independently scrollable. + - Thanks to @pxxush for reporting. +- (#1943) Fixed MCP task-query tool instructions so filter operators match the operators TaskNotes actually accepts. + - Thanks to @jordankbartos for reporting and proposing a fix in #1944. +- (#1945) Fixed Google Calendar export so overlapping sync services do not create duplicate events for the same task while the saved event ID is still catching up. + - Thanks to @martin-forge for reporting and contributing the fix. +- (#1946) Fixed the bottom task in virtualized Task List Bases being partially hidden behind Obsidian's mobile bottom bar. + - Thanks to @3zra47 for reporting. +- (#1947) Fixed mobile Task List cards with left-positioned subtask chevrons so the chevron remains visible and project/detail badges stay on the main row. + - Thanks to @Jomo94 for reporting. +- (#1948) Fixed Agenda Calendar Bases so completed recurring instances can appear on their recorded completion dates, even when recurring task projections are hidden or the completion date is outside the recurrence pattern. + - Thanks to @Jomo94 for reporting. +`});var Nve,Rve=y(()=>{Nve=`# TaskNotes 4.9.0 + +## Security + +- (#1923) Restricted the HTTP API server to loopback and limited browser CORS access to loopback origins. + - Thanks to @martin-forge for reporting. + +## Added + +- (#1932) Added middle-click support for opening task cards in a new tab. + - Thanks to @imsuck for the request. + +## Fixed + +- (#1934) Fixed custom priority colors being overridden by default task-card priority styles in views. + - Thanks to @KittehBit for reporting. +- (#1933) Added the note path to fallback frontmatter parse warnings so malformed task YAML is easier to find. + - Thanks to @rayvermey for reporting. +- (#1931) Made the Pomodoro task chooser open from cached task data and ignore repeated clicks while it is already opening. + - Thanks to @sumiyalairu03 for reporting. +- (#1930) Fixed starting the Pomodoro timer from its hotkey without starting time tracking for the selected Pomodoro task. + - Thanks to @sumiyalairu03 for reporting. +- (#1929) Fixed the bottom Relationships widget overlapping embedded content such as Bases/Kanban views in task notes. + - Thanks to @rchaklashiya for reporting and following up with the embed case. +- (#1922) Restored the native color picker alongside manual color text entry in Create/Edit Timeblock fields. + - Thanks to @AndreMonthy for reporting. +- (#1921) Fixed direct frontmatter edits to lifecycle-relevant task fields not triggering Google Calendar sync or auto-archive side effects. + - Thanks to @martin-forge for reporting and verifying the direct-edit reproduction. +- (#1919) Fixed the Pomodoro view rapidly resizing at certain sidebar sizes. + - Thanks to @RumiaKitinari for reporting. +- (#1898, #1907) Fixed Calendar time labels shifting into the middle of Day and sidebar calendar grids after switching views. + - Thanks to @ddevaal for reporting and confirming the regression, and to @kmaustral for confirming the sidebar case in 4.8.1. +- (#1936) Added a Calendar Base drag/drop resolution option so events can snap to smaller increments than the visible time slot grid. + - Thanks to @benmartinek for suggesting this. +- Improved mobile task cards, inline widgets, modals, and settings layouts so dense controls and long labels fit more comfortably on small screens. +- (#1916) Fixed Markdown task links using Obsidian's generated filename label instead of the TaskNote title in the task link overlay. + - Thanks to @minchinweb for reporting. +- (#1911) Fixed recurrence choices starting from today instead of the selected calendar date when creating a task from Calendar view. + - Thanks to @mikhailmarka for reporting. +- (#1912) Fixed "Create subtask" pre-filling the parent task's full folder path in the Projects field instead of using the normal Obsidian link text. + - Thanks to @pkuehne for reporting and @benmartinek for confirming. +`});var _ve,Fve=y(()=>{_ve=`# TaskNotes 4.8.1 + +## Fixed + +- (#1903) Improved the Edit Task modal on iPhone-sized screens so opening a task no longer automatically focuses the title field, and the mobile layout gives the title, fields, and action buttons more usable space. + - Thanks to @3zra47 for reporting the issue and sharing the screen recording. +- (#1909) Fixed compact Kanban task cards showing oversized status and priority indicators on touch devices. + - Thanks to @pxxush for reporting the issue. +- (#1908) Restored newly generated Calendar Bases to show the full day by default and inherit the calendar start/end settings instead of hard-coding 06:00-22:00. + - Thanks to @AndreMonthy for the report. +- (#1907) Fixed calendar time labels drifting away from the left axis in narrow sidebar calendar views. + - Thanks to @kmaustral for reporting the issue. +- (#1906) Fixed NLP priority shortcuts leaving partial text in task titles when custom priority values include words like \`high\` or \`low\`. + - Thanks to @RumiaKitinari for reporting the issue. +- (#1904, #1905) Fixed long tags in task cards wrapping instead of forcing horizontal scrolling in TaskNotes Bases views and note cards. + - Long tag pills can now wrap across lines and break within very long tag names on narrow screens. + - Thanks to @3zra47 for reporting the issue and to @zhouzhou626 for the contribution. +- (#1901) Fixed the task context menu creating an \`undefined\` property when adding or removing tags. + - Hardened task property updates so invalid frontmatter property names are rejected instead of written. + - Thanks to @mgrecar for reporting the issue. +- (#1902) Fixed Markdown-style project links in task frontmatter not appearing as subtasks on project pages. + - Thanks to @minchinweb for reporting the issue. + +## Changed + +- Improved the internal structure around service notifications, vault writes, and shared utilities to make future fixes easier to test and maintain. +`});var Lve,Ove=y(()=>{Lve=`# TaskNotes 4.8.0 + +## Added + +- (#353) Added a \`Has Subtasks\` filter for task queries, so views and API clients can show only project-style tasks or direct tasks. Thanks to @mdbraber for suggesting this. +- (#380) Added a test-reminder button in notification settings, so reminder setup can be checked without creating a real task reminder. Thanks to @mdbraber for suggesting this. +- (#711, #168) Added an optional task-creation setting to open the new task note after saving, either in the current tab or a new tab. Thanks to @phortx and @23426356587 for suggesting this, and to @edward-peters and @obsilover for the follow-up. +- (#1041, #1800) Added copy-drag support for timeblocks: hold Ctrl, Cmd, or Alt/Option while dragging an existing timeblock to duplicate it at the new date and time. Thanks to @0-BSCode and @cweekly for suggesting this. +- (#1052) Added a public JavaScript API for in-vault scripts at \`app.plugins.plugins.tasknotes.api.parseNaturalLanguage(text)\`, so Templater, QuickAdd, and MetaBind workflows can use TaskNotes' natural-language parser without running the HTTP API. Thanks to @edakimling for suggesting this. +- (#1235) Added a task-card toggle for blocked tasks, so you can expand a blocked task to see the tasks it is waiting on. Thanks to @craziedde for suggesting this. +- (#1254) Added \`../\` and \`./\` normalization for folder templates after variables are expanded, so instant task conversion can target sibling folders such as \`{{currentNotePath}}/../Tasks\`. Thanks to @rdick for suggesting this. +- (#1267) Added Daily Notes-style date tokens such as \`YYYY\`, \`MM\`, \`DD\`, \`MMMM\`, and \`dddd\` to TaskNotes folder templates. Thanks to @paulsen-it for suggesting this. +- (#1380) Added tag actions to task context menus, including add/remove actions for individual tasks and batch-selected tasks. Thanks to @Chuhtra for suggesting this. +- (#1377) Added right-click Mini Calendar actions for opening daily notes from day cells and weekly notes from week numbers. Thanks to @hasanyilmaz for suggesting this. +- (#1151) Added a Mini Calendar max color note count option, so one-note days can use the strongest heatmap color when that better fits the view. Thanks to @arreme for suggesting this. +- (#1376) Added backslash escapes for NLP trigger tokens, so text like \`\\@context\`, \`\\*done\`, or \`\\tomorrow\` can stay in the task title. Thanks to @JerryLu086 for suggesting this. +- (#1366) Added CSS variables for compacting nested task-card indentation, with smaller defaults on mobile and documented snippets for tighter task-link lists. Thanks to @rk-kontur for suggesting this. +- (#1502, #603) Added calendar indicators for external events that have linked notes or tasks, and showed loaded event titles in task-card calendar metadata instead of only the linked event count. Thanks to @Robubble and @mdbraber for suggesting this, and to @ubidev for the follow-up. +- (#1522) Added a per-status option to skip rarely used statuses when cycling task-card status indicators. Thanks to @Glint-Eye for suggesting this. +- (#144) Added an "Open note in new tab" action to the task context menu. Thanks to @cathywu for suggesting this and @macbikegeek for the follow-up feedback. +- (#167) Added an optional next-status override for each status, so forward cycling can jump to a configured status instead of always following the status order. Thanks to @DanBrazelton for suggesting this, and to @michelebugio, @Moyf, @anareaty, and @vorrermid for the follow-up feedback. +- (#1520) Made tag and context fields show available suggestions as soon as the field is focused. Thanks to @Glint-Eye for suggesting this, and to @craziedde for the follow-up. +- (#1541) Added \`{{currentNotePath}}\` and \`{{currentNoteTitle}}\` support to the default tasks folder, so normal task creation can place new tasks beside the active note without creating an inline link. Thanks to @ChristianAnyanwu for suggesting this, and to @abbasou and @ttlaylor for the follow-up feedback. +- (#648, #1605) Added clickable links in task-card contexts for note links, markdown links, and web URLs while keeping plain contexts as tag-search buttons. Thanks to @trdischat and @Glint-Eye for suggesting this, and to @renatomen for the follow-up feedback. +- (#1482) Added clickable custom-field links on task cards for wikilinks, markdown links, autolinks, and bare web URLs. Thanks to @ptbosch-figueiredorj for suggesting this, and to @Soleone for the follow-up use case. +- (#1471) Added Kanban column and swimlane-cell add buttons that open the TaskNotes creation modal with the grouped values already filled in. Thanks to @byheaven for suggesting this and @Davincible for the project-board use case. +- (#933) Added non-Markdown vault files such as canvases to project suggestions, using extension-qualified link targets so those files can be selected as task projects. Thanks to @Alvin21Bon for suggesting this. +- (#1475, #725) Added quote/backtick escapes for NLP input, so literal course codes or date words can stay in task titles without being parsed as estimates or dates. Thanks to @RumiaKitinari and @gavingwebb for suggesting this. +- (#1462) Added natural-language date entry to the task date picker, so existing due and scheduled dates can be changed with phrases such as "tomorrow at 3pm" when NLP is enabled. Thanks to @Ruboks-Cube for suggesting this. +- (#1526) Added a native date field to the task date picker, so scheduled and due dates can be changed with the device date picker while keeping optional times visible. Thanks to @jmartinmcfly for suggesting this and @23426356587 for the follow-up feedback. +- (#1603) Added Calendar view toggles for hiding completed or skipped recurring task instances while keeping future outstanding instances visible. Thanks to @wandererovertheseaofpiss for suggesting this. +- (#287, #273, #274) Added linked hover highlighting for Calendar and Agenda events that come from the same task note, so scheduled, due, and recurring entries are easier to connect. Thanks to @girisumit for suggesting this. +- (#280) Added project-specific CSS hooks to task cards and Calendar events, so project-based visual styling can be handled with user snippets. Thanks to @girisumit for suggesting this. +- (#1625) Added \`Shift\` + \`Cmd\`/\`Ctrl\` + \`Enter\` in the Create Task modal to save the current task and reopen the modal for the next one. Thanks to @tcb678 for suggesting this. +- (#1353) Focused the Create Task modal's natural-language input when the modal opens, with a longer mobile delay so the keyboard can open after layout. Thanks to @GiovanH for suggesting this. +- (#1664) Added project-based custom filename template variables, including the first project, all projects, and a short \`projectId\`. Thanks to @bendavis987 for the contribution. +- (#923) Added \`{{projectFilePath}}\` and \`{{projectFilePaths}}\` folder template variables, so task folders can mirror project note locations in the vault. Thanks to @PacoTaco2 for suggesting this. +- (#1697) Added cached Google Calendar, Microsoft Calendar, and ICS events to Mini Calendar days, with compact colored dots and event details from the existing calendar connection. Thanks to @RPGArchivist for suggesting this. +- (#1754) Added optional icons for priority values, so task cards can show a configured priority icon instead of only a colored dot. Thanks to @BrucePlumb for suggesting this and @prepare4robots for the follow-up feedback. +- (#1761) Added TaskNotes edit and task-action submenu entries to Obsidian's native file context menu for recognized task notes. Thanks to @delzero for suggesting this. +- (#1771) Added mobile drag handles to manually sorted Task List Bases views, so dragging can start from the handle without disabling normal text interaction on the rest of the card. Thanks to @PatrickGolz for suggesting this. +- (#1776) Allowed calendar timeline end times after midnight, such as \`26:00\` for a 2 AM next-day end. Thanks to @chrabia for suggesting this. +- (#1784, #1833) Added a per-view \`pinnedColumns\` option for TaskNotes Kanban views, so selected empty columns can stay visible as drop targets while other empty columns remain hidden. Thanks to @loukandr for suggesting and prototyping this. +- (#1794) Added context updates to the task card context menu, so contexts can be added, toggled, or cleared without opening the task edit modal. Thanks to @m13ntrpn for suggesting this. +- (#315, #1356, #1748, #1809) Added a subtle task-card indicator and CSS hooks for tasks with note body details, including existing task bodies read through Obsidian's metadata cache. Thanks to @volodxyz, @Karut, @yeHHH1g, and @aliceinwaterdeep for suggesting this, and to @minchinweb for the follow-up. +- (#1808) Added advanced Kanban swimlane ordering through \`swimLaneOrder\`, so swimlane rows can stay in a stable configured order. Thanks to @rookledookle for suggesting this, and to @benmartinek and @chrabia for the follow-up feedback. +- (#1805) Added an ICS export option to omit completed tasks from generated calendar files. Thanks to @bepolymathe for suggesting this. +- (#659) Added Obsidian links to ICS export descriptions, so exported calendar events can open their source task notes. Thanks to @bepolymathe for suggesting this. +- (#589) Added an Appearance toggle to turn off strikethrough styling on completed task card titles. Thanks to @BrucePlumb for suggesting this. +- (#561) Added a "Last day" option to the custom recurrence month-day picker for month-end repeating tasks. Thanks to @TonyAtlas for suggesting this and @BrucePlumb for the follow-up. +- (#217) Added weekday selection to daily custom recurrence rules, so interval rules such as every three days can skip weekends from the recurrence modal. Thanks to @kmaustral for suggesting this. +- (#1818) Added an auto-height mode for TaskNotes Calendar Bases views so embedded agenda/list sections can size to their content instead of forcing an inner scroller. Thanks to @martin-forge for suggesting this. +- (#1201) Added a Calendar Bases toggle to hide the hourly breakdown in week, custom-days, and day views while keeping the all-day planning row visible. Thanks to @PacoTaco2 for suggesting this. +- (#1176) Added advanced Kanban WIP limits through \`wipLimits\`, so column headers can show \`(current/limit)\` counts and highlight exceeded limits. Thanks to @williamcheuk03 for suggesting this. +- (#914) Added a generated \`Due in\` countdown to the default Agenda Base and allowed Calendar Bases list agendas to span up to 365 days. Thanks to @williamcheuk03 for suggesting this. +- (#900) Added an instant-conversion setting to keep the original Markdown checkbox marker when converting a checkbox into a TaskNote link. Thanks to @dsebastien for suggesting this. +- (#898) Added a mobile-only calendar integration opt-out, so synced desktop calendar settings no longer have to trigger external calendar loading on Obsidian Mobile. Thanks to @cathywu for suggesting this. +- (#887) Added built-in scheduled and due date presets to the Quick actions palette for current tasks. Thanks to @willgraham345 for suggesting this and @anrie for the related preset feedback. +- (#819) Added a command to open Quick actions for the inline task link under the cursor. Thanks to @rlolingo for suggesting this. +- (#798, #1732, #1835) Added hotkeyable commands to edit the current task, add a project to the current task, and add an existing task as a subtask of the current note. Thanks to @xorander00 and @prepare4robots for requesting this, and to @musta-code and @ubidev for the follow-up suggestions. +- (#791) Added a UUID v4 task filename format and \`{{uuid}}\` custom filename template variable. Thanks to @bangbangbanggit for suggesting this. +- (#932) Added hotkeyable commands to cycle the current task's status and priority. Thanks to @rxunique for suggesting this and @luckb0x for the follow-up feedback. +- (#1655) Added live elapsed time to the optional active time tracking status bar item. Thanks to @connradolisboa for suggesting this. +- (#1622) Allowed multiple comma-separated default reminder offsets for timed Google Calendar task exports. Thanks to @solidabstract for suggesting this. +- (#706, #820, #1040) Added direct Pomodoro duration editing, hour-aware timer formatting, clearer one-minute controls, and an optional active Pomodoro status bar countdown. Thanks to @SublunarSage, @lj1446615403-cloud, @0-BSCode, and @thestrike72 for the suggestions and feedback. +- (#873) Added an optional built-in sound for task reminder notifications, with volume and preview controls in Settings. Thanks to @berzernberg for suggesting this. +- Added a generated Pomodoro statistics Base with daily and monthly summary views for Pomodoro history stored in daily notes. + +## Changed + +- Expanded the bug report template to ask for Obsidian "Show debug info" output, affected task frontmatter, relevant Bases file contents, reproduction steps, and related logs or screenshots. +- Release notes now show the default \`.base\` file regeneration reminder only on the current version section, keeping older bundled sections focused on their own changes. +- Updated the release notes GitHub prompt to invite feedback while still asking satisfied users to star the project. +- (#239) Ordered Kanban status and priority columns by the configured status order and priority weights when no manual column order is saved. Thanks to @ScumbagScalawag for asking about this, and to @nightroman, @lavir, and @elvarb for the follow-up discussion. +- (#269) Marked Kanban status columns that come from values outside the configured TaskNotes statuses, so manually edited or external status values are visible as non-standard instead of blending into the board. Thanks to @cstelmach for suggesting this and @digitaldoctors for the follow-up. +- Refined Kanban empty columns, swimlane rows, and column drag handles, and added a per-view compact card layout option for denser boards. +- Kept Kanban swimlane rows from shrinking to share the viewport so the Max Swimlane Height setting is respected. +- Added guidance in Pomodoro statistics and Base file settings explaining that Pomodoro Base views require daily notes storage. +- (#323) Reordered task modal action buttons to match the right-click task menu order. Thanks to @23426356587 for suggesting this. +- (#1189) Made the Create/Edit Task modal priority picker follow the priority order configured in Settings. Thanks to @n1njaznutz for suggesting this. +- Made task-card priority dots and configured priority icons slightly larger for better visibility. +- (#1244) Clarified the Task Properties documentation for custom property keys and status values in Bases filters and sorting. Thanks to @Arachnidai for suggesting this. +- (#1234) Kept right-aligned subtask chevrons visible on task cards instead of only showing them on hover. Thanks to @n1njaznutz for suggesting this. +- (#1237) Made today's date more visible in the Mini Calendar view when another day is selected. Thanks to @riekusr for suggesting this. +- (#1348) Let long task titles wrap inside the Create/Edit Task modal title field while keeping saved titles single-line, and widened the contexts and tags fields in the modal details area. Thanks to @hasanyilmaz for suggesting this. +- (#1392) Made TaskNotes date fields accept compact \`YYYYMMDD\` typing and pasted dates. Thanks to @kazerniel for suggesting this. +- (#1431) Showed the year on task-card due and scheduled dates when the date is outside the current year. Thanks to @kazerniel for suggesting this. +- (#1429) Opened TaskNotes view commands in a new tab when they load configured Base files, so they do not replace the active note. Thanks to @Ruboks-Cube for suggesting this. +- (#1426) Added copy actions for TaskNotes Bases views, including current-view filenames, links, and titles from the result count menu, plus selected-task copy actions in the batch menu, while keeping the native Bases copy and CSV export actions available. Thanks to @kmaustral for suggesting this. +- Improved keyboard access, mobile layout, and theme color consistency across task cards, TaskNotes Kanban, Bases Kanban, calendar controls, stats, settings, and filter popovers. +- (#1526) Made the Create/Edit Task modal due and scheduled date buttons open a calendar-first picker where clicking a date saves immediately, with time entry still available in the picker. Thanks to @jmartinmcfly for suggesting this and @23426356587 for the follow-up feedback. +- (#1642) Made completion-based custom recurrence use flexible weekly, monthly, and yearly intervals without forcing a fixed weekday, month day, or month. Thanks to @Volker-brdb for suggesting this. +- (#1724) Moved recurring task complete/skip instance actions into the date area of the task context menu. Thanks to @prepare4robots for suggesting this. +- (#1762) Used the configured Google Calendar task export target as the default calendar when creating manual external calendar events. Thanks to @chrabia for suggesting this. +- (#1774) Made expandable project chevrons visible and easier to tap on mobile. Thanks to @sh0nuff for suggesting this. +- (#190) Made task-card and inline task-link action controls easier to tap on mobile, including always-visible task options on touch layouts. Thanks to @Poly-0000 for suggesting this. +- (#518, #1710, #1785) Added an opt-in setting for Create subtask to inherit the parent task's projects, contexts, priority, and non-identifying tags while always keeping the parent-task project link. Thanks to @bepolymathe, @Jalpara, and @poulpoulsen for reporting this, and to @tomsymonds, @AndyEveritt, @wedgen, @lindsaylearns, and @hokfujow for the follow-up feedback. +- (#1790) Extended the identifying-tag hiding setting to task modal tag suggestions, and kept hidden identifying tag children in place when editing other tags. Thanks to @loukandr for suggesting this. +- (#1804) Made the inline-created task folder setting visible even when instant conversion is disabled, and clarified that leaving it empty uses the default tasks folder. Thanks to @CaFeZn for suggesting this. +- (#1822) Matched the Task Edit Modal subtask list order to the existing relationship sort, so active and higher-priority subtasks appear ahead of completed ones. Thanks to @Glint-Eye for suggesting this. +- (#1233, #1339) Added an Appearance setting to expand project subtasks by default in task cards, while still letting individual cards be collapsed. Thanks to @n1njaznutz and @hasanyilmaz for suggesting this and @kazerniel and @benmartinek for the follow-up. +- (#763) Made the Relationships widget appear on project notes that match Project Autosuggest tag or property filters, even before any tasks link to the project. Thanks to @ChadHattabaugh for suggesting this. +- (#732) Remembered the Task & Project Statistics filters between openings, including the selected date range, custom dates, and minimum time filter. Thanks to @RumiaKitinari for suggesting this. +- (#1335) Added optional default times for new task scheduled and due dates, so default-dated tasks can appear as timed calendar events instead of all-day events. Thanks to @echo-saurav for suggesting this. +- (#1327) Made TaskNotes Bases search match any word in a multi-word search instead of requiring the whole phrase. Thanks to @craziedde for suggesting this. +- (#1318) Made aliased inline task links use the alias text inside the task widget, so \`[[Task title|short label]]\` can display as \`short label\`. Thanks to @3zra47 for suggesting this and @kazerniel for the follow-up. +- (#1325) Added \`./\` and \`../\` support to Include folders filters for project and file autosuggest, resolved from the active note's folder. Thanks to @EpolPers for suggesting this. +- (#1313) Added generated \`llms.txt\` and \`llms-full.txt\` files to the documentation site, so the primary docs can be shared with LLM tools more easily. Thanks to @JacksonMcDonaldDev for suggesting this. +- (#1308) Added a Calendar view option to stop date links from creating missing daily notes, while still opening existing daily notes. Thanks to @Arachnidai for suggesting this. +- (#1300) Allowed priority, status, calendar subscription, and timeblock color settings to use Obsidian theme color names such as \`red\`, \`blue\`, and \`cyan\`. Thanks to @thestrike72 for suggesting this. +- (#1299) Added a command that creates or opens a task and immediately starts time tracking for it. Thanks to @slipstyle for suggesting this. +- (#1284) Added an exact-match option for hiding task identification tags, so \`#task\` can be hidden while nested tags such as \`#task/project\` remain visible. Thanks to @3zra47 for suggesting this. +- (#1009) Added a confirmed Delete button to the Edit Task modal, so unwanted task notes can be removed without first opening the note file. Thanks to @jalooc for suggesting this. +- Improved the internal structure of Calendar, Kanban, Bases, task cards, and task modals to make future changes easier to test and maintain. + +## Fixed + +- (#697, #1374) Recognized manually authored task notes that use a single scalar tag such as \`tags: task\`, so they appear in TaskNotes views and menus like notes using YAML list tags. Thanks to @aubreyz and @phortx for reporting this, and to @jleewastaken for the follow-up. +- Removed the upward hover shift from calendar events while keeping the hover shadow feedback. +- Made same-column manual-order drops in TaskNotes Kanban settle immediately when the local order patch is safe, including virtual columns through a stable reorder path that avoids layout jumps. +- Made single-card cross-column drops in TaskNotes Kanban settle through a local state patch when the move is safe, reducing the wait for the full Bases refresh. +- Fixed Calendar timeblocks created from a selected time range so they appear as soon as Obsidian indexes the daily note update, instead of waiting for a later refresh. +- Replaced the external calendar event emoji marker with the calendar icon and kept it in the same top-right event corner. +- Restored Task List group toggles and recurring calendar month controls to compact icon buttons instead of inherited boxed theme buttons. +- Refined the settings tab navigation styling so tabs read as quieter inline navigation instead of default buttons. +- (#263) Made the instant inline task conversion button respond to touch/pointer activation, so mobile multi-line selections can be converted into TaskNotes. Thanks to @cathywu for reporting this. +- (#216) Preserved \`@context\` markers when converting Tasks-plugin-style checkbox tasks into TaskNotes, while keeping those contexts out of the created task title. Thanks to @ksdavidc for suggesting this, and to @hangryscribe3, @nayatiuh, and @natleahh for the follow-up feedback. +- (#508) Showed project note names instead of full project paths in grouped Kanban and Task List headings, while keeping the headings linked to the project note. Thanks to @elvarb for reporting this and @dmodify for confirming it in Task List. +- (#408) Used the task title as the native system notification title for task reminders instead of always showing \`TaskNotes Reminder\`. Thanks to @DudeThatsErin for reporting this and @phillipadsmith for the follow-up. +- (#385) Let Mini Calendar month controls shrink and wrap cleanly in narrow sidebars. Thanks to @iholston for reporting this. +- Fixed Calendar List view task cards so they use the available row width without duplicate list cells, row-hover backgrounds, or linked-hover styling. +- (#552) Made instant task convert buttons appear for checkbox tasks inside callouts, and kept converted links inside the callout list. Thanks to @Oblique82 for reporting this and @ksdavidc for the follow-up. +- (#559) Treated notes linked to one loaded recurring calendar event instance as related to the other instances in that series. Thanks to @cathywu for reporting this and @mdbraber for the implementation notes. +- (#685) Made Calendar list views respect the All-day slot option by hiding all-day events from the list when that option is turned off. Thanks to @RumiaKitinari for reporting this. +- (#643) Stopped custom filename templates such as \`task-{year}{month}{day}{hour}{minute}\` from incorrectly showing the "filename shortened" notice when creating tasks. Thanks to @minchinweb for reporting this. +- (#722) Made Skip Break reset a queued Pomodoro break back to the next focus timer without starting a session. Thanks to @Goossiii for reporting this and @YIRU69 for the follow-up. +- (#782) Made recurrence weekday choices follow the configured first day of week, and made the quick "Weekdays only" recurrence use locale weekend data instead of assuming Monday through Friday everywhere. Thanks to @BKSalman for reporting this. +- (#872) Made note-level task cards appear immediately, and stay visible while editing, when a task note is embedded as a Canvas file node. Thanks to @bangbangbanggit for reporting this and @benmartinek for the follow-up. +- (#856) Fixed filters for number custom fields so numeric task values match equivalent filter values entered as text. Thanks to @thoughtcipher for reporting this. +- (#1039) Restored clearer TaskNotes Bases grouping for nested project paths, and made the Calendar refresh control an icon button again. Thanks to @dblinnikov for reporting this. +- (#1034) Let embedded TaskNotes Calendar views size to their content by default, so month, week, and day embeds no longer reserve full-pane proportions inside notes. Thanks to @same774 for reporting this. +- (#1023) Kept task modal custom fields scrollable above the iPhone keyboard while creating or editing tasks. Thanks to @3zra47 for reporting this. +- (#1019) Kept active Pomodoro and time-tracking task references working after the tracked task file is renamed. Thanks to @AndreMonthy for reporting this. +- (#1037) Let embedded TaskNotes Calendar year views size to their content and kept the year title from wrapping vertically. Thanks to @same774 for reporting this. +- (#1047) Wrapped long file paths in the Edit Task modal metadata section, so narrow mobile screens no longer get a sideways scrollbar from the File row. Thanks to @3zra47 for reporting this. +- (#1051) Preserved extra values on a property-based task identification field when saving a task, so list properties such as \`class: [task, habit]\` no longer get collapsed to only the identifying value. Thanks to @WhoIsSeanGalt for reporting this. +- (#1060) Reused and revealed an already-open Calendar/Base view when running view commands, so a view kept in the sidebar no longer reopens in a new main tab. Thanks to @kmaustral for reporting this. +- (#1075) Hid the native WebKit date-input label that could appear as \`Label\` when editing scheduled dates on macOS. Thanks to @3zra47 for reporting this. +- (#1076) Allowed timeblocks to end at midnight using \`00:00\`, and accepted \`24:00\` as an explicit end-of-day value in timeblock validation. Thanks to @skoove for reporting this and @gregor202 for the follow-up. +- (#1086) Fixed the Calendar \`+ more\` control in dark mode so expanded all-day task groups stay readable. Thanks to @same774 for reporting this. +- (#1100) Applied Advanced Calendar View search and title filters to the tasks used for calendar rendering, so filtering controls affect which tasks appear on the calendar. Thanks to @quiet-coder-io for reporting this. +- (#1147) Added a delete action for recent Pomodoro statistics sessions, so erroneous Pomodoro history can be removed without editing plugin storage or daily-note frontmatter manually. Thanks to @RumiaKitinari for reporting this and @BrucePlumb for the follow-up. +- (#1150) Kept recurring tasks' due dates visible in Calendar Bases views, and showed their scheduled date when recurrence instances are hidden. Thanks to @thomatino for reporting this and @BrucePlumb for the follow-up. +- (#1159) Softened Calendar time-entry styling so recorded time blocks no longer visually outweigh task events. Thanks to @hatespinach for reporting this. +- (#1191) Aligned the task-card and relationships widgets inside notes with Obsidian's editor margins, including readable-line-width layouts. Thanks to @minchinweb for reporting this. +- (#1183) Kept the Calendar create menu open after drag-selecting a time range, so the selected duration can be used when creating a task. Thanks to @randomness42 for reporting this. +- (#1179) Stopped Calendar Bases views from repainting after unrelated note updates when the visible calendar data has not changed. Thanks to @same774 for reporting this. +- (#1156) Kept property-based task identification through the \`tags\` property from rewriting task tags as a plain text value, and generated default Bases now use tag membership for that setting. Thanks to @seepage87 for the detailed migration report and @chrsdk for the follow-up. +- (#1232) Fixed generated Task List Base date filters so recurring tasks scheduled for today appear in the Today view, and today's completed recurring instances stay hidden. Thanks to @mvichosfm for reporting this and @ArthurGideon and @VarunNikam22 for the follow-up. +- (#1231) Fixed the generated Task List Base Overdue view so tasks with scheduled dates in the past appear alongside tasks with due dates in the past. Thanks to @Lorite for reporting this and @dictionarymouse for the follow-up. +- (#1228) Matched the task details editor's Markdown heading colors to the active Obsidian theme, including themes that customize heading colors. Thanks to @BrucePlumb for requesting this. +- (#1227) Refreshed the relationships widget when project references are indexed or updated so project notes can show related tasks automatically again. Thanks to @luckb0x for reporting this. +- (#1219) Fixed Kanban drags that start on an expanded subtask card so they move that subtask instead of dragging the parent card. Thanks to @craziedde for reporting this. +- (#990) Treated one-item status lists written by Obsidian Properties as the same status value in TaskNotes Kanban, so they no longer create duplicate columns. Thanks to @mlevison for reporting this. +- (#983) Let Agenda Calendar views wrap their header controls and task titles inside narrow sidebars, so Today and refresh controls and task icons remain visible without sideways scrolling. Thanks to @3zra47 for reporting this. +- (#982) Made TaskNotes task-card typography scale from Obsidian's text font size setting, so Bases and Agenda task text follows larger mobile font settings. Thanks to @3zra47 for suggesting this and @chrsdk and @scottaltham-payroc for the follow-up. +- (#966) Made reminder delete buttons larger and always visible on mobile, so reminders can be removed from the Manage All Reminders modal on iPad. Thanks to @PSG2017 for reporting this. +- (#964) Made Pomodoro and time-tracking task selection use the current recurring instance status, so a recurring task can still be selected after an earlier instance was completed. Thanks to @lomarcanys for reporting this. +- (#944) Preserved number and boolean custom field values when moving tasks between grouped Kanban or Task List columns, and when creating a task from a grouped Kanban column. Thanks to @thoughtcipher for reporting this. +- (#935) Fixed Task List priority sorting so descending order puts higher-weighted priorities first, and due dates are used before scheduled dates when priority values tie. Thanks to @Glint-Eye for reporting this and @kacoroski for the follow-up. +- (#922) Made the \`Blocked\` task-card pill expand the blocker tasks, and rendered \`blockedBy\` dependencies as clickable links when that property is shown on cards. Thanks to @prayidae for reporting this and following up. +- (#919) Fixed exported ICS task events so they use valid calendar event statuses and can be imported by stricter calendar apps. Thanks to @benoitjadinon for reporting this. +- (#1213) Fixed embedded Task List Bases in Obsidian pop-out windows so typing below the embed no longer leaves a large blank gap. Thanks to @same774 for reporting this. +- (#1243) Removed quoted multi-word custom field NLP expressions from created task titles after saving the custom field value. Thanks to @Arachnidai for reporting this. +- (#1252) Hardened the calendar-first task date picker for iPad taps so date buttons use direct touch manipulation. Thanks to @alxandrharris for reporting this. +- (#1261) Removed the extra Task List Base scrollbar when an embedded task list note is placed in a sidebar, while keeping normal embedded task lists scrollable in the main note area. Thanks to @cathywu for reporting this. +- (#1347) Lowered TaskNotes task-card tag CSS specificity so hierarchical tag colors from Obsidian themes and tag-color plugins can apply correctly. Thanks to @3Fish for reporting this. +- (#1374) Recognized status and priority labels entered through Obsidian Properties or Bases as their configured TaskNotes values. Thanks to @phortx for reporting this. +- (#1373) Parsed numeric natural-language dates with the configured calendar locale, so \`en-GB\` treats \`11/06/2026\` as 11 June instead of November 6, and \`YYYY/MM/DD\` works consistently. Thanks to @AleMunin for reporting this and @imsuck for the follow-up. +- (#1370) Prevented recurring task series from being queued for auto-archive when their parent status uses auto-archive, so ongoing recurring tasks are not moved away after completing an occurrence. Thanks to @Jomo94 for reporting this and @martin-forge for the follow-up discussion. +- (#1367) Made recurring task completion counts use the total expected instances for finite \`COUNT\` or \`UNTIL\` recurrences, and stopped showing a made-up percentage for unbounded recurrences. Thanks to @saurinni for reporting this. +- (#1365) Preserved email and other URI links from converted inline task titles by moving the original links into the new task body, and rendered \`message:\`/\`mailto:\` markdown links as external links in TaskNotes surfaces. Thanks to @phillipadsmith for reporting this and @hasanyilmaz for the follow-up. +- (#1350) Refreshed inline task widgets in Reading mode after task property edits, so changed dates and other visible properties no longer stay stale until the note is reopened. Thanks to @tmsbn for reporting this. +- (#1329) Pulled the relationships widget up to the end of the note content without removing its normal spacing, and kept that placement updated while editing and on load so it no longer covers the editor. Thanks to @Volker-brdb for reporting this. +- (#1326) Treated empty task frontmatter values as missing, so empty titles fall back to the filename and blank date, priority, and recurrence fields are ignored. Thanks to @craziedde for suggesting this. +- (#1316) Stopped stale Workspace state from overriding the configured Calendar view mode, so switching Workspaces no longer forces an old Day/Week/List choice over the view default. Thanks to @kmaustral for reporting this and following up. +- (#1302) Read task frontmatter directly from the task file when Obsidian has not indexed its metadata yet, so visible tasks can still be opened, updated, and selected instead of reporting "Task not found". Thanks to @WorldTeacher for reporting this and @Steven-AA for confirming it. +- Kept just-written task data available while Obsidian's metadata cache catches up, so immediate reads after task edits no longer briefly return stale values. +- (#1297) Made the Create or open task footer tappable, so mobile users can create the typed task without needing the Shift+Enter shortcut. Thanks to @slipstyle for reporting this. +- (#1288) Allowed formula properties to appear in Calendar property-based event start and end date selectors. Thanks to @hasanyilmaz for reporting this. +- Made TaskNotes Kanban drags show a lightweight held-card preview, so the dragged card remains easy to track while the source column opens the drop slot. +- (#1423) Refreshed TaskNotes Bases views when subtasks are deleted, so expanded project cards drop removed subtasks and stop showing project controls when the last subtask is gone. Thanks to @normenmueller for reporting this. +- (#1419) Kept custom user field name, key, and default-value edits in Task Properties settings when closing settings without first blurring the field. Thanks to @s33a for reporting this and @kacoroski for the follow-up. +- Reduced redundant settings writes by coalescing overlapping saves, so settings changes made in quick succession finish with the latest values without repeating every intermediate save cycle. +- (#1331, #1411) Made Agenda Calendar Bases respect the Base sort order within each day instead of falling back to alphabetical title order. Thanks to @bane73 and @ky1ejs for reporting this. +- (#1383) Made task modal markdown editors expose the active editor API expected by plugins such as Templater. Thanks to @tomsymonds for reporting this. +- Fixed the first-run Create/Edit Task modal so the default fields appear immediately after installing TaskNotes, without needing to open Modal Fields settings or restart Obsidian. +- (#1895) Restored the natural-language preview in the Create Task modal. Thanks to @ssonhub for reporting this. +- (#1898) Cleared stale Calendar time-axis column widths when switching views, so Day, Week, and 3-day views keep the time labels anchored on the left. Thanks to @ddevaal for reporting this. +- (#1439) Fixed generated Bases dependency filters so \`blockedBy\` entries stored as links, strings, or dependency objects are handled consistently in Not Blocked and Relationships views. Thanks to @prayidae for reporting this and following up. +- (#1435) Prevented malformed task dependency, status, or priority values from breaking the task context menu. Thanks to @23maverick23 for reporting this. +- (#1434) Kept older filename-titled tasks readable after turning off "Store title in filename" by falling back to the filename when a task has no usable title property. Thanks to @hujuDev for reporting this. +- (#1433) Made the Due date and Scheduled date weekday picker follow the configured first day of week. Thanks to @sandchipper for reporting this. +- (#1430) Showed custom user-field property keys in Modal Fields settings instead of internal field IDs. Thanks to @JerryLu086 for reporting this. +- (#1427) Fixed project autosuggest Required Tags filters so frontmatter tags parsed by Obsidian are handled the same way as direct tag-property filters. Thanks to @ProHaller for reporting this. +- (#1495) Added an Update default files action for generated Bases views, so task-tag or task-identification setting changes can refresh existing \`.base\` filters without deleting files manually. Thanks to @Liya430 for reporting this. +- (#1512) Prevented the split Create/Edit Task modal details pane from collapsing to a one-character-wide column under the Minimal theme. Thanks to @willfanguy for reporting this and sharing detailed CSS notes. +- (#1524) Fixed task-card font sizes shrinking when a Bases view is opened in an Obsidian pop-out window. Thanks to @Glint-Eye for reporting this. +- (#1535) Fixed the generated Relationships Base Subtasks filter so single project links do not trigger a Bases \`contains\` error. Thanks to @DanaKyle for reporting this. +- (#1102) Refreshed task cards when a task status is edited directly in Obsidian frontmatter, so the card no longer stays on the old status until it is clicked. Thanks to @Wayment9504 for reporting this. +- (#1105) Added an explicit Close action to the mobile task options menu, so iPhone users do not need to tap near the top system bar to dismiss it. Thanks to @J-R-Troutman for reporting this. +- (#1550) Prevented mobile Calendar event drags from opening the task context menu before the drag can begin. Thanks to @stil-sudo for suggesting this. +- (#1563) Removed duplicate entries from Calendar event related notes when the same linked file is also a TaskNote. Thanks to @VarunNikam22 for reporting this. +- (#1566) Rendered grouped multi-project values as individual links when a Bases group title contains multiple project links. Thanks to @ptsouchlos for suggesting this. +- (#1569) Allowed local ICS calendar paths inside the vault to be pasted as absolute filesystem paths, and showed a clearer error when the file is outside the vault. Thanks to @Photon89 for reporting this and following up. +- (#1584) Sanitized task-card status and priority class names, so custom values with spaces no longer create invalid CSS classes. Thanks to @omber for reporting this. +- (#1587) Stored dependencies added from the task context menu as wikilinks, matching the Edit Task modal. Thanks to @mgrecar for reporting this. +- (#1590) Clarified HTTP API task creation docs and OpenAPI schema for writable \`blockedBy\` dependencies, and marked \`blocking\` as a read-only derived relationship. Thanks to @hGriff0n for reporting this. +- (#1591) Added a startup guard that avoids saving default settings over an existing settings file if Obsidian temporarily returns no plugin data during an update. Thanks to @GGlider for reporting this. +- (#1593) Made the New button in TaskNotes Bases views open the TaskNotes create task modal again, so new tasks respect the configured default tasks folder. Thanks to @katlandreth for reporting this. +- (#1594) Made task cards inside recurring task notes complete the task's current scheduled occurrence instead of today's date when no calendar or view date is supplied. Thanks to @ngraham20 for reporting this. +- (#1601) Prevented overlapping Live Preview relationship-widget injections from leaving duplicate subtask/relationship sections in a note. Thanks to @wealthychef1 for reporting this and @benmartinek for confirming it. +- (#1610) Made expanded subtasks in TaskNotes Bases views follow the current view's sorted task order instead of a fixed fallback order. Thanks to @MrZzard for reporting this and @slipstyle for confirming it. +- (#1609) Restored scrolling in wide split-layout task edit modals when the form content is taller than the modal. Thanks to @3zra47 for reporting this. +- (#1614) Wrote unchecked boolean custom user-field defaults to new task frontmatter, including tasks created through instant conversion. Thanks to @kobalteule for reporting this. +- (#1611) Made generated default Bases urgency scores fall back safely when the next-date distance is missing. Thanks to @benoitjadinon for reporting this and suggesting the formula fix. +- (#1623) Honored "Store title in filename" across task creation and edits, so the mapped title property is omitted from frontmatter and stale title fields are removed on save. Thanks to @VenturaNotes for reporting this, and to @Ender367, @slipstyle, and @loukandr for confirming and tracing affected paths. +- (#1621) Made Kanban swimlane labels stop freezing on mobile and kept their label column compact, leaving more room for task cards while horizontally scrolling. Thanks to @karenchoe428 for reporting this. +- (#1615) Detected Obsidian custom multi-text properties exposed through \`widget: "multitext"\` as list properties, so Kanban can split those values into multiple columns. Thanks to @konton71 for reporting this. +- (#1626) Expanded recurring ICS subscription events through the one-year subscription window for high-frequency recurring calendars. Thanks to @pib for reporting this. +- (#1628) Refreshed Calendar Bases views promptly when switching between filtered Agenda views, so the previous view's task set does not stay visible until the delayed refresh. Thanks to @Lanalangz for reporting this. +- (#1629) Saved \`blockedBy\` dependencies selected in the Create Task modal. Thanks to @obsilover for reporting this. +- (#1634) Aligned custom status icons in inline tasks with the default inline status circle. Thanks to @ttlaylor for reporting this and @basbarten for confirming it. +- (#1636) Restored the active styling for the Calendar list-view toolbar button. Thanks to @vroablec for reporting this. +- (#1493, #1638) Kept task time tracking consistent when switching or clearing tasks during an active Pomodoro. Thanks to @ROS-SDN and @katonapng for reporting this, and to @anomatomato for confirming it. +- (#1639) Respected the aliased-link overlay exclusion in Reading mode even when the alias text matches the task title. Thanks to @MiracleXYZ for reporting this. +- Fixed actively tracked task cards so the blue time-tracking outline stays visible along the card edges. +- (#1657) Preserved Bases view defaults when creating tasks from the TaskNotes Kanban/List view New button, so project-scoped views can pass their project assignment into the create task modal. Thanks to @casualQuads122 for reporting this. +- (#728, #1831) Preserved frontmatter defaults supplied by Obsidian's Bases New action when opening the TaskNotes create task modal from custom Bases views, so filtered views can prefill matching tags, projects, contexts, and custom fields. Thanks to @DillPickle80 and @echo-saurav for suggesting this, and to @prayidae and @renatomen for the detailed follow-up. +- (#726) Added an instant-conversion option to use the closest heading above the converted line as a project, so checkbox tasks under project headings can inherit that project automatically. Thanks to @ghelton for suggesting this. +- (#1662) Preserved frontmatter from ICS event note templates when quoted event variables or Templater expressions are used. Thanks to @victorhg for reporting this. +- (#1663) Fixed Japanese and other Unicode tags on task cards so Kanban tag pills keep the same rounded styling as ASCII tags. Thanks to @kutty-1119 for reporting this. +- (#1649) Restored daily-note navigation from the Calendar Day view date header. Thanks to @BaccanoMob for reporting this. +- (#1648, #1665) Fixed the API endpoint list in Integrations settings so it uses the configured bearer token when API authentication is enabled, instead of reporting the running local server as inaccessible. Thanks to @npondel and @warm-july for reporting this. +- (#1668) Fixed the Create Task magic wand so NLP-triggered custom field values are copied into the custom property inputs before saving. Thanks to @hokfujow for reporting this. +- (#1669) Stopped the startup settings migration check from rewriting \`data.json\` just because saved calendar defaults are \`false\`, \`0\`, empty, or \`null\`, reducing unnecessary sync churn. Thanks to @thehyperadvisor for reporting this. +- (#1674) Improved the timeblock creation error when Daily Notes cannot read its configured folder, so the modal notice points to the Daily Notes core plugin settings instead of only logging the folder lookup failure. Thanks to @Ender367 for reporting this. +- (#1680) Fixed TaskNotes Calendar Bases options stored under \`options\`, so Agenda views respect \`showPropertyBasedEvents: false\` and no longer show duplicate property-based rows for the same task. Thanks to @xiaoyaozhu1991 for reporting this and @KondrotM for confirming it. +- (#1681) Reduced the cost of inline checkbox convert buttons by only scanning the visible editor range instead of the full document. Thanks to @en-ot for reporting this and @hokfujow for the follow-up. +- (#1689) Fixed task reminders added or rescheduled through direct frontmatter edits so the notification queue refreshes immediately and relative reminders recalculate from the latest task dates. Thanks to @garzonjav for reporting this. +- (#1693) Fixed generated default Bases formulas so empty due and scheduled dates are checked with \`.isEmpty()\` instead of date-field truthiness. Thanks to @benoitjadinon for reporting this. +- (#1702) Removed the forced bottom gap under TaskNotes custom Bases views, so calendar and other TaskNotes views can fill the available pane height. Thanks to @AudreyLooby for reporting this. +- (#1719) Fixed task cards in reading mode so Obsidian 1.12.x header changes no longer place the card above the title and properties or drop it after returning to a tab. Thanks to @tholbrook9 for reporting this and tracing the DOM change. +- (#1722) Saved the source note immediately after converting an inline checkbox task to a TaskNote, so Kanban views do not keep showing the stale inline task alongside the new task file. Thanks to @literallydope for reporting this and sharing screenshots. +- (#1750) Fixed generated default Bases filters for property-based task identification when the identifying property name contains spaces. Thanks to @Igorgro for reporting this. +- (#1745) Clarified the inline task documentation so \`Create new inline task\` is distinguished from current-line conversion. Thanks to @yvos for reporting the mismatch. +- (#1485) Stopped Google Calendar manual refresh from showing a success notice after token refresh or calendar-list failures. Thanks to @ebanDev for reporting this. +- (#1474) Made priority-based Kanban swimlanes follow the configured priority order instead of alphabetical task data order. Thanks to @kanzaki1201 for reporting this and @SoTHISIsFitness for the follow-up investigation. +- (#1470) Restored pointer cursors on TaskNotes interactive elements under Obsidian themes that set \`--cursor\` to the default cursor. Thanks to @TheFrostedDev for reporting this. +- (#1463) Documented the supported \`FilterQuery\` payload for \`POST /api/tasks/query\`, including context filtering examples and generated API schema details. Thanks to @tcb678 for reporting this and @soloidx for sharing a working query example. +- (#1464) Made \`context\` on \`GET /api/tasks\` follow the same filtering guidance as \`project\`, so the API now points clients to \`POST /api/tasks/query\` instead of ignoring the parameter. Thanks to @tcb678 for suggesting this. +- (#1457) Rendered scheduled-to-due calendar spans with scheduled times as daily timed events instead of moving them to the all-day section. Thanks to @atos2212-blip for reporting this and @rayvermey for confirming it. +- (#1450) Returned configured user fields in HTTP API task responses under \`customProperties\`, while keeping the configured frontmatter keys available on each task. Thanks to @Admorei for reporting this and @nschenone for the follow-up. +- (#1449) Let embedded Agenda views use auto-height sizing by default, so one-day list embeds no longer reserve a large empty calendar block. Thanks to @GlebYavorski for reporting this. +- (#1446) Kept custom Kanban columns from \`columnOrder\` available when they are empty, so \`hideEmptyColumns: false\` can show drop targets for custom grouped values. Thanks to @akhtsang for reporting this. +- (#1459) Avoided double "Failed to create task" prefixes in task creation error notices. Thanks to @Sineapple for reporting this, and to @slipstyle and @Stockemer for the follow-up investigation. +- (#1469) Fixed Convert current note to task so saving the untouched edit modal writes the task frontmatter instead of reporting no changes. Thanks to @slipstyle for reporting this, and to @jhoogeboom and @ngraham20 for confirming it. +- (#1466) Prefilled the current note as the project when creating a task from an embedded Subtasks/Relationships Base filtered with \`this.file.asLink()\`. Thanks to @jhoogeboom for reporting this, and to @cybersader, @fsmontenegro, and @benmartinek for the follow-up discussion. +- (#1476) Showed linked parent-task project titles instead of timestamp filenames in project stats and grouped task views when the linked task has a frontmatter title. Thanks to @RumiaKitinari for reporting this. +- (#1487) Let Calendar task event titles wrap instead of clipping long names, and removed the redundant due-date prefix from due task events. Thanks to @Alexander-Bergmann for reporting this. +- (#1488, #1739) Enabled Kanban touch dragging on touch-capable desktop and convertible devices, not only mobile Obsidian. Thanks to @tmoyland001 and @mgsima for reporting the drag failures, and @SoTHISIsFitness for investigating related task-property cases. +- (#1738) Fixed Outlook calendar subscriptions whose event timezones reference the base Windows timezone name while the feed defines a suffixed timezone name. Thanks to @Mirrimo for reporting this, @rafavital for confirming it, and @rogerfsh for tracing the ICS timezone mismatch. +- (#1734) Fixed dependency picker search when task priority values are stored as non-string frontmatter values. Thanks to @MatthewClarkeDev for reporting this and identifying the stack trace. +- (#1733) Preserved wikilinks in task titles and rendered them as clickable links on task cards. Thanks to @bitscorch for suggesting this. +- (#1728) Applied the "Use parent note as project" default when creating a new task from the command palette or ribbon. Thanks to @greatEmily for reporting this. +- (#1759) Advanced stale due dates when recurring tasks move to their next scheduled occurrence, so work-window tasks do not remain overdue after completion. Thanks to @MattPryze for reporting this. +- (#1766) Fixed Calendar Bases date navigation from custom note properties, so embedded calendar views can open on the date stored in the selected property instead of falling back to today. Thanks to @chrabia for reporting this. +- (#1767) Aligned the start and end time rows in the timeblock creation modal. Thanks to @loiveli for reporting this. +- (#1783) Replaced the default browser drag ghost for Kanban cards so dragging a card no longer makes the next card look semi-transparent. Thanks to @loukandr for reporting this and tracing the drag image behavior. +- (#1796) Restored expanded subtasks immediately after renaming a parent task file and updating links. Thanks to @bung69 for reporting this. +- (#1797) Improved manual ordering so long Kanban columns remain scrollable while dragging, mobile Kanban drops can place a card relative to another card, Kanban/Task List drops resolve the final drop position more reliably, generated manual-order ranks match Bases sorting, and manual-order properties such as \`sort_order\` render on task cards when enabled. Thanks to @SKIERZZ for reporting this and sharing videos. +- (#1812) Separated Microsoft OAuth token status from calendar sync status, and surfaced Microsoft calendar fetch errors in the integrations settings card instead of leaving them console-only. Thanks to @henninger80 for the detailed report. +- (#1814) Restored NLP project autosuggest in the Create or Open Task command, so \`+\` project suggestions use the same filtered project lookup as the Create Task modal. Thanks to @adammahad for reporting this. +- (#1820) Kept API-created tasks readable immediately after creation even if Obsidian has not finished indexing the new file metadata yet. Thanks to @vadminas for reporting and tracing the cache desync. +- (#1823) Prevented zero-duration timed external calendar events from rendering under more than one day in list-style calendar views. Thanks to @martin-forge for reporting and tracing the Google Calendar case. +- (#1841) Prevented Kanban boards from duplicating columns when wikilinked status values are grouped through Bases. Thanks to @lendamico for reporting and sharing the screen recording. +- (#1846) Saved NLP-triggered boolean custom fields as real booleans instead of quoted strings, so they match checkbox-created values and Bases filters. Thanks to @DevOps-Toast for reporting and sharing screenshots. +- (#1849) Prevented repeated clicks on task-card scheduled and due date labels from stacking duplicate date menus when Obsidian native menus are disabled. Thanks to @3zra47 for reporting. +- (#1850) Added mobile bottom spacing to TaskNotes list views so the final task can scroll above Obsidian's floating mobile controls. Thanks to @AlejandroRigau for reporting and sharing the iPhone screenshot. +- (#1852) Improved mobile timed calendar event rendering with shorter time labels, tighter spacing, and event-colored task/calendar blocks. Thanks to @redrumthebum for reporting and sharing screenshots. +- (#1757, #1853, #1775) Respected an existing \`mdbase.yaml\` \`types_folder\` when regenerating mdbase task type definitions, so the generated \`task.md\` can live outside the vault-root \`_types\` folder. Thanks to @aldrichtr for the original request and implementation exploration, and @hangryscribe3 for the follow-up request. +- (#1858) Included task body details in single-task HTTP API and MCP reads. Thanks to @vanillaflava for reporting and outlining the expected behavior. +- (#1859) Clarified the Google Calendar setup guide for OAuth testing-mode \`access_denied\` errors. Thanks to @PE-Boy for reporting and @tiagoarroz for the workaround. +- (#1860) Preserved accented characters in tags when converting checkbox tasks to TaskNotes. Thanks to @e-zz for reporting. +- (#1869) Preserved Calendar Month View scroll position after task updates. Thanks to @sisyowo for reporting and linking the earlier Kanban fix. +- (#1873) Prevented Calendar Bases from rendering in Obsidian pop-out windows because restoring FullCalendar there can freeze Obsidian. Thanks to @misolex for reporting. +- (#1497, #1870) Fixed NLP file suggestions for custom fields so selected wikilinks are captured as custom field values, including list-type fields. Thanks to @Naesue and @Sineapple for reporting this, and to @bradleyed and @Xananax for the follow-up details. +- (#1888) Allowed project autosuggest required property filters to match any comma-separated value, such as \`project, area\`. Thanks to @BrianHicks for suggesting. +- (#1886) Added a command to postpone active overdue scheduled tasks to today. Thanks to @chrabia for the suggestion. +- (#1889) Fixed Kanban swimlanes for list-valued properties so tags and contexts use individual list items instead of comma-joined values. Thanks to @pkropotin for reporting. +- (#1890) Fixed scheduled-date Kanban columns dropping tasks when date-only and timed tasks on the same day are sorted by a scheduled-time formula. Thanks to @chrabia for reporting and investigating. +- (#773) Added ICS export filters for archived tasks, completed tasks, due dates, and scheduled dates. Thanks to @ras0q for suggesting this and @slipstyle for the scheduled-date follow-up. +- (#765) Reduced side-pane gutters around embedded TaskNotes Bases views, so embedded task lists use about the same horizontal space as directly opened Bases views. Thanks to @TonyAtlas for suggesting this. +- (#1892) Fixed nested Markdown list indentation in the Task Edit Modal details editor. Thanks to @Glint-Eye for reporting. +- (#1891) Fixed TaskNotes modal markdown editors collapsing to one-character-wide lines when Pretty Properties is installed. Thanks to @bkennedy-improving for reporting. +- (#1499) Respected excluded folders when opening tasks directly from view results and when building dependency/project indexes, so template-folder tasks no longer appear through TaskNotes views. Thanks to @Liya430 for reporting. +- (#136, #1500) Made the Pomodoro countdown derive remaining time from the session clock instead of from counted interval ticks, so delayed, backgrounded, or screen-off ticks catch up cleanly without over-recording a completed session. Thanks to @Poly-0000 for reporting and documenting the original background timer issue, @Totobal5 for the earlier worker-based fix, and @CoffeaUrbana for the Android screen-off report. +- Restored padding in task modal Markdown editors. +- Made the markdown editor areas in task modals easier to click and focus. +- Strengthened local CSS linting to catch unscoped selectors, unknown CSS, and fixed-position overlays before review. +- Reduced false-positive plugin review warnings by making background auto-export and auto-archive schedulers non-overlapping and tightening type/string conversion paths. +- (#1882) Made Google Calendar task descriptions use mobile-friendly plain text for Obsidian links and display labels for wiki-style project/context links. Thanks to @martin-forge for the contribution. +- (#1883) Improved Google Calendar task sync recovery so failed deletions, offline sync requests, reconnects, and quick create/update races are retried more reliably. Thanks to @martin-forge for the contribution. +`});var zve,Bve=y(()=>{zve=`# TaskNotes 4.7.2 + +## Changed + +- Improved local lint checks so package and CSS issues reported by Obsidian's online review can be caught before submission. +- Cleaned up stylesheet compatibility issues reported by Obsidian's online review without changing the intended TaskNotes appearance. +- Improved spacing and alignment in task, timeblock, and webhook modals after the stylesheet cleanup. +- Reworked optional calendar and ICS subscription refresh scheduling to avoid interval-based network polling while preserving the same refresh intervals. +- Cleaned up additional source patterns reported by Obsidian's online review, including unsafe default object stringification and redundant external type unions. +- Prevented a console error when plugin listeners are cleaned up after reloads. +- Added a local lint check to prevent interval-based polling in files that also perform network requests. +`});var jve,$ve=y(()=>{jve="# TaskNotes 4.7.1\n\n## Changed\n\n- Release assets are now built with GitHub artifact attestations so users and reviewers can verify the provenance of `main.js`, `manifest.json`, and `styles.css`.\n"});var Uve,Hve=y(()=>{Uve=`# TaskNotes 4.7.0 + +## Changed + +- Enabled lint checks that mirror Obsidian community plugin review findings, including dynamic code execution, Promise handling, deprecated APIs, unsafe stringification, directive comments, Node built-in imports, and explicit \`any\` usage. +- Clarified privacy documentation for optional integrations that make periodic background network refreshes. +- Cleaned up internal Obsidian and Bases compatibility adapters used by search and grouped views. +- (#1839, #1881) Updated default Base urgency scoring so timed tasks earlier in the day sort above later tasks with the same priority and date + - Thanks to @loukandr for the contribution + +## Fixed + +- Fixed project autocomplete searches so non-empty \`+\` queries only return files matching the query in the basename, title, aliases, or explicitly searchable metadata rows. +- (#1713) Fixed all-tasks ICS export when a task uses a space-separated scheduled datetime such as \`2025-08-12 18:00\` + - Thanks to @bepolymathe for requesting this and @m4to-3pe for following up +- Fixed Pomodoro stats reopening immediately after a plugin reload before the Pomodoro service has finished initializing. +- (#1872) Fixed unarchiving moved tasks so the destination task folder processes template variables such as \`{{project}}\` before moving the file + - Thanks to @OXI-717 for reporting +- (#1870) Fixed custom user field NLP triggers with file autosuggest so selecting a wikilink suggestion stores the link in the user field instead of leaving it in the task title + - Thanks to @Sineapple for reporting +- (#1878) Fixed completed tasks still appearing as active blockers for dependent tasks + - Thanks to @macbikegeek for reporting +- (#1880) Fixed the status bar time-tracking label for task titles that contain a dash + - Thanks to @ubidev for reporting +- (#1854) Fixed modal task completion so completed tasks receive a completed date consistently + - Thanks to @misolex for reporting +- (#1124, #1838, #1881) Fixed default Base views and formulas excluding tasks scheduled or due today at a non-midnight time from day-level comparisons + - Thanks to @kmaustral for reporting and @loukandr for the fix + +## Removed + +- Removed JavaScript webhook transform support and examples. JSON webhook transform templates remain supported. +`});var Vve,Wve=y(()=>{Vve=`# TaskNotes 4.6.0 + +## Changed + +- TaskNotes now requires Obsidian 1.12.2 or later, matching the Obsidian APIs used by the plugin. +- Improved internal code quality by resolving lint warnings, moving static inline styles into CSS utilities, and extending sentence-case lint coverage to English localization strings, with no intended behavior changes. + +## Fixed + +- Fixed TaskNotes failing to load when Obsidian opened without an active Markdown file. +`});var qve,Gve=y(()=>{qve=`# TaskNotes 4.5.3 + +## Fixed + +- (#1834, #1847) Fixed empty Bases formula and custom properties showing \`null\` or \`undefined\` on TaskNotes task cards. + - A big thanks to @Glint-Eye and @3zra47 for reporting. +- (#1836) Fixed TaskNotes Bases views not refreshing task cards after status, archive, and auto-archive updates. + - A big thanks to @kmaustral for reporting. +`});var Yve,Kve=y(()=>{Yve=`# TaskNotes 4.5.2 + +## Added + +- (#1342, #1793) Added native tag autocomplete to time entry descriptions by using the embedded markdown editor in the time entry editor modal. + - Thanks to @fastrick for the request and @renatomen for the PR. +- (#1756, #1798) Added HTTP API support for configured custom user fields so task responses include them and create/update requests can round-trip their values. + - Thanks to @Treygec for the request and PR. +- (#1777) Added a Modal Fields setting to choose whether Tab/Shift+Tab move focus out of the task details editor or use the markdown editor's indentation behavior. + - Thanks to @P-Sc for the PR. + +## Changed + +- Updated the Obsidian API dependency to 1.12.3 and switched the Bases integration to the official API type declarations. +- Bases task cards and property-event cards now render metadata values through Obsidian's native Bases value renderer so links, dates, lists, icons, and formula values display more faithfully. + +## Fixed + +- (#1778) Fixed MCP initialize requests using newer protocol versions such as \`2025-11-25\` failing instead of negotiating down to TaskNotes' supported MCP version. + - Thanks to @SakulaPor for reporting. +- (#1781) Fixed duplicate metadata properties on Bases task cards when bare and \`note.\`-prefixed property IDs map to the same TaskNotes field. + - Thanks to @loukandr for reporting and tracing the issue. +- (#1787) Removed the "(click to change)" helper text from recurrence tooltips on task cards. + - Thanks to @kazerniel for reporting. +- (#1828) Fixed subtask creation from a task card dropping the parent task project when natural-language input also adds projects. + - Thanks to @prepare4robots for reporting. +- (#1786) Fixed TaskNotes task cards and relationships/subtasks widgets appearing inside embedded task-note heading or block sections. + - Skips note-level widget injection in detached or embedded Markdown editor contexts used by plugins such as Block Link Plus. + - Thanks to @3zra47 for reporting. +- (#1815) Fixed the Priority property settings so the NLP trigger character field is visible and editable even when priority NLP parsing is disabled. + - Thanks to @spiv for reporting. +- (#1035) Fixed the task modal title field causing the modal to jump to the bottom when focused on iPhone. + - Thanks to @3zra47 for reporting and following up. +- (#1045) Fixed inline linked recurring tasks keeping the previous day's completed state after the calendar day changes. + - Thanks to @3zra47 for reporting and following up. +- (#1788) Fixed Task List subgroup headers and cards rendering without clear indentation. + - Thanks to @renatomen for the PR. +- (#1810) Updated Japanese Kanban terminology to use the more natural katakana spelling. + - Thanks to @sigma7863 for the PR. +- (#1633) Fixed Bases task cards using fallback labels instead of Bases display names for mapped task fields and file properties. + - Thanks to @Sarryaz for reporting the Bases task card i18n and field-mapping issue. +- (#884) Fixed untranslated strings and English placeholder examples across non-English interface translations. + - Thanks to @berzernberg for reporting Russian translation gaps. +- (#1765, #1769) Fixed auto-archived tasks leaving stale Google Calendar events when cleanup runs before calendar sync is ready or after the task moves into the archive folder. + - Thanks to @martin-forge for reporting and the PR. +- (#1764) Fixed Google Calendar sync using stale task metadata after rapid task updates, and fixed late recurring completions/skips recording the completion day instead of the scheduled occurrence date. + - Thanks to @martin-forge for the PR and to @jpmoo for reporting the recurring completion issues. +- (#1782) Fixed CI test runs resolving the NLP parser package from a local sibling checkout instead of the published dependency. + - Thanks to @martin-forge for reporting. +- Published [\`mdbase-tasknotes\`](https://github.com/callumalpass/mdbase-tasknotes) 0.1.3 with compatibility fixes for TaskNotes-generated mdbase schemas. + - Includes clearer create-path diagnostics, natural-language \`mtn list --due\` filters, timer log datetime filters, home-directory path expansion, project wikilink preservation, and correct \`mtn --version\` reporting. + - Thanks to @tparsons9, @anomatomato, @npondel, @plashal, and @waspeer for the reports and PR. +- (#1667) Fixed NLP scheduled-date parsing so standalone \`scheduled\` and \`start\` triggers can set scheduled dates alongside due dates. + - Thanks to @hokfujow for reporting and @UniqueClone for the NLP core PR. +- Fixed NLP parser title cleanup for explicit date triggers and Japanese/Chinese priority phrases. +- (#1658) Fixed Pomodoro stats date bucketing for sessions near local midnight. + - Pomodoro session stats now compare the recorded session calendar date against UTC-anchored target days without shifting through UTC or the reader's current timezone. + - Pomodoro daily-note storage now writes sessions to the daily note matching the recorded session date. + - Thanks to @ewgdg for reporting, @AntonIlinykh and @dkchacha for follow-up discussion, and @ITblacksheep for PR #1758. +- (#1813) Fixed Pomodoro timer UI stalls caused by refreshing session statistics on every timer tick. + - Pomodoro stats now refresh on initial render and session completion instead of once per second. + - Pomodoro daily-note stats now read the relevant date/range instead of routing through all history. + - Native Pomodoro notifications now respect the notification setting and granted permission before showing. + - Thanks to @Szu-Szu for reporting and @its-thex for confirming. +- (#1744) Fixed Bases Task List views so changing the per-view \`Expanded relationships\` option takes effect on re-render. + - Restores the expected \`show-all\` behavior for setups that hide subtasks at the top level with \`note.projects.isEmpty()\`. + - Thanks to @minol-dev for reporting, @Glint-Eye for follow-up discussion, and @stanley-910 for PR #1792 exploring the related standalone-subtask workflow. +- Fixed tag clicks in task cards opening the task edit modal in addition to the tag search panel, and kept rendered tag metadata on a single row inside task cards. +`});var Zve,Qve=y(()=>{Zve=`# TaskNotes 4.5.1 + +## Fixed + +- (#1672) Fixed custom date ranges in the MCP time summary tool so \`from\` and \`to\` dates work as expected + - Thanks to @pib for the fix +- (#1742) Fixed calendar week and day views so the time scale stays aligned on the left instead of drifting inward + - Thanks to @ysafonov for the report and screenshot +`});var Jve,Xve=y(()=>{Jve=`# TaskNotes 4.5.0 + +## Fixed + +- (#1652) Fixed API, MCP, and NLP task creation so it respects your configured filename format when title storage in filenames is disabled + - Thanks to @36mimu36 for reporting, and @rafavital and @warm-july for follow-up discussion and reports +- (#1601, #1709) Fixed reading-mode relationship widgets sometimes rendering multiple times during startup + - Applied the same protection to task cards so overlapping refreshes are coalesced there too + - Thanks to @wealthychef1 and @CarlJohnson99 for reporting, and @benmartinek for confirming the behavior +- (#1713) Fixed ICS export so date-only scheduled tasks are written as all-day events instead of midnight events + - Thanks to @bepolymathe for the request and interoperability details +- (#267, #948, #1682, #1717, #1725) Fixed expanded subtasks and dependency cards in Bases Task List and Kanban views so related items can inherit the current view's filters instead of always showing every linked task + - Added a per-view "Expanded relationships" option so you can switch between inherited filters and showing all related tasks + - Thanks to @mdbraber, @GardarikanetS, @Glint-Eye, @prepare4robots, and @robmcphers0n for the original reports and feature requests, and @marblebyte for follow-up discussion +- Improved custom view and search-pane activation when reopening deferred tabs +- (#1720) Fixed Bases Task List cards showing icon tokens such as \`clock\` instead of readable date-like values, and fixed property labels to use Bases display names instead of raw property IDs + - Thanks to @Sirnii for reporting +- (#1633) Fixed interactive task-card labels and ribbon labels so Bases-backed cards use translations and configured display names instead of hardcoded English or raw property IDs + - Thanks to @Sarryaz for reporting +- (#1651) Fixed date \`is\` query filtering so date-only searches also match timed \`scheduled\` and \`due\` values during prefiltering + - Thanks to @36mimu36 for reporting +- (#1644) Fixed generated default task views so recurring tasks without a \`complete_instances\` property still appear as incomplete where appropriate + - Thanks to @bkennedy-improving for reporting, and @SandroK for follow-up discussion on related default-view behavior +- (#1513, #1686) Fixed a calendar issue where creating or editing events and timeblocks could reset the visible date back to today + - In-place calendar recreation now preserves the visible date unless you explicitly navigate elsewhere + - Thanks to @owenoxen for opening #1513, and @Lorite for opening #1686 and contributing the fix +- Fixed documentation deployment CI failures caused by \`docs-builder/src/js/main.js\` being excluded by a broad \`.gitignore\` rule +- Reduced background calendar-sync overhead when persisting sync tokens +- Prevented duplicate auto-stop time-tracking listeners from accumulating after settings reloads +- Fixed a settings-lifecycle issue that could accumulate calendar update callbacks while the Integrations tab is repeatedly opened +- (#1630) Fixed TaskNote inline task cards ignoring centered "Readable line length" layout in the Minimal theme + - Thanks to @martin-forge for reporting +- Fixed a broken docs cross-reference from Property Types Reference to Task Properties settings +- Fixed docs site links so internal Markdown links resolve to app routes instead of broken \`.md\` paths +- Fixed docs release-note links by building Markdown pages even when they are not listed directly in the sidebar + +## Added + +- (#1704) Added an option to widen the current day column in multi-day calendar time-grid views + - You can control the width multiplier and choose whether it applies to week view, custom multi-day view, or both + - Thanks to @dictionarymouse for the feature request +- Added TaskNotes Obsidian CLI commands for task creation, time tracking, and Pomodoro control + - Includes shared NLP-to-task conversion across the CLI, modal, and API capture flows, plus new user documentation for the built-in CLI commands +- (#1716) Added roomier subtask and dependency cards inside the task modal while keeping the task options menu available + - Thanks to @hokfujow for the feature request +- (#1619, #386, #621) Added drag-to-reorder for Kanban and Task List views + - Supports grouped Task List moves, manual ordering via the \`tasknotes_manual_order\` property, and improved drag/drop behavior for swimlanes, filtered views, and interactive task controls + - To use it, sort the view by the Manual Order field (\`tasknotes_manual_order\` by default), or regenerate the built-in \`.base\` templates from **Settings → TaskNotes → General → Create Default Files** + - Thanks to @ac8318740 for the original contribution in PR #1619, @iholston and @dsebastien for opening #386 and #621, and @mdbraber, @elvarb, @LucidToday, @craziedde, @kmaustral, @SKIERZZ, @sookochoff, and @kanzaki1201 for follow-up discussion and testing across the linked issues and PR +- Added a standalone [TaskNotes Specification](https://github.com/callumalpass/tasknotes-spec) repo and docs section covering the data model, field mapping, recurrence behavior, validation rules, and conformance tests +- Added [tasknotes-tui](https://github.com/callumalpass/tasknotes-tui), a terminal UI for working with TaskNotes vaults + - Includes keyboard-driven views, date navigation, time tracking, recurring task support, and a command palette + +## Changed + +- Refactored several internal modules to reduce coupling and make maintenance safer +- Updated generated \`_types/task.md\` output so \`dateCreated\` and \`dateModified\` include generated timestamp values, and \`recurrence_anchor\` defaults to \`scheduled\` +- Cleaned up API, webhook, NLP, privacy, settings, and view documentation for clarity and accuracy +- Expanded Task List and Kanban documentation for drag-to-reorder, including manual-order sorting, grouped and swimlane scope, and filtered-view limitations +`});var eke,tke=y(()=>{eke="# TaskNotes 4.4.0\n\n## Added\n\n- [Mdbase](https://mdbase.dev) type generation now includes `tn_role` annotations so external tools can identify each field's role even when frontmatter names are customized\n- (#1618) Mdbase type matching now follows your task identification settings (tag or frontmatter property), with fallback to tag matching when needed\n - Thanks to @jimbo108108 for reporting\n- Mdbase type status fields now include `tn_completed_values` so external tools can reliably identify which status values count as completed\n- (#1576) Added an optional `Checklist Progress` task-card property that renders a compact progress bar and `completed/total` count from top-level markdown checkboxes\n - Uses metadata cache list items and excludes nested checklist entries so progress reflects top-level task steps\n - In Bases views, map `tasks` (`file.tasks`) to `Checklist Progress`\n - Existing `.base` files need `file.tasks` added to the view `order` YAML manually\n - Newly generated `.base` templates now include `file.tasks` in view `order` by default\n - Thanks to @phortx for opening #1576 and for the earlier implementation PR, and @piyushaswani55 for feedback in the issue discussion\n\n## Changed\n\n- Mdbase type generation no longer overwrites `mdbase.yaml` if the file already exists, preserving user customisations\n- Webhooks now fire consistently regardless of whether updates come from the UI, HTTP API, or MCP\n- Webhook runtime state now syncs automatically when plugin settings change\n- Shared HTTP response/body parsing utilities are now consolidated in a dedicated `httpUtils` module\n- Release notes now include a reminder on every release page that default generated `.base` template changes never overwrite existing user `.base` files, and that users can regenerate templates from Settings to pick up updates\n\n## Fixed\n\n- (#1608) Fixed task title frontmatter being removed when `storeTitleInFilename` is enabled\n - `title` is now retained in frontmatter while filename derivation from title remains unchanged\n - Thanks to @victoraraujo105 for the PR\n- (#1602) Fixed time tracking statistics showing incorrect or zero values for Today/Week/Month due to UTC-anchored date range boundaries in Stats View\n - Updated range calculations to use local calendar-day boundaries consistently\n- (#1602) Fixed inconsistent `timeEntries` timestamp formats across create/edit/drag/resize flows\n - Time entry timestamps are now written in canonical UTC ISO format (`toISOString()` with `Z`) across all write paths\n- (#1602) Fixed denormalized `timeEntries.duration` drift after edits\n - Time tracking calculations now derive duration from `startTime`/`endTime`\n - Time entry save paths now strip legacy `duration` values instead of persisting them\n - Thanks to @dy66 for opening #1602\n"});var rke,nke=y(()=>{rke=`# TaskNotes 4.3.3 + +## Changed + +- Published [\`mdbase-tasknotes\`](https://github.com/callumalpass/mdbase-tasknotes) (\`mtn\`), a standalone CLI for managing tasks in markdown files via mdbase + - Works on the same vault and \`_types/task.md\` schema that TaskNotes generates, without requiring the plugin or HTTP API + - Preferable over [tasknotes-cli](https://github.com/callumalpass/tasknotes-cli) as a lighter-weight alternative and when Obsidian is not running, on remote machines, or in scripts and CI environments + - Supports natural language task creation, time tracking, project aggregation, statistics, and an interactive REPL + +- Extracted shared natural language parsing logic into the standalone npm package [\`tasknotes-nlp-core\`](https://github.com/callumalpass/tasknotes-nlp-core) + - The NLP parser and related language configuration are now shared through this package + - This keeps behavior consistent between the plugin and CLI tools + +## Added + +- (#1549) Added setting to reset markdown checkboxes when recurring tasks are completed + - When enabled, all checked checkboxes (\`- [x]\`) in the task body are reset to unchecked when a recurring task instance is completed and rescheduled + - Useful for recurring tasks with subtask checklists that need to be repeated each instance + - Configurable via Settings > Features > Recurring Tasks > "Reset checkboxes on recurrence" + - Thanks to @phortx for the feature request + +- (#1548) Added ability to create calendar events on connected external calendars directly from the calendar view + - When clicking or dragging to select a time slot, a new "Create calendar event" option appears in the context menu + - Opens a modal to enter event title, description, location, and select which calendar to create on + - Supports both Google Calendar and Microsoft Calendar providers + - Thanks to @Robubble for the feature request + +- (#1597) Added MCP server for AI agent integration + - Exposes TaskNotes tools at \`/mcp\` endpoint, gated behind \`enableMCP\` setting + - Supports tasks (CRUD, query, toggle status/archive, parse from text), time tracking, pomodoro, calendar events, and task statistics + - Thanks to @dstotijn for the contribution + +## Fixed + +- Fixed generated [mdbase](https://mdbase.dev) type definitions for task dependencies using the wrong field type + - In \`_types/task.md\`, \`blockedBy[].uid\` now uses \`type: link\` (was \`type: string\`) + - Better matches how dependency links are serialized in task frontmatter (\`[[...]]\`) + +- Fixed generated mdbase reminder type definitions to better match TaskNotes reminder data + - In \`_types/task.md\`, \`reminders[].type\` now uses enum values \`absolute|relative\` + - \`reminders[].relatedTo\` now uses enum values \`due|scheduled\` + - \`reminders[].absoluteTime\` now uses \`type: datetime\` (was \`type: string\`) + +- (#1597) Fixed webhook payloads for time tracking start-with-description containing stale data + - Thanks to @dstotijn for the fix + +- (#1581) Fixed Pomodoro starting break instead of work session after app restart + - After completing a work session and restarting, pressing Start would incorrectly start a break + - Now properly resets \`nextSessionType\` when clearing stale sessions or stopping the timer + - Thanks to @Sirnii for the detailed bug report and root cause analysis + +- (#1577) Fixed Edit Note/Task modal hiding action buttons when content exceeds viewport height + - Added vertical scroll to modal content area while keeping buttons pinned at bottom + - Thanks to @hossam-elshabory for reporting and @ivannin for helping in discussion + +- (#1600) Fixed kanban view grouping not working when more than 20 views exist + - The \`getGroupByPropertyId()\` method had a hardcoded loop limit of 20 iterations + - Views at index 20 or higher would not be found, causing groupBy to return null + - Thanks to @IHaveNoShame for reporting + +- (#1595) Fixed task modal floating buttons blocking content on mobile + - Added mobile-specific (\`body.is-mobile\`) CSS to ensure proper flex layout + - Button container now stays pinned at bottom without overlapping scrollable content + - Thanks to @Jomo94 for reporting + +- (#1590) Fixed HTTP API not allowing \`blockedBy\` dependencies when creating tasks + - Added \`blockedBy\` field support to \`TaskService.createTask()\` + - Updated API documentation with \`blockedBy\`, \`recurrence\`, and \`reminders\` fields + - Thanks to @hGriff0n for reporting + +- (#1582) Fixed recurring tasks not appearing at end of visible calendar range for non-UTC timezones + - Daily/weekly recurring tasks with times after ~1pm would disappear on the last day of the visible range for users in positive UTC offsets (e.g., UTC+11) + - Fixed date boundary comparisons in both \`generateRecurringInstances()\` and \`generateRecurringTaskInstances()\` to compare dates only, not timestamps + - Thanks to @benefitbug for reporting + +- (#1580) Fixed Google Calendar sync failing after OAuth token expires with unhelpful error message + - When refresh tokens expire or are revoked (e.g., Google Cloud project in Testing mode, user revoked access), the error message was confusing: "Failed to refresh google token: Request failed, status 400" + - Now detects irrecoverable token errors (\`invalid_grant\`, \`invalid_client\`) and automatically disconnects the OAuth connection + - Shows actionable error message: "Google Calendar connection expired. Please reconnect in Settings > Integrations." + - Prevents repeated failed refresh attempts and error message spam + - Thanks to @osxisl for reporting and @Naesue for helping in discussion + +- (#1584) Fixed DOMTokenList error when task status values contain spaces + - Clicking the status ring on a task card threw an error when status contained spaces (e.g., "In Progress") + - Status and priority values are now sanitized before being used as CSS class names + - Thanks to @omber for reporting +`});var ake,ike=y(()=>{ake=`# TaskNotes 4.3.2 + +## Added + +- (#1520) Tag and Context fields in Edit Task modal now show all available suggestions immediately on focus + - Previously required typing at least one character before suggestions appeared + - Already-selected values are excluded from the suggestion list + - Thanks to @Glint-Eye for the suggestion + +- (#1506) Added setting to configure the default color for new timeblocks + - New color picker in Settings > Features > Timeblocking + - Previously hardcoded to indigo; now user-configurable + - Thanks to @phillipadsmith for the suggestion + +## Fixed + +- Fixed [mdbase-spec](https://mdbase.dev) type definition generation not triggering when settings change + +- (#1456) Fixed inline tasks jumping visually when marked as completed + - Thanks to @3zra47 for reporting + +- (#1364) Fixed auto-stop time tracking not triggering when completing recurring task instances + - Thanks to @slipstyle for reporting + +- (#1465) Fixed all-day events synced to Google Calendar receiving wrong notification time + - All-day events now use Google Calendar's configured all-day notification defaults instead of a minutes-based reminder + - Thanks to @Jomo94 for reporting + +- (#1470) Fixed cursor showing as default instead of pointer on interactive elements + - Thanks to @TheFrostedDev for reporting + +- (#1491) Fixed boolean property values being quoted as strings in Bases filter generation + - When using a boolean property (e.g. \`tasknote: true\`) for task identification, the filter now correctly handles the value + - Thanks to @denisgorod for reporting + +- (#1494) Fixed Kanban swimlane resetting to "None" on initial load and after navigation + - Thanks to @tnguyen2018 for reporting + +- (#1555) Fixed "Folder already exists" error when creating tasks or converting inline tasks + - Thanks to @jkune5 for reporting + +- (#1532) Fixed expanded task modal buttons being cut off when content exceeds viewport height + - Thanks to @willfanguy for reporting + +- (#1542) Fixed declined and cancelled events from ICS calendar subscriptions appearing in calendar view + - Thanks to @karenchoe428 for reporting + +- (#1556) Fixed completion-based recurring tasks not rescheduling when the recurrence interval is large + - Thanks to @kazerniel for reporting + +- (#1492) Fixed hardcoded "open" status leaking into filenames, recurring task displays, and parsing fallbacks + - Users with custom default statuses (e.g. "inbox") no longer see "open" where their configured default should appear + - Recurring tasks now show their actual configured status instead of always displaying "open" when not completed + - Thanks to @macdrifter for reporting + +- (#1501) Fixed Google/Microsoft Calendar event colors not showing in agenda/list view + - Per-event and calendar-level colors now display correctly in the list view, matching grid view behavior + - Added today indicator highlighting to list view day headers + - Thanks to @Robubble for the suggestion +`});var ske,oke=y(()=>{ske=`# TaskNotes 4.3.1 + +## Added + +- (#1546) Added sticky kanban column headers that remain visible while scrolling + - Thanks to @normenmueller for the contribution + +- (#1458) Added CSS color classes to context tags for custom styling + - Each context tag now receives a unique CSS class based on its name (e.g., \`context-tag--color-0\` through \`context-tag--color-19\`) + - Enables styling individual contexts via CSS snippets + - Thanks to @phortx for the contribution + +- Added [mdbase-spec](https://mdbase.dev) type definition generation + - New setting in Integrations tab to generate mdbase-spec v0.2.0 type definition files (\`mdbase.yaml\` and \`_types/task.md\`) at the vault root + - Type definitions are derived from TaskNotes settings (statuses, priorities, field mappings, user fields) and regenerated automatically when settings change + - Enables interoperability with other tools that support the mdbase-spec format + +## Fixed + +- (#1472) Fixed task dependencies not being stored as wikilinks in frontmatter + - Dependencies now retain their \`[[wikilink]]\` format when saved, preventing them from breaking on file rename + - Thanks to @renekalff for reporting + +- (#1443) Fixed default status/priority not updating when the referenced custom value is deleted + - Deleting a custom status or priority that was set as the default now resets the default to the first available value + - Thanks to @l-mb for the contribution + +- (#1448) Fixed project removals not persisting from the task edit modal + - Removing all projects from a task now correctly clears the projects field + - Different link formats (e.g., markdown links vs wikilinks) no longer cause false change detection + - Thanks to @normenmueller for the contribution + +- (#1514), (#1517) Fixed task reminders not syncing to Google Calendar + - Task-specific reminders (both relative and absolute) now sync to Google Calendar + - Previously only the global default reminder setting was used, ignoring per-task reminders + - Thanks to @christenbc for the contribution + +- (#1525), (#1531) Fixed subtask status dot not refreshing visually when clicked + - Status dot, checkbox, and card styling now update instantly when cycling status + - Thanks to @christenbc for the contribution + +- (#1537) Fixed Google Calendar errors during bulk sync + - Added rate limiting to space out API calls, preventing errors when syncing many tasks at once + - Thanks to @Lorite for the contribution + +- (#1515), (#1540) Fixed time loss when setting recurrence and recurrence not clearing from Google Calendar + - Setting recurrence on a task with a scheduled time now preserves the time, preventing Google Calendar events from appearing as all-day + - Clearing recurrence from a task now also removes it from the synced Google Calendar event + - Thanks to @christenbc for the contribution + +- (#1428), (#1559) Fixed hierarchical tags with slashes (e.g., \`#project/sub-project\`) being truncated in link text + - Tags containing slashes, hyphens, and Unicode characters now render correctly + - Thanks to @normenmueller for the contribution and @ysafonov for reporting + +- (#1565) Fixed Google Calendar target calendar dropdown appearing empty after app restart + - The dropdown now re-populates once calendars are fetched during startup + - Thanks to @N-HEDGER for reporting + +- (#1567) Fixed inline task card widgets disappearing momentarily + - When the task cache is temporarily cleared (e.g., during Smart Connections processing), the previously-rendered widget is now preserved instead of reverting to a plain wiki link + - Thanks to @scztt for reporting + +- (#1568) Fixed deleted tasks not being removed from Google Calendar + - When a task file is deleted outside of TaskNotes (e.g., via Obsidian's file manager), the synced Google Calendar event is now cleaned up automatically + - Thanks to @kmaustral for reporting + +- Fixed Integrations tab spacing and layout issues + - Improved positioning of buttons and status indicators across Google Calendar, ICS, and Webhooks sections +`});var lke,cke=y(()=>{lke=`# TaskNotes 4.3.0 + +## Changed + +- (#1437) Unified template variable syntax and available variables across filename and body templates + - Both systems now use double-brace \`{{variable}}\` syntax consistently + - Single-brace \`{variable}\` syntax remains supported for backwards compatibility but is deprecated + - Settings UI shows a warning when deprecated single-brace syntax is detected + - Filename templates gain body template variables: \`{{contexts}}\`, \`{{tags}}\`, \`{{hashtags}}\`, \`{{timeEstimate}}\`, \`{{details}}\`, \`{{parentNote}}\` + - Body templates gain filename template variables: \`{{zettel}}\`, \`{{nano}}\`, and all extended date/time variables + - Thanks to @23maverick23 for reporting + +## Added + +- (#1361) Option to disable inline task overlay for aliased wikilinks + - New setting in Features → Inline Tasks: "Disable overlay for aliased links" + - When enabled, links with aliases like \`[[Task|Check Status]]\` render as plain links + - Links without aliases continue to show the interactive task widget + - Useful when embedding tasks in prose where the widget would be disruptive + - Thanks to @diegomarzaa for the contribution and @jldiaz for proposing this feature in #1117 + +- (#1199, #1205) Google Calendar export for tasks + - Sync tasks to Google Calendar based on scheduled or due dates + - Automatic sync on task create, update, complete, and delete + - Configurable event title templates with placeholders (\`{{title}}\`, \`{{status}}\`, \`{{priority}}\`, etc.) + - Event descriptions include task metadata and optional Obsidian deep link + - Support for all-day or timed events with customizable duration + - Event color customization using Google Calendar's color palette + - Default reminder setting for popup notifications + - Bulk sync and unlink actions in settings + - Task-event linking stored in frontmatter (\`googleCalendarEventId\`) + - Recurring tasks sync as Google Calendar recurring events + - Completed or skipped recurring instances are automatically excluded + - Thanks to @someromans and @Leonard-44 for requesting this feature, and @dmantisk, @farangkao, @rayvermey, and @rdpr for their input + +## Fixed + +- (#1413) Fixed angle-bracket links and project title display + - Angle-bracket links like \`[Spec]()\` now resolve correctly + - Project links display frontmatter \`title\` instead of raw filename/path when available + - Dependency values normalize consistently across wikilinks, markdown links, and angle-bracket variants + - Many thanks to @normenmueller for the contribution + +- (#1414) Kanban column headers now display configured priority labels instead of raw values + - Many thanks to @normenmueller for the contribution + +- (#1416) Fixed property-based task identification mutating tags unexpectedly + - Tags are only written when explicitly changed by the user + - Task tag is only added in tag-based identification mode + - Fixes #1391 + - Thanks to @loukandr for reporting and @normenmueller for the fix + +- (#1187) Fixed "Unknown view types" error when opening Bases views after upgrading from pre-V4 + - Users who had disabled Bases support in earlier versions could not open Bases views after upgrading + - Settings migration now automatically re-enables Bases support since the toggle was removed in V4 + - Thanks to @MiracleXYZ for reporting + +- (#1144) Fixed relationships.base showing empty views for Projects, Blocked By, and Blocking tabs + - The top-level task filter was excluding non-task files from the Projects view + - Projects can be any file type (not just tasks), so the filter is now applied per-view + - Subtasks, Blocked By, and Blocking views retain the task filter; Projects view does not + - Users with existing relationships.base files should delete and regenerate them to get the fix + - Thanks to @needo37 for reporting, and @n1njaznutz, @nestor50, and @IvyDliu for investigating and confirming the solution + +- Fixed calendar view type not persisting or applying when changed + - View type changes via header buttons (week/day/month) are now saved to the .base file + - View type changes via Bases settings panel now apply immediately without reload + +- (#1441) Fixed task dragging broken with "Span tasks between scheduled and due dates" enabled + - Span events can now be dragged to move tasks in time + - Dragging shifts both scheduled and due dates proportionally, preserving the span duration + - Previously, dragging span events would cause a visual/data mismatch where the calendar showed the wrong position + - Thanks to @Peeeet for reporting +`});var dke,uke=y(()=>{dke=`# TaskNotes 4.2.1 + +## Added + +- New Calendars API endpoint for access to calendar data + - Access calendar provider information and connection status + - Query events from Google Calendar, Microsoft Calendar, and ICS subscriptions + - Filter events by date range + - [\`tasknotes-cli\`](https://github.com/callumalpass/tasknotes-cli) has been updated to make use of this endpoint + +## Fixed + +- (#1424) Fixed "Create New Task" command creating tasks in active folder instead of default folder + - "Create New Task" now correctly uses the configured default task folder + - "Create New Inline Task" continues to use the inline task folder setting + - Thanks to @Gogo-XD for reporting and @TonyAtlas for confirming + +- (#1421), (#1042) Fixed natural language parser only setting one date when both scheduled and due dates are specified + - Entering something like "task due Jan 9 at Jan 9" now correctly sets both the due date and scheduled date + - Thanks to @wealthychef1 and @dblinnikov for reporting + +- (#1410) Fixed vim insert mode not activating in task creation modal + - The modal now correctly enters insert mode when vim keybindings are enabled + - Thanks to @Leo310 for the feature request + +- (#1422) Fixed tags with dashes not being parsed correctly + - Tags like \`#my-tag\` were being truncated to \`#my\` + - Thanks to @JerryLu086 for reporting + +- (#1419) Fixed custom statuses and priorities not saving in settings + - Values entered in text fields were sometimes lost when closing the settings modal + - Thanks to @s33a for reporting +`});var pke,mke=y(()=>{pke=`# TaskNotes 4.2.0 + +## Added + +- Added Korean (한국어) language support + - Full translation of all 1911 localization keys + - Korean language option now available in Settings → General → Language + +- Adopted Obsidian 1.11.0 API features with backwards compatibility + - Settings tab now displays TaskNotes icon in the sidebar (Obsidian 1.11.0+) + - Settings sections now use native \`SettingGroup\` for improved visual grouping (Obsidian 1.11.0+) + - Falls back gracefully to traditional section headers on older Obsidian versions + +- (#59) Added \`shortYear\` template variable for custom filename and folder templates + - Use \`{shortYear}\` in filename templates (e.g., "25" for 2025) + - Use \`{{shortYear}}\` in folder templates + - Thanks to @Pixeltica for the feature request + +- (#1393) Option to prevent auto-creation of default Base view files on startup + - New "Auto-create default files" toggle in Settings → Integrations → Bases Integration + - When disabled, deleted sample Base files will not be recreated on plugin load + - The manual "Create Default Files" button remains available for on-demand recreation + - Thanks to @wealthychef1 for the feature request + +- (#1408) Shift+click on status icon to cycle backwards through statuses + - Normal click cycles forward through status order + - Shift+click cycles in reverse order + - Thanks to @JerryLu086 for the feature request + +- (#1410) Task creation modal now starts in vim insert mode when vim keybindings are enabled + - Previously required pressing 'i' before typing when Obsidian vim mode was active + - The modal now automatically enters insert mode on focus, allowing immediate typing + - Thanks to @Leo310 for the feature request + +- Added button tooltips to calendar view toolbar + - Hovering over navigation and view buttons now shows descriptive hints + - Buttons include: Today, Previous, Next, Month, Week, Day, Year, List + +- Added tooltips to task modal action icons + - Icon buttons for status, date, project, priority, recurrence, and reminder now show tooltips on hover + - Improves discoverability for new users + +- (#503) Settings now sync automatically across devices via Obsidian Sync + - Changes to custom statuses, priorities, and other settings apply immediately without restart + - Thanks to @jhedlund for the feature request and @l-mb for the implementation + +- (#1403) Kanban view option to consolidate status icons in column headers + - New "Show status icon in column header only" toggle in Kanban view settings (disabled by default) + - When enabled and grouped by status, shows the icon in the column header and hides it on cards + - Reduces visual redundancy when the column already indicates the status + - Thanks to @l-mb for the feature request and implementation + +- (#1401) Calendar view option to span tasks between scheduled and due dates + - New "Span tasks between scheduled and due dates" toggle in Calendar view Layout settings + - When enabled, tasks with both scheduled and due dates display as multi-day bars + - Provides Gantt chart-style visualization for project planning + - Thanks to @0atman for the feature request + +- (#1334) \`{{currentNotePath}}\` now works for "Create new inline task" command + - The inline task folder setting with \`{{currentNotePath}}\` previously only worked for checkbox conversion + - Now also applies when using the "Create new inline task" command from the command palette + - Thanks to @kmaustral for the feature request + +- (#1264) Option to open Pomodoro timer in mobile sidebar instead of note panel + - New "Mobile sidebar" setting in Settings → Features → Pomodoro Timer + - Choose between: Note panel (default tab behavior), Left sidebar, or Right sidebar + - Allows quick swipe access to the timer without switching notes on mobile devices + - Thanks to @Evthestrike for the feature request + +- (#1220) Option to use ICS event end time as task due date + - New "Use ICS event end time as task due date" toggle in Settings → Integrations → Calendar Subscriptions + - When enabled, tasks created from calendar events will have their due date set to the event's end time + - For all-day events, uses the event date (not the ICS container end date which is the next day per ICS spec) + - For timed events, includes the exact end time + - Defaults to disabled to preserve existing behavior + - Thanks to @MiserMagus for the feature request + +- (#1108) Option to use task duration instead of due date for ICS calendar export + - New "Use task duration for event length" toggle in Settings → Integrations → Automatic ICS Export + - When enabled, exported calendar events use scheduled date + time estimate as DTSTART/DTEND + - This aligns with GTD workflows where scheduled + duration represents work planning, while due date represents deadlines + - When disabled (default), preserves existing behavior using due date as DTEND + - Thanks to @bepolymathe for the feature request + +## Fixed + +- (#1421) Fixed natural language parser only capturing one date when both scheduled and due dates are specified + - Input like "Task scheduled for tomorrow due next week" now correctly sets both scheduled and due dates + - Previously the parser would return early after finding the first date trigger, ignoring any subsequent triggers + - Thanks to @wealthychef1 for reporting + +- (#1384) Fixed title being sanitized even when "Store Task Title in Filename" is disabled + - Characters like \`?\`, \`<\`, \`>\`, \`:\`, etc. are now preserved in task titles when they won't be used in filenames + - When \`storeTitleInFilename\` is false, only minimal sanitization (whitespace normalization, control character removal) is applied + - Thanks to @allison-casey for reporting + +- (#1028), (#1140), (#1152), (#1354), (#1362) Fixed duplicate task entries appearing in Agenda view + - Tasks were shown twice: once as TaskNotes events and again as property-based events with a file icon + - Changed default Agenda template to disable property-based events (\`showPropertyBasedEvents: false\`) + - Users can re-enable property-based events in view settings if needed for non-task date properties + - Thanks to @YIRU69, @jhedlund, @dblinnikov, @Snakiest, @WeiYiAcc, @JacksonMcDonaldDev, @jimbo108108, and @krelltunez for reporting + +- (#1386) Fixed \`timeEstimateCategory\` formula showing "Long (>2h)" instead of "No estimate" for new tasks + - The condition didn't properly handle null values when \`timeEstimate\` property is unset + - Also fixed the same issue in \`trackingStatus\` formula + - Thanks to @nicou for reporting and @osxisl for the PR + +- (#1397) Fixed Bases views (Kanban, Calendar, Task List) resetting to Calendar view after a few minutes + - Also fixed CalendarView corrupting other view files when saving state on unload + - Thanks to @music-soul1-1 for reporting + +- (#1398) Fixed overdue strikethrough showing on completed tasks + - Completed tasks with past due dates no longer display overdue styling + - Respects the "Hide completed from overdue" setting which defaults to true + +- (#1363) Fixed calendar view showing nothing when a task has an invalid date format + - Tasks with malformed dates (e.g., "262025-12-16" instead of "2025-12-16") no longer crash the entire calendar + - Invalid tasks are now skipped with a console warning, allowing other events to display normally + - Thanks to @Erelen for reporting + +- Fixed today column in week/day calendar views using FullCalendar's default yellow instead of theme accent + - Today's column now uses a tint of the theme accent color for consistent styling + +- (#1399) Fixed drag-and-drop not working in Kanban view on mobile + - Cards and columns can now be dragged using long-press gesture on touch devices + - Includes haptic feedback and auto-scroll when dragging near edges + - Thanks to @l-mb for reporting and the fix + +- (#1381) Fixed Pomodoro "Change Task" menu not showing newly created tasks + - Tasks created while the Pomodoro view was open would not appear in the task selector + - Improved metadata cache synchronization to properly wait for new files to be indexed + - Thanks to @Ghosthael for reporting + +- (#1344) Fixed "Unsaved Changes" popup appearing randomly when closing task edit modal + - The popup would appear even when no changes were made to the task + - Caused by inconsistent trailing whitespace normalization when comparing details content + - Thanks to @hasanyilmaz for reporting + +- (#1402) Fixed Kanban swimlane view showing tasks in wrong column when grouped by formula + - After editing task metadata, cards would jump to "None" column until Obsidian reload + - Column assignment now uses Bases' computed grouping instead of cached formula outputs + - Thanks to @bailob for the fix + +- (#1352) Fixed date context menu not preserving time when using increment options + - Using +1 day, -1 day, +1 week, or -1 week on a task with a time (e.g., \`2025-12-10T16:00\`) now preserves the time + - Previously the time would be stripped, changing \`2025-12-10T16:00\` to \`2025-12-11\` instead of \`2025-12-11T16:00\` + - Thanks to @cathywu for the feature request + +- Fixed v3 saved views exporting incorrectly to Bases format + - Title filters now correctly use \`file.name\` instead of \`note.title\` + - Archived filters now generate valid boolean expressions instead of malformed comparisons + - "Is Blocked" filters now generate correct expressions with proper operator precedence + +- (#1036) Due dates can now be dragged in the calendar view + - Previously only scheduled dates were draggable; due dates were locked in place + - Dragging a due event now updates the task's due date property + - Thanks to @same774 for reporting + +- Improved calendar view responsiveness for user interactions + - Task creation, editing, timeblock changes, and view option toggles now update immediately + - Previously these actions waited 5 seconds due to the debounce intended for external file changes + - The 5-second debounce is now bypassed for direct user actions while still preventing flicker during typing + +- Improved visual affordance for Pomodoro timer duration adjustment buttons + - The +/- buttons below the timer now have visible backgrounds and borders + - Hover states show accent color border for clearer interactivity feedback + - Previously buttons were nearly invisible with transparent backgrounds + +- (#1409), (#1214), (#979) Improved Calendar, Agenda, Kanban, and Stats views in pop-out windows + - Drag-and-drop in Kanban view now works correctly when the view is in a new window + - Context menus (status, priority, task) now work correctly in pop-out windows + - Stats view drill-down modal now appears in the correct window + - Search boxes, task cards, and grouped task lists render correctly + - Root cause: Code was using global \`document\` and standard \`instanceof\` checks which fail across windows + - Solution: Use \`ownerDocument\` for DOM operations and Obsidian's cross-window \`instanceOf()\` method + - **Known limitation**: Calendar event dragging does not work in pop-out windows due to FullCalendar library using global \`document\` for mouse event listeners. Use context menus or edit modals as a workaround. + - Updated FullCalendar to v6.1.20 + - Thanks to @Snakiest, @same774, and @3zra47 for reporting + +- (#1337) Fixed "Convert current note to task" hotkey not applying default values from settings + - When user configured default status/priority as "None", the modal would show "Open" and "Normal" instead + - Root cause: Task edit modal was refreshing data from file and overwriting user-configured defaults + - Now preserves constructor-provided task data when converting non-task files + - Thanks to @guihasparyk for reporting + +- (#1304) Fixed "Cannot find function map on type Link" error in Blocking view + - Error occurred when embedding the Relationships base and opening the Blocking view + - Root cause: When \`blockedBy\` contained a single dependency, Bases returned it as a Link object without a \`.map()\` method + - Fixed by wrapping \`blockedBy\` with \`list()\` before calling \`.map()\`, consistent with the Blocked By view + - Thanks to @prayidae for reporting + +- (#1295) Fixed missing navigation link to Default Base Templates page on tasknotes.dev + - The page existed but was not accessible from the site navigation + - Thanks to @Arachnidai for reporting + +- (#1223) Fixed "Go to today's note" command opening wrong date in positive UTC offset timezones + - In timezones like Japan (UTC+9), early morning use of this command opened yesterday's note + - Root cause: Incorrectly extracting UTC date components instead of local timezone date + - Thanks to @BrucePlumb for reporting +`});var fke,hke=y(()=>{fke=`# TaskNotes 4.1.3 + +This patch fixes a critical performance issue affecting the Calendar views. As a bonus, it adds a configurable "split" view to the task creation/edit modals. + +## Added + +- Split layout for task modals on wide screens (900px+) + - Details editor appears in a dedicated right column when the modal is expanded + - New setting "Split layout on wide screens" in Modal Fields settings tab to toggle this behavior + - Improves usability by showing form fields and details side-by-side + +## Fixed + +- (#1330) Fixed calendar view regression taking 5 seconds to load and respond to user interactions + - Initial calendar load is now immediate again + - User interactions (drag/drop, creating timeblocks, etc.) respond instantly + - Removed redundant date filtering (FullCalendar handles this more efficiently) + - Thanks to @ysafonov, @kmaustral, @sunjiawe, @Мизгирь, and @FiliusIcari for reporting +`});var gke,yke=y(()=>{gke=`# TaskNotes 4.1.2 + +## Fixed + +- Significant performance improvements for Bases views (TaskList, Kanban, Calendar) + - Reduced \`extractDataItems\` time from ~4 seconds to ~5-10ms for large vaults (6000+ tasks) + - Computed file properties (\`file.backlinks\`, \`file.links\`, etc.) are now fetched lazily during render instead of upfront + - Only visible items (with virtualization) trigger expensive property computations + - Added debouncing to \`onDataUpdated\` to prevent UI freezes during typing + - Timeblock generation now uses Obsidian's metadataCache instead of file reads + - Added date range filtering for calendar events to skip events outside visible range + - (#1285) Calendar view uses 5-second debounce to prevent flickering while typing + - Thanks to @steven-murray for reporting +- Calendar view switching (month/week/day/list) is now much faster + - View type is now saved on unload instead of on every change +- Fixed task edit modal archive button being too narrow on mobile devices +- (#1319) Added missing properties to Field Mapping settings + - \`recurrence_anchor\` - now in Settings > Task Properties > Task Details + - \`skipped_instances\` - now in Settings > Task Properties > Metadata Properties + - Thanks to @kazerniel for reporting +- (#1310) Fixed inline task conversion deleting text when task title exceeds filename limits + - Text that cannot fit in the filename is now preserved in the task note's body + - Thanks to @prayidae for reporting +- (#1301) Fixed inline task wikilinks leaving blank space when no metadata properties are visible + - Thanks to @Richard-UMPV for reporting +- (#1317) Fixed project autosuggest filters not working correctly when only "Required Property Key" is configured + - NLP \`+\` trigger now properly filters by property existence when no property value is specified + - Modal "Add to project" button now shows consistent results with inline autosuggest + - Thanks to @JacksonMcDonaldDev for reporting +- (#1287), (#1307) The "New" button in Bases views now opens the TaskNotes creation modal + - Tasks created from Bases views now respect default properties (status, priority, etc.) + - Tasks are now created in the configured default folder instead of the views folder + - Thanks to @anareaty and @sylvainfct-dot for reporting +- (#1291) Fixed Microsoft Calendar OAuth documentation using wrong redirect URI + - Added instructions for configuring via Azure manifest editor + - Thanks to @PlecotusAustriacus for reporting + +## Added + +- (#803) New command "Convert current note to task" to add task properties to an existing note + - Thanks to @GardarikanetS and @diegomarzaa for suggesting +- (#1080) Custom user fields now support default values + - Each field type has an appropriate input: text field, number input, toggle, date preset dropdown, or comma-separated list + - Defaults are applied when creating tasks via modal, instant conversion, "Create or open task" command, or HTTP API + - Thanks to @bradyrx for suggesting + +## Changed + +- Added documentation link to settings panel (links to tasknotes.dev) +- Reorganized settings panel for improved discoverability + - Removed "Defaults" tab - default values are now configured alongside each property in the Task Properties tab + - Moved task filename format settings to the Title property section + - Moved project autosuggest settings to the Projects property section + - Body template setting moved to the Features tab + - Added descriptions to each property explaining its purpose + - Moved "Folder for converted tasks" setting to General tab under Task Storage for better discoverability + - Updated setting description to clarify that leaving empty uses the default tasks folder + +`});var vke,kke=y(()=>{vke='# TaskNotes 4.1.1\n\n## Added\n\n- (#1277) Icon autosuggestion for custom status settings\n - Type to search through all available Lucide icons\n - Thanks to @Arachnidai for the suggestion\n- New formula properties in default Base templates\n - **Date calculations**: `daysUntilDue`, `daysUntilScheduled`, `daysSinceCreated`, `daysSinceModified`\n - **Boolean helpers**: `isOverdue`, `isDueToday`, `isDueThisWeek`, `isScheduledToday`, `isRecurring`, `hasTimeEstimate`\n - **Time tracking**: `timeRemaining`, `efficiencyRatio`, `timeTrackedThisWeek`, `timeTrackedToday`, `timeTrackedFormatted`\n - **Grouping**: `dueMonth`, `dueWeek`, `scheduledMonth`, `scheduledWeek`, `dueDateCategory`, `timeEstimateCategory`, `ageCategory`, `createdMonth`, `modifiedMonth`, `priorityCategory`, `projectCount`, `contextCount`, `trackingStatus`\n - **Combined due/scheduled**: `nextDate`, `daysUntilNext`, `hasDate`, `isToday`, `isThisWeek`, `nextDateCategory`, `nextDateMonth`, `nextDateWeek` - work with whichever date comes first\n - **Sorting**: `priorityWeight`, `urgencyScore` (combines priority with date proximity)\n - **Display**: `dueDateDisplay` (relative dates like "Today", "Tomorrow", "3d ago")\n - Action-oriented views (Not Blocked, Today, Overdue, This Week) now sort by urgency score, showing most important tasks first\n - See [Default Base Templates documentation](https://tasknotes.dev/views/default-base-templates) for full details\n - **Note**: To get these new formulas, either copy them from the documentation, or delete your `.base` files in `TaskNotes/Views/` and restart Obsidian to regenerate them\n\n## Changed\n\n- (#1282) Added spacing between task title and metadata in inline task widgets for improved readability\n - Thanks to @3zra47 for the suggestion\n- Custom status icons now display in all context menus (task context menu, batch operations menu, and task creation/edit modals)\n- Added embedded video guide for Google Calendar OAuth setup in documentation\n - Thanks to [@antoneheyward](https://www.youtube.com/@antoneheyward) for the tutorial\n\n## Fixed\n\n- (#1279) Fixed Kanban column width setting not being respected on mobile devices\n - Thanks to @guncav for reporting\n- (#1026), (#1177) Fixed recurring task completion from Base views recording the wrong date for users in negative UTC offset timezones (e.g., PST/PDT) when completing tasks in the evening\n - The bug caused `complete_instances` to record the next day instead of the user\'s current calendar day\n - Thanks to @3zra47 and @nslee123 for reporting and providing detailed reproduction steps\n\n'});var Tke,bke=y(()=>{Tke=`# TaskNotes 4.1.0 + +## Added + +- (#1245), (#793) Added custom icon support for task statuses + - Configure a Lucide icon name (e.g., \`check\`, \`circle\`, \`clock\`) per status in Settings → Task Properties → Task Statuses + - Icons display instead of the colored dot, inheriting the status color + - Browse available icons at [lucide.dev](https://lucide.dev) + - Improves accessibility by allowing shape-based status differentiation + - Thanks to @3Fish for the feature request and @Raonmir2, @aubreyz, @prayidae, and @anareaty for the discussion on accessibility and icon-based indicators + +- (#1259) Added [Property Types Reference](../settings/property-types-reference.md) documentation + - Documents expected data types (text, list, date, number) for all frontmatter properties + - Includes format specifications, examples, and a complete YAML reference + - Thanks to @Oblique82 for the suggestion + +- (#1248) Added formula property support for sub-grouping in Bases Task List view + - Formula properties (e.g., \`formula.myFormula\`) now appear in the Sub-group by dropdown + - Supports all Bases Value types including strings, numbers, booleans, dates, and lists + - Thanks to @prayidae for the feature request + +- (#1070) Added formula property support for swimlanes in Bases Kanban view + - Formula properties now appear in the Swim Lane dropdown + - Fixed swimlanes displaying empty when grouping by formula properties + - Note: Dragging tasks between formula-based columns/swimlanes is disabled (formulas are computed values) + - Thanks to @cathywu for reporting + +- (#1010), (#1126) Added batch task selection and editing in Task List and Kanban views + - Shift+click to select multiple tasks + - Right-click selected tasks to open batch context menu + - Batch operations: change status, priority, due date, scheduled date, archive, delete + - Drag multiple selected cards in Kanban to move them together + - Click the selection count indicator to clear selection + - Thanks to @jalooc and @solidabstract for the feature requests + +- (#1207) Added inline search box to Bases views (Task List, Kanban, Calendar) + - Enable via "Enable search box" toggle in view settings + - Searches across title, status, priority, tags, contexts, projects, and visible custom properties + - Press Escape or click × to clear search + - Thanks to @renatomen for the PR + +- (#363) Added "Create or open task" command with NLP-based quick task creation + - Open via command palette or assign a hotkey + - Search existing tasks or type natural language to create new tasks (e.g., "Buy groceries tomorrow #shopping") + - Press Enter to select an existing task, Shift+Enter to create a new task + - Real-time preview shows parsed title, due date, priority, tags, and other metadata + - Can be used when adding sub-tasks to create sub-tasks on-the-fly + - Thanks to @luciolebrillante for the feature request + +- (#1044), (#1222) Added unsaved changes confirmation when closing task edit modal + - Detects modifications to any field (title, dates, priority, tags, etc.) + - Shows confirmation dialog with Save/Discard/Keep Editing options + - Prevents accidental data loss from clicking outside the modal or pressing Escape + - Thanks to @renatomen for the PR and @0-BSCode for the feature request + +- (#904) Added visual highlighting for overdue and past dates on task cards + - Overdue due dates now display in red text + - Past scheduled dates now display in blue text + - Thanks to @ras0q for the suggestion + +- (#1164) Added \`priorityWeight\` formula to all default Bases templates for priority-based sorting + - Formula maps each priority value to a numeric weight based on your custom priority configuration + - Sort by \`formula.priorityWeight\` in ascending order to get highest priority tasks first + - Example: \`if(priority=="high",0,if(priority=="normal",1,if(priority=="low",2,999)))\` + - Thanks to @jhedlund for the suggestion + +- (#1257), (#1064) Added configurable event stacking options for Bases Calendar view + - **Allow events to overlap**: Toggle whether timed events visually overlap or display side-by-side in week/day views + - **Max stacked events**: Limit horizontal event stacking in week/day views (0 = unlimited) + - **Max events per day**: Limit events shown per day cell in month view (0 = auto based on cell height) + - **Max event rows per day**: Limit event rows per day cell in month view (0 = unlimited) + - Configure per-view in the Bases Calendar view settings under Layout + - Thanks to @3zra47 and @hasanyilmaz for the feature requests + +## Changed + +- Improved inline task conversion to merge TasksPlugin and NLP parsing results + - Previously, if a task had hashtags (e.g., \`- [ ] Buy milk tomorrow #groceries\`), NLP parsing was skipped entirely + - Now NLP always parses the clean title to extract dates/times, then merges with TasksPlugin-extracted metadata + - TasksPlugin explicit values (emoji dates like 📅) take priority over NLP-inferred values + - Tags, contexts, and projects from both sources are combined and deduplicated + +- Polished task card styling for a more native Obsidian look + - Simplified hover and focus states to use native Obsidian colors + - Removed blur filter and shadows from metadata pills + - Fixed subtask chevron vertical alignment with status dot + - Reduced swimlane label column width in Kanban view + +- (#1151) Increased mini calendar heatmap color intensity for better visibility + - Days with notes now show more noticeable colors, especially with low note counts + - Intensity levels increased from 10/25/45/65% to 25/40/55/70% + - Thanks to @arreme for the suggestion + +## Fixed + +- (#1271) Fixed custom user fields not appearing in task modals after creation + - New custom fields are now automatically added to both creation and edit modals + - Deleting a custom field also removes it from modal configuration + - Updating a field's display name syncs to the modal configuration + - Thanks to @craziedde for reporting + +- (#1256) Fixed links in custom properties not rendering as clickable in task cards + - Wikilinks (\`[[Note]]\`) now render correctly in Bases views + - Markdown links (\`[text](url)\`) now render correctly in all views + - Links in list-type properties are also properly rendered + - Thanks to @3zra47 for reporting + +- (#1157) Fixed inline task embeds breaking layout when placed in indented bullet lists + - Task titles now wrap naturally within line boundaries instead of forcing the entire card to a new line + - Metadata (dates, tags, etc.) stays inline when space permits, with horizontal scrolling on hover when needed + - Thanks to @3zra47 for reporting + +- (#1241) Fixed deleting custom priorities in settings removing the wrong priority when multiple priorities exist + - Thanks to @Anthonyhunter100 for reporting + +- (#1165) Fixed Kanban view grouping by list properties (contexts, tags, projects) treating multiple values as a single combined column + - Tasks with multiple values now appear in each individual column (e.g., a task with \`contexts: [work, call]\` appears in both "work" and "call" columns) + - Added "Show items in multiple columns" option (enabled by default) to control this behavior + - Fixed drag-and-drop to properly add/remove individual values instead of replacing the entire list + - Fixed swimlane mode to also respect list property explosion + - Thanks to @dictionarymouse for reporting + +- (#1217) Fixed inconsistent Ctrl+Click/Cmd+Click behavior for opening notes in new tabs + - Note cards and internal links now properly support Ctrl/Cmd+Click to open in new tab + - Added middle-click support for opening in new tab + - Thanks to @diegomarzaa for reporting + +- (#1265) Fixed task edit modal corrupting markdown-style project links on save + - Links like \`[Project Name](path.md)\` were being wrapped in extra brackets: \`[[[Project Name](path.md)]]\` + - Plain text project names are now preserved as-is instead of being converted to wikilinks + - Markdown-style project links now resolve properly and display as linked (not orange/unresolved) + - Thanks to @minchinweb for reporting + +- (#1266) Fixed Kanban view scroll position resetting to top of column after any change + - Clicking status dots, priority, or other task properties no longer jumps the column back to top + - Scroll position is now preserved for both regular columns and swimlane cells + - Thanks to @essouflenfer for reporting + +- (#485), (#1221), (#1262) Fixed NLP parser not recognizing non-ASCII characters in tags, contexts, and projects + - Tags like \`#investigación\` were being truncated at accented characters (e.g., \`#investigaci\`) + - Non-Latin scripts (Chinese, Cyrillic, Japanese, etc.) were not recognized at all (e.g., \`@家\`, \`#杂事\`, \`@ознакомиться\`) + - Parser now uses Unicode-aware regex patterns to support all languages and scripts + - Thanks to @Arachnidai, @fidelaznar, and @qian1ing for reporting + +- (#1249) Fixed project preview in task creation modal showing quadruple brackets (\`[[[[Project]]]]\`) + - Projects selected from autocomplete were being wrapped in extra wikilink brackets in the preview display + - Thanks to @2vzqwz8tvg-png for reporting + +- (#1249) Fixed custom priority ordering in settings being unclear and non-intuitive + - Priority cards are now draggable to reorder (like statuses) + - Priorities are displayed in weight order (lowest to highest priority) + - New priorities are added at the end (highest priority) instead of with a fixed weight + - Thanks to @2vzqwz8tvg-png for reporting + +- (#1272) Fixed recurrence anchor not being saved when set to "completion" during task creation + - Selecting "completion" as the recurrence anchor now correctly persists to the task frontmatter + - Thanks to @blaxcky for reporting + +- (#1128) Fixed NLP parser not allowing slashes in context names + - Contexts like \`@shopping/groceries\` were being split into \`@shopping\` and \`/groceries\` + - Hierarchical context names now work the same as tags and projects + - Thanks to @wealthychef1 for reporting + +- (#1170) Fixed \`dateCreated\` and \`dateModified\` not using custom property names when creating notes from calendar events + - Notes created from ICS events now respect the field mapping configured in settings + - Thanks to @maddie-m for reporting + +- (#1171) Fixed calendar event toggles not responding to changes after initial load + - Toggling "Show scheduled tasks", "Show due tasks", and other event filters now correctly updates the calendar + - Previously, changing these toggles had no effect until the view was reloaded + - Thanks to @hangryscribe3 for reporting + +- (#1198) Fixed project links being created relative to the wrong file when editing from Bases views + - Relative paths in project links are now correctly resolved relative to the task note file + - Previously, editing a task from a Bases view would create project links relative to the \`.base\` file + - Thanks to @minchinweb for reporting + +`});var wke,Ske=y(()=>{wke=`# TaskNotes 4.0.5 + +## Changed + +- (#790) Task edit modal now shows unresolved project links with appropriate styling + - Similar to how dependencies are displayed, unresolved projects now appear with visual indication + - Hovering over an unresolved project shows a tooltip explaining it couldn't be resolved + - Thanks to @aubreyz for reporting + +## Fixed + +- (#1011) Fixed chevrons incorrectly showing on tasks with no subtasks + - Project index was incorrectly adding all linked files instead of only files referenced in the projects field + - Now properly parses the projects field and only indexes those specific files as projects + - Also fixed alias handling in project and dependency links - aliases are now correctly stripped before link resolution + - Thanks to @craziedde for reporting +- (#1200) Fixed kanban drag & drop not updating task properties correctly + - Dragging tasks to different columns now properly triggers business logic (completedDate, auto-archive, webhooks) + - Previously, kanban updates bypassed \`updateProperty\` and directly modified frontmatter + - Thanks very much to @tvoklov for the PR +- (#1203) Fixed autocomplete dropdown being clipped inside NLP field boundaries + - Configure CodeMirror tooltips to render in document.body instead of constrained editor container + - Prevents suggestion dropdown from being hidden when it extends beyond the NLP field height + - Thanks to @Andrei-Ioda for reporting +- (#1172) Fixed task lists and checkboxes rendering incorrectly in task details editor + - Remove padding-left override on \`.cm-line\` to allow CodeMirror decorations (checkboxes, indentation) to render properly + - Content padding is now handled by \`.cm-content\` while \`.cm-line\` uses natural spacing + - Thanks to @nightroman for reporting +- Fixed relationships widget not appearing on project notes without frontmatter + - Widget now correctly shows on any note referenced as a project by tasks, regardless of whether the note has frontmatter +- Fixed task card and relationships widgets not appearing when opening notes in source mode + - Removed live preview mode restriction to allow widgets to render in both source and live preview modes +- (#901) Fixed calendar view toolbar buttons overflowing on narrow screens + - Added \`flex-wrap: wrap\` to calendar header toolbar to allow buttons to wrap to multiple lines + - Thanks to @RumiaKitinari for reporting +- (#1193), (#1194), (#1185) Fixed new calendar views not respecting user's default calendar settings + - Previously, new Bases calendar views used hardcoded inline defaults instead of user-configured preferences + - Calendar view initialization now correctly uses \`plugin.settings.calendarViewSettings\` as the fallback + - Thanks @ki5ck, @minchinweb and @ThamirysOlv for reporting +- Fixed calendar to ensure that it respects user's locale + - Tries to use calendar locale, then tries UI language, then system language, then falls back to English +- (#1043) Fixed default reminders with "at time of event" (0 offset) not being applied to tasks + - UI was displaying "1" instead of "0" for zero-offset reminders in settings + - Thanks to @dblinnikov for reporting +- (#1206) Fixed NLP status parsing regressions with trigger prefixes and temporal keywords + - Manually typing status trigger + label now correctly parses (e.g., \`*Done\` when label is \`Done\`) + - Status values containing temporal keywords no longer misparsed as dates (e.g., \`Expedite = Now\`) + - Thanks very much to @renatomen for the PR +- (#1212) Fixed "Show release notes on update" toggle not saving correctly + - Thanks to @Jon-dog for reporting +- (#1197) Add Portuguese language to list of translations in general tab settings + - Allows users to select the Portuguese translation option + - Thanks to @andysteel for the PR +- Fixed file properties displaying incorrectly in Bases views + - File properties like \`file.name\`, \`file.basename\`, \`file.size\`, etc. were showing as "Title" or returning null + - Now correctly extracts and displays all file properties from Obsidian's file metadata + - Supports both direct TFile properties (name, basename, extension, path, size, ctime, mtime) and computed properties (links, embeds, tags, backlinks, aliases) +`});var Cke,xke=y(()=>{Cke=`# TaskNotes 4.0.4 + +## Added + +- (#1134, #779) Added CMD+Enter (Mac) / Ctrl+Enter (Windows/Linux) keyboard shortcut support for saving in all modals + - Works from any input field in task creation, task edit, time entry, timeblock, and property selector modals + - Thanks to @luckb0x, @hamlim and @nightroman for the feature requests + +## Fixed + +- (#1181) Fixed vertical overflow in Kanban view columns with fewer than 15 tasks + - Prevents cards from extending beyond column boundaries before virtualization activates + - Thanks to @lomarcanys for reporting +- (#1177) Bases views now anchor recurring completion and calendar navigation to the right date + - Recurring completion from Bases Task List/Kanban uses the task's scheduled/due date instead of "today" (fixes complete_instances) + - Bases calendar navigation and property-based events use UTC anchors to avoid previous-day jumps + - Thanks to @nslee123 for flagging the issue +- Bases calendar navigation now respects UTC-anchored dates to avoid landing on the previous day + - Corrected all-day end date calculation to prevent off-by-one spans + - Added regression test for the UTC anchor behavior + - Thanks to KaCii for [flagging the issue](https://discord.com/channels/686053708261228577/1433165116702199880/1439757826380660767) + +## Changed + +- Refactored plugin styling to better align with Obsidian's native UI conventions + - Replaced all \`cursor: pointer\` with \`cursor: var(--cursor)\` (100+ instances) to follow Obsidian's cursor convention + - Removed forced \`border: none; box-shadow: none\` rules that were fighting against Obsidian's native button styling + - Scoped custom \`.tn-btn\` button system to settings modal only (\`.mod-settings\`), allowing Obsidian's native button styles to work elsewhere + - Thanks to @kepano for guidance +`});var Eke,Dke=y(()=>{Eke=`# TaskNotes 4.0.3 + +## Fixed + +- (#1157) Fixed task embeds appearing on new line instead of inline with bullets in lists + - Changed inline task cards to use span elements instead of divs for proper inline flow + - Added max-width constraint to prevent wrapping when tasks are wider than editor + - Task embeds now display correctly inline with bullet points during live preview + - Thanks to @3zra47 for reporting +- (#1168) Fixed mini calendar stealing focus every few seconds when pinned to sidebar + - Thanks to @DearHaruHaru for reporting +- (#1161, #1162) Fixed "unexpected scalar" YAML parsing error in generated tasks-default.base template + - Changed nested quotes in "Not Blocked" filter from double to single quotes + - Thanks to @benschifman and @InterstellarRaccoon for reporting, @GarrettKaupp for identifying the fix + +## Changed + +- Updated task modal UI to use native Obsidian patterns for better theme compatibility + - Thanks to @kepano for feedback + +`});var Pke,Ake=y(()=>{Pke=`# TaskNotes 4.0.2 + +This release fixes some of the more urgent (and easy-to-fix) bugs that were introduced in the v4 major release. Thanks to everyone for your patience, and to those who have reported issues, for taking the time to do so. There will be more releases over the coming weeks to iron out some of v4's kinks. + +## Added + +- Added "Not Blocked" view to default task list template + - Shows incomplete tasks that are ready to work on (not blocked by incomplete dependencies) + - Uses Bases \`list.filter()\` to check completion status of each blocking task + - This new view can be accessed by regenerating the Task List view, or by copying the filters from the [default base templates documentation](https://tasknotes.dev/views/default-base-templates) + +## Fixed + +- (#1145, #1156) Fixed default Kanban view requiring manual 'Group by' configuration + - Default Kanban template now automatically includes \`groupBy\` property set to status + - Resolves "Kanban requires a 'Group by' property to be configured" error on first use + - Users no longer need to manually configure grouping through the Sort menu + - Thanks to @randomness42 and @seepage87 for reporting +- Fixed user-defined custom fields appearing as \`user:field_xxx\` in generated base templates + - Custom fields now use their actual property names (e.g., \`effort\` instead of \`user:field_1761435303709\`) + - Ensures Bases can properly query user-defined properties + - Also fixed \`totalTrackedTime\` to correctly map to the configured \`timeEntries\` property name +- (#1145) Improved Kanban error message when no 'Group by' property is configured + - Now includes instructions: "Click the 'Sort' button and select a property under 'Group by'" + - Thanks to @randomness42 for the suggestion +- (#1139, #1141) Fixed relationships widget not appearing in project notes + - Project references are now resolved to full file paths when indexing + - Uses Obsidian's link resolution API to handle wikilinks, markdown links, and relative paths + - Restores v3.x behavior where subtasks appear in parent project notes + - Thanks to @jhedlund, @n1njaznutz, and @luckb0x for reporting and testing +- Fixed dependency blocking status to be status-aware + - "Blocked (x)" pill now only appears when tasks have **incomplete** blocking dependencies + - Tasks with all completed blocking dependencies no longer show as blocked +- Fixed cache invalidation bug causing blocking/blocked pills to disappear when editing tasks + - When a task is modified, only forward dependencies are cleared (stored in its frontmatter) + - Reverse dependencies are preserved (stored in other tasks' frontmatter) + +## Changed + +- Removed custom TaskNotes icon from task modals + - Task creation and edit modals now use Obsidian's standard title styling + - Thanks to @kepano for the suggestion +- Moved default base templates documentation to \`docs/views/\` + - Location: \`docs/views/default-base-templates.md\` + - Added cross-references to official Obsidian Bases documentation + - Updated code comments to reference new documentation path +- Fixed incorrect quote escaping in default base templates documentation + - YAML examples now use proper single quotes for strings containing double quotes +`});var Mke,Ike=y(()=>{Mke=`# TaskNotes 4 + +TaskNotes 4.0.1 is a stability-focused major release that finishes the migration to Obsidian's Bases core plugin. Every task-facing view (Task List, Kanban, Calendar, Agenda, Mini Calendar, and the embedded Relationships widget) now runs on \`.base\` files. This refactor simplifies the plugin codebase, removes bespoke UI logic, and lets workflows feel native to Obsidian—views are just files in your vault. + +## Highlights + +**New features and improvements:** + +- Performance improvements + - Virtual scrolling in Task List and Kanban views handles **30,000+ tasks** without performance degradation +- **OAuth calendar integration** + - Google Calendar and Microsoft Outlook bi-directional sync + - Drag calendar events in the TaskNotes calendar to update them online +- **Configurable modals and NLP** + - New Modal Fields settings tab for moving, hiding, or requiring fields in create/edit modals + - Rich markdown editor and customizable NLP triggers, including autocomplete for user fields +- **Time management features** + - Time Entry Editor Modal + - Improved Timeblock creation and management + - Completion-based recurrence with \`recurrence_anchor\` field + - Skippable recurrence instances + +**Bases architecture changes:** + +- **Bases-first architecture** + - Task views ship as \`.base\` files inside \`TaskNotes/Views/\` + - Commands and ribbon buttons now open files you control + - Filtering/grouping/sorting uses Bases YAML instead of TaskNotes-specific UI + - Agenda is a dedicated list-mode calendar \`.base\` file for fast daily/weekly reviews +- **Inline workflows stay in sync** + - Unified Relationships widget embeds a Bases view so project subtasks, dependencies, and blocking tasks stay in one place + - Task cards inside notes honor the same Bases filtering/grouping rules as standalone views + +## Why Bases? + +Moving everything to Bases allowed us to delete thousands of lines of bespoke filtering logic, state management, and widget code. The plugin now leans on Obsidian's supported API, which: + +- Reduces maintenance overhead and improves reliability +- Lets advanced users version-control and audit their view definitions +- Makes saved views portable between vaults +- Keeps TaskNotes behavior consistent with other Obsidian-native workflows + +## Upgrade Notes + +- Obsidian **1.10.1 or later** is required (Bases public API with group-by support) +- Enable the **Bases** core plugin before opening TaskNotes views +- Run **Settings → TaskNotes → General → Create Default Files** if you need fresh \`.base\` files +- Use **Export All Saved Views to Bases** to convert any legacy FilterBar saved views into \`.base\` files +- The Relationships widget uses \`TaskNotes/Views/relationships.base\`; adjust that file to change what appears inside notes + +## Breaking Changes + +- The old FilterBar UI has been removed—all filtering and saved views live in \`.base\` files +- Legacy widget settings (\`showProjectSubtasks\`, \`showTaskDependencies\`, etc.) were replaced with \`showRelationships\` and \`relationshipsPosition\` +- Task view commands now fail if their mapped \`.base\` file is missing; configure paths under **Settings → TaskNotes → General → View Commands** +- **Priority sorting now uses alphabetical order instead of custom weights** + - In v3, TaskNotes used priority "weights" to determine sort order (higher weight = higher priority) + - In v4, Obsidian's Bases plugin sorts priorities alphabetically by their value + - The weight field has been removed from the settings UI + - **Workaround**: Name your priority values to sort alphabetically in your desired order + - Example: \`1-urgent\`, \`2-high\`, \`3-medium\`, \`4-normal\`, \`5-low\` + - Or: \`a-urgent\`, \`b-high\`, \`c-medium\`, \`d-normal\`, \`e-low\` +- Agenda view has been replaced by the list view in Calendar + - Grouping is not supported in this view, so the "Overdue" group is no longer provided + - A separate "Overdue" view is available in the "Task List" base file + +## Known Issues + +- Users upgrading from versions prior to 3.x should export saved views to Bases before deleting old plugin data +- Embedded Bases views still require the Bases plugin to remain enabled; disabling Bases will hide TaskNotes task views + +## Details + +### Added + +- Virtual scrolling and lazy rendering to Bases views for handling thousands of notes without performance degradation - Thanks to @aubreyz and @turingexmachina for reporting performance issues and help with diagnosis +- Google Calendar and Microsoft Outlook integration via OAuth 2.0 with automatic syncing +- Time Entry Editor Modal for managing time entries (Alt-drag on calendar to create) +- Kanban Swimlane Layout with horizontal grouping and configurable column widths +- Saved View Converter button in settings to convert v3 saved filter views to \`.base\` files +- Context menus for time entries and ICS events in calendar views +- Calendar icon to ICS event titles for better visual distinction +- Hover tooltips for timeblocks in calendar views +- MiniCalendar view for Bases integration with monthly grid and dot indicators - Thanks to @aubreyz and @turingexmachina for reporting performance issues and help with diagnosis +- (#1090) Portuguese (Brazil) translation - Thanks to @andysteel for the contribution +- Configurable task modal fields with drag-and-drop reordering in new "Modal Fields" settings tab +- Rich markdown editor for NLP task creation with syntax highlighting and wikilink support +- Customizable NLP triggers with autocomplete and keyboard navigation +- Inline task link overlay enhancements with configurable visible properties +- Kanban column reordering via drag and drop with saved order per grouping property +- Mini calendar enhancements including week numbers, heat map visualization, note preview tooltips, and keyboard navigation +- Unified Relationships widget consolidating project subtasks, dependencies, and blocking relationships with automatic tabs +- Updated task card styling with improved hover effects, shadows, and gradient accents +- (#361) Completion-based recurrence support with \`recurrence_anchor\` field for tasks that recur based on completion date - Thanks to @luciolebrillante for the original feature request, and @jhedlund, @nschenone, @BryanWall, @realJohnDoe, and @kazerniel for additional input and interest +- (#416) Support for skipped recurrence instances with \`skipped_instances\` field and right-click skip/unskip in calendar - Thanks to @mdbraber for suggesting the array approach and @jerzy-dudzic for reporting the issue +- Sub-grouping support to Bases Task List view with nested grouping by any property and collapsible groups +- Documentation for default Bases templates showing all default \`.base\` file templates with examples + +### Changed + +- All views (Calendar, MiniCalendar, Kanban, Tasks, Agenda, Project Subtasks) now use Bases architecture with \`.base\` files +- Calendar sources (Google, Microsoft, ICS events) can be toggled independently with improved timezone handling +- Reorganized settings tabs with OAuth calendar settings in Integrations tab +- Refactored Bases integration to use public API and trust pre-sorted data +- Refactored calendar modules to use ES6 imports instead of lazy require() calls +- Time entry events now show task context menu on right-click +- Replaced MinimalNativeCache with just-in-time TaskManager for zero startup time and always-fresh task data +- Completed internationalization with 100% translation coverage across all 6 supported languages +- Migrated to i18n-state-manager CLI tool for improved translation management +- Bases view templates now generate dynamically based on user settings with adaptive task filters +- Updated Bases CalendarView to show TaskNotes in property-based events +- NLP system overhaul with consolidated trigger configuration and direct NaturalLanguageParser usage +- Simplified TaskCard interface and refactored TaskLinkWidget for consistency +- Settings UI enhancements with NLP triggers configurable through Features tab +- Refactored Bases views to use Component lifecycle properly with automatic cleanup +- Improved development experience by converting ESLint errors to warnings +- Renamed "Advanced Calendar" to "Calendar" throughout the UI +- Improved timeblock visual styling in calendar views with reduced border width and softer shadows +- Updated "Export All Views" button to "Export V3 Views" to clarify it migrates v3 saved views +- Improved internationalization (i18n) support in General settings tab with all Bases integration settings using translation keys +- Changed default Tasks List template view order with "All Tasks" first and added "Unscheduled" view + +### Fixed + +- (#843) Fixed task tag being added when "Identify tasks by" is set to "Property" - Thanks to @jack2game for reporting +- Fixed dark mode calendar borders +- Fixed Bases Kanban column ordering - Thanks to @mweichert for reporting +- Fixed state management bug in FilterSettingsComponent +- Fixed timezone handling for recurring events +- (#1022, #684) Fixed tasks randomly disappearing when Smart Connections plugin is enabled by eliminating race condition - Thanks to @alejandrospoz, @seepage87, @amarjt, @luckb0x, and camara-tech for reporting and help debugging +- (#992) Fixed "Failed to resolve module specifier 'obsidian'" error when moving recurring task instances in calendar - Thanks to @jalooc for reporting +- Fixed task dependencies not displaying on task cards with proper isBlocked and isBlocking flags +- Fixed Bases property mapping for user-configured field names +- Fixed Bases views not respecting user-configured visible properties +- Fixed MiniCalendar UTC anchoring for consistent timezone-independent date handling +- Fixed DateValue conversion in BasesDataAdapter for property-based events in CalendarView +- (#1084) Fixed word wrapping in NLP preview items - Thanks to @maybetm for the fix +- (#975) Fixed advanced calendar list headers not respecting theme colors - Thanks to @hugohil for the fix +- (#1089) Fixed embedded task list bases growing unbounded and leaving large empty space - Thanks to @same774 for reporting with screenshot +- Fixed "Highlight today" toggle and calendar view type persistence in Bases Calendar view options +- (#1050) Fixed task modal adding unwanted empty contexts and projects arrays - Thanks to @nightroman for reporting +- Fixed inline task link overlay layout prioritization and horizontal scrolling for metadata +- Fixed group collapse/expand functionality in TaskListView +- Fixed config loading race condition in KanbanView and CalendarView +- Fixed MiniCalendarView to use direct Bases API like other views +- (#893) Fixed yearly recurring tasks not always updating scheduled date to next occurrence when completed - Thanks to @VenturaNotes for reporting +- (#951) Fixed yearly recurring tasks not showing up in calendar's weekly, 3-day, or day views - Thanks to @bespokecomp for reporting +- (#889) Fixed git merge conflicts in calendar subscription metadata by storing in memory instead of disk - Thanks to @karlfrohlich for reporting +- Fixed recurrence modal not loading DTSTART date/time when editing existing recurrence rules +- (#1097) Fixed custom properties and formulas not displaying in Bases views using getValue() method - Thanks to @cathywu for reporting +- (#1099) Fixed issues with default Bases file creation including double-prefix bug and race condition - Thanks to @kmaustral for reporting +- (#1110) Fixed open recurring tasks appearing crossed out in Tasks view by using UTC-anchored dates - Thanks to @kmaustral for reporting +- (#1118) Fixed user-defined fields not working in inline task conversion to TaskNote - Thanks to @guncav for reporting +- Fixed kanban column width CSS constraints not matching settings slider range +- Fixed Kanban view showing empty columns for all user-defined statuses when grouping by status - Thanks to @williamcheuk03 for reporting +- (#1103) Fixed TaskNotes/Views folder being created unnecessarily on startup - Thanks to @Wayment9504 for reporting +- (#1133) Fixed empty priority columns not showing in Kanban view when "Hide empty columns" is disabled - Thanks to @luckb0x for reporting +- Fixed OAuth calendar cards showing "Unknown account" by removing non-functional Account field - Thanks to @Oblique for reporting +- Fixed incorrect Bases syntax in default template files with correct parameter naming +- Fixed incorrect Bases syntax in "Export V3 Views" feature with correct YAML structure +- (#1127) Fixed custom priority colors not being respected in Task List and Subtasks sections - Thanks to @HPmattsloper for reporting +- (#1043) Fixed inability to set "at time of event" (0 offset) as default reminder in settings - Thanks to @dblinnikov for reporting +- (#1055) Fixed break sessions being logged as \`type: work\` when started via command/hotkey - Thanks to @0-BSCode for reporting and debugging +- (#1024) Fixed date/time picker immediately closing when selecting time on iPhone by refactoring to native Modal components - Thanks to @3zra47 for reporting +- (#1122) Fixed inline task titles being truncated too aggressively with increased max-width - Thanks to @jacorvillo for reporting +- Fixed Obsidian crashes when invalid time values entered in Bases calendar view configuration +- (#1120) Fixed custom field mappings not being respected throughout the application - Thanks to @kmaustral for reporting +- (#1121) Fixed custom user fields being saved with auto-generated IDs instead of user-defined property keys - Thanks to @guncav for reporting +- (#1123) Fixed relationships widget only displaying on task notes, now appears on both task and project notes - Thanks to @dblinnikov for reporting +- Fixed time entries not showing in calendar view for tasks without scheduled or due dates +- (#1091) Fixed task card and relationships widgets appearing inside footnote editors - Thanks to @3zra47 for reporting +- (#1086) Fixed calendar "+more" popover showing white text on white background in dark mode - Thanks to @same774 for reporting +- (#1076) Fixed inability to create timeblocks ending at midnight (00:00) - Thanks to @skoove for reporting +- (#958) Fixed cursor jumping and layout shifts when typing near task card or relationships widgets in live preview - Thanks to @thesmithmode for detailed debugging information +- (#513) Fixed task card and relationships widgets not appearing in reading mode and fixed critical memory leak - Thanks to @berzernberg for reporting + +### Removed + +- Removed StatusSuggestionService (functionality consolidated into NaturalLanguageParser) +- Removed legacy FilterBar UI - all filtering now lives in \`.base\` files +- Removed legacy views + +`});var Nke,Rke=y(()=>{Nke=`# TaskNotes 4.0.0-beta.3 + +> **Beta Release** +> +> You may encounter issues. Report problems on [GitHub Issues](https://github.com/callumalpass/tasknotes/issues). + +## Added + +- Updated task card styling + - Increased status dot size from 16px to 18px + - Added subtle shadows and transitions to card hover states + - Updated hover effects on status and priority dots with scaling and removed glow + - Modified metadata pills with backdrop blur and adjusted spacing + - Added box shadows to interactive elements (dates, projects, tags) on hover + - Updated animations to use cubic-bezier easing + - Added gradient accents to subtask and blocking task borders + - Fixed subtasks appearing behind parent card hover backgrounds + - Fixed subtask click and context menu events bubbling to parent cards + - Fixed subtasks inheriting parent priority and status colors + +- (#361) Added completion-based recurrence support with \`recurrence_anchor\` field + - Tasks can now recur based on completion date instead of scheduled date + - Set \`recurrence_anchor: completion\` in task frontmatter to enable this behavior + - When completing a recurring task, the next occurrence will be scheduled relative to the completion date + - The DTSTART in the RRULE automatically updates to the completion date, ensuring calendar views show future occurrences at the correct dates + - Defaults to \`scheduled\` (original behavior) if not specified + - Useful for tasks like "Exercise weekly" where you want the next occurrence 7 days after you actually complete it, not 7 days after it was scheduled + - Example: Complete a weekly task 2 days late, and the next occurrence will be 7 days from the completion date (not the original scheduled date) + - Thanks to @luciolebrillante for the original feature request, and @jhedlund, @nschenone, @BryanWall, @realJohnDoe, and @kazerniel for additional input and interest + +- (#416) Added support for skipped recurrence instances with \`skipped_instances\` field + - Recurring tasks can now have individual instances marked as "skipped" without completing them + - Skipped instances are stored in the \`skipped_instances\` frontmatter array (e.g., \`["2025-11-15", "2025-11-22"]\`) + - Right-click on a recurring task instance in calendar views to skip/unskip it + - Visual styling differentiates skipped instances: + - Calendar views: Gray background with muted appearance + - Task cards: Strike-through text with gray styling + - Skipped instances don't affect the recurrence pattern - future instances continue as scheduled + - Useful for holidays, vacations, or other planned exceptions to recurring tasks + - Thanks to @mdbraber for the suggestion to use an array similar to \`complete_instances\`, and @jerzy-dudzic for reporting the issue + + +## Fixed + +- (#893) Fixed yearly recurring tasks not always updating scheduled date to next occurrence when completed + - Increased look-ahead period for yearly recurrence from 365 days to 800 days (~2.2 years) + - Also optimized look-ahead periods for other frequencies: daily (30 days), weekly (90 days), monthly (400 days) + - Ensures the next occurrence is always found when completing recurring task instances + - Thanks to @VenturaNotes for reporting + +- (#951) Fixed yearly recurring tasks not showing up in calendar's weekly, 3-day, or day views + - Extended the look-ahead period for yearly recurring tasks when generating calendar instances + - Calendar views now look ahead ~2.2 years for yearly tasks to ensure occurrences appear even in short date ranges + - Only displays instances that fall within the actual visible calendar range + - Weekly recurring tasks were unaffected and continued to work correctly + - Thanks to @bespokecomp for reporting + +- (#889) Fixed git merge conflicts in calendar subscription metadata + - Calendar subscription \`lastFetched\` and \`lastError\` fields are now stored in memory instead of being saved to disk + - Prevents git conflicts when syncing vaults across multiple computers that independently fetch calendar subscriptions + - The "last synced" timestamp in settings will reset on plugin reload, but subscriptions will re-fetch automatically + - Thanks to @karlfrohlich for reporting + +- Fixed recurrence modal not loading DTSTART date/time when editing existing recurrence rules + - The custom recurrence modal now correctly parses and displays the start date and time fields + - Fixed parser that was splitting on \`=\` instead of \`:\` for DTSTART values + +- (#1097) Fixed custom properties and formulas not displaying in Bases views + - Updated TaskCard to use Bases API's getValue() method for formulas and custom note properties + - Formulas now work correctly using \`formula.NAME\` syntax + - Custom note properties now work correctly using \`note.PROPERTY\` syntax + - Thanks to @cathywu for reporting + +- (#1099) Fixed issues with default Bases file creation + - Fixed double-prefix bug in relationships template that generated invalid filter expressions like \`note.note.projects\` + - Fixed race condition where files created during plugin load wouldn't appear in file explorer + - Default Bases files now generate with correct property paths and appear reliably in the file explorer + - Thanks to @kmaustral for reporting + +- (#1110) Fixed open recurring tasks appearing crossed out in Tasks view + - Removed stale \`selectedDate\` property that was never updated in v4 + - Tasks view now uses fresh UTC-anchored "today" for correct recurring task completion status + - Fixes issue where tasks completed yesterday would appear crossed out today for users in positive UTC offset timezones + - Also fixed KanbanView to use UTC-anchored dates for consistency + - Thanks to @kmaustral for reporting + +- (#1118) Fixed user-defined fields not working in inline task conversion + - User-defined fields like \`>customfield value\` now properly convert to frontmatter when using the "TaskNote: Convert task to TaskNote" command + - Fixed fields appearing with internal IDs (e.g., \`field_1761435101864\`) instead of configured frontmatter key names + - Array values are now properly joined with commas + - Added \`userFields\` property to \`ParsedTaskData\` interface to support custom fields throughout the conversion flow + - Thanks to @guncav for reporting + +- Fixed kanban column width CSS constraints not matching settings + - Updated CSS min-width from 280px to 200px and max-width from 350px to 500px to match slider range + - Column width slider now works correctly across the full 200-500px range + +- Kanban view now shows empty columns for all user-defined statuses when grouping by status + - Empty columns appear for custom statuses defined in settings, even when no tasks have that status + - Allows users to drag tasks into empty status columns + - Works in both flat kanban view and swimlane mode + - Respects the existing "Hide empty columns" setting + - Thanks to @williamcheuk03 for reporting this issue +`});var _ke,Fke=y(()=>{_ke=`# TaskNotes 4.0.0-beta.2 + +> **Beta Release** +> +> You may encounter issues. Report problems on [GitHub Issues](https://github.com/callumalpass/tasknotes/issues). + +## Added + +- (#1090) Portuguese (Brazil) translation + - Full Portuguese (pt-BR) localization support + - A big thanks to @andysteel for the contribution +- **Configurable task modal fields** + - New "Modal Fields" settings tab for complete control over task creation and edit modals + - Configure which fields appear in creation vs edit modals independently + - Drag-and-drop reordering of fields within groups (metadata, organization, dependencies, custom) + - Enable/disable individual fields (including core fields like contexts, tags, time estimate) + - Organize fields into groups + - Automatic migration of existing user-defined fields + - Title and details fields support visibility toggling (ordering fixed for consistency) +- **Rich markdown editor for NLP task creation** + - Replaced plain textarea with full CodeMirror markdown editor + - Live preview, syntax highlighting, and wikilink support + - Ctrl/Cmd+Enter keyboard shortcut to save task + - Esc/Tab keyboard shortcuts for modal control +- **Customizable NLP triggers with autocomplete** + - Configure custom trigger characters/strings for each property type (tags, contexts, projects, status, priority) + - Supports user-defined field triggers + - CodeMirror-based autocomplete with keyboard navigation (arrow keys, Enter, Tab) + - Quote support for multi-word values in user fields + - Native tag suggester integration when using # trigger +- **Inline task link overlay enhancements** + - Configurable visible properties for inline task cards + - PropertySelectorModal for selecting which properties to display + - Improved layout: title prioritized, horizontal scrolling for metadata + - Real-time updates when task data changes +- **New utility services** + - \`TriggerConfigService\` - manages NLP trigger configurations + - \`PropertySelectorModal\` - reusable multi-select property picker + - Property helpers for consistent property handling across views +- Kanban column reordering via drag and drop + - Drag column headers to reorder columns + - Column order is saved per grouping property + - Visual feedback during drag operations +- Mini calendar enhancements (in progress) + - Week numbers column + - Heat map intensity visualization + - Note preview tooltips on hover + - Keyboard navigation +- **Unified Relationships widget** + - Consolidated project subtasks, task dependencies, and blocking relationships into a single dynamic widget + - Four automatic tabs: Subtasks (Kanban), Projects (List), Blocked By (List), Blocking (Kanban) + - Tabs automatically show/hide based on available relationship data + - Bases views handle all data updates reactively - no manual refresh needed + - Single configuration setting: show/hide and position (top/bottom) + - Significantly reduced code complexity (430 fewer lines) + +## Fixed + +- (#1084) Fixed word wrapping in NLP preview items + - Thanks to @maybetm for the fix +- (#975) Fixed advanced calendar list headers not respecting theme colors + - Thanks to @hugohil for the fix +- (#1089) Fixed embedded task list bases growing unbounded and leaving large empty space + - Embedded bases now scroll internally instead of expanding to show all tasks + - Consistent behavior between task list and kanban embedded views + - Thanks to @same774 for reporting with screenshot +- **Bases Calendar view options now working correctly** + - Fixed "Highlight today" toggle not applying - now properly adds/removes CSS class when toggled + - Fixed calendar view type (month/week/day/etc) not being saved when changed via calendar buttons + - View type is now persisted when users click month/week/day buttons in the calendar UI +- (#1050) Task modal no longer adds unwanted empty contexts and projects arrays + - FieldMapper now checks if arrays are empty before writing to frontmatter + - Thanks to @nightroman for reporting this issue +- **Inline task link overlay fixes** + - Fixed layout prioritization: title now prioritized over metadata + - Added horizontal scrolling for metadata to prevent overflow + - Fixed real-time update listeners for task data changes +- Fixed group collapse/expand functionality in TaskListView + - Re-registered click event listener for group headers using Component API + - Groups can now be properly collapsed and expanded +- Fixed config loading race condition in KanbanView and CalendarView + - Config is now properly loaded in onload() lifecycle method + - Views wait for config before rendering options +- Fixed MiniCalendarView to use direct Bases API like other views + - Consistent use of Component lifecycle methods + - Proper cleanup in onunload() + +## Changed + +- **NLP system overhaul** + - Replaced \`StatusSuggestionService\` wrapper with direct \`NaturalLanguageParser\` usage + - Consolidated trigger configuration into unified \`TriggerConfigService\` + - Enhanced \`NaturalLanguageParser\` with full trigger and user field support + - Removed custom # tag autocomplete in favor of Obsidian's native tag suggester (when using # trigger) +- **Task card and editor improvements** + - Simplified \`TaskCard\` interface - removed unused options (showCheckbox, showArchiveButton, groupByDate) + - Refactored \`TaskLinkWidget\` to use unified \`TaskCard\` component for consistency + - Added support for inline vs. block layout modes in task cards + - Improved task card BEM CSS with better styling for inline mode +- **Settings UI enhancements** + - NLP triggers now configurable through Settings > Features tab + - Added settings for inline task card visible properties + - Improved appearance tab with property selector integration + - Better organization of NLP-related settings +- Refactored Bases views to use Component lifecycle properly + - Views now extend Component and use onload()/onunload() + - Automatic cleanup of event listeners via Component.registerDomEvent() + - Improved state management and ephemeral state handling +- Improved development experience + - Converted ESLint errors to warnings for non-blocking development + - Fixed various linting issues and unused imports + +## Removed + +- Removed \`StatusSuggestionService\` (functionality consolidated into \`NaturalLanguageParser\`) + +## Breaking Changes + +- **Relationships widget settings consolidated** (automatic migration) + - Old settings removed: \`showProjectSubtasks\`, \`projectSubtasksPosition\`, \`showTaskDependencies\`, \`taskDependenciesPosition\` + - New unified settings: \`showRelationships\`, \`relationshipsPosition\` + - Widget now appears on ALL notes (tasks, projects, regular notes) - Bases filtering controls which tabs are visible + - **Migration**: Existing users will see the new unified widget automatically. If you had project subtasks enabled, relationships widget will be enabled by default + - **Bases file change**: The command mapping changed from \`'project-subtasks': 'TaskNotes/Views/project-subtasks.base'\` to \`'relationships': 'TaskNotes/Views/relationships.base'\` + - Run "Create Default Files" in Settings > General to create the new \`relationships.base\` file + +`});var Lke,Oke=y(()=>{Lke=`# TaskNotes 4.0.0-beta.1 + +> **Beta Release** +> +> You may encounter issues. Report problems on [GitHub Issues](https://github.com/callumalpass/tasknotes/issues). + +## Added + +- Added context menus for time entries and ICS events in calendar + - Time entries: Right-click shows task context menu, left-click opens time entry editor modal + - ICS/Google/Microsoft Calendar events: Right-click shows ICS event context menu with options to show details, create task/note, link note, and copy info +- Added calendar icon to ICS event titles for better visual distinction +- Added hover tooltips for timeblocks in calendar views +- Added **MiniCalendar view** for Bases integration + - Monthly calendar grid with dot indicators on days with notes + - Configurable date property (file.ctime, note.dateCreated, etc.) + - Fuzzy selector modal for selecting notes on clicked days + - Ctrl+click (or Cmd+click on Mac) on any day opens/creates daily note +- Added virtual scrolling and lazy rendering to Bases views for high-performance handling of large datasets + - TaskListView: Virtual scrolling for 100+ tasks in flat and grouped views with collapsible groups + - KanbanView: Virtual scrolling for regular columns (30+ tasks) and swimlane cells (30+ tasks per cell) + - Tested with up to **30,000 notes** with no performance degradation + - Thanks to @aubreyz and @turingexmachina for their reports of performance issues and diagnosis help + + +## Changed + +- Refactored Bases integration to use public API and trust pre-sorted data + - Migrated all three views (Task List, Kanban, Calendar) to clean class-based architecture + - Removed legacy view files and ~500 lines of redundant sorting/grouping logic + - Introduced BasesDataAdapter, PropertyMappingService, and BasesViewBase abstractions + - Trusts Bases plugin to provide pre-sorted and pre-grouped data via public API + - Reduced code duplication by 40% while maintaining full feature parity +- Refactored calendar modules to use ES6 imports instead of lazy require() calls + - Removed all dynamic require() calls from calendar-core.ts and calendar-view.ts + - Consolidated all imports at module top level + - Improves code maintainability, makes dependencies explicit, and follows modern TypeScript best practices +- Time entry events now show task context menu on right-click (previously had no context menu) +- Replaced MinimalNativeCache with just-in-time TaskManager for improved reliability + - Removed complex index synchronization in favor of direct MetadataCache queries + - Eliminated 7 internal indexes (tasksByDate, tasksByStatus, overdueTasks, etc.) + - Added minimal DependencyCache for task dependencies and project references only + - Zero startup time (no index building required) + - Always provides fresh, accurate task data from Obsidian's MetadataCache +- Completed internationalization with 100% translation coverage across all supported languages + - Added 90 missing translation keys to English base + - Completed 829 translations across 6 languages (German, Spanish, French, Japanese, Russian, Chinese) + - All locales now have complete coverage (1745/1745 keys) + - Improved translation quality for migration system, calendar settings, statistics, ICS events, and filter components +- Migrated to i18n-state-manager CLI tool for translation management + - Replaced custom scripts with more robust i18n-state-manager package + - Added i18n-state.config.json for project-specific patterns + - New features: find-unused, check-duplicates, improved stale detection + - Hash-based state tracking and ripgrep-based scanning for performance +- Bases view templates now generate dynamically based on user settings + - Task filters adapt to user's task identification method (tag or property) + - Property ordering reflects defaultVisibleProperties setting + - Uses correct YAML object notation for Bases filters + - Maintains backward compatibility with legacy static templates +- Updated Bases CalendarView to show TaskNotes in property-based events + - Tasks can now be visualized on calendar via any date property (dateCreated, scheduled, due, etc.) + - Previously all TaskNotes were filtered out from property-based events + +## Fixed + +- (#1022, #684) Fixed tasks randomly disappearing when Smart Connections plugin is enabled + - Eliminated race condition caused by index synchronization delays + - TaskManager now reads directly from Obsidian's MetadataCache instead of maintaining separate indexes + - No more timing-sensitive code that could conflict with other plugins' metadata processing + - Tasks will always be visible regardless of other plugins' processing times + - Thanks to @alejandrospoz, @seepage87, @amarjt, @luckb0x, camara-tech for reporting and help debugging. +- (#992) Fixed "Failed to resolve module specifier 'obsidian'" error when moving recurring task instances in calendar + - Removed unnecessary dynamic imports that were causing module resolution failures + - Consolidated imports at top of calendar-core.ts module + - Thanks to @jalooc for reporting this issue +- Fixed task dependencies not displaying on task cards + - TaskManager now properly calculates isBlocked and isBlocking flags from dependency data + - Added missing property extractors and renderers in TaskCard for all dependency-related fields + - Dependency information now shows correctly in Bases views, task note widgets, and other views + - Shows "Blocked (n)" and "Blocking (n)" pills, plus detailed task links +- Fixed Bases property mapping for user-configured field names + - PropertyMappingService now correctly strips prefixes and applies FieldMapper transformations + - Example: User configures "state" → "status", Bases provides "note.state", now correctly maps to "status" + - Ensures TaskCard properly recognizes and renders user-configured properties +- Fixed Bases views not respecting user-configured visible properties + - Now prioritizes Bases 1.10.0+ public API config.getOrder() method + - Removed reliance on internal API paths that no longer work + - Filters out blocked/blocking properties when using defaults (only shown when explicitly requested via blockedBy) +- Fixed MiniCalendar UTC anchoring for consistent timezone-independent date handling +- Fixed DateValue conversion in BasesDataAdapter + - DateValue objects have {date: Date, time: boolean} structure + - Now properly checks for value.date instanceof Date before legacy conversion methods + - Fixes property-based events in CalendarView + +`});var zke,Bke=y(()=>{zke=`# TaskNotes 4.0.0-beta.0 + +> **Beta Release** +> +> You may encounter issues. Report problems on [GitHub Issues](https://github.com/callumalpass/tasknotes/issues). + +## What's New in v4 + +TaskNotes v4 migrates all views to the Bases system. + +### Breaking Changes + +- **Minimum Obsidian version: 1.10.1** +- **View commands now use Bases files** - Ribbon icons and command palette commands (Calendar, Kanban, Tasks, Agenda, Project Subtasks) now open \`.base\` files created automatically in your vault +- **Saved filter views** - Custom saved views can be converted to \`.base\` files using a conversion button in settings + +## Added + +### OAuth Calendar Integration + +- Google Calendar and Microsoft Outlook integration via OAuth 2.0 + - View and sync calendar events in Bases calendar + - Drag events in the TaskNotes bases calendar to change the event's time online + - Events sync every 15 minutes or upon local change + - Requires creating your own OAuth application (approximately 15 minutes) + - See [Calendar Setup Guide](https://tasknotes.dev/calendar-setup) + +### Time Entry Editor Modal + +- Dedicated interface for managing time entries + - Alt-drag on Bases calendar to create time entries + - View total tracked time per task + - Edit and delete time entries + - Access via Task Action Palette (Alt/Opt + Enter) + +### Kanban Swimlane Layout + +- Horizontal swimlane grouping option for Bases Kanban + - Group tasks by status, priority, or other fields + - Hide empty columns + - Configurable column widths + - Improved drag-and-drop in swimlane mode + +### Saved View Converter + +- Conversion button in settings to convert saved filter views to \`.base\` files +- Original settings preserved +- Converted views created in \`TaskNotes/Views/\` + +## Changed + +### View System Architecture + +- All views now use Bases architecture + - Calendar, Kanban, Tasks, Agenda, and Project Subtasks are \`.base\` files + - Views stored in \`TaskNotes/Views/\` + - Keyboard shortcuts and ribbon icons map to \`.base\` files + - Configure file paths in Settings → Integrations → Bases Integration + +### Calendar + +- Control which calendar sources display + - Toggle Google Calendar, Microsoft Calendar, and ICS events independently + - Configurable list view with custom day count (2-10 days) + - Improved timezone handling for recurring events + +### Settings + +- Reorganized settings tabs + - OAuth calendar settings in Integrations tab + - Updated help text + +## Fixed + +- (#843) Fixed task tag being added when "Identify tasks by" is set to "Property" + - TaskCreationModal, TaskEditModal, and InstantTaskConvertService now respect taskIdentificationMethod setting + - Thanks to @jack2game +- Fixed dark mode calendar borders +- Fixed Bases Kanban column ordering - Thanks to @mweichert +- Fixed state management bug in FilterSettingsComponent +- Fixed timezone handling for recurring events + +## Migration Guide + +### First Launch + +1. Default view files are created automatically in \`TaskNotes/Views/\` +2. Ribbon and command palette commands now open \`.base\` files +3. Review Settings → General to customize view file paths + +### Converting Saved Filter Views + +1. Go to Settings → General +2. Click the conversion button to convert saved filter views to \`.base\` files +3. Converted views appear in a file in \`TaskNotes/Views/\` + +### Calendar Integration (Optional) + +1. Go to Settings → Integrations → OAuth Calendar Integration +2. Follow the [Calendar Setup Guide](https://tasknotes.dev/calendar-setup) +3. Create OAuth applications with Google and/or Microsoft (approximately 15 minutes) +4. Enter Client ID and Secret in calendar cards +5. Click Connect + +## Known Limitations + +- Quick OAuth setup is disabled - only advanced setup (your own credentials) is available +- Saved filter views require manual conversion using the button in settings +- Migration is one-way - downgrading to v3 may require manual reconfiguration +- OAuth setup requires creating applications with Google/Microsoft + +## Feedback + +Report issues on [GitHub](https://github.com/callumalpass/tasknotes/issues). Include: + +- Obsidian version +- Steps to reproduce +- Console errors (Ctrl/Cmd + Shift + I) +- Whether issue occurs after migration or fresh install +`});var jke,$ke,Uke=y(()=>{Kye();Qye();Xye();tve();nve();ive();ove();cve();uve();mve();hve();yve();kve();bve();Sve();xve();Dve();Ave();Ive();Rve();Fve();Ove();Bve();$ve();Hve();Wve();Gve();Kve();Qve();Xve();tke();nke();ike();oke();cke();uke();mke();hke();yke();kke();bke();Ske();xke();Dke();Ake();Ike();Rke();Fke();Oke();Bke();jke="4.13.5",$ke=[{version:"4.13.5",content:Yye,date:"2026-09-24T07:11:25+10:00",isCurrent:!0},{version:"4.13.4",content:Zye,date:"2026-09-22T09:10:49+10:00",isCurrent:!1},{version:"4.13.3",content:Jye,date:"2026-09-21T20:07:07+10:00",isCurrent:!1},{version:"4.13.2",content:eve,date:"2026-09-19T15:31:36+10:00",isCurrent:!1},{version:"4.13.1",content:rve,date:"2026-09-15T20:58:32+10:00",isCurrent:!1},{version:"4.13.0",content:ave,date:"2026-09-13T21:51:00+10:00",isCurrent:!1},{version:"4.12.5",content:sve,date:"2026-08-26T12:59:44+10:00",isCurrent:!1},{version:"4.12.4",content:lve,date:"2026-08-24T00:23:43+10:00",isCurrent:!1},{version:"4.12.3",content:dve,date:"2026-08-10T08:08:05+10:00",isCurrent:!1},{version:"4.12.2",content:pve,date:"2026-08-09T15:41:43+10:00",isCurrent:!1},{version:"4.12.1",content:fve,date:"2026-08-08T13:02:07+10:00",isCurrent:!1},{version:"4.12.0",content:gve,date:"2026-08-07T18:42:18+10:00",isCurrent:!1},{version:"4.11.1",content:vve,date:"2026-06-26T08:38:30+10:00",isCurrent:!1},{version:"4.11.0",content:Tve,date:"2026-06-10T08:09:52+10:00",isCurrent:!1},{version:"4.10.2",content:wve,date:"2026-06-05T22:52:07+10:00",isCurrent:!1},{version:"4.10.1",content:Cve,date:"2026-06-05T10:16:05+10:00",isCurrent:!1},{version:"4.10.0",content:Eve,date:"2026-06-01T21:50:12+10:00",isCurrent:!1},{version:"4.9.2",content:Pve,date:"2026-05-30T05:43:04+10:00",isCurrent:!1},{version:"4.9.1",content:Mve,date:"2026-05-26T18:40:45+10:00",isCurrent:!1},{version:"4.9.0",content:Nve,date:"2026-05-24T09:35:31+10:00",isCurrent:!1},{version:"4.8.1",content:_ve,date:"2026-05-20T17:46:40+10:00",isCurrent:!1},{version:"4.8.0",content:Lve,date:"2026-05-19T18:47:44+10:00",isCurrent:!1},{version:"4.7.2",content:zve,date:"2026-05-14T22:13:36+10:00",isCurrent:!1},{version:"4.7.1",content:jve,date:"2026-05-14T08:02:31+10:00",isCurrent:!1},{version:"4.7.0",content:Uve,date:"2026-05-14T06:40:12+10:00",isCurrent:!1},{version:"4.6.0",content:Vve,date:"2026-05-13T08:24:23+10:00",isCurrent:!1},{version:"4.5.3",content:qve,date:"2026-04-30T22:32:11+10:00",isCurrent:!1},{version:"4.5.2",content:Yve,date:"2026-04-26T20:11:43+10:00",isCurrent:!1},{version:"4.5.1",content:Zve,date:"2026-03-31T20:39:11+11:00",isCurrent:!1},{version:"4.5.0",content:Jve,date:"2026-03-31T08:48:09+11:00",isCurrent:!1},{version:"4.4.0",content:eke,date:"2026-02-17T21:53:32+11:00",isCurrent:!1},{version:"4.3.3",content:rke,date:"2026-02-15T15:09:21+11:00",isCurrent:!1},{version:"4.3.2",content:ake,date:"2026-02-08T19:22:37+11:00",isCurrent:!1},{version:"4.3.1",content:ske,date:"2026-02-08T14:06:51+11:00",isCurrent:!1},{version:"4.3.0",content:lke,date:"2026-01-07T20:31:36+11:00",isCurrent:!1},{version:"4.2.1",content:dke,date:"2026-01-04T11:51:59+11:00",isCurrent:!1},{version:"4.2.0",content:pke,date:"2026-01-02T08:38:48+11:00",isCurrent:!1},{version:"4.1.3",content:fke,date:"2025-12-08T21:28:48+11:00",isCurrent:!1},{version:"4.1.2",content:gke,date:"2025-12-07T16:22:44+11:00",isCurrent:!1},{version:"4.1.1",content:vke,date:"2025-12-01T21:44:07+11:00",isCurrent:!1},{version:"4.1.0",content:Tke,date:"2025-11-30T18:58:10+11:00",isCurrent:!1},{version:"4.0.5",content:wke,date:"2025-11-23T20:27:09+11:00",isCurrent:!1},{version:"4.0.4",content:Cke,date:"2025-11-20T23:38:28+11:00",isCurrent:!1},{version:"4.0.3",content:Eke,date:"2025-11-20T08:16:00+11:00",isCurrent:!1},{version:"4.0.2",content:Pke,date:"2025-11-19T21:50:00+11:00",isCurrent:!1},{version:"4.0.1",content:Mke,date:"2025-11-18T22:29:23+11:00",isCurrent:!1},{version:"4.0.0-beta.3",content:Nke,date:"2025-11-17T07:51:37+11:00",isCurrent:!1},{version:"4.0.0-beta.2",content:_ke,date:"2025-11-09T20:36:35+11:00",isCurrent:!1},{version:"4.0.0-beta.1",content:Lke,date:"2025-11-04T20:05:28+11:00",isCurrent:!1},{version:"4.0.0-beta.0",content:zke,date:"2025-10-30T00:02:44+11:00",isCurrent:!1}]});function IW(n){try{return decodeURIComponent(n)}catch(e){return n}}function Vke(n){let e=n.trim();return e.startsWith("<")&&e.endsWith(">")?e.slice(1,-1).trim():e}function xR(n){var a;if(!n)return"";let e=IW(Vke(n));return((a=e.split(/[#!^]/)[0])!=null?a:e).replace(/^\/+/,"").replace(/\.md$/i,"").trim()}function NW(n){return n?IW(n).trim().replace(/^[#^]+/,"").trim():""}function Hke(n){var r;let e=xR(n),t=e.split("/").filter(Boolean);return(r=t[t.length-1])!=null?r:e}function aE(n){if(!n)return;let e=IW(Vke(n)),t=e.search(/[#^]/);if(t!==-1)return NW(e.slice(t))||void 0}function Dc(n,e){let t=NW(e);if(!t)return;let r=n==null?void 0:n.trim();return r?`${r} > ${t}`:t}function RW(n,e,t,r){let a=xR(n)||NW(n);if(!a||!e)return!1;let i=xR(e),s=xR(t),o=new Set([i,Hke(i)]);s&&(o.add(s),o.add(Hke(s)));let l=aE(t);if(l){o.add(l);let c=Dc(r,l);c&&o.add(c)}return o.has(a)}function Dk(n,e,t){let r=n==null?void 0:n.trim();if(r&&!RW(r,e,t))return r}var ER=y(()=>{});var _W={};Xe(_W,{TaskLinkDetectionService:()=>iE});var Ah,iE,DR=y(()=>{Ah=require("obsidian");q();ER();iE=class{constructor(e,t){this.linkCache=new Map;this.plugin=e,this.logger=t!=null?t:M({tag:"TaskLinkDetectionService",isDebugEnabled:()=>e.settings.enableDebugLogging})}async detectTaskLink(e,t,r="wikilink"){let a=r==="wikilink"?this.parseWikilink(e):this.parseMarkdownLink(e);if(!a)return{isValidTaskLink:!1};let{linkPath:i,displayText:s}=a,o=`${t}:${i}`,l=this.linkCache.get(o);if(l){let p=this.plugin.app.vault.getAbstractFileByPath(i);if(p instanceof Ah.TFile&&p.stat.mtime===l.lastModified)return l.result}let c=this.resolveLinkPath(i,t);if(!c){let p={isValidTaskLink:!1};return this.cacheResult(o,p,0),p}let d=this.plugin.app.vault.getAbstractFileByPath(c);if(!(d instanceof Ah.TFile)){let p={isValidTaskLink:!1};return this.cacheResult(o,p,0),p}try{let p=await this.plugin.cacheManager.getTaskInfo(c);if(p){let m=this.resolveDisplayText(a,r,p,i,s),f={isValidTaskLink:!0,taskPath:c,taskInfo:p,displayText:m};return this.cacheResult(o,f,d.stat.mtime),f}}catch(p){this.logger.debug("Error checking task info for link",{category:"stale-data",operation:"detect-task-link",details:{resolvedPath:c},error:p})}let u={isValidTaskLink:!1};return this.cacheResult(o,u,d.stat.mtime),u}resolveDisplayText(e,t,r,a,i){return t==="markdown"?i?Dk(i,r.path,a):Dc(r.title,e.subpath):e.hasExplicitAlias?i:Dc(r.title,e.subpath)}parseWikilink(e){let t=e.slice(2,-2).trim();if(!t)return null;let r=t.indexOf("|");if(r!==-1){let i=t.slice(0,r).trim(),s=t.slice(r+1).trim();if(!i||!s)return null;let o=(0,Ah.parseLinktext)(i);return{linkPath:o.path,displayText:s,subpath:o.subpath||void 0,hasExplicitAlias:!0}}let a=(0,Ah.parseLinktext)(t);return{linkPath:a.path,subpath:a.subpath||void 0,hasExplicitAlias:!1}}parseMarkdownLink(e){let t=e.match(/^\[([^\]]*)\]\(([^)]+)\)$/);if(!t)return null;let r=t[1].trim(),a=t[2].trim();if(a.startsWith("<")&&a.endsWith(">")&&(a=a.slice(1,-1).trim()),!a)return null;try{a=decodeURIComponent(a)}catch(s){this.logger.debug("Failed to decode URI component",{category:"validation",operation:"parse-markdown-link",details:{linkPath:a},error:s})}let i=(0,Ah.parseLinktext)(a);return{linkPath:i.path,displayText:r||void 0,subpath:i.subpath||void 0,hasExplicitAlias:!!r}}resolveLinkPath(e,t){try{let r=this.plugin.app.metadataCache.getFirstLinkpathDest(e,t);return(r==null?void 0:r.path)||null}catch(r){return this.logger.debug("Error resolving link path",{category:"provider",operation:"resolve-link-path",details:{linkPath:e,sourcePath:t},error:r}),null}}cacheResult(e,t,r){if(this.linkCache.set(e,{result:t,lastModified:r}),this.linkCache.size>1e3){let a=this.linkCache.keys().next().value;this.linkCache.delete(a)}}clearCacheForFile(e){for(let[t]of this.linkCache)t.includes(e)&&this.linkCache.delete(t)}clearCache(){this.linkCache.clear()}findWikilinks(e){let t=[],r=/\[\[([^\]]+)\]\]/g,a;for(;(a=r.exec(e))!==null;)t.push({match:a[0],start:a.index,end:a.index+a[0].length,type:"wikilink"});let i=/\[([^\]]*)\]\(([^)]+)\)/g;for(r.lastIndex=0;(a=i.exec(e))!==null;)t.push({match:a[0],start:a.index,end:a.index+a[0].length,type:"markdown"});return t.sort((s,o)=>s.start-o.start)}cleanup(){this.linkCache.clear()}}});var Wke,Mh,FW=y(()=>{Wke=require("@codemirror/view");PR();Ua();Yl();xe();Mh=class n extends Wke.WidgetType{constructor(t,r,a,i,s=Br(new Date),o){super();this.subpath=o;this.taskInfo=t,this.plugin=r,this.originalText=a,this.displayText=i,this.targetDate=s,this.targetDateKey=ae(s)}toDOM(t){let r=this.plugin.settings.inlineVisibleProperties||["status","priority","due","scheduled","recurrence"],a=di(r,this.plugin),i=activeWindow.createSpan();i.className="tasknotes-plugin tasknotes-inline-widget",i.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),i.classList.add("tn-static-display-inline-cccfa456"),i.classList.add("tn-static-vertical-align-baseline-657d9c46"),i.addEventListener("pointerdown",o=>{o.stopPropagation()}),i.addEventListener("mousedown",o=>{o.stopPropagation(),o.button===0&&o.preventDefault()}),i.addEventListener("mouseup",o=>{o.stopPropagation()});let s=pr(this.taskInfo,this.plugin,a,{layout:"inline",targetDate:this.targetDate,displayText:this.displayText,navigationSubpath:this.subpath});return i.appendChild(s),s.dataset.originalText=this.originalText,s.addEventListener("tasknotes:task-updated",()=>{window.setTimeout(()=>{t&&typeof t.dispatch=="function"&&Qp(t,this.taskInfo.path)},50)}),i}eq(t){return t instanceof n?this.taskInfo.path===t.taskInfo.path&&this.taskInfo.status===t.taskInfo.status&&this.taskInfo.title===t.taskInfo.title&&this.taskInfo.priority===t.taskInfo.priority&&this.taskInfo.archived===t.taskInfo.archived&&this.taskInfo.due===t.taskInfo.due&&this.taskInfo.scheduled===t.taskInfo.scheduled&&this.taskInfo.recurrence===t.taskInfo.recurrence&&this.displayText===t.displayText&&this.subpath===t.subpath&&this.originalText===t.originalText&&this.targetDateKey===t.targetDateKey&&JSON.stringify(this.taskInfo.complete_instances)===JSON.stringify(t.taskInfo.complete_instances)&&JSON.stringify(this.taskInfo.skipped_instances)===JSON.stringify(t.taskInfo.skipped_instances)&&this.taskInfo.dateModified===t.taskInfo.dateModified:!1}ignoreEvent(t){return t.type==="mousedown"||t.type==="click"}get estimatedHeight(){return-1}get block(){return!1}}});function mGe(n){return Pc.ViewPlugin.fromClass(class{constructor(e){this.eventListeners=[];this.activeWidgets=new Map;this.lastKnownTasks=new Map;this.view=e,this.decorations=this.buildDecorations(e),this.setupEventListeners()}destroy(){this.eventListeners.forEach(e=>{n.emitter.offref(e)}),this.eventListeners=[],this.activeWidgets.clear(),this.lastKnownTasks.clear()}setupEventListeners(){let e=n.emitter.on(Ra,()=>{this.refreshDecorations()}),t=n.emitter.on(rt,()=>{this.refreshDecorations()}),r=n.emitter.on(Di,s=>{s!=null&&s.path&&this.lastKnownTasks.delete(s.path),this.refreshDecorations()}),a=n.emitter.on(Ou,()=>{this.lastKnownTasks.clear(),this.refreshDecorations()}),i=n.emitter.on("settings-changed",()=>{this.refreshDecorations()});this.eventListeners.push(e,t,r,a,i)}refreshDecorations(){this.view&&typeof this.view.dispatch=="function"&&queueMicrotask(()=>{try{this.activeWidgets.clear(),this.view.dispatch({effects:[AR.of({})]})}catch(e){sE.error("Error dispatching task link update:",{category:"validation",operation:"dispatching-task-link-update",error:e})}})}update(e){var r,a;if(this.view=e.view,!((r=n==null?void 0:n.settings)!=null&&r.enableTaskLinkOverlay)){this.decorations=Pc.Decoration.none;return}try{if(!e.state.field(Vi.editorLivePreviewField)){this.decorations=Pc.Decoration.none;return}}catch(i){this.decorations=Pc.Decoration.none;return}let t=e.transactions.some(i=>i.effects.some(s=>s.is(AR)));if(e.docChanged||e.selectionSet||t){if(t){let i=(a=e.transactions.flatMap(s=>s.effects).find(s=>s.is(AR)))==null?void 0:a.value;if(i!=null&&i.taskPath)for(let[s]of this.activeWidgets.entries())s.includes(i.taskPath)&&this.activeWidgets.delete(s);else this.activeWidgets.clear()}this.decorations=this.buildDecorations(e.view)}}buildDecorations(e){var t,r;try{if(!((t=n==null?void 0:n.settings)!=null&&t.enableTaskLinkOverlay))return Pc.Decoration.none;if(!e.state.field(Vi.editorLivePreviewField))return Pc.Decoration.none;let i=e.state.field(Vi.editorInfoField,!1),s=(r=i==null?void 0:i.file)==null?void 0:r.path;return fGe(e.state,n,this.activeWidgets,s,this.lastKnownTasks)}catch(a){return sE.error("Error building task link decorations:",{category:"persistence",operation:"building-task-link-decorations",error:a}),Pc.Decoration.none}}},{decorations:e=>e.decorations})}function fGe(n,e,t,r,a){var l,c,d;let i=new MR.RangeSetBuilder;if(!n||!e||!t)return i.finish();let s=n.doc;if(!s||!e.app||!e.app.workspace)return i.finish();let o=e.taskLinkDetectionService||new iE(e);if(!r){let u=e.app.workspace.getActiveViewOfType(Vi.MarkdownView);if(!u)return i.finish();r=(l=u.file)==null?void 0:l.path}if(!r||typeof r!="string"||r.length===0)return i.finish();try{let u=s.toString();if(typeof u!="string"||u.length>1e5)return i.finish();let p=(c=n.selection)==null?void 0:c.main.head,m=o.findWikilinks(u);if(!Array.isArray(m))return i.finish();for(let f of m)try{if(!f||typeof f.match!="string"||typeof f.start!="number"||typeof f.end!="number"||f.start<0||f.end<=f.start||f.start>=u.length||f.end>u.length||e.settings.disableOverlayOnAlias&&f.type==="wikilink"&&f.match.includes("|"))continue;let h=f.type==="wikilink"?hGe(f.match):gGe(f.match);if(!h)continue;let{linkPath:g}=h;if(!g||typeof g!="string"||g.trim().length===0)continue;let v=yGe(g,r,e);if(!v)continue;let k=vGe(v,e);if(k)a==null||a.set(v,k);else if(a!=null&&a.has(v)){let T=e.app.vault.getAbstractFileByPath(v),b=T instanceof Vi.TFile?e.app.metadataCache.getFileCache(T):null;!(T instanceof Vi.TFile)||!e.cacheManager.isValidFile(v)||b!=null&&!e.cacheManager.isTaskFile(b.frontmatter)?(a.delete(v),t.clear()):k=(d=a.get(v))!=null?d:null}if(k){if(!k.title||typeof k.title!="string"||p!==void 0&&p>=f.start&&p500)return null;let t=e.indexOf("|");if(t!==-1){let a=e.slice(0,t).trim(),i=e.slice(t+1).trim();if(!a||!i)return null;let s=(0,Vi.parseLinktext)(a);return s.path?{linkPath:s.path,displayText:i,subpath:s.subpath||void 0,hasExplicitAlias:!0}:null}let r=(0,Vi.parseLinktext)(e);return r.path?{linkPath:r.path,subpath:r.subpath||void 0,hasExplicitAlias:!1}:null}function gGe(n){if(!n||typeof n!="string")return null;let e=n.match(/^\[([^\]]*)\]\(([^)]+)\)$/);if(!e)return null;let t=e[1].trim(),r=e[2].trim();if(r.startsWith("<")&&r.endsWith(">")&&(r=r.slice(1,-1).trim()),!r||r.length===0||r.length>500)return null;try{r=decodeURIComponent(r)}catch(i){}let a=(0,Vi.parseLinktext)(r);return a.path?{linkPath:a.path,displayText:t||void 0,subpath:a.subpath||void 0,hasExplicitAlias:!!t}:null}function yGe(n,e,t){if(!n||typeof n!="string"||n.trim().length===0||!e||typeof e!="string"||!t||!t.app||!t.app.metadataCache)return null;try{let r=t.app.metadataCache.getFirstLinkpathDest(n,e);return!r||!r.path||typeof r.path!="string"?null:r.path}catch(r){return null}}function vGe(n,e){if(!n||typeof n!="string"||n.trim().length===0||!e)return null;try{let t=/[<>:"|?*]/,r=n.split("").some(s=>{let o=s.charCodeAt(0);return o<=31||o===127});if(t.test(n)||r)return null;let a=e.cacheManager;if(!a||!a.getCachedTaskInfoSync)return null;let i=a.getCachedTaskInfoSync(n);return i&&typeof i=="object"&&i.title?i:null}catch(t){return null}}function qke(n){return mGe(n)}function Qp(n,e){if(!n||typeof n.dispatch!="function"){sE.warn("Invalid EditorView passed to dispatchTaskUpdate:",{category:"validation",operation:"invalid-editorview-passed-dispatchtaskupdate",details:{value:n}});return}try{n.dispatch({effects:[AR.of({taskPath:e})]})}catch(t){sE.error("Error dispatching task update:",{category:"validation",operation:"dispatching-task-update",error:t})}}var MR,Pc,Vi,sE,AR,PR=y(()=>{MR=require("@codemirror/state"),Pc=require("@codemirror/view"),Vi=require("obsidian");Pr();DR();FW();q();ER();sE=M({tag:"Editor/TaskLinkOverlay"}),AR=MR.StateEffect.define()});var Pk,LW=y(()=>{Pk=class{constructor(){this.states=new WeakMap;this.disposed=!1}schedule(e,t){if(this.disposed)return;let r=this.getState(e);if(r.version+=1,r.running){r.rerun=!0;return}r.running=!0,this.runLoop(e,t)}dispose(){this.disposed=!0}getState(e){let t=this.states.get(e);return t||(t={running:!1,rerun:!1,version:0},this.states.set(e,t)),t}async runLoop(e,t){let r=this.getState(e);try{do{r.rerun=!1;let a=r.version;await t({isCurrent:()=>{var i;return!this.disposed&&((i=this.states.get(e))==null?void 0:i.version)===a}})}while(r.rerun&&!this.disposed)}finally{r.running=!1,r.rerun&&!this.disposed&&(r.running=!0,this.runLoop(e,t))}}}});function Gke(n){return!!(n!=null&&n.closest(".canvas-node-content"))}function Kke(n){if(!n||typeof n!="object")return!1;let e=n;return"parent"in e&&e.parent==null}function OW(n){return!!(n!=null&&n.closest(kGe))}function Ak(n,e=TGe){var t,r,a;if(Gke(n.dom))return!1;if(OW(n.dom))return!0;try{let i=n.state.field(Yke.editorInfoField,!1);return((a=(r=(t=i==null?void 0:i.leaf)==null?void 0:t.view)==null?void 0:r.getMode)==null?void 0:a.call(r))==="preview"||Kke(i==null?void 0:i.leaf)?!0:Gke(i==null?void 0:i.containerEl)?!1:OW(i==null?void 0:i.containerEl)}catch(i){return e.debug("Error checking markdown widget editor context",{category:"provider",operation:"check-editor-context",error:i}),!1}}function Mk(n){var t;if(Kke(n))return!0;let e=(t=n.view)==null?void 0:t.containerEl;return OW(e)}var Yke,kGe,TGe,oE=y(()=>{Yke=require("obsidian");q();kGe=[".blp-inline-edit-root",".internal-embed.markdown-embed",".markdown-embed",".popover.hover-popover"].join(", "),TGe=M({tag:"MarkdownWidgetContext"})});function bGe(n,e){let t=e;for(;t!=null&&t.parentElement&&t.parentElement!==n;)t=t.parentElement;return(t==null?void 0:t.parentElement)===n?t:null}function zW(n){for(let e=0;e{});function xGe(n,e){if(typeof n.requestAnimationFrame=="function"){let r=n.requestAnimationFrame(e);return{id:r,cancel:()=>n.cancelAnimationFrame(r)}}let t=n.setTimeout(e,0);return{id:t,cancel:()=>n.clearTimeout(t)}}function Jke(n){var e;return typeof((e=n.performance)==null?void 0:e.now)=="function"?n.performance.now():Date.now()}function Xke(n,e){if(n.nodeType!==Node.ELEMENT_NODE)return!1;let t=n;return t.matches(e)||!!t.querySelector(e)}function EGe(n,e){return[...Array.from(n.addedNodes),...Array.from(n.removedNodes)].some(r=>Xke(r,e)||Xke(r,".markdown-preview-sizer"))}function DGe(n){let e=n.view;return!(e instanceof eTe.MarkdownView)||e.getMode()!=="preview"||Mk(n)?null:e.previewMode.containerEl}function RR(n,e,t,r,a,i,s={}){var h,g;let o=DGe(n);if(!o||r.has(o))return;let l=(h=s.scrollQuietPeriodMs)!=null?h:CGe,c=(g=s.requireHeaderAnchor)!=null?g:!1,d=null,u=Number.NEGATIVE_INFINITY,p=()=>{var v;u=Jke((v=o.ownerDocument.defaultView)!=null?v:window)};o.addEventListener("scroll",p,{capture:!0,passive:!0});let m=()=>{var k;if(d)return;let v=(k=o.ownerDocument.defaultView)!=null?k:window;d=xGe(v,()=>{if(d=null,!o.isConnected||!i(n))return;let T=o.querySelector(".markdown-preview-sizer");if(!(!T||T.querySelector(e))&&!(c&&!Qke(T))){if(l>0&&Jke(v)-u{v.some(k=>EGe(k,e))&&m()});f.observe(o,{childList:!0,subtree:!0}),r.add(o),a.push(()=>{d==null||d.cancel(),o.removeEventListener("scroll",p,{capture:!0}),f.disconnect()})}var eTe,CGe,BW=y(()=>{eTe=require("obsidian");oE();NR();CGe=200});function aTe(n){let e=new Set,t=n.previewMode.containerEl.querySelector(".markdown-preview-sizer"),r=n.containerEl.querySelector(".cm-sizer");return t&&e.add(t),r&&e.add(r),Array.from(e).flatMap(a=>Nk(a).filter(i=>i.classList.contains(lE)))}function iTe(n){aTe(n).forEach(e=>{var t;(t=e.component)==null||t.unload(),e.remove()})}function Nk(n){return Array.from(n.children).filter(e=>e.instanceOf(HTMLElement))}function AGe(n,e){var s;let t=n.settings.projectAutosuggest;if(!t)return!1;let r=(s=t.requiredTags)!=null?s:[];if(r.some(o=>!o.trim().startsWith("-"))&&ir.matchesTagConditions(uy(e),r))return!0;let i=cy(t);return i.enabled&&dy(e==null?void 0:e.frontmatter,i)}function _R(n,e,t){var r;return!!((r=n.dependencyCache)!=null&&r.isFileUsedAsProject(e.path)||AGe(n,t))}function MGe(n){var r;let e=n.querySelector(".cm-content");if(e)return(r=e.closest(".cm-contentContainer"))!=null?r:e;let t=Nk(n).filter(a=>!a.classList.contains(lE)&&!a.classList.contains("embedded-backlinks")&&!a.classList.contains("markdown-preview-pusher")&&!a.classList.contains("mod-footer"));return t.length>0?t[t.length-1]:null}function tTe(n){let e=Number.parseFloat(n);return Number.isFinite(e)?e:null}function IGe(n){var i;let t=((i=n.ownerDocument.defaultView)!=null?i:window).getComputedStyle(n),r=tTe(t.marginTop);if(r!==null)return r;let a=tTe(t.fontSize);return a!==null?a*1.5:24}function rTe(n){let e=n.getBoundingClientRect();return e.width<=0&&e.height<=0?null:e.bottom}function NGe(n){let e=rTe(n);return n.querySelectorAll("*").forEach(t=>{let r=rTe(t);r!==null&&(e===null||r>e)&&(e=r)}),e}function RGe(n){let e=null;for(let t of n){let r=NGe(t);r!==null&&(e===null||r>e)&&(e=r)}return e}function sTe(n,e){e.style.removeProperty("--tn-relationships-widget-margin-top");let t=n.querySelector(".cm-content");if(!t)return;let r=RGe(Nk(t)),a=t.closest(".cm-contentContainer");if(r===null||!a)return;let i=Math.max(0,Math.round(a.getBoundingClientRect().bottom-r));if(i>0){let s=IGe(e),o=Math.round(s-i);e.style.setProperty("--tn-relationships-widget-margin-top",`${o}px`)}}function oTe(n,e){let t=MGe(n);t?IR(t,e):n.appendChild(e),sTe(n,e)}async function lTe(n,e){let t=activeWindow.createDiv();t.className=`tasknotes-plugin ${lE}`,t.setAttribute("contenteditable","false"),t.setAttribute("spellcheck","false"),t.setAttribute("data-widget-type","relationships"),t.setAttribute("data-note-path",e);let r=activeWindow.createDiv();r.className="relationships__bases-container",t.appendChild(r);let a=new ba.Component;a.load(),t.component=a;try{let i=n.settings.commandFileMapping.relationships;if(!i){let o=activeWindow.createDiv();return o.className="relationships__error",o.textContent="Relationships view not configured",r.appendChild(o),t}let s=`![[${i}]]`;await ba.MarkdownRenderer.render(n.app,s,r,e,a)}catch(i){Ac.error("[TaskNotes] Error rendering Bases view in relationships widget:",{category:"internal",operation:"rendering-bases-view-relationships-widget",error:i});let s=activeWindow.createDiv();s.className="relationships__error",s.textContent="Failed to load relationships view",r.appendChild(s)}return t}function cTe(n){return nTe.ViewPlugin.fromClass(class extends jW{constructor(e){super(e,n)}destroy(){super.destroy()}})}async function _Ge(n,e,t){var c,d,u;let r=n.view;if(!(r instanceof ba.MarkdownView)||r.getMode()!=="preview"||Mk(n))return;let a=r.file;if(!a||!e.settings.showRelationships)return;let i=!1,s=!1,o=e.app.metadataCache.getFileCache(a);if(o!=null&&o.frontmatter&&(i=e.cacheManager.isTaskFile(o.frontmatter)),s=_R(e,a,o),!i&&!s){try{let p=aTe(r);(p.some(h=>h.dataset.notePath!==a.path)||o!==null)&&p.forEach(h=>{var g;(g=h.component)==null||g.unload(),h.remove()})}catch(p){Ac.debug("[TaskNotes] Error cleaning up relationships widget in reading mode:",{category:"persistence",operation:"cleaning-up-relationships-widget-reading-mode",error:p})}return}let l=null;try{let m=r.previewMode.containerEl;iTe(r);let f=e.settings.relationshipsPosition||"bottom",h=a.path;if(l=await lTe(e,h),t&&!t.isCurrent()){(c=l.component)==null||c.unload(),l.remove();return}let g=m.querySelector(".markdown-preview-sizer");if(!g){(d=l.component)==null||d.unload(),l.remove(),Ac.warn("[TaskNotes] Could not find .markdown-preview-sizer for relationships in reading mode",{category:"stale-data",operation:"find-markdown-preview-sizer-relationships-reading-mode"});return}if(f==="top"){let v=Nk(g).find(k=>k.classList.contains("tasknotes-task-card-note-widget"));v?IR(v,l):Ik(g,l)}else oTe(g,l)}catch(p){(u=l==null?void 0:l.component)==null||u.unload(),l==null||l.remove(),Ac.error("[TaskNotes] Error injecting relationships widget in reading mode:",{category:"persistence",operation:"injecting-relationships-widget-reading-mode",error:p})}}function dTe(n){var S;let e=[],t=[],r=[],a=[],i=new WeakSet,s=new Pk,o=C=>{s.schedule(C,x=>_Ge(C,n,x))},l=C=>{let x=C.view;return n.settings.showRelationships&&x instanceof ba.MarkdownView&&x.getMode()==="preview"&&!!x.file},c=C=>{RR(C,`.${lE}`,o,i,a,l)},d=()=>{n.app.workspace.getLeavesOfType("markdown").forEach(C=>{c(C)})},u=(C,x)=>{var _;let E=C.view;return E instanceof ba.MarkdownView&&(!x||((_=E.file)==null?void 0:_.path)===x.path)},p=C=>{n.app.workspace.getLeavesOfType("markdown").forEach(E=>{u(E,C)&&(o(E),c(E))})},m=null,f=()=>{m&&window.clearTimeout(m),m=window.setTimeout(()=>{n.app.workspace.getLeavesOfType("markdown").forEach(x=>{o(x)}),d()},100)},h=n.app.workspace.on("layout-change",f);e.push(h);let g=n.app.workspace.on("active-leaf-change",C=>{C&&(o(C),c(C))});e.push(g);let v=n.app.workspace.on("file-open",C=>{p(C instanceof ba.TFile?C:null)});e.push(v);let k=new Map,T=n.app.metadataCache.on("changed",C=>{let x=k.get(C.path);x&&window.clearTimeout(x);let E=n.app.workspace.getLeavesOfType("markdown"),_=E.filter(I=>{var R;let A=I.view;return A instanceof ba.MarkdownView&&((R=A.file)==null?void 0:R.path)===C.path&&A.getMode()==="preview"});if(_.length>0){k.delete(C.path),_.forEach(I=>{o(I),c(I)});return}let F=window.setTimeout(()=>{k.delete(C.path),E.forEach(I=>{var R;let A=I.view;A instanceof ba.MarkdownView&&((R=A.file)==null?void 0:R.path)===C.path&&(o(I),c(I))})},500);k.set(C.path,F)});t.push(T);let b=(S=n.dependencyCache)==null?void 0:S.on(bp,f);return b&&r.push(b),n.app.workspace.getLeavesOfType("markdown").forEach(C=>{o(C)}),d(),()=>{s.dispose(),m&&window.clearTimeout(m),k.forEach(C=>window.clearTimeout(C)),k.clear(),a.forEach(C=>C()),e.forEach(C=>n.app.workspace.offref(C)),t.forEach(C=>n.app.metadataCache.offref(C)),r.forEach(C=>{var x;return(x=n.dependencyCache)==null?void 0:x.offref(C)}),n.app.workspace.getLeavesOfType("markdown").forEach(C=>{C.view instanceof ba.MarkdownView&&iTe(C.view)})}}var nTe,ba,Ac,lE,PGe,jW,uTe=y(()=>{nTe=require("@codemirror/view"),ba=require("obsidian");mU();LW();BW();oE();NR();Ad();B0();z0();q();Ac=M({tag:"Editor/RelationshipsDecorations"}),lE="tasknotes-relationships-widget",PGe="task-card-injected";jW=class{constructor(e,t){this.plugin=t;this.currentFile=null;this.currentWidget=null;this.widgetContainer=null;this.debounceTimer=null;this.eventListeners=[];this.dependencyCacheEventListeners=[];this.injectionRunId=0;this.bottomOffsetFrame=null;this.view=e,this.currentFile=this.getFileFromView(e),this.setupEventListeners(),this.debouncedInjectWidget(e)}update(e){this.view=e.view;let t=this.getFileFromView(e.view);t!==this.currentFile?(this.currentFile=t,this.debouncedInjectWidget(e.view)):(e.docChanged||e.geometryChanged||e.viewportChanged)&&this.scheduleBottomOffsetRefresh()}destroy(){this.injectionRunId++,this.debounceTimer&&(window.clearTimeout(this.debounceTimer),this.debounceTimer=null),this.bottomOffsetFrame!==null&&(window.cancelAnimationFrame(this.bottomOffsetFrame),this.bottomOffsetFrame=null),this.removeWidget(),this.eventListeners.forEach(e=>{this.plugin.emitter.offref(e)}),this.eventListeners=[],this.dependencyCacheEventListeners.forEach(e=>{var t;(t=this.plugin.dependencyCache)==null||t.offref(e)}),this.dependencyCacheEventListeners=[]}setupEventListeners(){var a;let e=this.plugin.emitter.on(PGe,()=>{this.debouncedInjectWidget(this.view)});this.eventListeners.push(e);let t=this.plugin.emitter.on("settings-changed",()=>{this.debouncedInjectWidget(this.view)});this.eventListeners.push(t);let r=(a=this.plugin.dependencyCache)==null?void 0:a.on(bp,()=>{this.debouncedInjectWidget(this.view)});r&&this.dependencyCacheEventListeners.push(r)}debouncedInjectWidget(e){this.debounceTimer&&window.clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout(()=>{this.debounceTimer=null,this.injectWidget(e)},100)}scheduleBottomOffsetRefresh(){!this.currentWidget||!this.widgetContainer||(this.plugin.settings.relationshipsPosition||"bottom")!=="bottom"||(this.bottomOffsetFrame!==null&&window.cancelAnimationFrame(this.bottomOffsetFrame),this.bottomOffsetFrame=window.requestAnimationFrame(()=>{var e,t;this.bottomOffsetFrame=null,(e=this.currentWidget)!=null&&e.isConnected&&((t=this.widgetContainer)!=null&&t.isConnected)&&sTe(this.widgetContainer,this.currentWidget)}))}getFileFromView(e){try{let t=e.state.field(ba.editorInfoField,!1);return(t==null?void 0:t.file)||null}catch(t){return Ac.debug("[TaskNotes] Error getting file from editor view:",{category:"persistence",operation:"getting-file-editor-view",error:t}),null}}isTableCellEditor(e){try{let t=e.dom;if(!t)return!1;if(Ak(e)||t.closest("td, th")||t.closest(".cm-table-widget")||t.closest(".popover.hover-popover")||t.closest(".markdown-embed[data-type='footnote']"))return!0;let o=e.state.field(ba.editorInfoField,!1);if(!(o!=null&&o.file)){let l=t.parentElement,c=0,d=20;for(;l&&l!==activeDocument.body&&ca.classList.contains(lE)).forEach(a=>{var s;(s=a.component)==null||s.unload(),a.remove()}),this.currentWidget=null,this.widgetContainer=null}catch(r){Ac.error("[TaskNotes] Error cleaning up orphaned relationships widgets:",{category:"stale-data",operation:"cleaning-up-orphaned-relationships-widgets",error:r})}}async injectWidget(e){var r,a;let t=++this.injectionRunId;if(this.removeWidget(),!this.isTableCellEditor(e)){this.cleanupOrphanedWidgets(e);try{if(!this.plugin.settings.showRelationships)return;let i=this.currentFile||this.getFileFromView(e);if(!(i instanceof ba.TFile))return;let s=!1,o=!1,l=this.plugin.app.metadataCache.getFileCache(i);if(l!=null&&l.frontmatter?(s=this.plugin.cacheManager.isTaskFile(l.frontmatter),o=_R(this.plugin,i,l)):o=_R(this.plugin,i,l),!s&&!o)return;let c=i.path,d=this.plugin.settings.relationshipsPosition||"bottom",u=(r=e.dom.closest(".markdown-source-view"))==null?void 0:r.querySelector(".cm-sizer");if(!u){Ac.warn("[TaskNotes] Could not find .cm-sizer container for relationships widget",{category:"stale-data",operation:"find-cm-sizer-container-relationships-widget"});return}let p=await lTe(this.plugin,c);if(t!==this.injectionRunId){(a=p.component)==null||a.unload(),p.remove();return}if(this.cleanupOrphanedWidgets(e),this.currentWidget=p,this.widgetContainer=u,d==="top"){let m=Nk(u).find(f=>f.classList.contains("tasknotes-task-card-note-widget"));m?IR(m,p):Ik(u,p)}else oTe(u,p),this.scheduleBottomOffsetRefresh()}catch(i){Ac.error("[TaskNotes] Error injecting relationships widget:",{category:"internal",operation:"injecting-relationships-widget",error:i}),this.removeWidget()}}}}});function HW(n,e){let t=activeWindow.createDiv();t.className=`tasknotes-plugin task-card-note-widget ${Ih}`,t.setAttribute("contenteditable","false"),t.setAttribute("spellcheck","false"),t.setAttribute("data-widget-type","task-card"),t.setAttribute("data-task-path",e.path);let r=new hi.Component;r.load(),t.component=r;let a=n.settings.defaultVisibleProperties?di(n.settings.defaultVisibleProperties,n):void 0,i=pr(e,n,a);return i.classList.add("task-card-note-widget__card"),t.appendChild(i),t}function $W(n){n.querySelectorAll(`.${Ih}`).forEach(e=>{var r;(r=e.component)==null||r.unload(),e.remove()})}function mTe(n){return n.querySelector(".markdown-preview-sizer")}function LGe(n){let e=n,t=n.ownerDocument.defaultView;for(;e;){let r=t==null?void 0:t.getComputedStyle(e);if(e.style.display==="none"||(r==null?void 0:r.display)==="none"||(r==null?void 0:r.visibility)==="hidden")return!0;e=e.parentElement}return!1}function fTe(n,e){if(n.isEditing||e.querySelector(".markdown-source-view, .cm-editor"))return!0;let t=mTe(e);return!!(t&&LGe(t))}function OGe(n,e){let t=Array.from(e.querySelectorAll(`.${Ih}`));if(t.length===0)return!0;let r=t.some(i=>i.parentElement===e),a=t.some(i=>!!i.closest(".markdown-preview-sizer"));return fTe(n,e)?!r:r||!a}function zGe(n){var a;let e=(a=n.view)==null?void 0:a.canvas,t=e==null?void 0:e.nodes,r=t==null?void 0:t.values;return typeof r!="function"?[]:Array.from(r.call(t))}function BGe(n){return typeof n.filePath=="string"&&n.filePath.trim()?n.filePath:typeof n.file=="string"&&n.file.trim()?n.file:n.file instanceof hi.TFile?n.file.path:null}function hTe(n){return pTe.ViewPlugin.fromClass(class extends UW{constructor(e){super(e,n)}destroy(){super.destroy()}})}async function jGe(n,e,t){var s,o;let r=n.view;if(!(r instanceof hi.MarkdownView)||r.getMode()!=="preview"||Mk(n))return;let a=r.file;if(!a||!e.settings.showTaskCardInNote)return;let i=e.cacheManager.getCachedTaskInfoSync(a.path);if(!i){try{let c=r.previewMode.containerEl,u=Array.from(c.querySelectorAll(`.${Ih}`)).some(f=>f.dataset.taskPath!==a.path),p=e.app.metadataCache.getFileCache(a),m=p!==null&&(!p.frontmatter||!e.cacheManager.isTaskFile(p.frontmatter));(u||m)&&$W(c)}catch(l){Mc.debug("[TaskNotes] Error cleaning up task card in reading mode:",{category:"persistence",operation:"cleaning-up-task-card-reading-mode",error:l})}return}try{let c=r.previewMode.containerEl;$W(c);let d=HW(e,i);if(t&&!t.isCurrent()){(s=d.component)==null||s.unload(),d.remove();return}let u=c.querySelector(".markdown-preview-sizer");if(!u){Mc.warn("[TaskNotes] Could not find .markdown-preview-sizer for task card in reading mode",{category:"stale-data",operation:"find-markdown-preview-sizer-task-card-reading-mode"});return}if(!Zke(u,d)){(o=d.component)==null||o.unload(),d.remove();return}}catch(l){Mc.error("[TaskNotes] Error injecting task card widget in reading mode:",{category:"persistence",operation:"injecting-task-card-widget-reading-mode",error:l})}}function gTe(n,e={}){if(n.settings.showTaskCardInNote)for(let t of n.app.workspace.getLeavesOfType("canvas"))for(let r of zGe(t)){let a=BGe(r),i=r.contentEl;if(!a||!i)continue;let s=fTe(r,i),o=i.querySelector(".markdown-source-view, .cm-editor");if(o!=null&&o.querySelector(`.${Ih}`))continue;let l=mTe(i);if(!s&&!l||!e.force&&!OGe(r,i))continue;let c=n.cacheManager.getCachedTaskInfoSync(a);if($W(i),!c)continue;let d=HW(n,c);s?i.insertBefore(d,i.firstChild):l&&Ik(l,d)}}function yTe(n){let e=[],t=[],r=[],a=[],i=[],s=new WeakSet,o=[],l=new WeakSet,c=new Pk,d=A=>{c.schedule(A,R=>jGe(A,n,R))},u=A=>{let R=A.view;return n.settings.showTaskCardInNote&&R instanceof hi.MarkdownView&&R.getMode()==="preview"&&!!R.file},p=A=>{RR(A,`.${Ih}`,d,l,o,u,{requireHeaderAnchor:!0})},m=()=>{n.app.workspace.getLeavesOfType("markdown").forEach(A=>{p(A)})},f=(A,R)=>{var U;let O=A.view;return O instanceof hi.MarkdownView&&(!R||((U=O.file)==null?void 0:U.path)===R.path)},h=A=>{n.app.workspace.getLeavesOfType("markdown").forEach(O=>{f(O,A)&&(d(O),p(O))})},g=null,v=null,k=(A={})=>{v&&window.clearTimeout(v),v=window.setTimeout(()=>{gTe(n,A),v=null},100)},T=()=>{for(let A of n.app.workspace.getLeavesOfType("canvas")){let R=A.view.containerEl;if(!R||s.has(R))continue;let O=new MutationObserver(()=>{k()});O.observe(R,{attributes:!0,attributeFilter:["class","style"],childList:!0,subtree:!0});let U=()=>{k({force:!0})};R.addEventListener("pointerdown",U,!0),R.addEventListener("focusin",U,!0),i.push(()=>{R.removeEventListener("pointerdown",U,!0),R.removeEventListener("focusin",U,!0)}),s.add(R),a.push(O)}},b=()=>{g&&window.clearTimeout(g),g=window.setTimeout(()=>{n.app.workspace.getLeavesOfType("markdown").forEach(R=>{d(R)}),m(),T(),k({force:!0})},100)},w=n.app.workspace.on("layout-change",b);e.push(w);let S=n.app.workspace.on("active-leaf-change",A=>{A&&(d(A),p(A),T(),k())});e.push(S);let C=n.app.workspace.on("file-open",A=>{h(A instanceof hi.TFile?A:null),T(),k({force:!0})});e.push(C);let x=new Map,E=n.app.metadataCache.on("changed",A=>{let R=x.get(A.path);R&&window.clearTimeout(R);let O=n.app.workspace.getLeavesOfType("markdown"),U=O.filter(oe=>{var de;let X=oe.view;return X instanceof hi.MarkdownView&&((de=X.file)==null?void 0:de.path)===A.path&&X.getMode()==="preview"});if(U.length>0){x.delete(A.path),U.forEach(oe=>{d(oe),p(oe)}),k({force:!0});return}let pe=window.setTimeout(()=>{x.delete(A.path),O.forEach(oe=>{var de;let X=oe.view;X instanceof hi.MarkdownView&&((de=X.file)==null?void 0:de.path)===A.path&&(d(oe),p(oe))}),k({force:!0})},500);x.set(A.path,pe)});t.push(E);let _=n.emitter.on(rt,b);r.push(_);let F=n.emitter.on(Ra,b);return r.push(F),n.app.workspace.getLeavesOfType("markdown").forEach(A=>{d(A)}),m(),T(),k({force:!0}),()=>{g&&window.clearTimeout(g),v&&window.clearTimeout(v),x.forEach(A=>window.clearTimeout(A)),x.clear(),c.dispose(),o.forEach(A=>A()),a.forEach(A=>A.disconnect()),i.forEach(A=>A()),e.forEach(A=>n.app.workspace.offref(A)),t.forEach(A=>n.app.metadataCache.offref(A)),r.forEach(A=>n.emitter.offref(A))}}var pTe,hi,Mc,Ih,FGe,UW,vTe=y(()=>{pTe=require("@codemirror/view");Pr();hi=require("obsidian");Ua();Yl();LW();BW();oE();NR();q();Mc=M({tag:"Editor/TaskCardNoteDecorations"}),Ih="tasknotes-task-card-note-widget",FGe="task-card-injected";UW=class{constructor(e,t){this.plugin=t;this.cachedTask=null;this.currentFile=null;this.eventListeners=[];this.currentWidget=null;this.widgetContainer=null;this.debounceTimer=null;this.view=e,this.currentFile=this.getFileFromView(e),this.setupEventListeners(),this.loadTaskForCurrentFile(e)}update(e){this.view=e.view;let t=this.getFileFromView(e.view);t!==this.currentFile&&(this.currentFile=t,this.loadTaskForCurrentFile(e.view))}destroy(){this.debounceTimer&&(window.clearTimeout(this.debounceTimer),this.debounceTimer=null),this.removeWidget(),this.eventListeners.forEach(e=>{this.plugin.emitter.offref(e)}),this.eventListeners=[]}setupEventListeners(){let e=()=>{this.debounceTimer&&window.clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout(()=>{this.loadTaskForCurrentFile(this.view)},100)},t=this.plugin.emitter.on(Ra,e),r=this.plugin.emitter.on(rt,e),a=this.plugin.emitter.on(Di,e),i=this.plugin.emitter.on(Ou,e),s=this.plugin.emitter.on("settings-changed",e);this.eventListeners.push(t,r,a,i,s)}removeWidget(){var e;this.currentWidget&&((e=this.currentWidget.component)==null||e.unload(),this.currentWidget.remove(),this.currentWidget=null),this.widgetContainer=null}cleanupOrphanedWidgets(e){var t;try{let r=(t=e.dom.closest(".canvas-node-content"))!=null?t:e.dom.closest(".workspace-leaf-content");if(!r){Mc.debug("[TaskNotes] Could not find workspace-leaf-content for orphan cleanup",{category:"stale-data",operation:"find-workspace-leaf-content-orphan-cleanup"});return}r.querySelectorAll(`.${Ih}`).forEach(a=>{var i;a!==this.currentWidget&&((i=a.component)==null||i.unload(),a.remove())})}catch(r){Mc.error("[TaskNotes] Error cleaning up orphaned task card widgets:",{category:"stale-data",operation:"cleaning-up-orphaned-task-card-widgets",error:r})}}loadTaskForCurrentFile(e){var r,a,i,s,o,l,c,d,u,p,m,f,h;let t=this.getFileFromView(e);if(t instanceof hi.TFile)try{let g=this.plugin.cacheManager.getCachedTaskInfoSync(t.path),v=T=>!(T!=null&&T.timeEntries)||T.timeEntries.length===0?!1:!T.timeEntries[T.timeEntries.length-1].endTime;(((r=this.cachedTask)==null?void 0:r.title)!==(g==null?void 0:g.title)||((a=this.cachedTask)==null?void 0:a.status)!==(g==null?void 0:g.status)||((i=this.cachedTask)==null?void 0:i.priority)!==(g==null?void 0:g.priority)||((s=this.cachedTask)==null?void 0:s.due)!==(g==null?void 0:g.due)||((o=this.cachedTask)==null?void 0:o.scheduled)!==(g==null?void 0:g.scheduled)||((l=this.cachedTask)==null?void 0:l.path)!==(g==null?void 0:g.path)||((c=this.cachedTask)==null?void 0:c.archived)!==(g==null?void 0:g.archived)||((d=this.cachedTask)==null?void 0:d.timeEstimate)!==(g==null?void 0:g.timeEstimate)||((u=this.cachedTask)==null?void 0:u.recurrence)!==(g==null?void 0:g.recurrence)||v(this.cachedTask)!==v(g)||JSON.stringify(((p=this.cachedTask)==null?void 0:p.tags)||[])!==JSON.stringify((g==null?void 0:g.tags)||[])||JSON.stringify(((m=this.cachedTask)==null?void 0:m.contexts)||[])!==JSON.stringify((g==null?void 0:g.contexts)||[])||JSON.stringify(((f=this.cachedTask)==null?void 0:f.projects)||[])!==JSON.stringify((g==null?void 0:g.projects)||[])||JSON.stringify(((h=this.cachedTask)==null?void 0:h.complete_instances)||[])!==JSON.stringify((g==null?void 0:g.complete_instances)||[]))&&(this.cachedTask=g,this.injectWidget(e))}catch(g){Mc.error("[TaskNotes] Error loading task for task note:",{category:"persistence",operation:"loading-task-task-note",error:g})}else this.cachedTask!==null&&(this.cachedTask=null,this.injectWidget(e))}getFileFromView(e){try{let t=e.state.field(hi.editorInfoField,!1);return(t==null?void 0:t.file)||null}catch(t){return Mc.debug("[TaskNotes] Error getting file from editor view:",{category:"persistence",operation:"getting-file-editor-view",error:t}),null}}isTableCellEditor(e){try{let t=e.dom;if(!t)return!1;if(Ak(e)||t.closest("td, th")||t.closest(".cm-table-widget")||t.closest(".popover.hover-popover")||t.closest(".markdown-embed[data-type='footnote']"))return!0;let o=e.state.field(hi.editorInfoField,!1);if(!(o!=null&&o.file)){let l=t.parentElement,c=0,d=20;for(;l&&l!==activeDocument.body&&c{gTe(this.plugin,{force:!0})},0);return}this.cleanupOrphanedWidgets(e);try{if(!this.plugin.settings.showTaskCardInNote||!this.cachedTask)return;let r=(t=e.dom.closest(".markdown-source-view"))==null?void 0:t.querySelector(".cm-sizer");if(!r){Mc.warn("[TaskNotes] Could not find .cm-sizer container for task card widget",{category:"stale-data",operation:"find-cm-sizer-container-task-card-widget"});return}let a=HW(this.plugin,this.cachedTask);this.currentWidget=a,this.widgetContainer=r,Ik(r,a),this.plugin.emitter.trigger(FGe,{container:r})}catch(r){Mc.error("[TaskNotes] Error injecting task card widget:",{category:"persistence",operation:"injecting-task-card-widget",error:r}),this.removeWidget()}}}});function $Ge(n){try{return decodeURIComponent(n)}catch(e){return n}}function cE(n){let e=$Ge(n).trim();if(!e)return"";if(e.startsWith("app://"))try{e=new URL(e).pathname}catch(t){}return e=e.replace(/^\/+/,""),e=e.split("#")[0].trim(),e.endsWith(".md")&&(e=e.slice(0,-3)),e}function kTe(n){var r;let e=cE(n),t=e.split("/");return(r=t[t.length-1])!=null?r:e}function UGe(n,e){let t=cE(n),r=cE(e);return!t||!r?!1:t===r?!0:kTe(t)===kTe(r)}function HGe(n){let e=[],t=/!?\[\[([^\]]+)\]\]/g,r;for(;(r=t.exec(n))!==null;){if(r[0].startsWith("!"))continue;let a=r[1].trim();if(!a)continue;let i=a.indexOf("|"),s=i===-1?a:a.slice(0,i),o=cE(s);o&&e.push({target:o,hasAlias:i!==-1,subpath:aE(s)})}return e}function VGe(n,e,t){let r=cE(t);if(!r)return null;let a=()=>{for(let s=e.index;s0?(e.index=0,a()):null)}function WGe(n,e){return`${n}\0${e}`}function qGe(){return{index:0}}function YGe(n){var r;if(!n.disableOverlayOnAlias)return!1;if(n.hasExplicitAlias)return!0;let e=n.linkText.trim(),t=Dc(n.taskTitle,(r=n.taskSubpath)!=null?r:aE(n.originalLinkPath));return t&&e===t||RW(e,n.taskPath,n.originalLinkPath,n.taskTitle)?!1:e!==n.originalLinkPath&&e!==n.taskTitle}function KGe(n,e){var t,r,a;try{return(a=(r=(t=n.getSectionInfo)==null?void 0:t.call(n,e))==null?void 0:r.text)!=null?a:""}catch(i){return""}}function TTe(n){return new VW(n).createPostProcessor()}var LR,FR,GGe,VW,bTe=y(()=>{LR=require("obsidian");Pr();FW();q();ER();FR=M({tag:"Editor/ReadingModeTaskLinkProcessor"});GGe=".task-inline-preview--reading-mode[data-task-path]";VW=class{constructor(e){this.sourceLinkCursors=new Map;this.refreshTimer=null;this.pendingRefreshAll=!1;this.pendingRefreshTaskPaths=new Set;this.plugin=e,this.setupEventListeners()}createPostProcessor(){return(e,t)=>{var l,c,d;if(!this.plugin.settings.enableTaskLinkOverlay)return;let r=e.querySelectorAll("a"),a=KGe(t,e),i=HGe(a),s=WGe(t.sourcePath,a),o=(l=this.sourceLinkCursors.get(s))!=null?l:qGe();this.sourceLinkCursors.set(s,o);for(let u of Array.from(r)){let p=u,m=p.getAttribute("href"),f=p.getAttribute("data-href")||m||"",h=i.length>0?VGe(i,o,f):null;p.classList.contains("internal-link")?this.processLink(p,t.sourcePath,"internal",(c=h==null?void 0:h.hasAlias)!=null?c:!1,h==null?void 0:h.subpath):m&&!m.startsWith("http://")&&!m.startsWith("https://")&&!m.includes("://")&&this.processLink(p,t.sourcePath,"external",(d=h==null?void 0:h.hasAlias)!=null?d:!1,h==null?void 0:h.subpath)}}}async processLink(e,t,r,a,i){try{let s=e.getAttribute("href");if(!s)return;let o=s;if(r==="internal"){if(s.startsWith("app://")){let d=new URL(s);o=decodeURIComponent(d.pathname),o.startsWith("/")&&(o=o.substring(1))}}else{if(s.startsWith("http://")||s.startsWith("https://")||s.includes("://"))return;o=s}let l=this.resolveLinkPath(o,t);if(!l)return;let c=this.getTaskInfo(l);if(!c)return;await this.replaceWithTaskWidget(e,c,o,a,i)}catch(s){FR.debug("Error processing link in reading mode:",{category:"persistence",operation:"processing-link-reading-mode",error:s})}}setupEventListeners(){this.plugin.registerEvent(this.plugin.emitter.on(rt,e=>{var t,r,a,i;this.scheduleReadingModeWidgetRefresh((i=(r=e==null?void 0:e.path)!=null?r:(t=e==null?void 0:e.updatedTask)==null?void 0:t.path)!=null?i:(a=e==null?void 0:e.task)==null?void 0:a.path)})),this.plugin.registerEvent(this.plugin.emitter.on(Di,e=>{this.scheduleReadingModeWidgetRefresh(e==null?void 0:e.path)})),this.plugin.registerEvent(this.plugin.emitter.on(Ra,()=>{this.scheduleReadingModeWidgetRefresh()})),this.plugin.registerEvent(this.plugin.emitter.on(Ou,()=>{this.scheduleReadingModeWidgetRefresh()})),this.plugin.registerEvent(this.plugin.emitter.on("settings-changed",()=>{this.scheduleReadingModeWidgetRefresh()})),this.plugin.register(()=>{this.refreshTimer!==null&&(window.clearTimeout(this.refreshTimer),this.refreshTimer=null)})}scheduleReadingModeWidgetRefresh(e){e?this.pendingRefreshAll||this.pendingRefreshTaskPaths.add(e):(this.pendingRefreshAll=!0,this.pendingRefreshTaskPaths.clear()),this.refreshTimer!==null&&window.clearTimeout(this.refreshTimer),this.refreshTimer=window.setTimeout(()=>{this.refreshTimer=null;let t=this.pendingRefreshAll?void 0:new Set(this.pendingRefreshTaskPaths);this.pendingRefreshAll=!1,this.pendingRefreshTaskPaths.clear(),this.refreshReadingModeWidgets(t)},100)}refreshReadingModeWidgets(e){let t=this.getReadingModeContainers();if(t.length!==0)for(let r of t){let a=Array.from(r.querySelectorAll(GGe));for(let i of a){let s=i.dataset.taskPath;if(!s||e&&!e.has(s))continue;if(!this.plugin.settings.enableTaskLinkOverlay){this.replaceWidgetWithOriginalLink(i);continue}let o=this.getTaskInfo(s);if(!o){this.replaceWidgetWithOriginalLink(i);continue}let l=i.dataset.originalLinkPath||o.path,c=i.dataset.originalText||o.title,d=i.dataset.displayText||void 0,u=new Mh(o,this.plugin,c,d,void 0,(0,LR.parseLinktext)(l).subpath||void 0),p=this.createReadingModeWidget(u,o,l,c,d);i.replaceWith(p)}}}getReadingModeContainers(){var r,a,i,s,o;let e=(i=(a=(r=this.plugin.app.workspace).getLeavesOfType)==null?void 0:a.call(r,"markdown"))!=null?i:[],t=[];for(let l of e){let c=l.view;if(typeof c.getMode=="function"&&c.getMode()!=="preview")continue;let d=(o=(s=c.previewMode)==null?void 0:s.containerEl)!=null?o:c.containerEl;d&&t.push(d)}return t}replaceWidgetWithOriginalLink(e){let t=e.dataset.originalLinkPath;if(!t){e.remove();return}let r=activeWindow.createEl("a");r.className="internal-link",r.setAttribute("href",t),r.setAttribute("data-href",t),r.textContent=e.dataset.originalText||t,e.replaceWith(r)}resolveLinkPath(e,t){try{let r=this.plugin.app.metadataCache.getFirstLinkpathDest((0,LR.parseLinktext)(e).path,t);return(r==null?void 0:r.path)||null}catch(r){return FR.debug("Error resolving link path:",{category:"persistence",operation:"resolving-link-path",details:{value:e},error:r}),null}}getTaskInfo(e){try{if(!e||typeof e!="string"||e.trim().length===0)return null;let t=this.plugin.cacheManager;if(!t||!t.getCachedTaskInfoSync)return null;let r=t.getCachedTaskInfoSync(e);return r&&typeof r=="object"&&r.title?r:null}catch(t){return FR.debug("Error getting task info for:",{category:"persistence",operation:"getting-task-info",details:{value:e},error:t}),null}}async replaceWithTaskWidget(e,t,r,a,i){var s;try{let o=e.textContent||`[[${r}]]`,l=Dc(t.title,i!=null?i:aE(r));if(YGe({disableOverlayOnAlias:this.plugin.settings.disableOverlayOnAlias,hasExplicitAlias:a,linkText:e.textContent||"",originalLinkPath:r,taskSubpath:i,taskPath:t.path,taskTitle:t.title}))return;let c,d=e.textContent||"";a?c=d.trim()||void 0:l?c=l:d!==r&&d!==t.title&&(c=Dk(d,t.path,r));let u=new Mh(t,this.plugin,o,c,void 0,(0,LR.parseLinktext)(r).subpath||void 0),p=this.createReadingModeWidget(u,t,r,o,c);(s=e.parentNode)==null||s.replaceChild(p,e)}catch(o){FR.error("Error replacing wikilink with task widget:",{category:"persistence",operation:"replacing-wikilink-task-widget",error:o})}}createReadingModeWidget(e,t,r,a,i){let s={},o=e.toDOM(s);return o.classList.add("task-inline-preview--reading-mode"),o.dataset.taskPath=t.path,o.dataset.originalLinkPath=r,o.dataset.originalText=a,i&&(o.dataset.displayText=i),o}}});function JGe(n,e,t){let r;switch(n){case"P":e&&e==="-"?t.isNegative=!0:t.isNegative=!1;break;case"D":r="days";break;case"W":r="weeks";break;case"H":r="hours";break;case"M":r="minutes";break;case"S":r="seconds";break;default:return 0}if(r){if(!e&&e!==0)throw new Error('invalid duration value: Missing number before "'+n+'"');let a=parseInt(e,10);if(pE(a))throw new Error('invalid duration value: Invalid number "'+e+'" before "'+n+'"');t[r]=a}return 1}function lr(n){let e={},t=e.component=[];if(e.stack=[t],lr._eachLine(n,function(r,a){lr._handleContentLine(a,e)}),e.stack.length>1)throw new cu("invalid ical body. component began but did not end");return e=null,t.length==1?t[0]:t}function i5e(n){let e,t,r,a,i;if(!n||n.name!=="vcalendar")return n;for(e=n.getAllSubcomponents(),t=[],r={},i=0;i0&&n[t-1]==="\\")t+=1;else return t;return-1}function Rh(n,e,t){if(!n.length)return 0;let r=0,a=n.length-1,i,s;for(;r<=a;)if(i=r+Math.floor((a-r)/2),s=t(e,n[i]),s<0)a=i-1;else if(s>0)r=i+1;else break;return s<0?i:s>0?i+1:i}function Fh(n,e){if(!n||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if("clone"in n)return n.clone();if(Array.isArray(n)){let t=[];for(let r=0;r65535?2:1:(e+=Yi.newLineChar+" "+t.slice(0,Math.max(0,r)),t=t.slice(Math.max(0,r)),r=a=0)}return e.slice(Yi.newLineChar.length+1)}function Gi(n){switch(typeof n!="string"&&(typeof n=="number"&&(n=parseInt(n)),n=String(n)),n.length){case 0:return"00";case 1:return"0"+n;default:return n}}function la(n){return n<0?Math.ceil(n):Math.floor(n)}function Lh(n,e){for(let t in n){let r=Object.getOwnPropertyDescriptor(n,t);r&&!Object.getOwnPropertyDescriptor(e,t)&&Object.defineProperty(e,t,r)}return e}function Jp(n,e,t,r){let a=r;if(r[0]==="+"&&(a=r.slice(1)),a=qa(a),e!==void 0&&r '+e);if(t!==void 0&&r>t)throw new Error(n+': invalid value "'+r+'" must be < '+e);return a}function YW(n,e){return{matches:/.*/,fromICAL:function(r,a){return m5e(r,n,a)},toICAL:function(r,a){let i=e;return a&&(i=new RegExp(i.source+"|"+a,i.flags)),r.replace(i,function(s){switch(s){case"\\":return"\\\\";case";":return"\\;";case",":return"\\,";case` +`:return"\\n";default:return s}})}}}function p5e(n){switch(n){case"\\\\":return"\\";case"\\;":return";";case"\\,":return",";case"\\n":case"\\N":return` +`;default:return n}}function m5e(n,e,t){return n.indexOf("\\")===-1?n:(t&&(e=new RegExp(e.source+"|\\\\"+t,e.flags)),n.replace(e,p5e))}function on(n){typeof n[0]=="string"&&(n=[n]);let e=0,t=n.length,r="";for(;ee[0]?1:e[0]>n[0]?-1:0}var HR,ZGe,QGe,Rs,uE,_k,be,Me,XGe,VR,GW,e5e,t5e,r5e,n5e,cu,a5e,Fk,Lk,Kt,mr,gi,WR,s5e,lu,Nh,qi,mE,Rk,o5e,l5e,FTe,c5e,wTe,yl,WW,qW,d5e,u5e,STe,CTe,Zt,fE,qR,OR,zR,BR,Wi,xTe,ETe,DTe,ZW,QW,f5e,zn,h5e,Ns,g5e,y5e,v5e,k5e,T5e,su,PTe,ATe,fr,UR,MTe,b5e,ITe,jR,$R,Xp,_h,em,Ic,tm,w5e,S5e,So,GR,dE,YR,KW,Yi,LTe=y(()=>{HR=class n{constructor(e){z(this,"icaltype","binary");this.value=e}static fromString(e){return new n(e)}decodeValue(){return this._b64_decode(this.value)}setEncodedValue(e){this.value=this._b64_encode(e)}_b64_encode(e){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r,a,i,s,o,l,c,d,u=0,p=0,m="",f=[];if(!e)return e;do r=e.charCodeAt(u++),a=e.charCodeAt(u++),i=e.charCodeAt(u++),d=r<<16|a<<8|i,s=d>>18&63,o=d>>12&63,l=d>>6&63,c=d&63,f[p++]=t.charAt(s)+t.charAt(o)+t.charAt(l)+t.charAt(c);while(u>16&255,a=d>>8&255,i=d&255,l==64?f[p++]=String.fromCharCode(r):c==64?f[p++]=String.fromCharCode(r,a):f[p++]=String.fromCharCode(r,a,i);while(ur)-(t0?-1:0}toString(){return this.start+"/"+(this.end||this.duration)}toJSON(){return[this.start.toString(),(this.end||this.duration).toString()]}toICALString(){return this.start.toICALString()+"/"+(this.end||this.duration).toICALString()}},be=class be{constructor(e,t){z(this,"icalclass","icaltime");z(this,"_cachedUnixTime",null);z(this,"zone",null);z(this,"_pendingNormalization",!1);this.wrappedJSObject=this,this._time=Object.create(null),this._time.year=0,this._time.month=1,this._time.day=1,this._time.hour=0,this._time.minute=0,this._time.second=0,this._time.isDate=!1,this.fromData(e,t)}static daysInMonth(e,t){let r=[0,31,28,31,30,31,30,31,31,30,31,30,31],a=30;return e<1||e>12||(a=r[e],e==2&&(a+=be.isLeapYear(t))),a}static isLeapYear(e){return e<=1752?e%4==0:e%4==0&&e%100!=0||e%400==0}static fromDayOfYear(e,t){let r=t,a=e,i=new be;i.auto_normalize=!1;let s=be.isLeapYear(r)?1:0;if(a<1)return r--,s=be.isLeapYear(r)?1:0,a+=be.daysInYearPassedMonth[s][12],be.fromDayOfYear(a,r);if(a>be.daysInYearPassedMonth[s][12])return s=be.isLeapYear(r)?1:0,a-=be.daysInYearPassedMonth[s][12],r++,be.fromDayOfYear(a,r);i.year=r,i.isDate=!0;for(let o=11;o>=0;o--)if(a>be.daysInYearPassedMonth[s][o]){i.month=o+1,i.day=a-be.daysInYearPassedMonth[s][o];break}return i.auto_normalize=!0,i}static fromStringv2(e){return new be({year:parseInt(e.slice(0,4),10),month:parseInt(e.slice(5,7),10),day:parseInt(e.slice(8,10),10),isDate:!0})}static fromDateString(e){return new be({year:qa(e.slice(0,4)),month:qa(e.slice(5,7)),day:qa(e.slice(8,10)),isDate:!0})}static fromDateTimeString(e,t){if(e.length<19)throw new Error('invalid date-time value: "'+e+'"');let r,a;e.slice(-1)==="Z"?r=mr.utcTimezone:t&&(a=t.getParameter("tzid"),t.parent&&(t.parent.name==="standard"||t.parent.name==="daylight"?r=mr.localTimezone:a&&(r=t.parent.getTimeZoneByID(a))));let i={year:qa(e.slice(0,4)),month:qa(e.slice(5,7)),day:qa(e.slice(8,10)),hour:qa(e.slice(11,13)),minute:qa(e.slice(14,16)),second:qa(e.slice(17,19))};return a&&!r&&(i.timezone=a),new be(i,r)}static fromString(e,t){return e.length>10?be.fromDateTimeString(e,t):be.fromDateString(e)}static fromJSDate(e,t){return new be().fromJSDate(e,t)}static now(){return be.fromJSDate(new Date,!1)}static weekOneStarts(e,t){let r=be.fromData({year:e,month:1,day:1,isDate:!0}),a=r.dayOfWeek(),i=t||be.DEFAULT_WEEK_START;return a>be.THURSDAY&&(r.day+=7),i>be.THURSDAY&&(r.day-=7),r.day-=a-i,r}static getDominicalLetter(e){let t="GFEDCBA",r=(e+(e/4|0)+(e/400|0)-(e/100|0)-1)%7;return be.isLeapYear(e)?t[(r+6)%7]+t[r]:t[r]}static get epochTime(){return un(this,_k)||Us(this,_k,be.fromData({year:1970,month:1,day:1,hour:0,minute:0,second:0,isDate:!1,timezone:"Z"})),un(this,_k)}static _cmp_attr(e,t,r){return e[r]>t[r]?1:e[r]=0){o.day=1,i!=0&&i--,s=o.day;let l=o.dayOfWeek(),c=e-l;c<0&&(c+=7),s+=c,s-=e,a=e}else{o.day=r;let l=o.dayOfWeek();i++,a=l-e,a<0&&(a+=7),a=r-a}return a+=i*7,s+a}isNthWeekDay(e,t){let r=this.dayOfWeek();return t===0&&r===e||this.nthWeekDay(e,t)===this.day}weekNumber(e){let t=(this.year<<12)+(this.month<<8)+(this.day<<3)+e;if(t in be._wnCache)return be._wnCache[t];let r,a=this.clone();a.isDate=!0;let i=this.year;a.month==12&&a.day>25?(r=be.weekOneStarts(i+1,e),a.compare(r)<0?r=be.weekOneStarts(i,e):i++):(r=be.weekOneStarts(i,e),a.compare(r)<0&&(r=be.weekOneStarts(--i,e)));let s=a.subtractDate(r).toSeconds()/86400,o=la(s/7)+1;return be._wnCache[t]=o,o}addDuration(e){let t=e.isNegative?-1:1,r=this.second,a=this.minute,i=this.hour,s=this.day;r+=t*e.seconds,a+=t*e.minutes,i+=t*e.hours,s+=t*e.days,s+=t*7*e.weeks,this.second=r,this.minute=a,this.hour=i,this.day=s,this._cachedUnixTime=null}subtractDate(e){let t=this.toUnixTime()+this.utcOffset(),r=e.toUnixTime()+e.utcOffset();return Rs.fromSeconds(t-r)}subtractDateTz(e){let t=this.toUnixTime(),r=e.toUnixTime();return Rs.fromSeconds(t-r)}compare(e){if(e instanceof uE)return-1*e.compare(this);{let t=this.toUnixTime(),r=e.toUnixTime();return t>r?1:r>t?-1:0}}compareDateOnlyTz(e,t){let r=this.convertToZone(t),a=e.convertToZone(t),i=0;return(i=be._cmp_attr(r,a,"year"))!=0||(i=be._cmp_attr(r,a,"month"))!=0||(i=be._cmp_attr(r,a,"day"))!=0,i}convertToZone(e){let t=this.clone(),r=this.zone.tzid==e.tzid;return!this.isDate&&!r&&mr.convert_time(t,this.zone,e),t.zone=e,t}utcOffset(){return this.zone==mr.localTimezone||this.zone==mr.utcTimezone?0:this.zone.utcOffset(this)}toICALString(){let e=this.toString();return e.length>10?fr.icalendar.value["date-time"].toICAL(e):fr.icalendar.value.date.toICAL(e)}toString(){let e=this.year+"-"+Gi(this.month)+"-"+Gi(this.day);return this.isDate||(e+="T"+Gi(this.hour)+":"+Gi(this.minute)+":"+Gi(this.second),this.zone===mr.utcTimezone&&(e+="Z")),e}toJSDate(){return this.zone==mr.localTimezone?this.isDate?new Date(this.year,this.month-1,this.day):new Date(this.year,this.month-1,this.day,this.hour,this.minute,this.second,0):new Date(this.toUnixTime()*1e3)}_normalize(){return this._time.isDate&&(this._time.hour=0,this._time.minute=0,this._time.second=0),this.adjust(0,0,0,0),this}adjust(e,t,r,a,i){let s,o,l=0,c=0,d,u,p,m,f,h=i||this._time;if(h.isDate||(d=h.second+a,h.second=d%60,s=la(d/60),h.second<0&&(h.second+=60,s--),u=h.minute+r+s,h.minute=u%60,o=la(u/60),h.minute<0&&(h.minute+=60,o--),p=h.hour+t+o,h.hour=p%24,l=la(p/24),h.hour<0&&(h.hour+=24,l--)),h.month>12?c=la((h.month-1)/12):h.month<1&&(c=la(h.month/12)-1),h.year+=c,h.month-=12*c,m=h.day+e+l,m>0)for(;f=be.daysInMonth(h.month,h.year),!(m<=f);)h.month++,h.month>12&&(h.year++,h.month=1),m-=f;else for(;m<=0;)h.month==1?(h.year--,h.month=12):h.month--,m+=be.daysInMonth(h.month,h.year);return h.day=m,this._cachedUnixTime=null,this}fromUnixTime(e){this.zone=mr.utcTimezone;let t=new Date(e*1e3);this.year=t.getUTCFullYear(),this.month=t.getUTCMonth()+1,this.day=t.getUTCDate(),this._time.isDate?(this.hour=0,this.minute=0,this.second=0):(this.hour=t.getUTCHours(),this.minute=t.getUTCMinutes(),this.second=t.getUTCSeconds()),this._cachedUnixTime=null}toUnixTime(){if(this._cachedUnixTime!==null)return this._cachedUnixTime;let e=this.utcOffset(),t=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second-e);return this._cachedUnixTime=t/1e3,this._cachedUnixTime}toJSON(){let e=["year","month","day","hour","minute","second","isDate"],t=Object.create(null),r=0,a=e.length,i;for(;rt&&(r=-1);let c;if(r!==-1){if(s=n.slice(0,Math.max(0,r)).toLowerCase(),c=lr._parseParameters(n.slice(Math.max(0,r)),0,e.designSet),c[2]==-1)throw new cu("Invalid parameters in '"+n+"'");l=c[0];let v;if(typeof c[1]=="string"?v=c[1].length:v=c[1].reduce((k,T)=>k+T.length,0),a=v+c[2]+r,(i=n.slice(Math.max(0,a)).indexOf(VR))!==-1)o=n.slice(Math.max(0,a+i+1));else throw new cu("Missing parameter value in '"+n+"'")}else if(t!==-1){if(s=n.slice(0,Math.max(0,t)).toLowerCase(),o=n.slice(Math.max(0,t+1)),s==="begin"){let v=[o.toLowerCase(),[],[]];e.stack.length===1?e.component.push(v):e.component[2].push(v),e.stack.push(e.component),e.component=v,e.designSet||(e.designSet=fr.getDesignSet(e.component[0]));return}else if(s==="end"){e.component=e.stack.pop();return}}else throw new cu('invalid line (no token ";" or ":") "'+n+'"');let d,u=!1,p=!1,m,f,h;e.designSet.propertyGroups&&s.indexOf(".")!==-1?(f=s.split("."),l.group=f[0],h=f[1]):h=s,h in e.designSet.property&&(m=e.designSet.property[h],"multiValue"in m&&(u=m.multiValue),"structuredValue"in m&&(p=m.structuredValue),o&&"detectType"in m&&(d=m.detectType(o))),d||("value"in l?d=l.value.toLowerCase():m?d=m.defaultType:d=t5e),delete l.value;let g;u&&p?(o=lr._parseMultiValue(o,p,d,[],u,e.designSet,p),g=[h,l,d,o]):u?(g=[h,l,d],lr._parseMultiValue(o,u,d,g,null,e.designSet,!1)):p?(o=lr._parseMultiValue(o,p,d,[],null,e.designSet,p),g=[h,l,d,o]):(o=lr._parseValue(o,d,e.designSet,!1),g=[h,l,d,o]),e.component[0]==="vcard"&&e.component[1].length===0&&!(s==="version"&&o==="4.0")&&(e.designSet=fr.getDesignSet("vcard3")),e.component[1].push(g)};lr._parseValue=function(n,e,t,r){return e in t.value&&"fromICAL"in t.value[e]?t.value[e].fromICAL(n,r):n};lr._parseParameters=function(n,e,t){let r=e,a=0,i=e5e,s={},o,l,c,d=-1,u,p,m;for(;a!==!1&&(a=n.indexOf(i,a+1))!==-1;){if(o=n.slice(r+1,a),o.length==0)throw new cu("Empty parameter name in '"+n+"'");if(l=o.toLowerCase(),m=!1,p=!1,l in t.param&&t.param[l].valueType?u=t.param[l].valueType:u=r5e,l in t.param&&(p=t.param[l].multiValue,t.param[l].multiValueSeparateDQuote&&(m=lr._rfc6868Escape('"'+p+'"'))),n[a+1]==='"'){if(d=a+2,a=n.indexOf('"',d),p&&a!=-1){let v=!0;for(;v;)n[a+1]==p&&n[a+2]=='"'?a=n.indexOf('"',a+3):v=!1}if(a===-1)throw new cu('invalid line (no matching double quote) "'+n+'"');c=n.slice(d,a),r=n.indexOf(GW,a);let g=n.indexOf(VR,a);(r===-1||g!==-1&&r>g)&&(a=!1)}else{d=a+1;let g=n.indexOf(GW,d),v=n.indexOf(VR,d);v!==-1&&g>v?(g=v,a=!1):g===-1?(v===-1?g=n.length:g=v,a=!1):(r=g,a=g),c=n.slice(d,g)}let h=c.length;if(c=lr._rfc6868Escape(c),d+=h-c.length,p){let g=m||p;c=lr._parseMultiValue(c,g,u,[],null,t)}else c=lr._parseValue(c,u,t);p&&l in s?Array.isArray(s[l])?s[l].push(c):s[l]=[s[l],c]:s[l]=c}return[s,c,d]};lr._rfc6868Escape=function(n){return n.replace(/\^['n^]/g,function(e){return n5e[e]})};lr._parseMultiValue=function(n,e,t,r,a,i,s){let o=0,l=0,c;if(e.length===0)return n;for(;(o=RTe(n,e,l))!==-1;)c=n.slice(l,o),a?c=lr._parseMultiValue(c,a,t,[],null,i,s):c=lr._parseValue(c,t,i,s),r.push(c),l=o+e.length;return c=n.slice(l),a?c=lr._parseMultiValue(c,a,t,[],null,i,s):c=lr._parseValue(c,t,i,s),r.push(c),r.length==1?r[0]:r};lr._eachLine=function(n,e){let t=n.length,r=n.search(XGe),a=r,i,s,o;do a=n.indexOf(` +`,r)+1,a>1&&n[a-2]==="\r"?o=2:o=1,a===0&&(a=t,o=0),s=n[r],s===" "||s===" "?i+=n.slice(r+1,a-o):(i&&e(null,i),i=n.slice(r,a-o)),r=a;while(a!==t);i=i.trim(),i.length&&e(null,i)};a5e=["tzid","location","tznames","latitude","longitude"],Kt=class Kt{constructor(e){z(this,"tzid","");z(this,"location","");z(this,"tznames","");z(this,"latitude",0);z(this,"longitude",0);z(this,"component",null);z(this,"expandedUntilYear",0);z(this,"icalclass","icaltimezone");this.wrappedJSObject=this,this.fromData(e)}static _compare_change_fn(e,t){return e.yeart.year?1:e.montht.month?1:e.dayt.day?1:e.hourt.hour?1:e.minutet.minute?1:e.secondt.second?1:0}static convert_time(e,t,r){if(e.isDate||t.tzid==r.tzid||t==Kt.localTimezone||r==Kt.localTimezone)return e.zone=r,e;let a=t.utcOffset(e);return e.adjust(0,0,0,-a),a=r.utcOffset(e),e.adjust(0,0,0,a),null}static fromData(e){return new Kt().fromData(e)}static get utcTimezone(){return un(this,Fk)||Us(this,Fk,Kt.fromData({tzid:"UTC"})),un(this,Fk)}static get localTimezone(){return un(this,Lk)||Us(this,Lk,Kt.fromData({tzid:"floating"})),un(this,Lk)}static adjust_change(e,t,r,a,i){return Me.prototype.adjust.call(e,t,r,a,i,e)}fromData(e){if(this.expandedUntilYear=0,this.changes=[],e instanceof So)this.component=e;else{if(e&&"component"in e)if(typeof e.component=="string"){let t=lr(e.component);this.component=new So(t)}else e.component instanceof So?this.component=e.component:this.component=null;for(let t of a5e)e&&t in e&&(this[t]=e[t])}return this.component instanceof So&&!this.tzid&&(this.tzid=this.component.getFirstPropertyValue("tzid")),this}utcOffset(e){if(this==Kt.utcTimezone||this==Kt.localTimezone||(this._ensureCoverage(e.year),!this.changes.length))return 0;let t={year:e.year,month:e.month,day:e.day,hour:e.hour,minute:e.minute,second:e.second},r=this._findNearbyChange(t),a=-1,i=1;for(;;){let l=Fh(this.changes[r],!0);if(l.utcOffset=0?a=r:i=-1,i==-1&&a!=-1)break;if(r+=i,r<0)return 0;if(r>=this.changes.length)break}let s=this.changes[a];if(s.utcOffset-s.prevUtcOffset<0&&a>0){let l=Fh(s,!0);if(Kt.adjust_change(l,0,0,0,l.prevUtcOffset),Kt._compare_change_fn(t,l)<0){let c=this.changes[a-1],d=!1;s.is_daylight!=d&&c.is_daylight==d&&(s=c)}}return s.utcOffset}_findNearbyChange(e){let t=Rh(this.changes,e,Kt._compare_change_fn);return t>=this.changes.length?this.changes.length-1:t}_ensureCoverage(e){if(Kt._minimumExpansionYear==-1){let r=Me.now();Kt._minimumExpansionYear=r.year}let t=e;if(tt||!u));)i.year=u.year,i.month=u.month,i.day=u.day,i.hour=u.hour,i.minute=u.minute,i.second=u.second,i.isDate=u.isDate,Kt.adjust_change(i,0,0,0,-i.prevUtcOffset),r.push(i)}}return r}toString(){return this.tznames?this.tznames:this.tzid}};Fk=new WeakMap,Lk=new WeakMap,Al(Kt,Fk,null),Al(Kt,Lk,null),z(Kt,"_minimumExpansionYear",-1),z(Kt,"EXTRA_COVERAGE",5);mr=Kt,gi=null,WR={get count(){return gi===null?0:Object.keys(gi).length},reset:function(){gi=Object.create(null);let n=mr.utcTimezone;gi.Z=n,gi.UTC=n,gi.GMT=n},_hard_reset:function(){gi=null},has:function(n){return gi===null?!1:!!gi[n]},get:function(n){return gi===null&&this.reset(),gi[n]},register:function(n,e){if(gi===null&&this.reset(),typeof n=="string"&&e instanceof mr&&([n,e]=[e,n]),e||(n instanceof mr?e=n.tzid:n.name==="vtimezone"&&(n=new mr(n),e=n.tzid)),!e)throw new TypeError("Neither a timezone nor a name was passed");if(n instanceof mr)gi[e]=n;else throw new TypeError("timezone must be ICAL.Timezone or ICAL.Component")},remove:function(n){return gi===null?null:delete gi[n]}};s5e=Object.freeze({__proto__:null,binsearchInsert:Rh,clone:Fh,extend:Lh,foldline:_Te,formatClassType:ou,isStrictlyNaN:pE,pad2:Gi,strictParseInt:qa,trunc:la,unescapedIndexOf:RTe,updateTimezones:i5e}),lu=class n{constructor(e){z(this,"hours",0);z(this,"minutes",0);z(this,"factor",1);z(this,"icaltype","utc-offset");this.fromData(e)}static fromString(e){let t={};return t.factor=e[0]==="+"?1:-1,t.hours=qa(e.slice(1,3)),t.minutes=qa(e.slice(4,6)),new n(t)}static fromSeconds(e){let t=new n;return t.fromSeconds(e),t}clone(){return n.fromSeconds(this.toSeconds())}fromData(e){if(e)for(let[t,r]of Object.entries(e))this[t]=r;this._normalize()}fromSeconds(e){let t=Math.abs(e);return this.factor=e<0?-1:1,this.hours=la(t/3600),t-=this.hours*3600,this.minutes=la(t/60),this}toSeconds(){return this.factor*(60*this.minutes+3600*this.hours)}compare(e){let t=this.toSeconds(),r=e.toSeconds();return(t>r)-(r>t)}_normalize(){let e=this.toSeconds(),t=this.factor;for(;e<-43200;)e+=97200;for(;e>50400;)e-=97200;this.fromSeconds(e),e==0&&(this.factor=t)}toICALString(){return fr.icalendar.value["utc-offset"].toICAL(this.toString())}toString(){return(this.factor==1?"+":"-")+Gi(this.hours)+":"+Gi(this.minutes)}},Nh=class n extends Me{constructor(t,r,a){super(t,r);z(this,"icalclass","vcardtime");z(this,"icaltype","date-and-or-time");this.icaltype=a||"date-and-or-time"}static fromDateAndOrTimeString(t,r){function a(g,v,k){return g?qa(g.slice(v,v+k)):null}let i=t.split("T"),s=i[0],o=i[1],l=o?fr.vcard.value.time._splitZone(o):[],c=l[0],d=l[1],u=s?s.length:0,p=d?d.length:0,m=s&&s[0]=="-"&&s[1]=="-",f=d&&d[0]=="-",h={year:m?null:a(s,0,4),month:m&&(u==4||u==7)?a(s,2,2):u==7||u==10?a(s,5,2):null,day:u==5?a(s,3,2):u==7&&m?a(s,5,2):u==10?a(s,8,2):null,hour:f?null:a(d,0,2),minute:f&&p==3?a(d,1,2):p>4?f?a(d,1,2):a(d,3,2):null,second:p==4?a(d,2,2):p==6?a(d,4,2):p==8?a(d,6,2):null};return c=="Z"?c=mr.utcTimezone:c&&c[3]==":"?c=lu.fromString(c):c=null,new n(h,c,r)}clone(){return new n(this._time,this.zone,this.icaltype)}_normalize(){return this}utcOffset(){return this.zone instanceof lu?this.zone.toSeconds():Me.prototype.utcOffset.apply(this,arguments)}toICALString(){return fr.vcard.value[this.icaltype].toICAL(this.toString())}toString(){let t=this.year,r=this.month,a=this.day,i=this.hour,s=this.minute,o=this.second,l=t!==null,c=r!==null,d=a!==null,u=i!==null,p=s!==null,m=o!==null,f=(l?Gi(t)+(c||d?"-":""):c||d?"--":"")+(c?Gi(r):"")+(d?"-"+Gi(a):""),h=(u?Gi(i):"-")+(u&&p?":":"")+(p?Gi(s):"")+(!u&&!p?"-":"")+(p&&m?":":"")+(m?Gi(o):""),g;switch(this.zone===mr.utcTimezone?g="Z":this.zone instanceof lu?g=this.zone.toString():this.zone===mr.localTimezone?g="":this.zone instanceof mr?g=lu.fromSeconds(this.zone.utcOffset(this)).toString():g="",this.icaltype){case"time":return h+g;case"date-and-or-time":case"date-time":return f+(h=="--"?"":"T"+h+g);case"date":return f}return null}},qi=class qi{constructor(e){z(this,"completed",!1);z(this,"rule",null);z(this,"dtstart",null);z(this,"last",null);z(this,"occurrence_number",0);z(this,"by_indices",null);z(this,"initialized",!1);z(this,"by_data",null);z(this,"days",null);z(this,"days_index",0);this.fromData(e)}fromData(e){if(this.rule=ou(e.rule,yl),!this.rule)throw new Error("iterator requires a (ICAL.Recur) rule");if(this.dtstart=ou(e.dtstart,Me),!this.dtstart)throw new Error("iterator requires a (ICAL.Time) dtstart");if(e.by_data?this.by_data=e.by_data:this.by_data=Fh(this.rule.parts,!0),e.occurrence_number&&(this.occurrence_number=e.occurrence_number),this.days=e.days||[],e.last&&(this.last=ou(e.last,Me)),this.by_indices=e.by_indices,this.by_indices||(this.by_indices={BYSECOND:0,BYMINUTE:0,BYHOUR:0,BYDAY:0,BYMONTH:0,BYWEEKNO:0,BYMONTHDAY:0}),this.initialized=e.initialized||!1,!this.initialized)try{this.init()}catch(t){if(t instanceof Rk)this.completed=!0;else throw t}}init(){this.initialized=!0,this.last=this.dtstart.clone();let e=this.by_data;if("BYDAY"in e&&this.sort_byday_rules(e.BYDAY),"BYYEARDAY"in e&&("BYMONTH"in e||"BYWEEKNO"in e||"BYMONTHDAY"in e))throw new Error("Invalid BYYEARDAY rule");if("BYWEEKNO"in e&&"BYMONTHDAY"in e)throw new Error("BYWEEKNO does not fit to BYMONTHDAY");if(this.rule.freq=="MONTHLY"&&("BYYEARDAY"in e||"BYWEEKNO"in e))throw new Error("For MONTHLY recurrences neither BYYEARDAY nor BYWEEKNO may appear");if(this.rule.freq=="WEEKLY"&&("BYYEARDAY"in e||"BYMONTHDAY"in e))throw new Error("For WEEKLY recurrences neither BYMONTHDAY nor BYYEARDAY may appear");if(this.rule.freq!="YEARLY"&&"BYYEARDAY"in e)throw new Error("BYYEARDAY may only appear in YEARLY rules");if(this.last.second=this.setup_defaults("BYSECOND","SECONDLY",this.dtstart.second),this.last.minute=this.setup_defaults("BYMINUTE","MINUTELY",this.dtstart.minute),this.last.hour=this.setup_defaults("BYHOUR","HOURLY",this.dtstart.hour),this.last.day=this.setup_defaults("BYMONTHDAY","DAILY",this.dtstart.day),this.last.month=this.setup_defaults("BYMONTH","MONTHLY",this.dtstart.month),this.rule.freq=="WEEKLY")if("BYDAY"in e){let[,t]=this.ruleDayOfWeek(e.BYDAY[0],this.rule.wkst),r=t-this.last.dayOfWeek(this.rule.wkst);(this.last.dayOfWeek(this.rule.wkst)=0||r<0)&&(this.last.day+=r)}else{let t=yl.numericDayToIcalDay(this.dtstart.dayOfWeek());e.BYDAY=[t]}if(this.rule.freq=="YEARLY"){let t=this.rule.until?this.rule.until.year:2e4;for(;this.last.year<=t&&(this.expand_year_days(this.last.year),!(this.days.length>0));)this.increment_year(this.rule.interval);if(this.days.length==0)throw new Rk;if(!this._nextByYearDay()&&!this.next_year()&&!this.next_year()&&!this.next_year())throw new Rk}if(this.rule.freq=="MONTHLY"){if(this.has_by_data("BYDAY")){let t=null,r=this.last.clone(),a=Me.daysInMonth(this.last.month,this.last.year);for(let i of this.by_data.BYDAY){this.last=r.clone();let[s,o]=this.ruleDayOfWeek(i),l=this.last.nthWeekDay(o,s);if(s>=6||s<=-6)throw new Error("Malformed values in BYDAY part");if(l>a||l<=0){if(t&&t.month==r.month)continue;for(;l>a||l<=0;)this.increment_month(),a=Me.daysInMonth(this.last.month,this.last.year),l=this.last.nthWeekDay(o,s)}this.last.day=l,(!t||this.last.compare(t)<0)&&(t=this.last.clone())}if(this.last=t.clone(),this.has_by_data("BYMONTHDAY")&&this._byDayAndMonthDay(!0),this.last.day>a||this.last.day==0)throw new Error("Malformed values in BYDAY part")}else if(this.has_by_data("BYMONTHDAY")){this.last.day=1;let t=this.normalizeByMonthDayRules(this.last.year,this.last.month,this.rule.parts.BYMONTHDAY).filter(r=>r>=this.last.day);if(t.length)this.last.day=t[0],this.by_data.BYMONTHDAY=t;else if(!this.next_month()&&!this.next_month()&&!this.next_month())throw new Rk}}}next(e=!1){let t=this.last?this.last.clone():null;if((this.rule.count&&this.occurrence_number>=this.rule.count||this.rule.until&&this.last.compare(this.rule.until)>0)&&(this.completed=!0),this.completed)return null;if(this.occurrence_number==0&&this.last.compare(this.dtstart)>=0)return this.occurrence_number++,this.last;let r,a=0;do switch(r=1,this.rule.freq){case"SECONDLY":this.next_second();break;case"MINUTELY":this.next_minute();break;case"HOURLY":this.next_hour();break;case"DAILY":this.next_day();break;case"WEEKLY":this.next_week();break;case"MONTHLY":if(r=this.next_month(),r)a=0;else if(++a==336)return this.completed=!0,null;break;case"YEARLY":if(r=this.next_year(),r)a=0;else if(++a==28)return this.completed=!0,null;break;default:return null}while(!this.check_contracting_rules()||this.last.compare(this.dtstart)<0||!r);if(this.last.compare(t)==0){if(e)throw new Error("Same occurrence found twice, protecting you from death by recursion");this.next(!0)}return this.rule.until&&this.last.compare(this.rule.until)>0?(this.completed=!0,null):(this.occurrence_number++,this.last)}next_second(){return this.next_generic("BYSECOND","SECONDLY","second","minute")}increment_second(e){return this.increment_generic(e,"second",60,"minute")}next_minute(){return this.next_generic("BYMINUTE","MINUTELY","minute","hour","next_second")}increment_minute(e){return this.increment_generic(e,"minute",60,"hour")}next_hour(){return this.next_generic("BYHOUR","HOURLY","hour","monthday","next_minute")}increment_hour(e){this.increment_generic(e,"hour",24,"monthday")}next_day(){let e=this.rule.freq=="DAILY";return this.next_hour()==0||(e?this.increment_monthday(this.rule.interval):this.increment_monthday(1)),0}next_week(){let e=0;if(this.next_weekday_by_week()==0)return e;if(this.has_by_data("BYWEEKNO")){this.by_indices.BYWEEKNO++,this.by_indices.BYWEEKNO==this.by_data.BYWEEKNO.length&&(this.by_indices.BYWEEKNO=0,e=1),this.last.month=1,this.last.day=1;let t=this.by_data.BYWEEKNO[this.by_indices.BYWEEKNO];this.last.day+=7*t,e&&this.increment_year(1)}else this.increment_monthday(7*this.rule.interval);return e}normalizeByMonthDayRules(e,t,r){let a=Me.daysInMonth(t,e),i=[],s=0,o=r.length,l;for(;sa)){if(l<0)l=a+(l+1);else if(l===0)continue;i.indexOf(l)===-1&&i.push(l)}}return i.sort(function(c,d){return c-d})}_byDayAndMonthDay(e){let t,r=this.by_data.BYDAY,a,i=0,s,o=r.length,l=0,c,d=this,u=this.last.day;function p(){for(c=Me.daysInMonth(d.last.month,d.last.year),t=d.normalizeByMonthDayRules(d.last.year,d.last.month,d.by_data.BYMONTHDAY),s=t.length;t[i]<=u&&!(e&&t[i]==u)&&ic){m();continue}let h=t[i++];if(h>=a)u=h;else{m();continue}for(let g=0;gt&&(this.last.day=1,this.increment_month(),this.is_day_in_byday(this.last)?(!this.has_by_data("BYSETPOS")||this.check_set_position(1))&&(e=1):e=0)}else if(this.has_by_data("BYMONTHDAY")){if(this.by_indices.BYMONTHDAY++,this.by_indices.BYMONTHDAY>=this.by_data.BYMONTHDAY.length&&(this.by_indices.BYMONTHDAY=0,this.increment_month(),this.by_indices.BYMONTHDAY>=this.by_data.BYMONTHDAY.length))return 0;let t=Me.daysInMonth(this.last.month,this.last.year),r=this.by_data.BYMONTHDAY[this.by_indices.BYMONTHDAY];r<0&&(r=t+r+1),r>t?(this.last.day=1,e=this.is_day_in_byday(this.last)):this.last.day=r}else{this.increment_month();let t=Me.daysInMonth(this.last.month,this.last.year);this.by_data.BYMONTHDAY[0]>t?e=0:this.last.day=this.by_data.BYMONTHDAY[0]}return e}next_weekday_by_week(){let e=0;if(this.next_hour()==0)return e;if(!this.has_by_data("BYDAY"))return 1;for(;;){let t=new Me;this.by_indices.BYDAY++,this.by_indices.BYDAY==Object.keys(this.by_data.BYDAY).length&&(this.by_indices.BYDAY=0,e=1);let r=this.by_data.BYDAY[this.by_indices.BYDAY],i=this.ruleDayOfWeek(r)[1];i-=this.rule.wkst,i<0&&(i+=7),t.year=this.last.year,t.month=this.last.month,t.day=this.last.day;let s=t.startDoyWeek(this.rule.wkst);if(i+s<1&&!e)continue;let o=Me.fromDayOfYear(s+i,this.last.year);return this.last.year=o.year,this.last.month=o.month,this.last.day=o.day,e}}next_year(){return this.next_hour()==0||(this.days.length==0||++this.days_index==this.days.length)&&(this.days_index=0,this.increment_year(this.rule.interval),this.has_by_data("BYMONTHDAY")&&(this.by_data.BYMONTHDAY=this.normalizeByMonthDayRules(this.last.year,this.last.month,this.rule.parts.BYMONTHDAY)),this.expand_year_days(this.last.year),this.days.length==0)?0:this._nextByYearDay()}_nextByYearDay(){let e=this.days[this.days_index],t=this.last.year;if(Math.abs(e)==366&&!Me.isLeapYear(this.last.year))return 0;e<1&&(e+=1,t+=1);let r=Me.fromDayOfYear(e,t);return this.last.day=r.day,this.last.month=r.month,1}ruleDayOfWeek(e,t){let r=e.match(/([+-]?[0-9])?(MO|TU|WE|TH|FR|SA|SU)/);if(r){let a=parseInt(r[1]||0,10);return e=yl.icalDayToNumericDay(r[2],t),[a,e]}else return[0,0]}next_generic(e,t,r,a,i){let s=e in this.by_data,o=this.rule.freq==t,l=0;if(i&&this[i]()==0)return l;if(s){this.by_indices[e]++;let c=this.by_data[e];this.by_indices[e]==c.length&&(this.by_indices[e]=0,l=1),this.last[r]=c[this.by_indices[e]]}else o&&this["increment_"+r](this.rule.interval);return s&&l&&o&&this["increment_"+a](1),l}increment_monthday(e){for(let t=0;tr&&(this.last.day-=r,this.increment_month())}}increment_month(){if(this.last.day=1,this.has_by_data("BYMONTH"))this.by_indices.BYMONTH++,this.by_indices.BYMONTH==this.by_data.BYMONTH.length&&(this.by_indices.BYMONTH=0,this.increment_year(1)),this.last.month=this.by_data.BYMONTH[this.by_indices.BYMONTH];else{this.rule.freq=="MONTHLY"?this.last.month+=this.rule.interval:this.last.month++,this.last.month--;let e=la(this.last.month/12);this.last.month%=12,this.last.month++,e!=0&&this.increment_year(e)}this.has_by_data("BYMONTHDAY")&&(this.by_data.BYMONTHDAY=this.normalizeByMonthDayRules(this.last.year,this.last.month,this.rule.parts.BYMONTHDAY))}increment_year(e){this.last.day=1,this.last.year+=e}increment_generic(e,t,r,a){this.last[t]+=e;let i=la(this.last[t]/r);this.last[t]%=r,i!=0&&this["increment_"+a](i)}has_by_data(e){return e in this.rule.parts}expand_year_days(e){let t=new Me;this.days=[];let r={},a=["BYDAY","BYWEEKNO","BYMONTHDAY","BYMONTH","BYYEARDAY"];for(let o of a)o in this.rule.parts&&(r[o]=this.rule.parts[o]);if("BYMONTH"in r&&"BYWEEKNO"in r){let o=1,l={};t.year=e,t.isDate=!0;for(let c=0;c0?(g=v+(f-1)*7,g<=l&&this.days.push(d+g)):(g=k+(f+1)*7,g>0&&this.days.push(d+g))}}this.days.sort(function(o,l){return o-l})}else if(i==2&&"BYDAY"in r&&"BYMONTHDAY"in r){let o=this.expand_by_day(e);for(let l of o){let c=Me.fromDayOfYear(l,e);this.by_data.BYMONTHDAY.indexOf(c.day)>=0&&this.days.push(l)}}else if(i==3&&"BYDAY"in r&&"BYMONTHDAY"in r&&"BYMONTH"in r){let o=this.expand_by_day(e);for(let l of o){let c=Me.fromDayOfYear(l,e);this.by_data.BYMONTH.indexOf(c.month)>=0&&this.by_data.BYMONTHDAY.indexOf(c.day)>=0&&this.days.push(l)}}else if(i==2&&"BYDAY"in r&&"BYWEEKNO"in r){let o=this.expand_by_day(e);for(let l of o){let d=Me.fromDayOfYear(l,e).weekNumber(this.rule.wkst);this.by_data.BYWEEKNO.indexOf(d)&&this.days.push(l)}}else if(!(i==3&&"BYDAY"in r&&"BYWEEKNO"in r&&"BYMONTHDAY"in r))if(i==1&&"BYYEARDAY"in r)this.days=this.days.concat(this.by_data.BYYEARDAY);else if(i==2&&"BYYEARDAY"in r&&"BYDAY"in r){let o=Me.isLeapYear(e)?366:365,l=new Set(this.expand_by_day(e));for(let c of this.by_data.BYYEARDAY)c<0&&(c+=o+1),l.has(c)&&this.days.push(c)}else this.days=[]}}let s=Me.isLeapYear(e)?366:365;return this.days.sort((o,l)=>(o<0&&(o+=s+1),l<0&&(l+=s+1),o-l)),0}expand_by_day(e){let t=[],r=this.last.clone();r.year=e,r.month=1,r.day=1,r.isDate=!0;let a=r.dayOfWeek();r.month=12,r.day=31,r.isDate=!0;let i=r.dayOfWeek(),s=r.dayOfYear();for(let o of this.by_data.BYDAY){let l=this.ruleDayOfWeek(o),c=l[0],d=l[1];if(c==0){let u=(d+7-a)%7+1;for(let p=u;p<=s;p+=7)t.push(p)}else if(c>0){let u;d>=a?u=d-a+1:u=d-a+8,t.push(u+(c-1)*7)}else{let u;c=-c,d<=i?u=s-i+d:u=s-i+d-7,t.push(u-(c-1)*7)}}return t}is_day_in_byday(e){if(this.by_data.BYDAY)for(let t of this.by_data.BYDAY){let r=this.ruleDayOfWeek(t),a=r[0],i=r[1],s=e.dayOfWeek();if(a==0&&i==s||e.nthWeekDay(i,a)==e.day)return 1}return 0}check_set_position(e){return this.has_by_data("BYSETPOS")?this.by_data.BYSETPOS.indexOf(e)!==-1:!1}sort_byday_rules(e){for(let t=0;ti){let s=e[t];e[t]=e[r],e[r]=s}}}check_contract_restriction(e,t){let r=qi._indexMap[e],a=qi._expandMap[this.rule.freq][r],i=!1;if(e in this.by_data&&a==qi.CONTRACT){let s=this.by_data[e];for(let o of s)if(o==t){i=!0;break}}else i=!0;return i}check_contracting_rules(){let e=this.last.dayOfWeek(),t=this.last.weekNumber(this.rule.wkst),r=this.last.dayOfYear();return this.check_contract_restriction("BYSECOND",this.last.second)&&this.check_contract_restriction("BYMINUTE",this.last.minute)&&this.check_contract_restriction("BYHOUR",this.last.hour)&&this.check_contract_restriction("BYDAY",yl.numericDayToIcalDay(e))&&this.check_contract_restriction("BYWEEKNO",t)&&this.check_contract_restriction("BYMONTHDAY",this.last.day)&&this.check_contract_restriction("BYMONTH",this.last.month)&&this.check_contract_restriction("BYYEARDAY",r)}setup_defaults(e,t,r){let a=qi._indexMap[e];return qi._expandMap[this.rule.freq][a]!=qi.CONTRACT&&(e in this.by_data||(this.by_data[e]=[r]),this.rule.freq!=t)?this.by_data[e][0]:r}toJSON(){let e=Object.create(null);return e.initialized=this.initialized,e.rule=this.rule.toJSON(),e.dtstart=this.dtstart.toJSON(),e.by_data=this.by_data,e.days=this.days,e.last=this.last.toJSON(),e.by_indices=this.by_indices,e.occurrence_number=this.occurrence_number,e}};z(qi,"_indexMap",{BYSECOND:0,BYMINUTE:1,BYHOUR:2,BYDAY:3,BYMONTHDAY:4,BYYEARDAY:5,BYWEEKNO:6,BYMONTH:7,BYSETPOS:8}),z(qi,"_expandMap",{SECONDLY:[1,1,1,1,1,1,1,1],MINUTELY:[2,1,1,1,1,1,1,1],HOURLY:[2,2,1,1,1,1,1,1],DAILY:[2,2,2,1,1,1,1,1],WEEKLY:[2,2,2,2,3,3,1,1],MONTHLY:[2,2,2,2,2,3,3,1],YEARLY:[2,2,2,2,2,2,2,2]}),z(qi,"UNKNOWN",0),z(qi,"CONTRACT",1),z(qi,"EXPAND",2),z(qi,"ILLEGAL",3);mE=qi,Rk=class extends Error{constructor(){super("Recurrence rule has no valid occurrences")}},o5e=/^(SU|MO|TU|WE|TH|FR|SA)$/,l5e=/^([+-])?(5[0-3]|[1-4][0-9]|[1-9])?(SU|MO|TU|WE|TH|FR|SA)$/,FTe={SU:Me.SUNDAY,MO:Me.MONDAY,TU:Me.TUESDAY,WE:Me.WEDNESDAY,TH:Me.THURSDAY,FR:Me.FRIDAY,SA:Me.SATURDAY},c5e=Object.fromEntries(Object.entries(FTe).map(n=>n.reverse())),wTe=["SECONDLY","MINUTELY","HOURLY","DAILY","WEEKLY","MONTHLY","YEARLY"],yl=class n{constructor(e){z(this,"parts",null);z(this,"interval",1);z(this,"wkst",Me.MONDAY);z(this,"until",null);z(this,"count",null);z(this,"freq",null);z(this,"icalclass","icalrecur");z(this,"icaltype","recur");this.wrappedJSObject=this,this.parts={},e&&typeof e=="object"&&this.fromData(e)}static fromString(e){let t=this._stringToData(e,!1);return new n(t)}static fromData(e){return new n(e)}static _stringToData(e,t){let r=Object.create(null),a=e.split(";"),i=a.length;for(let s=0;s7&&(a-=7),c5e[a]}iterator(e){return new mE({rule:this,dtstart:e})}clone(){return new n(this.toJSON())}isFinite(){return!!(this.count||this.until)}isByCount(){return!!(this.count&&!this.until)}addComponent(e,t){let r=e.toUpperCase();r in this.parts?this.parts[r].push(t):this.parts[r]=[t]}setComponent(e,t){this.parts[e.toUpperCase()]=t.slice()}getComponent(e){let t=e.toUpperCase();return t in this.parts?this.parts[t].slice():[]}getNextOccurrence(e,t){let r=this.iterator(e),a;do a=r.next();while(a&&a.compare(t)<=0);return a&&t.zone&&(a.zone=t.zone),a}fromData(e){for(let t in e){let r=t.toUpperCase();r in qW?Array.isArray(e[t])?this.parts[r]=e[t]:this.parts[r]=[e[t]]:this[t]=e[t]}this.interval&&typeof this.interval!="number"&&WW.INTERVAL(this.interval,this),this.wkst&&typeof this.wkst!="number"&&(this.wkst=n.icalDayToNumericDay(this.wkst)),this.until&&!(this.until instanceof Me)&&(this.until=Me.fromString(this.until))}toJSON(){let e=Object.create(null);e.freq=this.freq,this.count&&(e.count=this.count),this.interval>1&&(e.interval=this.interval);for(let[t,r]of Object.entries(this.parts))Array.isArray(r)&&r.length==1?e[t.toLowerCase()]=r[0]:e[t.toLowerCase()]=Fh(r);return this.until&&(e.until=this.until.toString()),"wkst"in this&&this.wkst!==Me.DEFAULT_WEEK_START&&(e.wkst=n.numericDayToIcalDay(this.wkst)),e}toString(){let e="FREQ="+this.freq;this.count&&(e+=";COUNT="+this.count),this.interval>1&&(e+=";INTERVAL="+this.interval);for(let[t,r]of Object.entries(this.parts))e+=";"+t+"="+r;return this.until&&(e+=";UNTIL="+this.until.toICALString()),"wkst"in this&&this.wkst!==Me.DEFAULT_WEEK_START&&(e+=";WKST="+n.numericDayToIcalDay(this.wkst)),e}};WW={FREQ:function(n,e,t){if(wTe.indexOf(n)!==-1)e.freq=n;else throw new Error('invalid frequency "'+n+'" expected: "'+wTe.join(", ")+'"')},COUNT:function(n,e,t){e.count=qa(n)},INTERVAL:function(n,e,t){e.interval=qa(n),e.interval<1&&(e.interval=1)},UNTIL:function(n,e,t){n.length>10?e.until=fr.icalendar.value["date-time"].fromICAL(n):e.until=fr.icalendar.value.date.fromICAL(n),t||(e.until=Me.fromString(e.until))},WKST:function(n,e,t){if(o5e.test(n))e.wkst=yl.icalDayToNumericDay(n);else throw new Error('invalid WKST value "'+n+'"')}},qW={BYSECOND:Jp.bind(void 0,"BYSECOND",0,60),BYMINUTE:Jp.bind(void 0,"BYMINUTE",0,59),BYHOUR:Jp.bind(void 0,"BYHOUR",0,23),BYDAY:function(n){if(l5e.test(n))return n;throw new Error('invalid BYDAY value "'+n+'"')},BYMONTHDAY:Jp.bind(void 0,"BYMONTHDAY",-31,31),BYYEARDAY:Jp.bind(void 0,"BYYEARDAY",-366,366),BYWEEKNO:Jp.bind(void 0,"BYWEEKNO",-53,53),BYMONTH:Jp.bind(void 0,"BYMONTH",1,12),BYSETPOS:Jp.bind(void 0,"BYSETPOS",-366,366)},d5e=/\\\\|\\;|\\,|\\[Nn]/g,u5e=/\\|;|,|\n/g,STe=/\\\\|\\,|\\[Nn]/g,CTe=/\\|,|\n/g;Zt={defaultType:"text"},fE={defaultType:"text",multiValue:","},qR={defaultType:"text",structuredValue:";"},OR={defaultType:"integer"},zR={defaultType:"date-time",allowedTypes:["date-time","date"]},BR={defaultType:"date-time"},Wi={defaultType:"uri"},xTe={defaultType:"utc-offset"},ETe={defaultType:"recur"},DTe={defaultType:"date-and-or-time",allowedTypes:["date-time","date","text"]};ZW={categories:fE,url:Wi,version:Zt,uid:Zt},QW={boolean:{values:["TRUE","FALSE"],fromICAL:function(n){switch(n){case"TRUE":return!0;case"FALSE":return!1;default:return!1}},toICAL:function(n){return n?"TRUE":"FALSE"}},float:{matches:/^[+-]?\d+\.\d+$/,fromICAL:function(n){let e=parseFloat(n);return pE(e)?0:e},toICAL:function(n){return String(n)}},integer:{fromICAL:function(n){let e=parseInt(n);return pE(e)?0:e},toICAL:function(n){return String(n)}},"utc-offset":{toICAL:function(n){return n.length<7?n.slice(0,3)+n.slice(4,6):n.slice(0,3)+n.slice(4,6)+n.slice(7,9)},fromICAL:function(n){return n.length<6?n.slice(0,3)+":"+n.slice(3,5):n.slice(0,3)+":"+n.slice(3,5)+":"+n.slice(5,7)},decorate:function(n){return lu.fromString(n)},undecorate:function(n){return n.toString()}}},f5e={cutype:{values:["INDIVIDUAL","GROUP","RESOURCE","ROOM","UNKNOWN"],allowXName:!0,allowIanaToken:!0},"delegated-from":{valueType:"cal-address",multiValue:",",multiValueSeparateDQuote:!0},"delegated-to":{valueType:"cal-address",multiValue:",",multiValueSeparateDQuote:!0},encoding:{values:["8BIT","BASE64"]},fbtype:{values:["FREE","BUSY","BUSY-UNAVAILABLE","BUSY-TENTATIVE"],allowXName:!0,allowIanaToken:!0},member:{valueType:"cal-address",multiValue:",",multiValueSeparateDQuote:!0},partstat:{values:["NEEDS-ACTION","ACCEPTED","DECLINED","TENTATIVE","DELEGATED","COMPLETED","IN-PROCESS"],allowXName:!0,allowIanaToken:!0},range:{values:["THISANDFUTURE"]},related:{values:["START","END"]},reltype:{values:["PARENT","CHILD","SIBLING"],allowXName:!0,allowIanaToken:!0},role:{values:["REQ-PARTICIPANT","CHAIR","OPT-PARTICIPANT","NON-PARTICIPANT"],allowXName:!0,allowIanaToken:!0},rsvp:{values:["TRUE","FALSE"]},"sent-by":{valueType:"cal-address"},tzid:{matches:/^\//},value:{values:["binary","boolean","cal-address","date","date-time","duration","float","integer","period","recur","text","time","uri","utc-offset"],allowXName:!0,allowIanaToken:!0}},zn=Lh(QW,{text:YW(d5e,u5e),uri:{},binary:{decorate:function(n){return HR.fromString(n)},undecorate:function(n){return n.toString()}},"cal-address":{},date:{decorate:function(n,e){return fr.strict?Me.fromDateString(n,e):Me.fromString(n,e)},undecorate:function(n){return n.toString()},fromICAL:function(n){return!fr.strict&&n.length>=15?zn["date-time"].fromICAL(n):n.slice(0,4)+"-"+n.slice(4,6)+"-"+n.slice(6,8)},toICAL:function(n){let e=n.length;return e==10?n.slice(0,4)+n.slice(5,7)+n.slice(8,10):e>=19?zn["date-time"].toICAL(n):n}},"date-time":{fromICAL:function(n){if(!fr.strict&&n.length==8)return zn.date.fromICAL(n);{let e=n.slice(0,4)+"-"+n.slice(4,6)+"-"+n.slice(6,8)+"T"+n.slice(9,11)+":"+n.slice(11,13)+":"+n.slice(13,15);return n[15]&&n[15]==="Z"&&(e+="Z"),e}},toICAL:function(n){let e=n.length;if(e==10&&!fr.strict)return zn.date.toICAL(n);if(e>=19){let t=n.slice(0,4)+n.slice(5,7)+n.slice(8,13)+n.slice(14,16)+n.slice(17,19);return n[19]&&n[19]==="Z"&&(t+="Z"),t}else return n},decorate:function(n,e){return fr.strict?Me.fromDateTimeString(n,e):Me.fromString(n,e)},undecorate:function(n){return n.toString()}},duration:{decorate:function(n){return Rs.fromString(n)},undecorate:function(n){return n.toString()}},period:{fromICAL:function(n){let e=n.split("/");return e[0]=zn["date-time"].fromICAL(e[0]),Rs.isValueString(e[1])||(e[1]=zn["date-time"].fromICAL(e[1])),e},toICAL:function(n){return n=n.slice(),!fr.strict&&n[0].length==10?n[0]=zn.date.toICAL(n[0]):n[0]=zn["date-time"].toICAL(n[0]),Rs.isValueString(n[1])||(!fr.strict&&n[1].length==10?n[1]=zn.date.toICAL(n[1]):n[1]=zn["date-time"].toICAL(n[1])),n.join("/")},decorate:function(n,e){return uE.fromJSON(n,e,!fr.strict)},undecorate:function(n){return n.toJSON()}},recur:{fromICAL:function(n){return yl._stringToData(n,!0)},toICAL:function(n){let e="";for(let[t,r]of Object.entries(n))t=="until"?r.length>10?r=zn["date-time"].toICAL(r):r=zn.date.toICAL(r):t=="wkst"?typeof r=="number"&&(r=yl.numericDayToIcalDay(r)):Array.isArray(r)&&(r=r.join(",")),e+=t.toUpperCase()+"="+r+";";return e.slice(0,Math.max(0,e.length-1))},decorate:function(e){return yl.fromData(e)},undecorate:function(n){return n.toJSON()}},time:{fromICAL:function(n){if(n.length<6)return n;let e=n.slice(0,2)+":"+n.slice(2,4)+":"+n.slice(4,6);return n[6]==="Z"&&(e+="Z"),e},toICAL:function(n){if(n.length<8)return n;let e=n.slice(0,2)+n.slice(3,5)+n.slice(6,8);return n[8]==="Z"&&(e+="Z"),e}}}),h5e=Lh(ZW,{action:Zt,attach:{defaultType:"uri"},attendee:{defaultType:"cal-address"},calscale:Zt,class:Zt,comment:Zt,completed:BR,contact:Zt,created:BR,description:Zt,dtend:zR,dtstamp:BR,dtstart:zR,due:zR,duration:{defaultType:"duration"},exdate:{defaultType:"date-time",allowedTypes:["date-time","date"],multiValue:","},exrule:ETe,freebusy:{defaultType:"period",multiValue:","},geo:{defaultType:"float",structuredValue:";"},"last-modified":BR,location:Zt,method:Zt,organizer:{defaultType:"cal-address"},"percent-complete":OR,priority:OR,prodid:Zt,"related-to":Zt,repeat:OR,rdate:{defaultType:"date-time",allowedTypes:["date-time","date","period"],multiValue:",",detectType:function(n){return n.indexOf("/")!==-1?"period":n.indexOf("T")===-1?"date":"date-time"}},"recurrence-id":zR,resources:fE,"request-status":qR,rrule:ETe,sequence:OR,status:Zt,summary:Zt,transp:Zt,trigger:{defaultType:"duration",allowedTypes:["duration","date-time"]},tzoffsetfrom:xTe,tzoffsetto:xTe,tzurl:Wi,tzid:Zt,tzname:Zt}),Ns=Lh(QW,{text:YW(STe,CTe),uri:YW(STe,CTe),date:{decorate:function(n){return Nh.fromDateAndOrTimeString(n,"date")},undecorate:function(n){return n.toString()},fromICAL:function(n){return n.length==8?zn.date.fromICAL(n):n[0]=="-"&&n.length==6?n.slice(0,4)+"-"+n.slice(4):n},toICAL:function(n){return n.length==10?zn.date.toICAL(n):n[0]=="-"&&n.length==7?n.slice(0,4)+n.slice(5):n}},time:{decorate:function(n){return Nh.fromDateAndOrTimeString("T"+n,"time")},undecorate:function(n){return n.toString()},fromICAL:function(n){let e=Ns.time._splitZone(n,!0),t=e[0],r=e[1];return r.length==6?r=r.slice(0,2)+":"+r.slice(2,4)+":"+r.slice(4,6):r.length==4&&r[0]!="-"?r=r.slice(0,2)+":"+r.slice(2,4):r.length==5&&(r=r.slice(0,3)+":"+r.slice(3,5)),t.length==5&&(t[0]=="-"||t[0]=="+")&&(t=t.slice(0,3)+":"+t.slice(3)),r+t},toICAL:function(n){let e=Ns.time._splitZone(n),t=e[0],r=e[1];return r.length==8?r=r.slice(0,2)+r.slice(3,5)+r.slice(6,8):r.length==5&&r[0]!="-"?r=r.slice(0,2)+r.slice(3,5):r.length==6&&(r=r.slice(0,3)+r.slice(4,6)),t.length==6&&(t[0]=="-"||t[0]=="+")&&(t=t.slice(0,3)+t.slice(4)),r+t},_splitZone:function(n,e){let t=n.length-1,r=n.length-(e?5:6),a=n[r],i,s;return n[t]=="Z"?(i=n[t],s=n.slice(0,Math.max(0,t))):n.length>6&&(a=="-"||a=="+")?(i=n.slice(r),s=n.slice(0,Math.max(0,r))):(i="",s=n),[i,s]}},"date-time":{decorate:function(n){return Nh.fromDateAndOrTimeString(n,"date-time")},undecorate:function(n){return n.toString()},fromICAL:function(n){return Ns["date-and-or-time"].fromICAL(n)},toICAL:function(n){return Ns["date-and-or-time"].toICAL(n)}},"date-and-or-time":{decorate:function(n){return Nh.fromDateAndOrTimeString(n,"date-and-or-time")},undecorate:function(n){return n.toString()},fromICAL:function(n){let e=n.split("T");return(e[0]?Ns.date.fromICAL(e[0]):"")+(e[1]?"T"+Ns.time.fromICAL(e[1]):"")},toICAL:function(n){let e=n.split("T");return Ns.date.toICAL(e[0])+(e[1]?"T"+Ns.time.toICAL(e[1]):"")}},timestamp:zn["date-time"],"language-tag":{matches:/^[a-zA-Z0-9-]+$/},"phone-number":{fromICAL:function(n){return Array.from(n).filter(function(e){return e==="\\"?void 0:e}).join("")},toICAL:function(n){return Array.from(n).map(function(e){return e===","||e===";"?"\\"+e:e}).join("")}}}),g5e={type:{valueType:"text",multiValue:","},value:{values:["text","uri","date","time","date-time","date-and-or-time","timestamp","boolean","integer","float","utc-offset","language-tag"],allowXName:!0,allowIanaToken:!0}},y5e=Lh(ZW,{adr:{defaultType:"text",structuredValue:";",multiValue:","},anniversary:DTe,bday:DTe,caladruri:Wi,caluri:Wi,clientpidmap:qR,email:Zt,fburl:Wi,fn:Zt,gender:qR,geo:Wi,impp:Wi,key:Wi,kind:Zt,lang:{defaultType:"language-tag"},logo:Wi,member:Wi,n:{defaultType:"text",structuredValue:";",multiValue:","},nickname:fE,note:Zt,org:{defaultType:"text",structuredValue:";"},photo:Wi,related:Wi,rev:{defaultType:"timestamp"},role:Zt,sound:Wi,source:Wi,tel:{defaultType:"uri",allowedTypes:["uri","text"]},title:Zt,tz:{defaultType:"text",allowedTypes:["text","utc-offset","uri"]},xml:Zt}),v5e=Lh(QW,{binary:zn.binary,date:Ns.date,"date-time":Ns["date-time"],"phone-number":Ns["phone-number"],uri:zn.uri,text:Ns.text,time:zn.time,vcard:zn.text,"utc-offset":{toICAL:function(n){return n.slice(0,7)},fromICAL:function(n){return n.slice(0,7)},decorate:function(n){return lu.fromString(n)},undecorate:function(n){return n.toString()}}}),k5e={type:{valueType:"text",multiValue:","},value:{values:["text","uri","date","date-time","phone-number","time","boolean","integer","float","utc-offset","vcard","binary"],allowXName:!0,allowIanaToken:!0}},T5e=Lh(ZW,{fn:Zt,n:{defaultType:"text",structuredValue:";",multiValue:","},nickname:fE,photo:{defaultType:"binary",allowedTypes:["binary","uri"]},bday:{defaultType:"date-time",allowedTypes:["date-time","date"],detectType:function(n){return n.indexOf("T")===-1?"date":"date-time"}},adr:{defaultType:"text",structuredValue:";",multiValue:","},label:Zt,tel:{defaultType:"phone-number"},email:Zt,mailer:Zt,tz:{defaultType:"utc-offset",allowedTypes:["utc-offset","text"]},geo:{defaultType:"float",structuredValue:";"},title:Zt,role:Zt,logo:{defaultType:"binary",allowedTypes:["binary","uri"]},agent:{defaultType:"vcard",allowedTypes:["vcard","text","uri"]},org:qR,note:fE,prodid:Zt,rev:{defaultType:"date-time",allowedTypes:["date-time","date"],detectType:function(n){return n.indexOf("T")===-1?"date":"date-time"}},"sort-string":Zt,sound:{defaultType:"binary",allowedTypes:["binary","uri"]},class:Zt,key:{defaultType:"binary",allowedTypes:["binary","text"]}}),su={name:"ical",value:zn,param:f5e,property:h5e,propertyGroups:!1},PTe={name:"vcard4",value:Ns,param:g5e,property:y5e,propertyGroups:!0},ATe={name:"vcard3",value:v5e,param:k5e,property:T5e,propertyGroups:!0},fr={strict:!0,defaultSet:su,defaultType:"unknown",components:{vcard:PTe,vcard3:ATe,vevent:su,vtodo:su,vjournal:su,valarm:su,vtimezone:su,daylight:su,standard:su},icalendar:su,vcard:PTe,vcard3:ATe,getDesignSet:function(n){return n&&n in fr.components?fr.components[n]:fr.defaultSet}},UR=`\r +`,MTe="unknown",b5e={'"':"^'","\n":"^n","^":"^^"};on.component=function(n,e){let t=n[0].toUpperCase(),r="BEGIN:"+t+UR,a=n[1],i=0,s=a.length,o=n[0];for(o==="vcard"&&n[1].length>0&&!(n[1][0][0]==="version"&&n[1][0][3]==="4.0")&&(o="vcard3"),e=e||fr.getDesignSet(o);i0&&typeof e[0]=="object"&&"icaltype"in e[0]&&this.resetType(e[0].icaltype),this.isDecorated)for(;r=0;s--)(!r||i[s][em]===r)&&this._removeObjectByIndex(e,a,s)}addSubcomponent(e){this._components||(this._components=[],this._hydratedComponentCount=0),e.parent&&e.parent.removeSubcomponent(e);let t=this.jCal[tm].push(e.jCal);return this._components[t-1]=e,this._hydratedComponentCount++,e.parent=this,e}removeSubcomponent(e){let t=this._removeObject(tm,"_components",e);return t&&this._hydratedComponentCount--,t}removeAllSubcomponents(e){let t=this._removeAllObjects(tm,"_components",e);return this._hydratedComponentCount=0,t}addProperty(e){if(!(e instanceof _h))throw new TypeError("must be instance of ICAL.Property");this._properties||(this._properties=[],this._hydratedPropertyCount=0),e.parent&&e.parent.removeProperty(e);let t=this.jCal[Ic].push(e.jCal);return this._properties[t-1]=e,this._hydratedPropertyCount++,e.parent=this,e}addPropertyWithValue(e,t){let r=new _h(e);return r.setValue(t),this.addProperty(r),r}updatePropertyWithValue(e,t){let r=this.getFirstProperty(e);return r?r.setValue(t):r=this.addPropertyWithValue(e,t),r}removeProperty(e){let t=this._removeObject(Ic,"_properties",e);return t&&this._hydratedPropertyCount--,t}removeAllProperties(e){let t=this._removeAllObjects(Ic,"_properties",e);return this._hydratedPropertyCount=0,t}toJSON(){return this.jCal}toString(){return on.component(this.jCal,this._designSet)}getTimeZoneByID(e){if(this.parent)return this.parent.getTimeZoneByID(e);if(!this._timezoneCache)return null;if(this._timezoneCache.has(e))return this._timezoneCache.get(e);let t=this.getAllSubcomponents("vtimezone");for(let r of t)if(r.getFirstProperty("tzid").getFirstValue()===e){let a=new mr({component:r,tzid:e});return this._timezoneCache.set(e,a),a}return null}},GR=class{constructor(e){z(this,"complete",!1);z(this,"ruleIterators",null);z(this,"ruleDates",null);z(this,"exDates",null);z(this,"ruleDateInc",0);z(this,"exDateInc",0);z(this,"exDate",null);z(this,"ruleDate",null);z(this,"dtstart",null);z(this,"last",null);this.ruleDates=[],this.exDates=[],this.fromData(e)}fromData(e){let t=ou(e.dtstart,Me);if(t)this.dtstart=t;else throw new Error(".dtstart (ICAL.Time) must be given");if(e.component)this._init(e.component);else{if(this.last=ou(e.last,Me)||t.clone(),!e.ruleIterators)throw new Error(".ruleIterators or .component must be given");this.ruleIterators=e.ruleIterators.map(function(r){return ou(r,mE)}),this.ruleDateInc=e.ruleDateInc,this.exDateInc=e.exDateInc,e.ruleDates&&(this.ruleDates=e.ruleDates.map(r=>ou(r,Me)),this.ruleDate=this.ruleDates[this.ruleDateInc]),e.exDates&&(this.exDates=e.exDates.map(r=>ou(r,Me)),this.exDate=this.exDates[this.exDateInc]),typeof e.complete!="undefined"&&(this.complete=e.complete)}}_compare_special(e,t){return!e.isDate&&t.isDate?new Me({year:e.year,month:e.month,day:e.day}).compare(t):e.compare(t)}next(){let e,t,r,a=500,i=0;for(;;){if(i++>a)throw new Error("max tries have occurred, rule may be impossible to fulfill.");if(t=this.ruleDate,e=this._nextRecurrenceIter(this.last),!t&&!e){this.complete=!0;break}if((!t||e&&t.compare(e.last)>0)&&(t=e.last.clone(),e.next()),this.ruleDate===t&&this._nextRuleDay(),this.last=t,this.exDate&&(r=this._compare_special(this.last,this.exDate),r>0&&this._nextExDay(),r===0)){this._nextExDay();continue}return this.last}}toJSON(){function e(r){return r.toJSON()}let t=Object.create(null);return t.ruleIterators=this.ruleIterators.map(e),this.ruleDates&&(t.ruleDates=this.ruleDates.map(e)),this.exDates&&(t.exDates=this.exDates.map(e)),t.ruleDateInc=this.ruleDateInc,t.exDateInc=this.exDateInc,t.last=this.last.toJSON(),t.dtstart=this.dtstart.toJSON(),t.complete=this.complete,t}_extractDates(e,t){let r=[],a=e.getAllProperties(t);for(let i=0,s=a.length;ic.compare(d));r.splice(l,0,o)}return r}_init(e){if(this.ruleIterators=[],this.last=this.dtstart.clone(),!e.hasProperty("rdate")&&!e.hasProperty("rrule")&&!e.hasProperty("recurrence-id")){this.ruleDate=this.last.clone(),this.complete=!0;return}if(e.hasProperty("rdate")&&(this.ruleDates=this._extractDates(e,"rdate"),this.ruleDates[0]&&this.ruleDates[0].compare(this.dtstart)<0?(this.ruleDateInc=0,this.last=this.ruleDates[0].clone()):this.ruleDateInc=Rh(this.ruleDates,this.last,(t,r)=>t.compare(r)),this.ruleDate=this.ruleDates[this.ruleDateInc]),e.hasProperty("rrule")){let t=e.getAllProperties("rrule"),r=0,a=t.length,i,s;for(;r0)&&(s=r)}return s}},dE=class dE{constructor(e,t){z(this,"exceptions",null);z(this,"strictExceptions",!1);e instanceof So||(t=e,e=null),e?this.component=e:this.component=new So("vevent"),this._rangeExceptionCache=Object.create(null),this.exceptions=Object.create(null),this.rangeExceptions=[],t&&t.strictExceptions&&(this.strictExceptions=t.strictExceptions),t&&t.exceptions?t.exceptions.forEach(this.relateException,this):this.component.parent&&!this.isRecurrenceException()&&this.component.parent.getAllSubcomponents("vevent").forEach(function(r){r.hasProperty("recurrence-id")&&this.relateException(r)},this)}relateException(e){if(this.isRecurrenceException())throw new Error("cannot relate exception to exceptions");if(e instanceof So&&(e=new dE(e)),this.strictExceptions&&e.uid!==this.uid)throw new Error("attempted to relate unrelated exception");let t=e.recurrenceId.toString();if(this.exceptions[t]=e,e.modifiesFuture()){let r=[e.recurrenceId.toUnixTime(),t],a=Rh(this.rangeExceptions,r,NTe);this.rangeExceptions.splice(a,0,r)}}modifiesFuture(){return this.component.hasProperty("recurrence-id")?this.component.getFirstProperty("recurrence-id").getParameter("range")===dE.THISANDFUTURE:!1}findRangeException(e){if(!this.rangeExceptions.length)return null;let t=e.toUnixTime(),r=Rh(this.rangeExceptions,[t],NTe);if(r-=1,r<0)return null;let a=this.rangeExceptions[r];return t@]+@[^\s<>@]+\.[^\s<>@]+$/.test(e)?e:void 0}function zTe(n){return OTe(n.getFirstPropertyValue("x-wr-calname"))}function JW(n,e){if(!e)return;let t=n.getAllProperties("attendee").find(a=>OTe(a.getFirstValue())===e);if(!t)return;let r=t.getParameter("partstat");return typeof r=="string"&&r.toUpperCase()==="DECLINED"}var BTe=y(()=>{});function jTe(n){let e=XW.get(n);if(e!==void 0)return e;try{return new Intl.DateTimeFormat("en-US",{timeZone:n}),XW.set(n,!0),!0}catch(t){return XW.set(n,!1),!1}}function eq(n){if(!n)return null;let e=n.trim();if(!e)return null;let t=e.replace(/^\([^)]+\)\s*/u,"").trim();if(jTe(t))return t;let r=C5e[t];return r&&jTe(r)?r:null}function x5e(n){let e=$Te.get(n);return e||(e=new Intl.DateTimeFormat("en-US",{timeZone:n,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}),$Te.set(n,e)),e}function E5e(n,e){let t=x5e(e).formatToParts(new Date(n)),r={};for(let i of t)r[i.type]=i.value;let a=parseInt(r.hour,10)%24;return{year:parseInt(r.year,10),month:parseInt(r.month,10),day:parseInt(r.day,10),hour:a,minute:parseInt(r.minute,10),second:parseInt(r.second,10)}}function tq(n,e){let t={year:n.year,month:n.month,day:n.day,hour:n.hour,minute:n.minute,second:n.second},r=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second);for(let a=0;a<3;a++){let i=E5e(r,e),s=Date.UTC(i.year,i.month-1,i.day,i.hour,i.minute,i.second),o=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second),l=s-o;if(l===0)break;r-=l}return new Date(r).toISOString()}var C5e,XW,$Te,UTe=y(()=>{C5e=Object.freeze({"AUS Central Standard Time":"Australia/Darwin","AUS Eastern Standard Time":"Australia/Sydney","Afghanistan Standard Time":"Asia/Kabul","Alaskan Standard Time":"America/Anchorage","Aleutian Standard Time":"America/Adak","Altai Standard Time":"Asia/Barnaul","Arab Standard Time":"Asia/Riyadh","Arabian Standard Time":"Asia/Dubai","Arabic Standard Time":"Asia/Baghdad","Argentina Standard Time":"America/Buenos_Aires","Astrakhan Standard Time":"Europe/Astrakhan","Atlantic Standard Time":"America/Halifax","Aus Central W. Standard Time":"Australia/Eucla","Azerbaijan Standard Time":"Asia/Baku","Azores Standard Time":"Atlantic/Azores","Bahia Standard Time":"America/Bahia","Bangladesh Standard Time":"Asia/Dhaka","Belarus Standard Time":"Europe/Minsk","Bougainville Standard Time":"Pacific/Bougainville","Canada Central Standard Time":"America/Regina","Cape Verde Standard Time":"Atlantic/Cape_Verde","Caucasus Standard Time":"Asia/Yerevan","Cen. Australia Standard Time":"Australia/Adelaide","Central America Standard Time":"America/Guatemala","Central Asia Standard Time":"Asia/Almaty","Central Brazilian Standard Time":"America/Cuiaba","Central Europe Standard Time":"Europe/Budapest","Central European Standard Time":"Europe/Warsaw","Central Pacific Standard Time":"Pacific/Guadalcanal","Central Standard Time":"America/Chicago","Central Standard Time (Mexico)":"America/Mexico_City","Chatham Islands Standard Time":"Pacific/Chatham","China Standard Time":"Asia/Shanghai","Cuba Standard Time":"America/Havana","Dateline Standard Time":"Etc/GMT+12","E. Africa Standard Time":"Africa/Nairobi","E. Australia Standard Time":"Australia/Brisbane","E. Europe Standard Time":"Europe/Chisinau","E. South America Standard Time":"America/Sao_Paulo","Easter Island Standard Time":"Pacific/Easter","Eastern Standard Time":"America/New_York","Eastern Standard Time (Mexico)":"America/Cancun","Egypt Standard Time":"Africa/Cairo","Ekaterinburg Standard Time":"Asia/Yekaterinburg","FLE Standard Time":"Europe/Kiev","Fiji Standard Time":"Pacific/Fiji","GMT Standard Time":"Europe/London","GTB Standard Time":"Europe/Bucharest","Georgian Standard Time":"Asia/Tbilisi","Greenland Standard Time":"America/Godthab","Greenwich Standard Time":"Atlantic/Reykjavik","Haiti Standard Time":"America/Port-au-Prince","Hawaiian Standard Time":"Pacific/Honolulu","India Standard Time":"Asia/Kolkata","Iran Standard Time":"Asia/Tehran","Israel Standard Time":"Asia/Jerusalem","Jordan Standard Time":"Asia/Amman","Kaliningrad Standard Time":"Europe/Kaliningrad","Korea Standard Time":"Asia/Seoul","Libya Standard Time":"Africa/Tripoli","Line Islands Standard Time":"Pacific/Kiritimati","Lord Howe Standard Time":"Australia/Lord_Howe","Magadan Standard Time":"Asia/Magadan","Magallanes Standard Time":"America/Punta_Arenas","Marquesas Standard Time":"Pacific/Marquesas","Mauritius Standard Time":"Indian/Mauritius","Middle East Standard Time":"Asia/Beirut","Montevideo Standard Time":"America/Montevideo","Morocco Standard Time":"Africa/Casablanca","Mountain Standard Time":"America/Denver","Mountain Standard Time (Mexico)":"America/Chihuahua","Myanmar Standard Time":"Asia/Yangon","N. Central Asia Standard Time":"Asia/Novosibirsk","Namibia Standard Time":"Africa/Windhoek","Nepal Standard Time":"Asia/Katmandu","New Zealand Standard Time":"Pacific/Auckland","Newfoundland Standard Time":"America/St_Johns","Norfolk Standard Time":"Pacific/Norfolk","North Asia East Standard Time":"Asia/Irkutsk","North Asia Standard Time":"Asia/Krasnoyarsk","North Korea Standard Time":"Asia/Pyongyang","Omsk Standard Time":"Asia/Omsk","Pacific SA Standard Time":"America/Santiago","Pacific Standard Time":"America/Los_Angeles","Pacific Standard Time (Mexico)":"America/Tijuana","Pakistan Standard Time":"Asia/Karachi","Paraguay Standard Time":"America/Asuncion","Qyzylorda Standard Time":"Asia/Qyzylorda","Romance Standard Time":"Europe/Paris","Russia Time Zone 10":"Asia/Srednekolymsk","Russia Time Zone 11":"Asia/Kamchatka","Russia Time Zone 3":"Europe/Samara","Russian Standard Time":"Europe/Moscow","SA Eastern Standard Time":"America/Cayenne","SA Pacific Standard Time":"America/Bogota","SA Western Standard Time":"America/La_Paz","SE Asia Standard Time":"Asia/Bangkok","Saint Pierre Standard Time":"America/Miquelon","Sakhalin Standard Time":"Asia/Sakhalin","Samoa Standard Time":"Pacific/Apia","Sao Tome Standard Time":"Africa/Sao_Tome","Saratov Standard Time":"Europe/Saratov","Singapore Standard Time":"Asia/Singapore","South Africa Standard Time":"Africa/Johannesburg","South Sudan Standard Time":"Africa/Juba","Sri Lanka Standard Time":"Asia/Colombo","Sudan Standard Time":"Africa/Khartoum","Syria Standard Time":"Asia/Damascus","Taipei Standard Time":"Asia/Taipei","Tasmania Standard Time":"Australia/Hobart","Tocantins Standard Time":"America/Araguaina","Tokyo Standard Time":"Asia/Tokyo","Tomsk Standard Time":"Asia/Tomsk","Tonga Standard Time":"Pacific/Tongatapu","Transbaikal Standard Time":"Asia/Chita","Turkey Standard Time":"Europe/Istanbul","Turks And Caicos Standard Time":"America/Grand_Turk","US Eastern Standard Time":"America/Indianapolis","US Mountain Standard Time":"America/Phoenix",UTC:"Etc/UTC","UTC+12":"Etc/GMT-12","UTC+13":"Etc/GMT-13","UTC-02":"Etc/GMT+2","UTC-08":"Etc/GMT+8","UTC-09":"Etc/GMT+9","UTC-11":"Etc/GMT+11","Ulaanbaatar Standard Time":"Asia/Ulaanbaatar","Venezuela Standard Time":"America/Caracas","Vladivostok Standard Time":"Asia/Vladivostok","Volgograd Standard Time":"Europe/Volgograd","W. Australia Standard Time":"Australia/Perth","W. Central Africa Standard Time":"Africa/Lagos","W. Europe Standard Time":"Europe/Berlin","W. Mongolia Standard Time":"Asia/Hovd","West Asia Standard Time":"Asia/Tashkent","West Bank Standard Time":"Asia/Hebron","West Pacific Standard Time":"Pacific/Port_Moresby","Yakutsk Standard Time":"Asia/Yakutsk"}),XW=new Map;$Te=new Map});function VTe(n){let e=n.getFirstPropertyValue("tzid");return typeof e=="string"?e.trim():null}function I5e(n){let e=n.replace(/\s+\([^)]+\)$/u,"").trim();return e&&e!==n?[e]:[]}function N5e(n,e){var t;return(t=n.getAllSubcomponents("vtimezone").find(r=>VTe(r)===e))!=null?t:null}function R5e(n,e){let t=new Yi.Component(JSON.parse(JSON.stringify(n.toJSON())));return t.updatePropertyWithValue("tzid",e),t}function _5e(n){n.getAllSubcomponents("vtimezone").forEach(t=>{let r=VTe(t);Yi.TimezoneService.register(t),r&&I5e(r).forEach(a=>{let i=N5e(n,a),s=i!=null?i:R5e(t,a),o=new Yi.Timezone({component:s,tzid:a});i||n.addSubcomponent(s),Yi.TimezoneService.register(o)})})}function rq(n){if(!M5e.test(n))return null;let[e,t,r]=n.split("-").map(Number);return Date.UTC(e,t-1,r)}function F5e(n){let e=n.getUTCFullYear().toString().padStart(4,"0"),t=(n.getUTCMonth()+1).toString().padStart(2,"0"),r=n.getUTCDate().toString().padStart(2,"0");return`${e}-${t}-${r}`}function L5e(n,e){let t=rq(n),r=rq(e);return t===null||r===null||r<=t?null:Math.round((r-t)/HTe)}function O5e(n,e){let t=rq(n);return t===null?n:F5e(new Date(t+e*HTe))}var ZR,hE,D5e,P5e,A5e,M5e,HTe,KR,WTe=y(()=>{ZR=require("obsidian");LTe();BTe();px();q();Oi();UTe();hE=M({tag:"Services/ICSSubscriptionService"}),D5e=365*24*60*60*1e3,P5e=3e3,A5e=1e4,M5e=/^\d{4}-\d{2}-\d{2}$/u,HTe=1440*60*1e3;KR=class extends fc{constructor(t){super();this.subscriptions=[];this.cache=new Map;this.refreshTimers=new Map;this.fileWatchers=new Map;this.pendingRefreshes=new Set;this.lastFetched=new Map;this.lastError=new Map;this.destroyed=!1;this.CACHE_GRACE_PERIOD=300*1e3;this.plugin=t}translate(t,r){return this.plugin.i18n.translate(t,r)}icalTimeToISOString(t,r){var s;if(t.isDate){let o=t.year.toString().padStart(4,"0"),l=t.month.toString().padStart(2,"0"),c=t.day.toString().padStart(2,"0");return`${o}-${l}-${c}`}let a=(s=t.zone)==null?void 0:s.tzid;if(a==="floating"||a===void 0){let o=eq(r);if(o)return tq(t,o);if(!(typeof r=="string"&&r.trim().length>0)){let c=this.getLocalTimeZoneForFloatingTime();if(c)return tq(t,c)}}let i=t.toUnixTime();return new Date(i*1e3).toISOString()}getLocalTimeZoneForFloatingTime(){try{return eq(Intl.DateTimeFormat().resolvedOptions().timeZone)}catch(t){return null}}rawTzidOf(t,r){let a=t.getFirstProperty(r);if(!a)return null;let i=a.getParameter("tzid");return typeof i=="string"?i:null}getRecurringInstanceEnd(t,r,a,i){if(!a)return;if(i){let o=L5e(r,a);return o===null?a:O5e(t,o)}let s=new Date(a).getTime()-new Date(r).getTime();return new Date(new Date(t).getTime()+s).toISOString()}async initialize(){this.destroyed=!1,await this.loadSubscriptions();let t=[];this.subscriptions.forEach(r=>{if(r.enabled){r.type==="remote"?this.startRefreshTimer(r):r.type==="local"&&this.startFileWatcher(r);let a=this.cache.get(r.id);(!a||new Date(a.expires)<=new Date)&&t.push(this.fetchSubscription(r.id))}}),await Promise.allSettled(t),this.emit("data-changed")}async loadSubscriptions(){try{let t=await this.plugin.loadData();this.subscriptions=(t==null?void 0:t.icsSubscriptions)||[]}catch(t){hE.error("Failed to load ICS subscriptions:",{category:"provider",operation:"load-ics-subscriptions",error:t}),this.subscriptions=[]}}async saveSubscriptions(){try{let t=await this.plugin.loadPluginDataForSafeWrite("save-ics-subscriptions");if(!t)return;t.icsSubscriptions=this.subscriptions,await this.plugin.saveData(t)}catch(t){throw hE.error("Failed to save ICS subscriptions:",{category:"provider",operation:"save-ics-subscriptions",error:t}),t}}getSubscriptions(){return[...this.subscriptions]}getLastFetched(t){return this.lastFetched.get(t)}getLastError(t){return this.lastError.get(t)}async addSubscription(t){let r={...t,filePath:t.type==="local"&&t.filePath?this.normalizeLocalICSFilePathIfPossible(t.filePath):t.filePath,id:this.generateId()};return this.subscriptions.push(r),await this.saveSubscriptions(),r.enabled&&(r.type==="remote"?(this.startRefreshTimer(r),await this.fetchSubscription(r.id)):r.type==="local"&&(this.startFileWatcher(r),await this.fetchSubscription(r.id))),this.emit("data-changed"),r}async updateSubscription(t,r){let a=this.subscriptions.findIndex(l=>l.id===t);if(a===-1)throw new Error("Subscription not found");let i=this.subscriptions[a],s={...r};typeof r.filePath=="string"&&(s.filePath=this.normalizeLocalICSFilePathIfPossible(r.filePath));let o={...i,...s};this.subscriptions[a]=o,await this.saveSubscriptions(),this.stopRefreshTimer(t),this.stopFileWatcher(t),o.enabled&&(o.type==="remote"?this.startRefreshTimer(o):o.type==="local"&&this.startFileWatcher(o)),(r.url&&r.url!==i.url||r.filePath&&r.filePath!==i.filePath)&&this.cache.delete(t),this.emit("data-changed")}async removeSubscription(t){let r=this.subscriptions.findIndex(a=>a.id===t);if(r===-1)throw new Error("Subscription not found");this.subscriptions.splice(r,1),await this.saveSubscriptions(),this.stopRefreshTimer(t),this.stopFileWatcher(t),this.cache.delete(t),this.lastFetched.delete(t),this.lastError.delete(t),this.emit("data-changed")}async fetchSubscription(t){let r=this.subscriptions.find(a=>a.id===t);if(!(!r||!r.enabled))try{let a;if(r.type==="remote"){if(!r.url)throw new Error("Remote subscription missing URL");a=(await(0,ZR.requestUrl)({url:r.url,method:"GET",headers:{Accept:"text/calendar,*/*;q=0.1","Accept-Language":"en-US,en;q=0.9","User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}})).text}else if(r.type==="local"){if(!r.filePath)throw new Error("Local subscription missing file path");let o=this.normalizeLocalICSFilePath(r.filePath);a=await this.readLocalICSFile(o),r.filePath!==o&&(r.filePath=o,await this.saveSubscriptions())}else throw new Error("Unknown subscription type");let i=this.parseICS(a,r.id),s={subscriptionId:t,events:i,lastUpdated:new Date().toISOString(),expires:new Date(Date.now()+r.refreshInterval*60*1e3).toISOString()};this.cache.set(t,s),this.lastFetched.set(t,new Date().toISOString()),this.lastError.delete(t),this.emit("data-changed")}catch(a){let i=a instanceof Error?a.message:String(a);this.lastError.set(t,i),r.type==="remote"?i.includes("404")?ve(this.plugin.emitter,this.translate("services.icsSubscription.notices.calendarNotFound",{name:r.name})):i.includes("500")||i.includes("OwaBasicUnsupportedException")?ve(this.plugin.emitter,this.translate("services.icsSubscription.notices.calendarAccessDenied",{name:r.name})):ve(this.plugin.emitter,this.translate("services.icsSubscription.notices.fetchRemoteFailed",{name:r.name,error:i})):ve(this.plugin.emitter,this.translate("services.icsSubscription.notices.readLocalFailed",{name:r.name,error:i}))}}parseICS(t,r){try{let a=Yi.parse(t),i=new Yi.Component(a);_5e(i);let s=zTe(i),o=i.getAllSubcomponents("vevent"),l=[],c=new Map;return o.forEach(d=>{let u=new Yi.Event(d),p=u.uid;if(!p)return;let m=d.getFirstPropertyValue("recurrence-id");if(m instanceof Yi.Time){c.has(p)||c.set(p,new Map);let f=m.toString();c.get(p).set(f,u)}}),o.forEach(d=>{var u,p;try{let m=new Yi.Event(d);if(d.getFirstPropertyValue("recurrence-id"))return;let h=d.getFirstPropertyValue("status");if(typeof h=="string"&&h.toUpperCase()==="CANCELLED")return;let g=(u=JW(d,s))!=null?u:!1;if(g&&!m.isRecurring())return;let v=m.summary||"Untitled Event",k=m.description||void 0,T=m.location||void 0,b=m.startDate,w=m.endDate;if(!b)return;let S=this.rawTzidOf(d,"dtstart"),C=this.rawTzidOf(d,"dtend"),x=b.isDate,E=this.icalTimeToISOString(b,S),_=w?this.icalTimeToISOString(w,C!=null?C:S):void 0,F=m.uid||`${r}-${l.length}`,I=`${r}-${F}`,A={id:I,subscriptionId:r,title:v,description:k,start:E,end:_,allDay:x,location:T,url:m.url||void 0};if(m.isRecurring()){let R=new Set;d.getAllProperties("exdate").forEach(Q=>{let Z=Q.getFirstValue();Z&&(Array.isArray(Z)?Z:[Z]).forEach(le=>{le&&typeof le.toString=="function"&&R.add(le.toString())})});let U=c.get(F)||new Map,pe=m.iterator(b),oe=new Yi.Time;oe.fromJSDate(new Date(Date.now()+D5e));let X,de=0,Oe=0;for(;(X=pe.next())&&de0));){let Q=X.toString();if(R.has(Q))continue;let Z=`${I}-${Oe}`,Ue=U.get(Q);if(Ue){let le=Ue.component.getFirstPropertyValue("status");if(typeof le=="string"&&le.toUpperCase()==="CANCELLED"||((p=JW(Ue.component,s))!=null?p:g))continue;let at=Ue.startDate,He=Ue.endDate,qr=Ue.component,jn=qr?this.rawTzidOf(qr,"dtstart"):null,Dr=qr?this.rawTzidOf(qr,"dtend"):null;at&&(l.push({id:Z,subscriptionId:r,title:Ue.summary||v,description:Ue.description||k,start:this.icalTimeToISOString(at,jn),end:He?this.icalTimeToISOString(He,Dr!=null?Dr:jn):void 0,allDay:at.isDate,location:Ue.location||T,url:Ue.url||A.url,recurringEventId:I}),Oe++)}else{if(g)continue;let le=this.icalTimeToISOString(X,S),at=this.getRecurringInstanceEnd(le,E,_,x);l.push({...A,id:Z,start:le,end:at,recurringEventId:I}),Oe++}}}else l.push(A)}catch(m){hE.warn("Failed to parse individual event:",{category:"provider",operation:"parse-individual-event",error:m})}}),l}catch(a){throw hE.error("Failed to parse ICS data:",{category:"provider",operation:"parse-ics-data",error:a}),new Error("Invalid ICS format")}}getAllEvents(){let t=[],r=new Date;return this.subscriptions.forEach(a=>{if(!a.enabled)return;let i=this.cache.get(a.id);if(!i){this.pendingRefreshes.has(a.id)||(this.pendingRefreshes.add(a.id),this.fetchSubscription(a.id).finally(()=>this.pendingRefreshes.delete(a.id)));return}let s=new Date(i.expires),o=new Date(s.getTime()+this.CACHE_GRACE_PERIOD);rs&&!this.pendingRefreshes.has(a.id)&&(this.pendingRefreshes.add(a.id),this.fetchSubscription(a.id).finally(()=>this.pendingRefreshes.delete(a.id)))):this.pendingRefreshes.has(a.id)||(this.pendingRefreshes.add(a.id),this.fetchSubscription(a.id).finally(()=>this.pendingRefreshes.delete(a.id)))}),t}getEventsForSubscription(t){let r=this.cache.get(t);if(!r){let l=this.subscriptions.find(c=>c.id===t);return l&&l.enabled&&!this.pendingRefreshes.has(t)&&(this.pendingRefreshes.add(t),this.fetchSubscription(t).finally(()=>this.pendingRefreshes.delete(t))),[]}let a=new Date,i=new Date(r.expires),s=new Date(i.getTime()+this.CACHE_GRACE_PERIOD);return a>=s?(this.pendingRefreshes.has(t)||(this.pendingRefreshes.add(t),this.fetchSubscription(t).finally(()=>this.pendingRefreshes.delete(t))),[]):(a>i&&!this.pendingRefreshes.has(t)&&(this.pendingRefreshes.add(t),this.fetchSubscription(t).finally(()=>this.pendingRefreshes.delete(t))),[...r.events])}async refreshAllSubscriptions(){let t=this.subscriptions.filter(r=>r.enabled);for(let r of t)await this.fetchSubscription(r.id)}getVaultBasePath(){let t=this.plugin.app.vault.adapter;if(typeof(t==null?void 0:t.getBasePath)=="function")try{let r=t.getBasePath();return typeof r=="string"&&r.trim()?r:void 0}catch(r){hE.warn("Failed to resolve vault base path for local ICS file:",{category:"provider",operation:"resolve-vault-base-path-local-ics-file",error:r});return}}normalizePathSeparators(t){return t.trim().replace(/\\/g,"/").replace(/^\.\/+/u,"")}isAbsoluteFilePath(t){return t.startsWith("/")||/^[A-Za-z]:\//u.test(t)}normalizeLocalICSFilePath(t){let r=this.normalizePathSeparators(t);if(!this.isAbsoluteFilePath(r))return r;let a=this.getVaultBasePath();if(a){let i=this.normalizePathSeparators(a).replace(/\/+$/u,"");if(r.startsWith(`${i}/`))return r.slice(i.length+1)}throw new Error('Local ICS files must be inside the current Obsidian vault. Move the file into the vault or use a vault-relative path such as "Calendar.ics".')}normalizeLocalICSFilePathIfPossible(t){try{return this.normalizeLocalICSFilePath(t)}catch(r){return this.normalizePathSeparators(t)}}async readLocalICSFile(t){try{let r=this.normalizeLocalICSFilePath(t),a=this.plugin.app.vault.getAbstractFileByPath(r);if(!a||!(a instanceof ZR.TFile))throw new Error(`File not found: ${r}`);if(a.extension!=="ics")throw new Error(`File is not an ICS file: ${r}`);return await this.plugin.app.vault.cachedRead(a)}catch(r){throw new Error(`Failed to read local ICS file "${t}": ${r instanceof Error?r.message:String(r)}`)}}startFileWatcher(t){if(!t.filePath)return;this.stopFileWatcher(t.id);let r=this.normalizeLocalICSFilePathIfPossible(t.filePath),a=(l,c)=>{(l.path===r||c===r)&&window.setTimeout(()=>{this.fetchSubscription(t.id)},1e3)},i=this.plugin.app.vault.on("modify",a),s=this.plugin.app.vault.on("rename",a),o=this.plugin.app.vault.on("delete",l=>{l.path===r&&this.lastError.set(t.id,"Local ICS file was deleted")});this.fileWatchers.set(t.id,()=>{this.plugin.app.vault.offref(i),this.plugin.app.vault.offref(s),this.plugin.app.vault.offref(o)}),this.startFileRefreshTimer(t)}stopFileWatcher(t){let r=this.fileWatchers.get(t);r&&(r(),this.fileWatchers.delete(t))}async refreshSubscription(t){await this.fetchSubscription(t)}startRefreshTimer(t){this.stopRefreshTimer(t.id),this.startRemoteRefreshTimer(t)}startFileRefreshTimer(t){let r=t.refreshInterval*60*1e3,a=window.setTimeout(()=>{this.refreshTimers.delete(t.id),this.fetchSubscription(t.id).finally(()=>{this.shouldContinueRefresh(t.id)&&this.startFileRefreshTimer(t)})},r);this.refreshTimers.set(t.id,a)}startRemoteRefreshTimer(t){let r=t.refreshInterval*60*1e3,a=window.setTimeout(()=>{this.refreshTimers.delete(t.id),this.fetchSubscription(t.id).finally(()=>{this.shouldContinueRefresh(t.id)&&this.startRemoteRefreshTimer(t)})},r);this.refreshTimers.set(t.id,a)}shouldContinueRefresh(t){return!this.destroyed&&this.subscriptions.some(r=>r.id===t&&r.enabled)}stopRefreshTimer(t){let r=this.refreshTimers.get(t);r&&(window.clearTimeout(r),this.refreshTimers.delete(t))}generateId(){return"ics_"+Math.random().toString(36).substring(2,11)+Date.now().toString(36)}destroy(){this.destroyed=!0,this.refreshTimers.forEach(t=>window.clearTimeout(t)),this.refreshTimers.clear(),this.fileWatchers.forEach(t=>t()),this.fileWatchers.clear(),this.cache.clear(),this.pendingRefreshes.clear(),this.removeAllListeners()}getLocalICSFiles(){return this.plugin.app.vault.getFiles().filter(t=>t.extension==="ics").sort((t,r)=>t.path.localeCompare(r.path))}}});function rm(n,e){return n.find(t=>t.id===e||e===nq&&t.primary===!0)}var z5e,nq,Ok,QR,nm=y(()=>{px();q();z5e=M({tag:"Services/CalendarProvider"}),nq="primary";Ok=class extends fc{ownsEvent(e){var t,r;return(r=(t=e.subscriptionId)==null?void 0:t.startsWith(`${this.providerId}-`))!=null?r:!1}extractEventIds(e){let t=e.subscriptionId.replace(`${this.providerId}-`,""),r=e.id.replace(`${this.providerId}-${t}-`,"");return{calendarId:t,eventId:r}}},QR=class{constructor(){this.providers=new Map}register(e){this.providers.set(e.providerId,e)}unregister(e){this.providers.delete(e)}getProvider(e){return this.providers.get(e)}getAllProviders(){return Array.from(this.providers.values())}findProviderForEvent(e){for(let t of this.providers.values())if(t.ownsEvent(e))return t}getAllEvents(){let e=[];for(let t of this.providers.values())e.push(...t.getAllEvents());return e}async refreshAll(){let e=Array.from(this.providers.values()).map(t=>t.refresh().catch(r=>{z5e.error(`Failed to refresh ${t.providerName}:`,{category:"provider",operation:"refresh",error:r})}));await Promise.all(e)}destroyAll(){for(let e of this.providers.values())e.destroy();this.providers.clear()}}});var gE,Nc,JR,qTe=y(()=>{gE=require("obsidian");Cr();kH();xe();kv();yt();JI();q();Oi();ya();nm();Nc=M({tag:"Services/ICSNoteService"}),JR=class{constructor(e){this.plugin=e}translate(e,t){return this.plugin.i18n.translate(e,t)}findEventById(e){var s,o,l,c,d,u,p,m,f,h;let t=e.trim();if(!t)return null;let r=(s=this.plugin.icsSubscriptionService)==null?void 0:s.getAllEvents().find(g=>g.id===t);if(r){let g=(l=(o=this.plugin.icsSubscriptionService)==null?void 0:o.getSubscriptions().find(v=>v.id===r.subscriptionId))==null?void 0:l.name;return{event:r,subscriptionName:g}}let a=(c=this.plugin.googleCalendarService)==null?void 0:c.getAllEvents().find(g=>g.id===t);if(a){let g=a.subscriptionId.replace("google-",""),v=(u=(d=this.plugin.googleCalendarService)==null?void 0:d.getAvailableCalendars())!=null?u:[],k=((p=rm(v,g))==null?void 0:p.summary)||"Google Calendar";return{event:a,subscriptionName:k}}let i=(m=this.plugin.microsoftCalendarService)==null?void 0:m.getAllEvents().find(g=>g.id===t);if(i){let g=i.subscriptionId.replace("microsoft-",""),v=((h=(f=this.plugin.microsoftCalendarService)==null?void 0:f.getAvailableCalendars().find(k=>k.id===g))==null?void 0:h.summary)||"Microsoft Calendar";return{event:i,subscriptionName:v}}return null}getLoadedCalendarEvents(){var e,t,r,a,i,s;return[...(t=(e=this.plugin.icsSubscriptionService)==null?void 0:e.getAllEvents())!=null?t:[],...(a=(r=this.plugin.googleCalendarService)==null?void 0:r.getAllEvents())!=null?a:[],...(s=(i=this.plugin.microsoftCalendarService)==null?void 0:i.getAllEvents())!=null?s:[]]}getExplicitSeriesId(e){var r;return((r=e.recurringEventId)==null?void 0:r.trim())||null}getRecurringRelatedNotesMode(){var e,t;return((t=(e=this.plugin.settings)==null?void 0:e.icsIntegration)==null?void 0:t.recurringEventRelatedNotesMode)==="instance"?"instance":"series"}buildEventSeriesIndex(){let e=new Map;for(let a of this.getLoadedCalendarEvents()){let i=this.getExplicitSeriesId(a);if(!i)continue;let s=e.get(i);s||(s=new Set,e.set(i,s)),s.add(a.id)}let t=new Map,r=new Map;for(let[a,i]of e){r.set(a,i);for(let s of i)t.set(s,a)}return{seriesIdByEventId:t,eventIdsBySeriesId:r}}getRelatedEventIds(e,t){var s;let r=new Set([e]);if(this.getRecurringRelatedNotesMode()==="instance")return r;let a=t.seriesIdByEventId.get(e),i=t.eventIdsBySeriesId.has(e)?e:a;if(i){r.add(i);for(let o of(s=t.eventIdsBySeriesId.get(i))!=null?s:[])r.add(o)}return r}eventIdsMatchSeries(e,t,r){for(let a of this.getRelatedEventIds(e,r))if(t.has(a))return!0;return!1}async getRelatedNoteCountsByEventId(){let e=new Map,t=this.plugin.fieldMapper.toUserField("icsEventId"),r=this.buildEventSeriesIndex(),a=(i,s)=>{for(let o of this.normalizeEventIds(i))for(let l of this.getRelatedEventIds(o,r)){let c=e.get(l);c||(c=new Set,e.set(l,c)),c.add(s)}};try{let i=await this.plugin.cacheManager.getAllTasks();for(let o of i)a(o.icsEventId,o.path);let s=this.plugin.app.vault.getMarkdownFiles();for(let o of s){let l=this.plugin.app.metadataCache.getFileCache(o),c=l==null?void 0:l.frontmatter;c&&a(c[t],o.path)}}catch(i){return Nc.error("Error counting related notes for ICS events:",{category:"provider",operation:"counting-related-notes-ics-events",error:i}),new Map}return new Map(Array.from(e.entries()).map(([i,s])=>[i,s.size]))}normalizeEventIds(e){return(Array.isArray(e)?e:e?[e]:[]).filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean)}async createTaskFromICS(e,t){var r;try{let a=this.plugin.icsSubscriptionService.getSubscriptions().find(l=>l.id===e.subscriptionId),i=(a==null?void 0:a.name)||"Unknown Calendar",s=(t==null?void 0:t.scheduled)!==void 0?t.scheduled:this.computeScheduledFromICSEvent(e),o={title:(t==null?void 0:t.title)||e.title,status:(t==null?void 0:t.status)||this.plugin.settings.defaultTaskStatus,priority:(t==null?void 0:t.priority)||this.plugin.settings.defaultTaskPriority,due:(t==null?void 0:t.due)!==void 0?t.due:(r=this.plugin.settings.icsIntegration)!=null&&r.useICSEndAsDue?this.computeDueFromICSEnd(e):void 0,scheduled:s,contexts:(t==null?void 0:t.contexts)||(e.location?[e.location]:void 0),projects:t==null?void 0:t.projects,tags:(t==null?void 0:t.tags)||[this.plugin.fieldMapper.toUserField("icsEventTag")],timeEstimate:(t==null?void 0:t.timeEstimate)||this.calculateEventDuration(e),details:(t==null?void 0:t.details)||this.buildICSEventDetails(e,i),icsEventId:[e.id],creationContext:"ics-event",dateCreated:qe(),dateModified:qe(),...Object.fromEntries(Object.entries(t||{}).filter(([l])=>l!=="due"))};return await this.plugin.taskService.createTask(o,{applyDefaults:!1})}catch(a){let i=a instanceof Error?a.message:String(a);throw Nc.error("Error creating task from ICS event:",{category:"provider",operation:"creating-task-ics-event",details:{icsEventId:e.id,icsEventTitle:e.title},error:i}),new Error(`Failed to create task from ICS event: ${i}`)}}computeScheduledFromICSEvent(e){try{if(!e.start)return;let t=e.allDay&&/^\d{4}-\d{2}-\d{2}$/.test(e.start)?e.start+"T00:00:00":e.start,r=new Date(t);return e.allDay?ae(r):D(r,"yyyy-MM-dd'T'HH:mm")}catch(t){return Nc.warn("Failed to compute scheduled from ICS event start:",{category:"provider",operation:"compute-scheduled-ics-event-start",details:{start:e.start},error:t}),e.start}}computeDueFromICSEnd(e){try{if(!e.end)return;if(e.allDay){if(!e.start)return;let a=/^\d{4}-\d{2}-\d{2}$/.test(e.start)?e.start+"T00:00:00":e.start,i=new Date(a);return ae(i)}let t=/^\d{4}-\d{2}-\d{2}$/.test(e.end)?e.end+"T00:00:00":e.end,r=new Date(t);return D(r,"yyyy-MM-dd'T'HH:mm")}catch(t){Nc.warn("Failed to compute due from ICS event end:",{category:"provider",operation:"compute-due-ics-event-end",details:{end:e.end},error:t});return}}async createNoteFromICS(e,t){var r;try{let a=this.plugin.icsSubscriptionService.getSubscriptions().find(_=>_.id===e.subscriptionId),i=(a==null?void 0:a.name)||"Unknown Calendar",s=e.allDay&&/^\d{4}-\d{2}-\d{2}$/.test(e.start)?e.start+"T00:00:00":e.start,o=new Date(s),l=(t==null?void 0:t.title)||`${e.title} - ${D(o,"PPP")}`,c=(t==null?void 0:t.folder)||((r=this.plugin.settings.icsIntegration)==null?void 0:r.defaultNoteFolder)||"",d=eN(c,{date:o,icsData:{title:e.title,location:e.location,description:e.description}}),u={title:e.title,priority:"",status:"",date:o,dueDate:e.end,scheduledDate:e.start,icsEventTitle:e.title,icsEventLocation:e.location,icsEventDescription:e.description},p=fue(u,this.plugin.settings),m=await vv(p,d,this.plugin.app.vault),f=d?`${d}/${m}.md`:`${m}.md`;d&&await qu(this.plugin.app.vault,d);let h={title:l,priority:"",status:"",contexts:e.location?[e.location]:[],tags:[this.plugin.fieldMapper.toUserField("icsEventTag")],timeEstimate:0,dueDate:e.end||"",scheduledDate:e.start||"",details:e.description||"",parentNote:"",icsEventTitle:e.title,icsEventStart:e.start,icsEventEnd:e.end||"",icsEventLocation:e.location||"",icsEventDescription:e.description||"",icsEventUrl:e.url||"",icsEventSubscription:i,icsEventId:e.id},g=this.plugin.fieldMapper.toUserField("dateCreated"),v=this.plugin.fieldMapper.toUserField("dateModified"),k={title:l,[g]:qe(),[v]:qe(),tags:[this.plugin.fieldMapper.toUserField("icsEventTag")],[this.plugin.fieldMapper.toUserField("icsEventId")]:[e.id]},T=this.buildICSEventDetails(e,i);if(t!=null&&t.template)try{let _=(0,gE.normalizePath)(t.template.trim()),F=this.plugin.app.vault.getAbstractFileByPath(_.endsWith(".md")?_:`${_}.md`);if(F instanceof gE.TFile){let I=await this.plugin.app.vault.read(F),A=dx(I,h);k={...k,...A.frontmatter},T=A.body||T}else Nc.warn(`ICS note template not found: ${_}`,{category:"provider",operation:"ics-note-template-not-found"}),ve(this.plugin.emitter,this.translate("services.icsNote.notices.templateNotFound",{path:_}))}catch(_){Nc.error("Error processing ICS note template:",{category:"provider",operation:"processing-ics-note-template",error:_}),ve(this.plugin.emitter,this.translate("services.icsNote.notices.templateProcessError",{template:t.template}))}let w=`${Object.keys(k).length>0?`--- +${Object.entries(k).map(([_,F])=>`${_}: ${this.formatYamlValue(F)}`).join(` +`)} +--- + +`:""}${T}`,S=await this.plugin.app.vault.create(f,w),C=Array.isArray(k.tags)?k.tags.filter(_=>typeof _=="string"):[],x=typeof k[g]=="string"?k[g]:void 0,E={title:l,path:S.path,tags:C,createdDate:x,lastModified:Date.now()};return{file:S,noteInfo:E}}catch(a){let i=a instanceof Error?a.message:String(a);throw Nc.error("Error creating note from ICS event:",{category:"provider",operation:"creating-note-ics-event",details:{icsEventId:e.id,icsEventTitle:e.title},error:i}),new Error(`Failed to create note from ICS event: ${i}`)}}async findRelatedNotes(e){try{let t=[],r=new Set,a=this.plugin.fieldMapper.toUserField("icsEventId"),i=this.buildEventSeriesIndex(),s=this.getRelatedEventIds(e.id,i),o=d=>this.normalizeEventIds(d).some(u=>this.eventIdsMatchSeries(u,s,i)),l=await this.plugin.cacheManager.getAllTasks();for(let d of l)if(o(d.icsEventId)){if(r.has(d.path))continue;t.push(d),r.add(d.path)}let c=this.plugin.app.vault.getMarkdownFiles();for(let d of c)try{let u=this.plugin.app.metadataCache.getFileCache(d),p=u==null?void 0:u.frontmatter;if(p&&o(p[a])){if(r.has(d.path))continue;let m={title:p.title||d.basename,path:d.path,tags:p.tags||[],createdDate:p.dateCreated,lastModified:d.stat.mtime};t.push(m),r.add(d.path)}}catch(u){continue}return t}catch(t){return Nc.error("Error finding related notes for ICS event:",{category:"provider",operation:"finding-related-notes-ics-event",error:t}),[]}}async linkNoteToICS(e,t){try{let r=this.plugin.app.vault.getAbstractFileByPath(e);if(!(r instanceof gE.TFile))throw new Error(`Cannot find note file: ${e}`);await yr(this.plugin.app,r,a=>{let i=this.plugin.fieldMapper.toUserField("icsEventId"),s=a[i],o=s?Array.isArray(s)?[...s]:[s]:[];o.includes(t.id)||o.push(t.id),a[i]=o;let l=this.plugin.fieldMapper.toUserField("dateModified");a[l]=qe()}),ve(this.plugin.emitter,this.translate("services.icsNote.notices.linkedToEvent",{title:t.title}))}catch(r){let a=r instanceof Error?r.message:String(r);throw Nc.error("Error linking note to ICS event:",{category:"provider",operation:"linking-note-ics-event",details:{notePath:e,icsEventId:t.id},error:a}),new Error(`Failed to link note to ICS event: ${a}`)}}buildICSEventDetails(e,t){let r=[];if(r.push(`# ${e.title}`),r.push(""),e.start){let a=e.allDay&&/^\d{4}-\d{2}-\d{2}$/.test(e.start)?e.start+"T00:00:00":e.start,i=new Date(a);r.push(`**Start:** ${D(i,"PPPp")}`)}if(e.end&&!e.allDay){let a=/^\d{4}-\d{2}-\d{2}$/.test(e.end)?e.end+"T00:00:00":e.end,i=new Date(a);r.push(`**End:** ${D(i,"PPPp")}`)}return e.location&&r.push(`**Location:** ${e.location}`),r.push(`**Calendar:** ${t}`),e.description&&(r.push(""),r.push("## Description"),r.push(e.description)),e.url&&(r.push(""),r.push(`**Event URL:** ${e.url}`)),r.join(` +`)}formatYamlValue(e){return typeof e=="string"?e.includes(":")||e.includes("#")||e.includes("[")||e.includes("{")?`"${e.replace(/"/g,'\\"')}"`:e:Array.isArray(e)?`[${e.map(t=>typeof t=="string"?`"${t}"`:t).join(", ")}]`:String(e)}calculateEventDuration(e){if(!(!e.start||!e.end))try{let t=e.allDay&&/^\d{4}-\d{2}-\d{2}$/.test(e.start)?e.start+"T00:00:00":e.start,r=e.allDay&&/^\d{4}-\d{2}-\d{2}$/.test(e.end)?e.end+"T00:00:00":e.end,a=new Date(t).getTime(),i=new Date(r).getTime();if(isNaN(a)||isNaN(i))return;let s=i-a,o=Math.round(s/(1e3*60));return o>0&&o<1440?o:void 0}catch(t){Nc.warn("Error calculating event duration:",{category:"provider",operation:"calculating-event-duration",error:t});return}}}});var GTe,_s,zk,WXt,Bk=y(()=>{GTe={TOKEN_REFRESH_BUFFER_MS:3e5,CALLBACK_PORT_START:8080,CALLBACK_PORT_END:8090},_s={REFRESH_INTERVAL_MS:900*1e3,MIN_MANUAL_REFRESH_INTERVAL_MS:30*1e3,MAX_RESULTS_PER_REQUEST:2500,VIEW_RANGE:{DAYS_BEFORE:180,DAYS_AFTER:90},DEFAULT_EVENT_DURATION_MS:3600*1e3,MAX_REMINDER_MINUTES:40320,RATE_LIMIT:{MAX_RETRIES:3,INITIAL_BACKOFF_MS:1e3,MAX_BACKOFF_MS:16e3,BACKOFF_MULTIPLIER:2}},zk={REFRESH_INTERVAL_MS:900*1e3,MIN_MANUAL_REFRESH_INTERVAL_MS:30*1e3,MAX_RESULTS_PER_REQUEST:50,VIEW_RANGE:{DAYS_BEFORE:30,DAYS_AFTER:90},DEFAULT_EVENT_DURATION_MS:3600*1e3,RATE_LIMIT:{MAX_RETRIES:3,INITIAL_BACKOFF_MS:1e3,MAX_BACKOFF_MS:16e3,BACKOFF_MULTIPLIER:2}},WXt={SECOND_MS:1e3,MINUTE_MS:60*1e3,HOUR_MS:3600*1e3,DAY_MS:1440*60*1e3}});var yE,vE,Ki,Oh,XR,wa,am,jk,Co,im,$k=y(()=>{yE=class extends Error{constructor(t,r){super(t);this.code=r;this.name="TaskNotesServiceError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},vE=class extends yE{constructor(t,r,a){super(t,a);this.provider=r;this.name="OAuthError"}},Ki=class extends vE{constructor(e){super(`${e} authentication expired. Please reconnect.`,e,"TOKEN_EXPIRED"),this.name="TokenExpiredError"}},Oh=class extends vE{constructor(t,r,a){let i=`${t} connection expired. Please reconnect in Settings > Integrations.`;super(i,t,"TOKEN_REFRESH_FAILED");this.oauthErrorCode=r;this.oauthErrorDescription=a;this.name="TokenRefreshError"}},XR=class extends vE{constructor(e){super(`${e} OAuth is not configured. Please provide OAuth credentials in settings.`,e,"NOT_CONFIGURED"),this.name="OAuthNotConfiguredError"}},wa=class extends yE{constructor(t,r,a){super(t,a);this.statusCode=r;this.name="GoogleCalendarError"}},am=class extends wa{constructor(e){super(`Calendar event not found: ${e}`,404,"EVENT_NOT_FOUND"),this.name="EventNotFoundError"}},jk=class extends wa{constructor(e){super(`Calendar not found: ${e}`,404,"CALENDAR_NOT_FOUND"),this.name="CalendarNotFoundError"}},Co=class extends wa{constructor(e){let t=e?`Rate limit exceeded. Retry after ${e} seconds.`:"Rate limit exceeded. Please try again later.";super(t,429,"RATE_LIMIT"),this.name="RateLimitError"}},im=class extends yE{constructor(t,r){super(t,"VALIDATION_ERROR");this.field=r;this.name="ValidationError"}}});function B5e(){if(sm.Platform.isDesktop&&sm.Platform.isDesktopApp)return aq||(aq=require("http")),aq;throw new Error("OAuth redirect handling is only available on desktop.")}var sm,xo,aq,e_,YTe=y(()=>{sm=require("obsidian");Bk();$k();q();Oi();xo=M({tag:"Services/OAuthService"}),aq=null;e_=class{constructor(e,t){this.callbackServer=null;this.pendingOAuthState=new Map;this.tokenRefreshPromises=new Map;this.connectionGenerations=new Map;this.configs={google:{provider:"google",clientId:"",redirectUri:"http://127.0.0.1:8080",scope:["https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/calendar.events"],authorizationEndpoint:"https://accounts.google.com/o/oauth2/v2/auth",tokenEndpoint:"https://oauth2.googleapis.com/token",deviceCodeEndpoint:"https://oauth2.googleapis.com/device/code",revocationEndpoint:"https://oauth2.googleapis.com/revoke"},microsoft:{provider:"microsoft",clientId:"",redirectUri:"http://localhost:8080",scope:["Calendars.Read","Calendars.ReadWrite","offline_access"],authorizationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/token",deviceCodeEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/devicecode",revocationEndpoint:"https://login.microsoftonline.com/common/oauth2/v2.0/logout"}};this.authenticationInProgress=!1;this.plugin=e,this.secretStore=t}getCredentials(e){return this.secretStore.getCredentials(e)}setCredentials(e,t){this.secretStore.setCredentials(e,t)}clearCredentials(e){this.secretStore.clearCredentials(e)}getConfig(e){var r;let t=this.secretStore.getCredentials(e);return{...this.configs[e],clientId:(r=t==null?void 0:t.clientId)!=null?r:"",clientSecret:t==null?void 0:t.clientSecret}}async authenticate(e){if(!this.getConfig(e).clientId)throw new XR(e);return await this.authenticateStandard(e)}async authenticateStandard(e){if(this.authenticationInProgress)throw new Error("An OAuth authorization is already in progress");this.authenticationInProgress=!0;try{let t=this.getConfig(e);if(!sm.Platform.isDesktopApp)throw ve(this.plugin.emitter,"OAUTH authentication requires the desktop app."),new Error("OAuth authentication requires the desktop app.");let r=this.generateCodeVerifier(),a=await this.generateCodeChallenge(r),i=this.generateState(),s=await this.startCallbackServer(0),o=t.redirectUri;t.redirectUri=`http://127.0.0.1:${s}`;try{let l=this.buildAuthorizationUrl(t,a,i);this.pendingOAuthState.set(i,{provider:e,codeVerifier:r,resolve:()=>{},reject:()=>{}}),ve(this.plugin.emitter,`Opening browser for ${e} authorization...`);let c=this.waitForCallback(i,3e5);this.openAuthorizationUrl(l).catch(p=>{var m;(m=this.pendingOAuthState.get(i))==null||m.reject(p instanceof Error?p:new Error("Could not open OAuth browser"))});let d=await c,u=await this.exchangeCodeForTokens(t,d,r);await this.storeConnection(e,u),ve(this.plugin.emitter,`Successfully connected to ${e} Calendar!`)}finally{let l=this.pendingOAuthState.get(i);this.pendingOAuthState.delete(i),l==null||l.reject(new Error("OAuth flow ended before authorization")),t.redirectUri=o}}catch(t){throw xo.error(`OAuth authentication failed for ${e}:`,{category:"provider",operation:"oauth-authentication",error:t}),ve(this.plugin.emitter,`Failed to connect to ${e}: ${t.message}`),t}finally{try{await this.stopCallbackServer()}finally{this.authenticationInProgress=!1}}}async openAuthorizationUrl(e){try{let r=require("electron").shell;if(r!=null&&r.openExternal){await r.openExternal(e);return}}catch(t){xo.warn("Failed to open OAuth URL in system browser; falling back to window.open.",{category:"provider",operation:"oauth-open-external",error:t})}window.open(e,"_blank")}generateCodeVerifier(){return this.base64UrlEncode(crypto.getRandomValues(new Uint8Array(32)))}async generateCodeChallenge(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return this.base64UrlEncode(new Uint8Array(r))}generateState(){return Array.from(crypto.getRandomValues(new Uint8Array(16))).map(e=>e.toString(16).padStart(2,"0")).join("")}base64UrlEncode(e){let t="";return e.forEach(r=>{t+=String.fromCharCode(r)}),btoa(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}buildAuthorizationUrl(e,t,r){let a=new URLSearchParams({client_id:e.clientId,redirect_uri:e.redirectUri,response_type:"code",scope:e.scope.join(" "),state:r,code_challenge:t,code_challenge_method:"S256"});return e.provider==="google"&&(a.set("access_type","offline"),a.set("prompt","consent")),`${e.authorizationEndpoint}?${a.toString()}`}async startCallbackServer(e){return new Promise((t,r)=>{if(this.callbackServer){r(new Error("An OAuth callback is already pending"));return}let a;try{a=B5e()}catch(i){r(i instanceof Error?i:new Error(String(i)));return}this.callbackServer=a.createServer((i,s)=>{this.handleCallback(i,s)}),this.callbackServer.once("error",i=>{xo.error("OAuth callback server error:",{category:"provider",operation:"oauth-callback-server",error:i}),r(i)}),this.callbackServer.listen(e,"127.0.0.1",()=>{var s,o;let i=(o=(s=this.callbackServer)==null?void 0:s.address)==null?void 0:o.call(s);if(!i||typeof i=="string"){r(new Error("OAuth listener did not expose its bound port"));return}t(i.port)})})}async stopCallbackServer(){return new Promise(e=>{if(!this.callbackServer){e();return}let t=this.callbackServer;this.callbackServer=null,t.close(()=>e())})}handleCallback(e,t){let r={"Content-Type":"text/html; charset=utf-8","Content-Security-Policy":"default-src 'none'; frame-ancestors 'none'; base-uri 'none'","X-Content-Type-Options":"nosniff","Cache-Control":"no-store"},a;try{a=new URL(e.url||"/","http://127.0.0.1")}catch(c){t.writeHead(400,r),t.end("Invalid callback");return}let i=a.searchParams.get("state"),s=i?this.pendingOAuthState.get(i):void 0,o=a.searchParams.get("code"),l=a.searchParams.get("error");if(e.method!=="GET"||a.pathname!=="/"||!i||!s||!o&&!l){t.writeHead(400,r),t.end("Invalid callback

No pending authorization matches this callback.

");return}this.pendingOAuthState.delete(i),t.writeHead(l?400:200,r),t.end(l?"Authorization failed

Authorization was not completed. Return to Obsidian.

":"Authorization complete

You can close this window and return to Obsidian.

"),l?s.reject(new Error("OAuth authorization failed")):s.resolve(o)}waitForCallback(e,t){return new Promise((r,a)=>{let i=this.pendingOAuthState.get(e);if(!i){a(new Error("Invalid OAuth state"));return}i.resolve=o=>{window.clearTimeout(s),r(o)},i.reject=o=>{window.clearTimeout(s),a(o)};let s=window.setTimeout(()=>{this.pendingOAuthState.has(e)&&(this.pendingOAuthState.delete(e),a(new Error("OAuth timeout - authorization took too long")))},t)})}async exchangeCodeForTokens(e,t,r){let a={client_id:e.clientId,code:t,code_verifier:r,redirect_uri:e.redirectUri,grant_type:"authorization_code"};e.clientSecret&&(a.client_secret=e.clientSecret);let i=new URLSearchParams(a);try{let s=await(0,sm.requestUrl)({url:e.tokenEndpoint,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:i.toString(),throw:!1});if(s.status!==200)throw xo.error("Token exchange failed with status:",{category:"provider",operation:"token-exchange-status",details:{value:s.status}}),xo.error("Response headers:",{category:"provider",operation:"response-headers",details:{value:s.headers}}),xo.error("Response body:",{category:"provider",operation:"response-body",details:{value:s.text}}),xo.error("Response JSON:",{category:"provider",operation:"response-json",details:{value:s.json}}),new Error(`Token exchange failed with status ${s.status}: ${s.text||JSON.stringify(s.json)}`);let o=s.json;if(!o.access_token)throw new Error("No access token in response");let l=o.expires_in||3600,c=Date.now()+l*1e3;return{accessToken:o.access_token,refreshToken:o.refresh_token,expiresAt:c,scope:o.scope||e.scope.join(" "),tokenType:o.token_type||"Bearer"}}catch(s){throw xo.error("Token exchange error:",{category:"provider",operation:"token-exchange",error:s}),new Error(`Failed to exchange code for tokens: ${s.message}`)}}async refreshToken(e){var o;let t=await this.getConnection(e);if(!t)throw new Error(`No ${e} connection found`);if(!t.tokens.refreshToken)throw new Error(`No refresh token available for ${e}`);let r=(o=this.connectionGenerations.get(e))!=null?o:0,a=this.getConfig(e),i={client_id:a.clientId,refresh_token:t.tokens.refreshToken,grant_type:"refresh_token"};a.clientSecret&&(i.client_secret=a.clientSecret);let s=new URLSearchParams(i);try{let l=await(0,sm.requestUrl)({url:a.tokenEndpoint,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:s.toString(),throw:!1});if(l.status!==200){let m,f;try{let g=l.json;m=g==null?void 0:g.error,f=g==null?void 0:g.error_description}catch(g){}throw xo.error("[OAuth] Token refresh failed:",{category:"provider",operation:"token-refresh",details:{status:l.status,description:f},error:m}),l.status===401||l.status===400&&(m==="invalid_grant"||m==="invalid_client")?this.clearConnection(e,r)?(ve(this.plugin.emitter,`${e} connection expired. Please reconnect in Settings > Integrations.`),new Oh(e,m,f)):new Error(`${e} OAuth connection changed during token refresh`):new Error(`Token refresh failed with status ${l.status}: ${m||l.text||"Unknown error"}`)}let c=l.json;if(!c.access_token)throw new Error("No access token in refresh response");let d=c.expires_in||3600,u=Date.now()+d*1e3,p={accessToken:c.access_token,refreshToken:c.refresh_token||t.tokens.refreshToken,expiresAt:u,scope:c.scope||t.tokens.scope,tokenType:c.token_type||"Bearer"};return await this.storeConnection(e,p,t.userEmail,r),p}catch(l){throw l instanceof Oh?l:(xo.error("Token refresh failed:",{category:"provider",operation:"token-refresh",error:l}),new Error(`Failed to refresh ${e} token: ${l.message}`))}}clearConnection(e,t){var a;let r=(a=this.connectionGenerations.get(e))!=null?a:0;return t!==void 0&&t!==r?!1:(this.secretStore.clearConnection(e),this.connectionGenerations.set(e,r+1),!0)}async getValidToken(e,t){this.assertExpectedConnectionGeneration(e,t);let r=await this.getConnection(e);if(this.assertExpectedConnectionGeneration(e,t),!r)throw new Ki(e);let a=Date.now(),i=GTe.TOKEN_REFRESH_BUFFER_MS;if(r.tokens.expiresAt-i{this.tokenRefreshPromises.delete(e)});this.tokenRefreshPromises.set(e,o);let l=await o;return this.assertExpectedConnectionGeneration(e,t),l.accessToken}return this.assertExpectedConnectionGeneration(e,t),r.tokens.accessToken}assertExpectedConnectionGeneration(e,t){if(t!==void 0&&this.getConnectionGeneration(e)!==t)throw new Error(`${e} OAuth connection changed during calendar operation`)}async storeConnection(e,t,r,a){var s,o;if(a!==void 0&&a!==((s=this.connectionGenerations.get(e))!=null?s:0))throw new Error(`${e} OAuth connection changed during token refresh`);let i={provider:e,tokens:t,userEmail:r,connectedAt:new Date().toISOString(),lastRefreshed:new Date().toISOString()};if(this.secretStore.setConnection(e,i),a===void 0){let l=(o=this.connectionGenerations.get(e))!=null?o:0;this.connectionGenerations.set(e,l+1)}}async getConnection(e){return this.secretStore.getConnection(e)}async isConnected(e){return await this.getConnection(e)!==null}getConnectionGeneration(e){var t;return(t=this.connectionGenerations.get(e))!=null?t:0}async isConnectionGenerationCurrent(e,t){return this.getConnectionGeneration(e)===t&&await this.isConnected(e)}async disconnect(e){let t=this.getConnectionGeneration(e),r=await this.getConnection(e);r&&this.clearConnection(e,t)&&(await this.revokeToken(e,r.tokens.accessToken),r.tokens.refreshToken&&await this.revokeToken(e,r.tokens.refreshToken),ve(this.plugin.emitter,`Disconnected from ${e} Calendar`))}async revokeToken(e,t){let r=this.getConfig(e);if(!r.revocationEndpoint){xo.warn(`No revocation endpoint configured for ${e}`,{category:"provider",operation:"no-revocation-endpoint-configured"});return}try{await(0,sm.requestUrl)({url:r.revocationEndpoint,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:t,...r.clientId&&{client_id:r.clientId}}).toString(),throw:!1})}catch(a){xo.error(`[OAuth] Failed to revoke token for ${e}:`,{category:"provider",operation:"revoke-token",error:a})}}async destroy(){for(let e of this.pendingOAuthState.values())e.reject(new Error("OAuth authorization cancelled"));this.pendingOAuthState.clear(),await this.stopCallbackServer(),this.tokenRefreshPromises.clear(),this.connectionGenerations.clear()}}});function iq(n,e){if(!n||n.trim()==="")throw new im(`${e} cannot be empty`,e)}function Eo(n,e){if(n==null)throw new im(`${e} is required`,e)}function t_(n){if(iq(n,"Calendar ID"),!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$|^[a-zA-Z0-9_-]+$|^[a-zA-Z0-9+/]+=*$/.test(n))throw new im("Invalid calendar ID format. Expected email-like, alphanumeric, or Base64 format.","calendarId")}function j5e(n){for(let e=0;e{$k()});function G5e(n){return V5e.test(n)||W5e.test(n)||q5e.test(n)}function Y5e(n){return $5e.has(n)?2:U5e.has(n)?1:0}function K5e(n,e){var i;let t=[];n.childNodes.forEach(s=>oq(s,t));let r=QTe(ZTe(t)),a=((i=n.getAttribute("href"))!=null?i:"").trim();if(!a||a===r){e.push(r);return}if(!r){e.push(a);return}e.push(`${r} (${a})`)}function oq(n,e){var i;if(n.nodeType===3){e.push((i=n.textContent)!=null?i:"");return}if(n.nodeType!==1)return;let t=n,r=t.tagName.toUpperCase();if(H5e.has(r))return;if(r==="BR"){e.push({weight:1});return}if(r==="A"){K5e(t,e);return}let a=Y5e(r);a>0&&e.push({weight:a}),r==="LI"&&e.push("- "),t.childNodes.forEach(s=>oq(s,e)),a>0&&e.push({weight:a})}function ZTe(n){let e="",t=0;for(let r of n){if(typeof r!="string"){t=Math.max(t,r.weight);continue}r.length!==0&&(t>0&&r.trim().length===0||(e.length>0&&t>0&&(e+=` +`.repeat(t)),t=0,e+=r))}return e}function QTe(n){return n.replace(/\u00a0/g," ").replace(/\r\n?/g,` +`).split(` +`).map(e=>e.replace(/[ \t]+/g," ").trim()).join(` +`).replace(/\n{3,}/g,` + +`).trim()}function Z5e(n){let e=(0,KTe.sanitizeHTMLToDom)(n),t=[];return e.childNodes.forEach(r=>oq(r,t)),QTe(ZTe(t))}function JTe(n){if(typeof n!="string"||n.length===0)return;if(!G5e(n))return n;let e=Z5e(n);return e.length>0?e:void 0}var KTe,$5e,U5e,H5e,V5e,W5e,q5e,XTe=y(()=>{KTe=require("obsidian"),$5e=new Set(["ADDRESS","ARTICLE","ASIDE","BLOCKQUOTE","DL","FIELDSET","FIGURE","FOOTER","FORM","H1","H2","H3","H4","H5","H6","HEADER","HR","MAIN","NAV","OL","P","PRE","SECTION","TABLE","UL"]),U5e=new Set(["DD","DIV","DT","FIGCAPTION","LI","TBODY","TD","TFOOT","TH","THEAD","TR"]),H5e=new Set(["SCRIPT","STYLE","TEMPLATE","HEAD"]),V5e=/<([a-z][\w:-]*)(?:\s[^>]*)?>[\s\S]*?<\/\1\s*>/i,W5e=/<(?:area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)(?:\s[^>]*)?\/?\s*>/i,q5e=//});var om,Do,Q5e,n_,ebe=y(()=>{om=require("obsidian");Cr();Bk();$k();sq();nm();q();Oi();XTe();Do=M({tag:"Services/GoogleCalendarService"}),Q5e={1:"#a4bdfc",2:"#7ae7bf",3:"#dbadff",4:"#ff887c",5:"#fbd75b",6:"#ffb878",7:"#46d6db",8:"#e1e1e1",9:"#5484ed",10:"#51b749",11:"#dc2127"},n_=class extends Ok{constructor(t,r){super();this.providerId="google";this.providerName="Google Calendar";this.baseUrl="https://www.googleapis.com/calendar/v3";this.cache=new Map;this.refreshTimer=null;this.availableCalendars=[];this.calendarColors=new Map;this.lastManualRefresh=0;this.plugin=t,this.oauthService=r}sleep(t){return new Promise(r=>window.setTimeout(r,t))}async withRetry(t,r){let{MAX_RETRIES:a,INITIAL_BACKOFF_MS:i,MAX_BACKOFF_MS:s,BACKOFF_MULTIPLIER:o}=_s.RATE_LIMIT,l=null,c=i;for(let d=0;d<=a;d++)try{return await t()}catch(u){l=u;let p=u.status===429,m=u.status>=500&&u.status<600,f=d===a;if(!p&&!m)throw u;if(f)throw Do.error(`[GoogleCalendar] ${r} failed after ${a} retries`,{category:"provider",operation:"retry-google-calendar-request",details:{context:r,attempts:a},error:u}),u;let h=Math.random()*.3*c,g=Math.min(c+h,s);Do.warn("Google Calendar request failed and will be retried",{category:"provider",operation:"retry-google-calendar-request",details:{context:r,status:u.status,delayMs:Math.round(g),nextAttempt:d+1,maxRetries:a},error:u}),await this.sleep(g),c=Math.min(c*o,s)}throw l instanceof Error?l:new Error(String(l))}getAvailableCalendars(){return this.availableCalendars}getConnectionGeneration(){return this.oauthService.getConnectionGeneration("google")}async isConnectionGenerationCurrent(t){return this.oauthService.isConnectionGenerationCurrent("google",t)}getEnabledCalendarIds(){return this.plugin.settings.enabledGoogleCalendars.length===0?this.availableCalendars.map(t=>t.id):this.plugin.settings.enabledGoogleCalendars}getSyncToken(t){return this.plugin.settings.googleCalendarSyncTokens[t]}async saveSyncToken(t,r){this.plugin.settings.googleCalendarSyncTokens[t]!==r&&(this.plugin.settings.googleCalendarSyncTokens[t]=r,await this.persistSettingsDataOnly())}async clearSyncToken(t){t in this.plugin.settings.googleCalendarSyncTokens&&(delete this.plugin.settings.googleCalendarSyncTokens[t],await this.persistSettingsDataOnly())}async persistSettingsDataOnly(){let t=this.plugin.saveSettingsDataOnly;typeof t=="function"&&await t.call(this.plugin)}async initialize(){await this.oauthService.isConnected("google")&&(await this.refreshAllCalendars(),this.startRefreshTimer())}startRefreshTimer(){this.refreshTimer&&window.clearTimeout(this.refreshTimer),this.refreshTimer=window.setTimeout(()=>{this.refreshTimer=null,this.refreshAllCalendars().catch(t=>{Do.error("Google Calendar refresh failed:",{category:"provider",operation:"google-calendar-refresh",error:t})}).finally(()=>{this.oauthService.isConnected("google").then(t=>{t&&this.startRefreshTimer()})})},_s.REFRESH_INTERVAL_MS)}stopRefreshTimer(){this.refreshTimer&&(window.clearTimeout(this.refreshTimer),this.refreshTimer=null)}async listCalendars(){try{return await this.withRetry(async()=>{let t=await this.oauthService.getValidToken("google"),i=(await(0,om.requestUrl)({url:`${this.baseUrl}/users/me/calendarList`,method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}})).json.items||[],s=[];for(let o of i)o.backgroundColor&&this.calendarColors.set(o.id,o.backgroundColor),s.push({id:o.id,summary:o.summary,description:o.description,backgroundColor:o.backgroundColor,primary:o.primary||!1});return s},"List calendars")}catch(t){throw Do.error("Failed to list calendars:",{category:"provider",operation:"list-calendars",error:t}),new wa(`Failed to fetch calendar list: ${t.message}`,t.status)}}async fetchCalendarEvents(t,r,a){try{let i=await this.oauthService.getValidToken("google"),s=this.getSyncToken(t),o=[],l,c,d=!s,u=!1,p,m;if(!s){let f=new Date;p=r||new Date(f.getTime()-_s.VIEW_RANGE.DAYS_BEFORE*24*60*60*1e3),m=a||new Date(f.getTime()+_s.VIEW_RANGE.DAYS_AFTER*24*60*60*1e3)}do try{let f=new URLSearchParams({singleEvents:"true",maxResults:_s.MAX_RESULTS_PER_REQUEST.toString()});s?f.set("syncToken",s):(f.set("timeMin",p.toISOString()),f.set("timeMax",m.toISOString()),f.set("orderBy","startTime")),l&&f.set("pageToken",l);let g=(await this.withRetry(async()=>await(0,om.requestUrl)({url:`${this.baseUrl}/calendars/${encodeURIComponent(t)}/events?${f.toString()}`,method:"GET",headers:{Authorization:`Bearer ${i}`,Accept:"application/json"}}),`Fetch events for ${t}`)).json,v=g.items||[];!d&&v.some(k=>k.status==="cancelled")&&(u=!0),o.push(...v),l=g.nextPageToken,g.nextSyncToken&&(c=g.nextSyncToken)}catch(f){if(f.status===410)return await this.clearSyncToken(t),await this.fetchCalendarEvents(t,r,a);throw f}while(l);return c&&await this.saveSyncToken(t,c),{events:o,isFullSync:d,hasDeletes:u}}catch(i){throw Do.error(`Failed to fetch events from calendar ${t}:`,{category:"provider",operation:"fetch-events-calendar",error:i}),new Error(`Failed to fetch calendar events: ${i.message}`)}}getCalendarColor(t){let r=this.calendarColors.get(t);if(r)return r;let a=rm(this.availableCalendars,t);return a?this.calendarColors.get(a.id):void 0}convertToICSEvent(t,r){var c,d;let a,i,s;if(t.start.date)a=t.start.date,i=(c=t.end)==null?void 0:c.date,s=!0;else{let u=new Date(t.start.dateTime),p=(d=t.end)!=null&&d.dateTime?new Date(t.end.dateTime):void 0;a=D(u,"yyyy-MM-dd'T'HH:mm:ss"),i=p?D(p,"yyyy-MM-dd'T'HH:mm:ss"):void 0,s=!1}let o;t.colorId&&(o=Q5e[t.colorId]),o||(o=this.getCalendarColor(r)),o||(o="#4285F4");let l=t.recurringEventId?`google-${r}-${t.recurringEventId}`:void 0;return{id:`google-${r}-${t.id}`,subscriptionId:`google-${r}`,title:t.summary||"Untitled Event",description:JTe(t.description),start:a,end:i,allDay:s,location:t.location,url:t.htmlLink,recurringEventId:l,color:o}}async refreshAllCalendars(t={}){try{if(!await this.oauthService.isConnected("google"))return;this.availableCalendars=await this.listCalendars();let a=this.getEnabledCalendarIds(),i=this.cache.get("all")||[];for(let s of a)try{let{events:o,isFullSync:l}=await this.fetchCalendarEvents(s);if(l){i=i.filter(d=>d.subscriptionId!==`google-${s}`);let c=o.filter(d=>d.status!=="cancelled").map(d=>this.convertToICSEvent(d,s));i.push(...c)}else for(let c of o){let d=`google-${s}-${c.id}`,u=i.findIndex(p=>p.id===d);if(c.status==="cancelled")u!==-1&&i.splice(u,1);else{let p=this.convertToICSEvent(c,s);u!==-1?i[u]=p:i.push(p)}}}catch(o){Do.error(`Failed to fetch events from calendar ${s}:`,{category:"provider",operation:"fetch-events-calendar",error:o})}this.cache.set("all",i),this.emit("data-changed")}catch(r){if(Do.error("Failed to refresh Google calendars:",{category:"provider",operation:"refresh-google-calendars",error:r}),r.message&&r.message.includes("401")&&Do.warn("[GoogleCalendar] Authentication expired - caller should handle re-authentication",{category:"provider",operation:"authentication-expired-caller-should-handle-re-authentication"}),t.propagateErrors)throw r}}getAllEvents(){return this.cache.get("all")||[]}getCachedEvents(){return this.getAllEvents()}async getEvents(t,r,a){let{events:i}=await this.fetchCalendarEvents(t,r,a);return i.filter(s=>s.status!=="cancelled").map(s=>this.convertToICSEvent(s,t))}async manualRefresh(){return this.refresh()}async refresh(){let r=Date.now()-this.lastManualRefresh,a=_s.MIN_MANUAL_REFRESH_INTERVAL_MS;if(rawait(0,om.requestUrl)({url:`${this.baseUrl}/calendars/${encodeURIComponent(t)}/events/${encodeURIComponent(r)}`,method:"GET",headers:{Authorization:`Bearer ${s}`,Accept:"application/json"}}),`Get event ${r}`)).json};c.status==="cancelled"&&(c.status="confirmed"),(a.title!==void 0||a.summary!==void 0)&&(c.summary=a.summary||a.title),a.description!==void 0&&(c.description=a.description),a.location!==void 0&&(c.location=a.location),a.reminders!==void 0&&(c.reminders=a.reminders),a.colorId!==void 0&&(c.colorId=a.colorId),a.recurrence!==void 0&&(c.recurrence=a.recurrence),a.start!==void 0&&(typeof a.start=="string"?a.isAllDay||!/T/.test(a.start)?c.start={date:a.start}:c.start={dateTime:a.start,timeZone:"UTC"}:c.start=a.start),a.end!==void 0&&(typeof a.end=="string"?a.isAllDay||!/T/.test(a.end)?c.end={date:a.end}:c.end={dateTime:a.end,timeZone:"UTC"}:c.end=a.end),c.start&&(c.start.date?(delete c.start.dateTime,delete c.start.timeZone):c.start.dateTime&&delete c.start.date),c.end&&(c.end.date?(delete c.end.dateTime,delete c.end.timeZone):c.end.dateTime&&delete c.end.date);let u=(await this.withRetry(async()=>await(0,om.requestUrl)({url:`${this.baseUrl}/calendars/${encodeURIComponent(t)}/events/${encodeURIComponent(r)}`,method:"PUT",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(c)}),`Update event ${r}`)).json,p=this.convertToICSEvent(u,t);return await this.refreshAllCalendars(),p}catch(s){throw Do.error("Failed to update Google Calendar event:",{category:"provider",operation:"update-google-calendar-event",error:s}),s.status===404?new am(r):s.status===401||s.status===403?new Ki("google"):s.status===429?new Co:new wa(`Failed to update event: ${s.message}`,s.status)}}async createEvent(t,r,a){t_(t),Eo(r,"event");let i=r.summary||r.title;Eo(i,"event.summary"),Eo(r.start,"event.start"),Eo(r.end,"event.end");try{let s=await this.oauthService.getValidToken("google",a),o={summary:i,description:r.description,location:r.location};r.reminders&&(o.reminders=r.reminders),r.colorId&&(o.colorId=r.colorId),r.recurrence&&r.recurrence.length>0&&(o.recurrence=r.recurrence),typeof r.start=="string"?r.isAllDay||!/T/.test(r.start)?(o.start={date:r.start},o.end={date:r.end}):(o.start={dateTime:r.start,timeZone:"UTC"},o.end={dateTime:r.end,timeZone:"UTC"}):(o.start=r.start,o.end=typeof r.end=="string"?{dateTime:r.end,timeZone:"UTC"}:r.end);let c=(await this.withRetry(async()=>await(0,om.requestUrl)({url:`${this.baseUrl}/calendars/${encodeURIComponent(t)}/events`,method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(o)}),`Create event in ${t}`)).json,d=this.convertToICSEvent(c,t);return await this.refreshAllCalendars(),d}catch(s){throw Do.error("Failed to create Google Calendar event:",{category:"provider",operation:"create-google-calendar-event",error:s}),s.status===404?new jk(t):s.status===401||s.status===403?new Ki("google"):s.status===429?new Co:new wa(`Failed to create event: ${s.message}`,s.status)}}async deleteEvent(t,r,a){t_(t),Uk(r);try{let i=await this.oauthService.getValidToken("google",a);await this.withRetry(async()=>await(0,om.requestUrl)({url:`${this.baseUrl}/calendars/${encodeURIComponent(t)}/events/${encodeURIComponent(r)}`,method:"DELETE",headers:{Authorization:`Bearer ${i}`}}),`Delete event ${r}`),await this.refreshAllCalendars()}catch(i){if(i.status===410)return;throw Do.error("Failed to delete Google Calendar event:",{category:"provider",operation:"delete-google-calendar-event",error:i}),i.status===404?new am(r):i.status===401||i.status===403?new Ki("google"):i.status===429?new Co:new wa(`Failed to delete event: ${i.message}`,i.status)}}async createCalendar(t,r){try{let a=await this.oauthService.getValidToken("google"),s=(await this.withRetry(async()=>await(0,om.requestUrl)({url:`${this.baseUrl}/calendars`,method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({summary:t,description:r,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone})}),"Create calendar")).json;return this.availableCalendars=await this.listCalendars(),s.id}catch(a){throw Do.error("Failed to create calendar:",{category:"provider",operation:"create-calendar",error:a}),a.status===401||a.status===403?new Ki("google"):a.status===429?new Co:new wa(`Failed to create calendar: ${a.message}`,a.status)}}destroy(){this.stopRefreshTimer(),this.cache.clear(),this.removeAllListeners()}}});var zh,yi,a_,tbe=y(()=>{zh=require("obsidian");Cr();Bk();$k();sq();nm();q();Oi();yi=M({tag:"Services/MicrosoftCalendarService"}),a_=class extends Ok{constructor(t,r){super();this.providerId="microsoft";this.providerName="Microsoft Calendar";this.baseUrl="https://graph.microsoft.com/v1.0";this.cache=new Map;this.refreshTimer=null;this.availableCalendars=[];this.lastManualRefresh=0;this.syncStatus={lastAttempt:null,lastSuccess:null,lastError:null,calendarErrors:[],calendarsChecked:0,eventsLoaded:0};this.plugin=t,this.oauthService=r}sleep(t){return new Promise(r=>window.setTimeout(r,t))}async withRetry(t,r){let{MAX_RETRIES:a,INITIAL_BACKOFF_MS:i,MAX_BACKOFF_MS:s,BACKOFF_MULTIPLIER:o}=zk.RATE_LIMIT,l=null,c=i;for(let d=0;d<=a;d++)try{return await t()}catch(u){l=u;let p=u.status===429,m=u.status>=500&&u.status<600,f=d===a;if(!p&&!m)throw u;if(f)throw yi.error(`[MicrosoftCalendar] ${r} failed after ${a} retries`,{category:"provider",operation:"retry-microsoft-calendar-request",details:{context:r,attempts:a},error:u}),u;let h=Math.random()*.3*c,g=Math.min(c+h,s);yi.warn("Microsoft Calendar request failed and will be retried",{category:"provider",operation:"retry-microsoft-calendar-request",details:{context:r,status:u.status,delayMs:Math.round(g),nextAttempt:d+1,maxRetries:a},error:u}),await this.sleep(g),c=Math.min(c*o,s)}throw l instanceof Error?l:new Error(String(l))}getAvailableCalendars(){return this.availableCalendars}getSyncStatus(){return{...this.syncStatus,calendarErrors:this.syncStatus.calendarErrors.map(t=>({...t}))}}getEnabledCalendarIds(){return this.plugin.settings.enabledMicrosoftCalendars.length===0?this.availableCalendars.map(t=>t.id):this.plugin.settings.enabledMicrosoftCalendars}getSyncToken(t){var r;return(r=this.plugin.settings.microsoftCalendarSyncTokens)==null?void 0:r[t]}async saveSyncToken(t,r){this.plugin.settings.microsoftCalendarSyncTokens||(this.plugin.settings.microsoftCalendarSyncTokens={}),this.plugin.settings.microsoftCalendarSyncTokens[t]!==r&&(this.plugin.settings.microsoftCalendarSyncTokens[t]=r,await this.persistSettingsDataOnly())}async clearSyncToken(t){this.plugin.settings.microsoftCalendarSyncTokens&&t in this.plugin.settings.microsoftCalendarSyncTokens&&(delete this.plugin.settings.microsoftCalendarSyncTokens[t],await this.persistSettingsDataOnly())}async persistSettingsDataOnly(){let t=this.plugin.saveSettingsDataOnly;typeof t=="function"&&await t.call(this.plugin)}getErrorMessage(t){if(t instanceof Error)return t.message;if(typeof t=="object"&&t!==null&&"message"in t){let r=t.message;if(typeof r=="string")return r}return String(t)}getErrorStatus(t){if(typeof t!="object"||t===null)return;let r=t.status;if(typeof r=="number")return r;let a=t.statusCode;return typeof a=="number"?a:void 0}createSyncError(t,r){return{calendarId:r==null?void 0:r.id,calendarName:r==null?void 0:r.summary,message:this.getErrorMessage(t),status:this.getErrorStatus(t),occurredAt:new Date().toISOString()}}formatSyncErrorSummary(t){if(t.length===0)return null;let r=t[0],a=r.calendarName||r.calendarId||"Microsoft calendar";return t.length===1?`${a}: ${r.message}`:`${t.length} Microsoft calendars failed to refresh. First error: ${a}: ${r.message}`}async initialize(){await this.oauthService.isConnected("microsoft")&&(await this.refreshAllCalendars(),this.startRefreshTimer())}startRefreshTimer(){this.refreshTimer&&window.clearTimeout(this.refreshTimer),this.refreshTimer=window.setTimeout(()=>{this.refreshTimer=null,this.refreshAllCalendars().catch(t=>{yi.error("Microsoft Calendar refresh failed:",{category:"provider",operation:"microsoft-calendar-refresh",error:t})}).finally(()=>{this.oauthService.isConnected("microsoft").then(t=>{t&&this.startRefreshTimer()})})},zk.REFRESH_INTERVAL_MS)}stopRefreshTimer(){this.refreshTimer&&(window.clearTimeout(this.refreshTimer),this.refreshTimer=null)}async listCalendars(){try{return await this.withRetry(async()=>{let t=await this.oauthService.getValidToken("microsoft"),r=[],a=`${this.baseUrl}/me/calendars`;for(;a;){let s=(await(0,zh.requestUrl)({url:a,method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}})).json,o=s.value||[];r.push(...o),a=s["@odata.nextLink"]}return r.map(i=>({id:i.id,summary:i.name,name:i.name,color:i.hexColor||void 0,backgroundColor:i.hexColor||void 0,primary:i.isDefaultCalendar||!1,isDefault:i.isDefaultCalendar||!1}))},"List calendars")}catch(t){throw yi.error("Failed to list calendars:",{category:"provider",operation:"list-calendars",error:t}),new wa(`Failed to fetch calendar list: ${t.message}`,t.status)}}async fetchCalendarEvents(t,r,a){try{let i=await this.oauthService.getValidToken("microsoft"),s=this.getSyncToken(t),o=[],l,c,d=!s,u=!1,p;if(s)p=s;else{let m=new Date,f=r||new Date(m.getTime()-720*60*60*1e3),h=a||new Date(m.getTime()+2160*60*60*1e3),g=new URLSearchParams({startDateTime:f.toISOString(),endDateTime:h.toISOString(),$top:zk.MAX_RESULTS_PER_REQUEST.toString()});p=`${this.baseUrl}/me/calendars/${encodeURIComponent(t)}/calendarView?${g.toString()}`}do try{let f=(await this.withRetry(async()=>{let g=[`odata.maxpagesize=${zk.MAX_RESULTS_PER_REQUEST}`,'outlook.timezone="UTC"'];return await(0,zh.requestUrl)({url:l||p,method:"GET",headers:{Authorization:`Bearer ${i}`,Accept:"application/json",Prefer:g.join(", ")}})},`Fetch events for ${t}`)).json,h=f.value||[];!d&&h.some(g=>g.isCancelled||g["@removed"])&&(u=!0),o.push(...h),l=f["@odata.nextLink"],f["@odata.deltaLink"]&&(c=f["@odata.deltaLink"])}catch(m){if(m.status===410)return await this.clearSyncToken(t),await this.fetchCalendarEvents(t,r,a);throw m}while(l);return c&&await this.saveSyncToken(t,c),{events:o,isFullSync:d,hasDeletes:u}}catch(i){yi.error(`Failed to fetch events from calendar ${t}:`,{category:"provider",operation:"fetch-events-calendar",error:i});let s=new Error(`Failed to fetch calendar events: ${this.getErrorMessage(i)}`),o=this.getErrorStatus(i);throw s.status=o,s.statusCode=o,s}}convertToICSEvent(t,r){var c,d;if(!t.start||!t.end)throw new Error("Event missing start/end");let a,i,s=t.isAllDay||!1;if(s)a=t.start.dateTime.split("T")[0],i=t.end.dateTime.split("T")[0];else{let u=this.ensureUtcDateTime(t.start.dateTime,t.start.timeZone),p=this.ensureUtcDateTime(t.end.dateTime,t.end.timeZone),m=Na(u),f=Na(p);a=D(m,"yyyy-MM-dd'T'HH:mm:ss"),i=D(f,"yyyy-MM-dd'T'HH:mm:ss")}let o="#0078D4",l=t.seriesMasterId?`microsoft-${r}-${t.seriesMasterId}`:void 0;return{id:`microsoft-${r}-${t.id}`,subscriptionId:`microsoft-${r}`,title:t.subject||"Untitled Event",description:t.bodyPreview||((c=t.body)==null?void 0:c.content),start:a,end:i,allDay:s,location:(d=t.location)==null?void 0:d.displayName,url:t.webLink,recurringEventId:l,color:o}}async refreshAllCalendars(){var r,a;let t=new Date().toISOString();this.syncStatus={...this.syncStatus,lastAttempt:t,lastError:null,calendarErrors:[],calendarsChecked:0,eventsLoaded:((r=this.cache.get("all"))==null?void 0:r.length)||0};try{if(!await this.oauthService.isConnected("microsoft"))return;this.availableCalendars=await this.listCalendars();let s=this.getEnabledCalendarIds(),o=new Map(this.availableCalendars.map(d=>[d.id,d])),l=[],c=this.cache.get("all")||[];for(let d of s)try{let{events:u,isFullSync:p}=await this.fetchCalendarEvents(d);if(p){c=c.filter(f=>f.subscriptionId!==`microsoft-${d}`);let m=u.filter(f=>!f.isCancelled&&!f["@removed"]).map(f=>this.convertToICSEvent(f,d));c.push(...m)}else for(let m of u){let f=m["@removed"],h=`microsoft-${d}-${m.id}`,g=c.findIndex(v=>v.id===h);if(f){g!==-1&&c.splice(g,1);continue}if(m.isCancelled)g!==-1&&c.splice(g,1);else try{let v=this.convertToICSEvent(m,d);g!==-1?c[g]=v:c.push(v)}catch(v){yi.warn("[MicrosoftCalendar] Failed to convert event during refresh",{category:"provider",operation:"convert-event-refresh",details:{value:m.id},error:v})}}}catch(u){yi.error(`Failed to fetch events from calendar ${d}:`,{category:"provider",operation:"fetch-events-calendar",error:u}),l.push(this.createSyncError(u,o.get(d)))}this.cache.set("all",c),this.syncStatus={lastAttempt:t,lastSuccess:l.length===0?new Date().toISOString():this.syncStatus.lastSuccess,lastError:this.formatSyncErrorSummary(l),calendarErrors:l,calendarsChecked:s.length,eventsLoaded:c.length},this.emit("data-changed")}catch(i){yi.error("Failed to refresh Microsoft calendars:",{category:"provider",operation:"refresh-microsoft-calendars",error:i});let s=this.createSyncError(i);this.syncStatus={...this.syncStatus,lastAttempt:t,lastError:s.message,calendarErrors:[s],calendarsChecked:0,eventsLoaded:((a=this.cache.get("all"))==null?void 0:a.length)||0},this.getErrorMessage(i).includes("401")&&yi.warn("[MicrosoftCalendar] Authentication expired - caller should handle re-authentication",{category:"provider",operation:"authentication-expired-caller-should-handle-re-authentication"})}}getAllEvents(){return this.cache.get("all")||[]}getCachedEvents(){return this.getAllEvents()}async getEvents(t,r,a){let{events:i}=await this.fetchCalendarEvents(t,r,a),s=[];for(let o of i)if(!(o["@removed"]||o.isCancelled))try{s.push(this.convertToICSEvent(o,t))}catch(l){yi.warn("[MicrosoftCalendar] Skipping event due to conversion failure",{category:"provider",operation:"skipping-event-due-conversion",details:{value:o.id},error:l})}return s}async manualRefresh(){return this.refresh()}async disconnect(){this.clearCache(),this.stopRefreshTimer()}async refresh(){let t=Date.now(),r=t-this.lastManualRefresh,a=zk.MIN_MANUAL_REFRESH_INTERVAL_MS;if(rawait(0,zh.requestUrl)({url:`${this.baseUrl}/me/calendars/${encodeURIComponent(t)}/events/${encodeURIComponent(r)}`,method:"PATCH",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(s)}),`Update event ${r}`)).json,u=this.convertToICSEvent(d,t);return await this.refreshAllCalendars(),u}catch(i){throw yi.error("Failed to update Microsoft Calendar event:",{category:"provider",operation:"update-microsoft-calendar-event",error:i}),i.status===404?new am(r):i.status===401||i.status===403?new Ki("microsoft"):i.status===429?new Co:new wa(`Failed to update event: ${i.message}`,i.status)}}async createEvent(t,r){r_(t),Eo(r,"event");let a=r.summary||r.title;Eo(a,"event.summary"),Eo(r.start,"event.start"),Eo(r.end,"event.end");try{let i=await this.oauthService.getValidToken("microsoft"),s={subject:a};if(r.description&&(s.body={contentType:"text",content:r.description}),r.location&&(s.location={displayName:r.location}),typeof r.start=="string"){let d=r.isAllDay||!/T/.test(r.start);s.start={dateTime:r.start,timeZone:"UTC"},s.end={dateTime:typeof r.end=="string"?r.end:r.end.dateTime||r.end.date,timeZone:"UTC"},s.isAllDay=d}else{let d=r.end;s.start={dateTime:r.start.dateTime||r.start.date,timeZone:r.start.timeZone||"UTC"},s.end={dateTime:typeof d=="string"?d:d.dateTime||d.date,timeZone:typeof d=="string"?"UTC":d.timeZone||"UTC"},r.start.date&&!r.start.dateTime&&(s.isAllDay=!0)}let l=(await this.withRetry(async()=>await(0,zh.requestUrl)({url:`${this.baseUrl}/me/calendars/${encodeURIComponent(t)}/events`,method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(s)}),`Create event in ${t}`)).json,c=this.convertToICSEvent(l,t);return await this.refreshAllCalendars(),c}catch(i){throw yi.error("Failed to create Microsoft Calendar event:",{category:"provider",operation:"create-microsoft-calendar-event",error:i}),i.status===404?new jk(t):i.status===401||i.status===403?new Ki("microsoft"):i.status===429?new Co:new wa(`Failed to create event: ${i.message}`,i.status)}}async deleteEvent(t,r){r_(t),Uk(r);try{let a=await this.oauthService.getValidToken("microsoft");await this.withRetry(async()=>await(0,zh.requestUrl)({url:`${this.baseUrl}/me/calendars/${encodeURIComponent(t)}/events/${encodeURIComponent(r)}`,method:"DELETE",headers:{Authorization:`Bearer ${a}`}}),`Delete event ${r}`),await this.refreshAllCalendars()}catch(a){throw a.status===404?new am(r):(yi.error("Failed to delete Microsoft Calendar event:",{category:"provider",operation:"delete-microsoft-calendar-event",error:a}),a.status===401||a.status===403?new Ki("microsoft"):a.status===429?new Co:new wa(`Failed to delete event: ${a.message}`,a.status))}}async createCalendar(t,r){try{let a=await this.oauthService.getValidToken("microsoft"),s=(await this.withRetry(async()=>await(0,zh.requestUrl)({url:`${this.baseUrl}/me/calendars`,method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({name:t})}),"Create calendar")).json;return this.availableCalendars=await this.listCalendars(),s.id}catch(a){throw yi.error("Failed to create calendar:",{category:"provider",operation:"create-calendar",error:a}),a.status===401||a.status===403?new Ki("microsoft"):a.status===429?new Co:new wa(`Failed to create calendar: ${a.message}`,a.status)}}ensureUtcDateTime(t,r){if(!t)throw new Error("Missing dateTime value");return/[+-]\d{2}:\d{2}$/.test(t)||t.endsWith("Z")?t:(r&&r.toUpperCase()!=="UTC"&&yi.warn(`[MicrosoftCalendar] Falling back to UTC conversion for timezone "${r}"`,{category:"provider",operation:"falling-back-utc-conversion-timezone"}),`${t.replace(/\.\d+$/,"")}Z`)}destroy(){this.stopRefreshTimer(),this.cache.clear(),this.removeAllListeners()}}});function J5e(n,e){return n!==null&&typeof n=="object"&&Object.prototype.hasOwnProperty.call(n,e)}function X5e(n,e){return JSON.stringify(n)===JSON.stringify(e)}function rbe(n,e,t){return!X5e(n==null?void 0:n.pomodoroState,e)||(n==null?void 0:n.lastPomodoroDate)!==t}function nbe(n,e){return e===void 0?J5e(n,"lastSelectedTaskPath"):(n==null?void 0:n.lastSelectedTaskPath)!==e}var abe=y(()=>{});var eYe,i_,ibe=y(()=>{eYe=` + let timerInterval = null; + + self.onmessage = function(event) { + if (event.data && event.data.command === "start") { + if (timerInterval) { + clearInterval(timerInterval); + } + + timerInterval = setInterval(function() { + self.postMessage({ type: "tick" }); + }, 1000); + return; + } + + if (event.data && event.data.command === "stop") { + if (timerInterval) { + clearInterval(timerInterval); + timerInterval = null; + } + } + }; +`,i_=class{constructor(e){this.onTick=e;this.worker=null;this.workerUrl=null;this.fallbackInterval=null;this.running=!1}start(){if(!this.running){if(this.running=!0,this.canUseWorker()){this.startWorkerTicker();return}this.fallbackInterval=window.setInterval(this.onTick,1e3)}}stop(){!this.running&&!this.worker&&this.fallbackInterval===null||(this.running=!1,this.worker&&(this.worker.postMessage({command:"stop"}),this.worker.terminate(),this.worker=null),this.workerUrl&&(URL.revokeObjectURL(this.workerUrl),this.workerUrl=null),this.fallbackInterval!==null&&(window.clearInterval(this.fallbackInterval),this.fallbackInterval=null))}destroy(){this.stop()}canUseWorker(){return typeof Worker!="undefined"&&typeof Blob!="undefined"&&typeof URL!="undefined"&&typeof URL.createObjectURL=="function"}startWorkerTicker(){let e=new Blob([eYe],{type:"application/javascript"});this.workerUrl=URL.createObjectURL(e),this.worker=new Worker(this.workerUrl),this.worker.onmessage=t=>{var r;((r=t.data)==null?void 0:r.type)==="tick"&&this.onTick()},this.worker.postMessage({command:"start"})}}});var obe={};Xe(obe,{PomodoroService:()=>kE});function s_(n){return(0,sbe.moment)(n)}function o_(n){return n!==null&&typeof n=="object"&&typeof n.id=="string"}var sbe,yn,Dt,kE,lq=y(()=>{sbe=require("obsidian"),yn=tt(od());Pr();Oi();ya();xe();PW();abe();ibe();gR();hM();q();Dt=M({tag:"Services/PomodoroService"});kE=class{constructor(e){this.ticker=null;this.activeAudioContexts=new Set;this.cleanupTimeouts=new Set;this.lastSelectedTaskPathLoaded=!1;this.completionInProgress=!1;this.plugin=e,this.state={isRunning:!1,timeRemaining:e.settings.pomodoroWorkDuration*60}}translate(e,t){return this.plugin.i18n.translate(e,t)}async initialize(){await this.loadState(),this.setupTicker(),this.subscribeToTaskFileRenames(),this.state.isRunning&&this.state.currentSession&&this.resumeTimer()}subscribeToTaskFileRenames(){this.taskFileRenameUnsubscribe||(this.taskFileRenameUnsubscribe=this.plugin.cacheManager.subscribe("file-renamed",e=>{if(!e||typeof e!="object")return;let{oldPath:t,newPath:r}=e;typeof t!="string"||typeof r!="string"||this.handleTaskFileRenamed(t,r)}))}async handleTaskFileRenamed(e,t){var i;if(!e||!t||e===t)return;let r=!1,a=!1;((i=this.state.currentSession)==null?void 0:i.taskPath)===e&&(this.state.currentSession.taskPath=t,r=!0),this.lastWorkSessionTaskPath===e&&(this.lastWorkSessionTaskPath=t),this.lastSelectedTaskPath===e&&(this.lastSelectedTaskPath=t,this.lastSelectedTaskPathLoaded=!0,a=!0);try{let s=await this.plugin.loadPluginDataForSafeWrite("persist-pomodoro-task-path-file-rename");if(!s)return;let o=!1;r&&(s.pomodoroState=this.state,s.lastPomodoroDate=ae(Xt()),o=!0),(a||s.lastSelectedTaskPath===e)&&(this.lastSelectedTaskPath=t,this.lastSelectedTaskPathLoaded=!0,s.lastSelectedTaskPath=t,o=!0),o&&await this.plugin.saveData(s)}catch(s){Dt.error("Failed to persist Pomodoro task path after file rename:",{category:"persistence",operation:"persist-pomodoro-task-path-file-rename",error:s})}r&&this.plugin.emitter.trigger(ai,{timeRemaining:this.state.timeRemaining,session:this.state.currentSession})}setWebhookNotifier(e){this.webhookNotifier=e}setupTicker(){var e;(e=this.ticker)==null||e.destroy(),this.ticker=new i_(()=>this.handleTimerTick())}handleTimerTick(){if(!this.state.isRunning||!this.state.currentSession)return;this.syncRunningTimeRemaining()<=0&&!this.completionInProgress&&(this.completionInProgress=!0,this.completePomodoro().finally(()=>{this.completionInProgress=!1}))}async loadState(){try{let e=await this.plugin.loadData();if(e!=null&&e.pomodoroState){this.state=e.pomodoroState,this.state.timeRemaining=Math.max(0,this.state.timeRemaining||0);let t=ae(Xt());if(e.lastPomodoroDate!==t&&this.state.currentSession&&(this.state.currentSession=void 0,this.state.isRunning=!1,this.state.nextSessionType=void 0),this.state.currentSession){let a=new Date(this.state.currentSession.startTime).getTime();(Date.now()-a)/(1e3*60*60)>24&&(this.state.currentSession=void 0,this.state.isRunning=!1,this.state.timeRemaining=this.plugin.settings.pomodoroWorkDuration*60,this.state.nextSessionType=void 0)}this.state.currentSession||(this.state.timeRemaining=this.plugin.settings.pomodoroWorkDuration*60,this.state.nextSessionType=void 0)}}catch(e){Dt.error("Failed to load pomodoro state:",{category:"persistence",operation:"load-pomodoro-state",error:e}),this.state={isRunning:!1,timeRemaining:this.plugin.settings.pomodoroWorkDuration*60}}}async saveState(){try{let e=await this.plugin.loadPluginDataForSafeWrite("save-pomodoro-state");if(!e)return;let t=ae(Xt());if(!rbe(e,this.state,t))return;e.pomodoroState=this.state,e.lastPomodoroDate=t,await this.plugin.saveData(e)}catch(e){Dt.error("Failed to save pomodoro state:",{category:"persistence",operation:"save-pomodoro-state",error:e})}}async saveLastSelectedTask(e){this.lastSelectedTaskPath=e,this.lastSelectedTaskPathLoaded=!0;try{let t=await this.plugin.loadPluginDataForSafeWrite("save-last-selected-task");if(!t||!nbe(t,e))return;e===void 0?delete t.lastSelectedTaskPath:t.lastSelectedTaskPath=e,await this.plugin.saveData(t)}catch(t){Dt.error("Failed to save last selected task:",{category:"persistence",operation:"save-last-selected-task",error:t})}}async getLastSelectedTaskPath(){if(this.lastSelectedTaskPathLoaded)return this.lastSelectedTaskPath;try{let e=await this.plugin.loadData(),t=e==null?void 0:e.lastSelectedTaskPath;return typeof t=="string"&&t.trim().length>0?this.lastSelectedTaskPath=t:this.lastSelectedTaskPath=void 0,this.lastSelectedTaskPathLoaded=!0,this.lastSelectedTaskPath}catch(e){Dt.error("Failed to load last selected task:",{category:"persistence",operation:"load-last-selected-task",error:e});return}}async startPomodoro(e,t){var c;if(this.state.isRunning){ve(this.plugin.emitter,this.translate("services.pomodoro.notices.alreadyRunning"));return}if(this.state.currentSession&&!this.state.isRunning){ve(this.plugin.emitter,this.translate("services.pomodoro.notices.resumeCurrentSession"));return}let r=this.state.nextSessionType==="short-break"||this.state.nextSessionType==="long-break"?this.plugin.settings.pomodoroWorkDuration*60:this.state.timeRemaining,a=t!==void 0?t*60:void 0,i=Kp(a!=null?a:r),s=i/60,o=qe(),l={id:Date.now().toString(),taskPath:e==null?void 0:e.path,startTime:o,plannedDuration:s,type:"work",completed:!1,activePeriods:[{startTime:o}]};if(e!=null&&e.path&&(this.lastWorkSessionTaskPath=e.path,this.lastSelectedTaskPath=e.path,this.lastSelectedTaskPathLoaded=!0),this.state.currentSession=l,this.state.isRunning=!0,this.state.timeRemaining=i,this.state.nextSessionType=void 0,await this.saveState(),this.startTimer(),e)try{await this.plugin.taskService.startTimeTracking(e)}catch(d){(c=d.message)!=null&&c.includes("Time tracking is already active")||Dt.error("Failed to start time tracking for Pomodoro:",{category:"internal",operation:"start-time-tracking-pomodoro",error:d})}if(this.plugin.emitter.trigger(cd,{session:l,task:e}),this.webhookNotifier)try{await this.webhookNotifier.triggerWebhook("pomodoro.started",{session:l,task:e})}catch(d){Dt.warn("Failed to trigger webhook for pomodoro start:",{category:"provider",operation:"trigger-webhook-pomodoro-start",error:d})}this.showPomodoroNotification(`Pomodoro started${e?` for: ${e.title}`:""}`)}async startPomodoroWithLastSelectedTask(e){let t=await this.getAutoStartTask();await this.startPomodoro(t,e)}async startBreak(e=!1){if(this.state.isRunning){ve(this.plugin.emitter,this.translate("services.pomodoro.notices.timerAlreadyRunning"));return}if(this.state.currentSession&&!this.state.isRunning){ve(this.plugin.emitter,this.translate("services.pomodoro.notices.resumeSessionInstead"));return}let t=e?Math.max(1,Math.min(60,this.plugin.settings.pomodoroLongBreakDuration)):Math.max(1,Math.min(30,this.plugin.settings.pomodoroShortBreakDuration)),r=qe(),a={id:Date.now().toString(),startTime:r,plannedDuration:t,type:e?"long-break":"short-break",completed:!1,activePeriods:[{startTime:r}]};this.state.currentSession=a,this.state.isRunning=!0,this.state.timeRemaining=a.plannedDuration*60,this.state.nextSessionType=void 0,await this.saveState(),this.startTimer(),ve(this.plugin.emitter,this.translate(e?"services.pomodoro.notices.longBreakStarted":"services.pomodoro.notices.shortBreakStarted"))}async pausePomodoro(){if(!this.state.isRunning)return;this.syncRunningTimeRemaining(),this.stopTimer(),this.state.isRunning=!1;let e=qe();if(this.state.currentSession&&this.state.currentSession.activePeriods.length>0){let t=this.state.currentSession.activePeriods[this.state.currentSession.activePeriods.length-1];t.endTime||(t.endTime=e)}if(this.state.currentSession&&this.state.currentSession.taskPath)try{let t=await this.plugin.cacheManager.getTaskInfo(this.state.currentSession.taskPath);t&&await this.plugin.taskService.stopTimeTracking(t)}catch(t){Dt.error("Failed to stop time tracking for Pomodoro pause:",{category:"internal",operation:"stop-time-tracking-pomodoro-pause",error:t})}await this.saveState(),this.plugin.emitter.trigger(ai,{timeRemaining:this.state.timeRemaining,session:this.state.currentSession}),ve(this.plugin.emitter,this.translate("services.pomodoro.notices.paused"))}async resumePomodoro(){var e;if(!(this.state.isRunning||!this.state.currentSession)){if(this.state.isRunning=!0,this.state.currentSession&&this.state.currentSession.activePeriods.push({startTime:qe()}),await this.saveState(),this.startTimer(),this.state.currentSession&&this.state.currentSession.taskPath)try{let t=await this.plugin.cacheManager.getTaskInfo(this.state.currentSession.taskPath);t&&await this.plugin.taskService.startTimeTracking(t)}catch(t){(e=t.message)!=null&&e.includes("Time tracking is already active")||Dt.error("Failed to start time tracking for Pomodoro resume:",{category:"internal",operation:"start-time-tracking-pomodoro-resume",error:t})}this.plugin.emitter.trigger(ai,{timeRemaining:this.state.timeRemaining,session:this.state.currentSession}),ve(this.plugin.emitter,this.translate("services.pomodoro.notices.resumed"))}}async stopPomodoro(){if(!this.state.currentSession)return;let e=this.state.isRunning;e&&this.syncRunningTimeRemaining(),this.stopTimer();let t=qe();if(this.state.currentSession){if(this.state.currentSession.interrupted=!0,this.state.currentSession.endTime=t,this.state.currentSession.activePeriods.length>0){let r=this.state.currentSession.activePeriods[this.state.currentSession.activePeriods.length-1];r.endTime||(r.endTime=t)}await this.addSessionToHistory(this.state.currentSession)}if(this.plugin.emitter.trigger(ud,{session:this.state.currentSession}),this.webhookNotifier&&this.state.currentSession)try{let r=this.state.currentSession.taskPath?await this.plugin.cacheManager.getTaskInfo(this.state.currentSession.taskPath):void 0;await this.webhookNotifier.triggerWebhook("pomodoro.interrupted",{session:this.state.currentSession,task:r})}catch(r){Dt.warn("Failed to trigger webhook for pomodoro interruption:",{category:"provider",operation:"trigger-webhook-pomodoro-interruption",error:r})}if(this.state.currentSession&&this.state.currentSession.taskPath&&e)try{let r=await this.plugin.cacheManager.getTaskInfo(this.state.currentSession.taskPath);r&&await this.plugin.taskService.stopTimeTracking(r)}catch(r){Dt.error("Failed to stop time tracking for Pomodoro interrupt:",{category:"internal",operation:"stop-time-tracking-pomodoro-interrupt",error:r})}this.state.currentSession=void 0,this.state.isRunning=!1,this.state.timeRemaining=this.plugin.settings.pomodoroWorkDuration*60,this.state.nextSessionType=void 0,await this.saveState(),this.plugin.emitter.trigger(ai,{timeRemaining:this.state.timeRemaining,session:this.state.currentSession}),e&&ve(this.plugin.emitter,this.translate("services.pomodoro.notices.stoppedAndReset"))}async skipBreak(){this.state.currentSession||this.state.nextSessionType!=="short-break"&&this.state.nextSessionType!=="long-break"||(this.stopTimer(),this.state.isRunning=!1,this.state.currentSession=void 0,this.state.timeRemaining=this.plugin.settings.pomodoroWorkDuration*60,this.state.nextSessionType=void 0,await this.saveState(),this.plugin.emitter.trigger(ai,{timeRemaining:this.state.timeRemaining,session:this.state.currentSession}))}startTimer(){var e;this.ticker||this.setupTicker(),this.syncRunningTimeRemaining(),(e=this.ticker)==null||e.start()}stopTimer(){var e;(e=this.ticker)==null||e.stop()}resumeTimer(){if(this.state.currentSession&&this.state.currentSession.startTime){let e=new Date(this.state.currentSession.startTime).getTime(),t=Date.now();if(e>t){this.stopPomodoro();return}!this.state.isRunning&&this.state.timeRemaining>0?this.state.timeRemaining=Math.min(this.state.timeRemaining,Kp(this.state.currentSession.plannedDuration*60)):this.state.isRunning&&(this.state.timeRemaining=wk(this.state.currentSession,t)),this.state.timeRemaining>0&&this.state.isRunning?this.startTimer():this.state.timeRemaining<=0&&this.completePomodoro()}}syncRunningTimeRemaining(e=Date.now()){return this.state.currentSession?(this.state.isRunning&&(this.state.timeRemaining=wk(this.state.currentSession,e)),this.plugin.emitter.trigger(ai,{timeRemaining:this.state.timeRemaining,session:this.state.currentSession}),this.state.timeRemaining):this.state.timeRemaining}async autoStartWorkSession(){if(!this.state.isRunning)try{let e=await this.getAutoStartTask();e?await this.startPomodoro(e):await this.startPomodoro()}catch(e){Dt.error("Failed to auto-start work session:",{category:"internal",operation:"auto-start-work-session",error:e})}}async getAutoStartTask(){var a;let e=[];this.lastWorkSessionTaskPath&&e.push(this.lastWorkSessionTaskPath),(a=this.state.currentSession)!=null&&a.taskPath&&e.push(this.state.currentSession.taskPath);let t=await this.getLastSelectedTaskPath();t&&e.push(t);let r=Array.from(new Set(e.filter(i=>typeof i=="string"&&i.length>0)));for(let i of r)try{let s=await this.plugin.cacheManager.getTaskInfo(i);if(!s){this.clearCachedTaskPath(i);continue}let o=Wf(s,new Date,this.plugin.statusManager,this.plugin.settings.defaultTaskStatus);if(s.archived||o)continue;return s}catch(s){Dt.warn(`Failed to load task for auto-start (${i}):`,{category:"persistence",operation:"load-task-auto-start",error:s})}}clearCachedTaskPath(e){this.lastWorkSessionTaskPath===e&&(this.lastWorkSessionTaskPath=void 0),this.lastSelectedTaskPath===e&&(this.lastSelectedTaskPath=void 0,this.lastSelectedTaskPathLoaded=!0)}async completePomodoro(){if(this.stopTimer(),!this.state.currentSession)return;let e=this.state.currentSession,t=Aye(e),r=t!==null?Mye(t):qe();if(e.completed=!0,e.endTime=r,e.type==="work"&&e.taskPath&&(this.lastWorkSessionTaskPath=e.taskPath),e.activePeriods.length>0){let o=e.activePeriods[e.activePeriods.length-1];o.endTime||(o.endTime=r)}if(e.type==="work"&&this.state.isRunning&&e.taskPath)try{let o=await this.plugin.cacheManager.getTaskInfo(e.taskPath);o&&await this.plugin.taskService.stopTimeTracking(o)}catch(o){Dt.error("Failed to stop time tracking for Pomodoro completion:",{category:"internal",operation:"stop-time-tracking-pomodoro-completion",error:o})}let a=!1;if(e.type==="work")try{a=((await this.getTodayStats()).pomodorosCompleted+1)%this.plugin.settings.pomodoroLongBreakInterval===0}catch(o){Dt.error("Failed to calculate break type:",{category:"internal",operation:"calculate-break-type",error:o}),a=!1}if(await this.addSessionToHistory(e),this.plugin.emitter.trigger(dd,{session:e,nextType:e.type==="work"?a?"long-break":"short-break":"work"}),this.webhookNotifier)try{let o=e.taskPath?await this.plugin.cacheManager.getTaskInfo(e.taskPath):void 0;await this.webhookNotifier.triggerWebhook("pomodoro.completed",{session:e,task:o})}catch(o){Dt.warn("Failed to trigger webhook for pomodoro completion:",{category:"provider",operation:"trigger-webhook-pomodoro-completion",error:o})}let i=e.type==="work"?"🍅 Pomodoro completed!":"☕ Break completed!",s=e.type==="work"?`Time for a ${a?"long break 💤":"short break ☕"}`:"Ready for the next pomodoro?";if(this.showPomodoroNotification(i,{body:s}),this.plugin.settings.pomodoroSoundEnabled&&this.playCompletionSound(),this.state.currentSession=void 0,this.state.isRunning=!1,e.type==="work"){let o=a?this.plugin.settings.pomodoroLongBreakDuration:this.plugin.settings.pomodoroShortBreakDuration;if(this.state.timeRemaining=o*60,this.state.nextSessionType=a?"long-break":"short-break",this.plugin.settings.pomodoroAutoStartBreaks){let l=window.setTimeout(()=>{this.startBreak(a)},1e3);this.cleanupTimeouts.add(l)}}else if(this.state.timeRemaining=this.plugin.settings.pomodoroWorkDuration*60,this.state.nextSessionType="work",this.plugin.settings.pomodoroAutoStartWork){let o=window.setTimeout(()=>{this.autoStartWorkSession()},1e3);this.cleanupTimeouts.add(o)}await this.saveState(),this.plugin.emitter.trigger(ai,{timeRemaining:this.state.timeRemaining,session:this.state.currentSession})}playCompletionSound(){try{let e=new(window.AudioContext||window.webkitAudioContext),t=e.createOscillator(),r=e.createGain();t.connect(r),r.connect(e.destination);let a=Math.max(0,Math.min(1,this.plugin.settings.pomodoroSoundVolume/100));r.gain.value=a*.3,t.frequency.value=800,t.type="sine",t.start(),t.stop(e.currentTime+.1),this.activeAudioContexts.add(e);let i=window.setTimeout(()=>{try{let o=e.createOscillator();o.connect(r),o.frequency.value=1e3,o.type="sine",o.start(),o.stop(e.currentTime+.1)}catch(o){Dt.error("Failed to play second beep:",{category:"provider",operation:"play-second-beep",error:o})}},150);this.cleanupTimeouts.add(i);let s=window.setTimeout(()=>{this.activeAudioContexts.delete(e),e.close().catch(()=>{})},300);this.cleanupTimeouts.add(s)}catch(e){Dt.error("Failed to play completion sound:",{category:"provider",operation:"play-completion-sound",error:e})}}showPomodoroNotification(e,t){if(this.plugin.settings.pomodoroNotifications&&!(typeof Notification=="undefined"||Notification.permission!=="granted"))try{new Notification(e,t)}catch(r){Dt.warn("Failed to show Pomodoro notification:",{category:"provider",operation:"show-pomodoro-notification",error:r})}}getState(){return{...this.state}}adjustSessionTime(e){if(this.state.currentSession){let t=Kp(this.state.timeRemaining+e);this.setCurrentSessionRemainingTime(t)}}setCurrentSessionRemainingTime(e){if(!this.state.currentSession)return;let t=Date.now();this.state.isRunning&&(this.state.timeRemaining=wk(this.state.currentSession,t));let r=Kp(e),a=CW(this.state.currentSession,t);this.state.timeRemaining=r,this.state.currentSession.plannedDuration=(a+r)/60,this.saveState(),this.plugin.emitter.trigger(ai,{timeRemaining:this.state.timeRemaining,session:this.state.currentSession})}adjustPreparedTimer(e){this.state.currentSession||(this.stopTimer(),this.state.timeRemaining=Kp(e),this.saveState(),this.plugin.emitter.trigger(ai,{timeRemaining:this.state.timeRemaining,session:this.state.currentSession}))}isRunning(){return this.state.isRunning}getCurrentSession(){return this.state.currentSession}getTimeRemaining(){return this.state.timeRemaining}async getPomodorosCompleted(){return(await this.getTodayStats()).pomodorosCompleted}async getCurrentStreak(){return(await this.getTodayStats()).currentStreak}async getTotalMinutesToday(){return(await this.getTodayStats()).totalMinutes}async assignTaskToCurrentSession(e){var s;if(!this.state.currentSession)return;let t=this.state.currentSession,r=t.taskPath,a=e==null?void 0:e.path,i=this.state.isRunning&&t.type==="work"&&r!==a;if(i&&r)try{let o=await this.plugin.cacheManager.getTaskInfo(r);o&&await this.plugin.taskService.stopTimeTracking(o)}catch(o){Dt.error("Failed to stop time tracking for previous Pomodoro task:",{category:"persistence",operation:"stop-time-tracking-previous-pomodoro-task",error:o})}if(t.taskPath=a,a?(this.lastWorkSessionTaskPath=a,this.lastSelectedTaskPath=a,this.lastSelectedTaskPathLoaded=!0):(this.lastWorkSessionTaskPath=void 0,this.lastSelectedTaskPath=void 0,this.lastSelectedTaskPathLoaded=!0),await this.saveState(),i&&e)try{await this.plugin.taskService.startTimeTracking(e)}catch(o){(s=o.message)!=null&&s.includes("Time tracking is already active")||Dt.error("Failed to start time tracking for new Pomodoro task:",{category:"persistence",operation:"start-time-tracking-new-pomodoro-task",error:o})}this.plugin.emitter.trigger(ai,{timeRemaining:this.state.timeRemaining,session:t})}async getSessionHistory(){try{let e=await this.loadPluginHistory(),t;if(this.plugin.settings.pomodoroStorageLocation==="daily-notes"){let r=await this.loadHistoryFromDailyNotes();t=r,e.length>0&&(t=this.mergeHistories(e,r))}else t=e;return eE(t)}catch(e){return Dt.error("Failed to load session history:",{category:"persistence",operation:"load-session-history",error:e}),[]}}async getSessionsForDate(e){try{let t=ae(e);if(!t)return[];let r=await this.loadPluginHistoryForDateKey(t),a;if(this.plugin.settings.pomodoroStorageLocation==="daily-notes"){let i=await this.loadHistoryFromDailyNoteForDateKey(t);a=r.length>0?this.mergeHistories(r,i):i}else a=r;return eE(a)}catch(t){return Dt.error("Failed to load session history for date:",{category:"validation",operation:"load-session-history-date",error:t}),[]}}async getSessionsForDateRange(e,t){try{let r=await this.loadPluginHistoryForDateRange(e,t),a;if(this.plugin.settings.pomodoroStorageLocation==="daily-notes"){let i=await this.loadHistoryFromDailyNotesForDateRange(e,t);a=r.length>0?this.mergeHistories(r,i):i}else a=r;return eE(a)}catch(r){return Dt.error("Failed to load session history for date range:",{category:"validation",operation:"load-session-history-date-range",error:r}),[]}}async saveSessionHistory(e){try{this.plugin.settings.pomodoroStorageLocation==="daily-notes"?await this.saveHistoryToDailyNotes(e):await this.savePluginHistory(e)}catch(t){Dt.error("Failed to save session history:",{category:"persistence",operation:"save-session-history",error:t})}}async deleteSessionFromHistory(e){let t=!1;try{let r=await this.loadPluginHistory(),a=r.filter(i=>i.id!==e.id);a.length!==r.length&&(await this.savePluginHistory(a),t=!0),this.plugin.settings.pomodoroStorageLocation==="daily-notes"&&(t=await this.deleteSessionFromDailyNote(e)||t)}catch(r){Dt.error("Failed to delete pomodoro session:",{category:"persistence",operation:"delete-pomodoro-session",error:r})}return t}async addSessionToHistory(e){if(!e.endTime){Dt.warn("Cannot add session to history without end time",{category:"persistence",operation:"add-session-history-without-end-time"});return}let t={id:e.id,startTime:e.startTime,endTime:e.endTime,plannedDuration:e.plannedDuration,type:e.type,taskPath:e.taskPath,completed:e.completed&&!e.interrupted,activePeriods:e.activePeriods.slice()};try{if(this.plugin.settings.pomodoroStorageLocation==="daily-notes")await this.addSingleSessionToDailyNote(t);else{let r=await this.getSessionHistory();r.push(t),await this.saveSessionHistory(r)}}catch(r){Dt.error("Failed to add session to history:",{category:"persistence",operation:"add-session-history",error:r})}}async getStatsForDate(e){let t=await this.getSessionsForDate(e);return xk(t)}async getStatsForDateRange(e,t){let r=await this.getSessionsForDateRange(e,t);return xk(r)}async getOverallStats(){let e=await this.getSessionHistory();return xk(e)}async getTodayStats(){let e=Xt(),t=Br(e);return this.getStatsForDate(t)}cleanup(){var e,t;this.stopTimer(),(e=this.ticker)==null||e.destroy(),this.ticker=null,(t=this.taskFileRenameUnsubscribe)==null||t.call(this),this.taskFileRenameUnsubscribe=void 0;for(let r of this.cleanupTimeouts)window.clearTimeout(r);this.cleanupTimeouts.clear();for(let r of this.activeAudioContexts)r.state!=="closed"&&r.close().catch(()=>{});this.activeAudioContexts.clear(),this.saveState()}async loadPluginHistory(){let e=await this.plugin.loadData(),t=e==null?void 0:e.pomodoroHistory;return Array.isArray(t)?t:[]}async savePluginHistory(e){let t=await this.plugin.loadPluginDataForSafeWrite("save-pomodoro-history");t&&(t.pomodoroHistory=e,await this.plugin.saveData(t))}async loadPluginHistoryForDateKey(e){return zye(await this.loadPluginHistory(),e)}async loadPluginHistoryForDateRange(e,t){return Bye(await this.loadPluginHistory(),e,t)}async saveHistoryToDailyNotes(e){try{if(!(0,yn.appHasDailyNotesPluginLoaded)())throw new Error("Daily notes must be enabled in the core Daily Notes plugin or Periodic Notes");let t=this.groupSessionsByDate(e);for(let[r,a]of t)await this.updateDailyNotePomodoros(r,a)}catch(t){throw Dt.error("Failed to save history to daily notes:",{category:"persistence",operation:"save-history-daily-notes",error:t}),t}}async loadHistoryFromDailyNotesForDateRange(e,t){try{if(!(0,yn.appHasDailyNotesPluginLoaded)())return[];let r=(0,yn.getAllDailyNotes)(),a=[];for(let i of jye(e,t)){let s=await this.loadHistoryFromDailyNoteForDateKey(i,r);a.push(...s)}return a}catch(r){return Dt.error("Failed to load history from daily notes for date range:",{category:"validation",operation:"load-history-daily-notes-date-range",error:r}),[]}}async loadHistoryFromDailyNoteForDateKey(e,t){try{if(!e||!(0,yn.appHasDailyNotesPluginLoaded)())return[];let r=t!=null?t:(0,yn.getAllDailyNotes)(),a=et(e),i=s_(a),s=(0,yn.getDailyNote)(i,r);return s?this.readPomodoroSessionsFromDailyNote(s):[]}catch(r){return Dt.warn(`Failed to load pomodoro history for daily note ${e}:`,{category:"persistence",operation:"load-pomodoro-history-daily-note",error:r}),[]}}async loadHistoryFromDailyNotes(){try{if(!(0,yn.appHasDailyNotesPluginLoaded)())return[];let e=[],t=(0,yn.getAllDailyNotes)();for(let[,r]of Object.entries(t))try{e.push(...this.readPomodoroSessionsFromDailyNote(r))}catch(a){Dt.warn(`Failed to read pomodoro data from daily note ${r.path}:`,{category:"persistence",operation:"read-pomodoro-data-daily-note",error:a})}return e}catch(e){return Dt.error("Failed to load history from daily notes:",{category:"persistence",operation:"load-history-daily-notes",error:e}),[]}}readPomodoroSessionsFromDailyNote(e){let t=this.plugin.app.metadataCache.getFileCache(e),r=t==null?void 0:t.frontmatter,a=this.plugin.fieldMapper.toUserField("pomodoros"),i=r==null?void 0:r[a];return Array.isArray(i)?i.filter(o_):[]}groupSessionsByDate(e){let t=new Map;for(let r of e){let a=Ck(r);a&&(t.has(a)||t.set(a,[]),t.get(a).push(r))}return t}async addSingleSessionToDailyNote(e){try{let t=Ck(e);if(!t)throw new Error(`Invalid Pomodoro session start time: ${e.startTime}`);let r=et(t),a=s_(r),i=(0,yn.getAllDailyNotes)(),s=(0,yn.getDailyNote)(a,i);if(!s&&(s=await(0,yn.createDailyNote)(a),!s))throw new Error("Failed to create daily note. Please check your Daily Notes plugin configuration and ensure the daily notes folder exists.");let o=this.plugin.fieldMapper.toUserField("pomodoros");await yr(this.plugin.app,s,l=>{let c=Array.isArray(l[o])?l[o].filter(o_):[];new Set(c.map(u=>u.id)).has(e.id)||(l[o]=[...c,e])})}catch(t){Dt.error("Failed to add session to daily note:",{category:"persistence",operation:"add-session-daily-note",error:t})}}async deleteSessionFromDailyNote(e){try{if(!(0,yn.appHasDailyNotesPluginLoaded)())return!1;let t=Ck(e);if(!t)return!1;let r=et(t),a=s_(r),i=(0,yn.getDailyNote)(a,(0,yn.getAllDailyNotes)());if(!i)return!1;let s=this.plugin.fieldMapper.toUserField("pomodoros"),o=!1;return await yr(this.plugin.app,i,l=>{let c=Array.isArray(l[s])?l[s].filter(o_):[],d=c.filter(u=>u.id!==e.id);d.length!==c.length&&(l[s]=d,o=!0)}),o}catch(t){return Dt.error("Failed to delete pomodoro session from daily note:",{category:"persistence",operation:"delete-pomodoro-session-daily-note",error:t}),!1}}async updateDailyNotePomodoros(e,t){try{let r=et(e),a=s_(r),i=(0,yn.getAllDailyNotes)(),s=(0,yn.getDailyNote)(a,i);if(!s&&(s=await(0,yn.createDailyNote)(a),!s))throw new Error("Failed to create daily note. Please check your Daily Notes plugin configuration and ensure the daily notes folder exists.");let o=this.plugin.fieldMapper.toUserField("pomodoros");await yr(this.plugin.app,s,l=>{let c=Array.isArray(l[o])?l[o].filter(o_):[],d=new Set(c.map(p=>p.id)),u=t.filter(p=>!d.has(p.id));u.length>0&&(l[o]=[...c,...u])})}catch(r){Dt.error(`Failed to update daily note for ${e}:`,{category:"validation",operation:"update-daily-note",error:r})}}mergeHistories(e,t){let r=[...t],a=new Set(t.map(i=>i.id));for(let i of e)a.has(i.id)||r.push(i);return r}async migrateTodailyNotes(){try{if(!(0,yn.appHasDailyNotesPluginLoaded)())throw new Error("Daily notes must be enabled in the core Daily Notes plugin or Periodic Notes for migration");let e=await this.plugin.loadData();if(!e)return;let t=e.pomodoroHistory||[];if(t.length===0)return;await this.saveHistoryToDailyNotes(t),e.pomodoroHistory=[],await this.plugin.saveData(e),ve(this.plugin.emitter,this.translate("services.pomodoro.notices.migrationSuccess",{count:t.length}))}catch(e){throw Dt.error("Failed to migrate pomodoro data to daily notes:",{category:"persistence",operation:"migrate-pomodoro-data-daily-notes",error:e}),ve(this.plugin.emitter,this.translate("services.pomodoro.notices.migrationFailure")),e}}}});var tYe,l_,lbe=y(()=>{E2();q();Oi();ya();tYe=M({tag:"Services/AutoExportService"}),l_=class{constructor(e){this.scheduledExportId=null;this.lastExportTime=null;this.nextExportTime=null;this.isRunning=!1;this.plugin=e}translate(e,t){return this.plugin.i18n.translate(e,t)}start(){this.plugin.settings.icsIntegration.enableAutoExport&&(this.stop(),this.isRunning=!0,this.scheduleNextExport())}stop(){this.isRunning=!1,this.scheduledExportId!==null&&(window.clearTimeout(this.scheduledExportId),this.scheduledExportId=null),this.nextExportTime=null}updateInterval(e){this.plugin.settings.icsIntegration.enableAutoExport&&this.start()}async exportNow(){await this.performExport()}getLastExportTime(){return this.lastExportTime}getNextExportTime(){return this.nextExportTime}scheduleNextExport(){if(!this.isRunning||!this.plugin.settings.icsIntegration.enableAutoExport){this.nextExportTime=null;return}let t=this.plugin.settings.icsIntegration.autoExportInterval*60*1e3;this.nextExportTime=new Date(Date.now()+t),this.scheduledExportId=window.setTimeout(()=>{this.scheduledExportId=null,this.performExport().finally(()=>{this.isRunning&&this.scheduleNextExport()})},t)}async performExport(){var e,t,r,a;try{let i=this.plugin.settings.icsIntegration.autoExportPath||"tasknotes-calendar.ics",s=await this.plugin.cacheManager.getAllTasks();if(s.length===0)return;let o={useDurationForExport:this.plugin.settings.icsIntegration.useDurationForExport,excludeArchived:(e=this.plugin.settings.icsIntegration.excludeArchivedFromExport)!=null?e:!1,excludeCompleted:(t=this.plugin.settings.icsIntegration.excludeCompletedFromExport)!=null?t:!1,completedStatuses:this.plugin.statusManager.getCompletedStatuses(),requireDueDate:(r=this.plugin.settings.icsIntegration.requireDueDateForExport)!=null?r:!1,requireScheduledDate:(a=this.plugin.settings.icsIntegration.requireScheduledDateForExport)!=null?a:!1,includeObsidianLink:!0,vaultName:this.plugin.app.vault.getName()},l=yp.generateMultipleTasksICSContent(s,o),c=i;await this.plugin.app.vault.adapter.exists(c)?await this.plugin.app.vault.adapter.write(c,l):await mf(this.plugin.app,c,l),this.lastExportTime=new Date}catch(i){tYe.error("TaskNotes: Auto export failed:",{category:"provider",operation:"auto-export",error:i}),(!this.lastExportTime||Date.now()-this.lastExportTime.getTime()>360*60*1e3)&&ve(this.plugin.emitter,this.translate("services.autoExport.notices.exportFailed",{error:i instanceof Error?i.message:String(i)}))}}destroy(){this.stop()}}});function nYe(n){var e,t;return(t=(e=n.updatedTask)!=null?e:n.taskInfo)!=null?t:n.task}function c_(n){if(n===void 0)return null;if(Array.isArray(n))return n.map(e=>c_(e));if(n&&typeof n=="object"){let e=n;return Object.keys(e).sort().reduce((t,r)=>(t[r]=c_(e[r]),t),{})}return n}function aYe(n,e){return JSON.stringify(c_(n))===JSON.stringify(c_(e))}function iYe(n,e){var t;return(t=rYe.find(r=>!aYe(n[r],e[r])))!=null?t:null}var dbe,cbe,rYe,d_,ube=y(()=>{dbe=require("obsidian");Pr();q();cbe=M({tag:"Services/TaskFileLifecycleReconciliationService"}),rYe=["status","title","scheduled","due","priority","recurrence","occurrence_materialization","complete_instances","skipped_instances","timeEstimate","tags","contexts","projects"];d_=class{constructor(e){this.plugin=e;this.taskSnapshots=new Map;this.taskUpdatedRef=null;this.handlingPaths=new Set}async initialize(){await this.captureCurrentTasks(),this.taskUpdatedRef=this.plugin.emitter.on(rt,e=>{this.handleTaskUpdatedEvent(e)})}destroy(){this.taskUpdatedRef&&(this.plugin.emitter.offref(this.taskUpdatedRef),this.taskUpdatedRef=null),this.handlingPaths.clear(),this.taskSnapshots.clear()}async handleTaskUpdatedEvent(e){var o;let t=nYe(e),r=(o=e.path)!=null?o:t==null?void 0:t.path;if(!r||!t)return;if(e.originalTask){e.originalTask.path!==r&&this.taskSnapshots.delete(e.originalTask.path),this.taskSnapshots.set(r,t);return}let a=this.taskSnapshots.get(r);if(this.taskSnapshots.set(r,t),!a||this.handlingPaths.has(r))return;let i=iYe(a,t);if(!i)return;let s=this.plugin.app.vault.getAbstractFileByPath(r);if(s instanceof dbe.TFile){this.handlingPaths.add(r);try{await this.plugin.taskService.applyPropertyChangeSideEffects(s,a,t,i,a[i],t[i])}catch(l){cbe.warn("Failed to reconcile direct task file edit:",{category:"persistence",operation:"reconcile-direct-task-file-edit",details:{taskPath:r,property:i},error:l})}finally{this.handlingPaths.delete(r)}}}async captureCurrentTasks(){try{let e=await this.plugin.cacheManager.getAllTasks();for(let t of e)this.taskSnapshots.set(t.path,t)}catch(e){cbe.warn("Failed to snapshot tasks for direct file edit reconciliation:",{category:"stale-data",operation:"snapshot-direct-task-file-reconciliation",error:e})}}}});var Pt,cq,ge,Rc,TE=y(()=>{(function(n){n.assertEqual=a=>{};function e(a){}n.assertIs=e;function t(a){throw new Error}n.assertNever=t,n.arrayToEnum=a=>{let i={};for(let s of a)i[s]=s;return i},n.getValidEnumValues=a=>{let i=n.objectKeys(a).filter(o=>typeof a[a[o]]!="number"),s={};for(let o of i)s[o]=a[o];return n.objectValues(s)},n.objectValues=a=>n.objectKeys(a).map(function(i){return a[i]}),n.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{let i=[];for(let s in a)Object.prototype.hasOwnProperty.call(a,s)&&i.push(s);return i},n.find=(a,i)=>{for(let s of a)if(i(s))return s},n.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function r(a,i=" | "){return a.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}n.joinValues=r,n.jsonStringifyReplacer=(a,i)=>typeof i=="bigint"?i.toString():i})(Pt||(Pt={}));(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(cq||(cq={}));ge=Pt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Rc=n=>{switch(typeof n){case"undefined":return ge.undefined;case"string":return ge.string;case"number":return Number.isNaN(n)?ge.nan:ge.number;case"boolean":return ge.boolean;case"function":return ge.function;case"bigint":return ge.bigint;case"symbol":return ge.symbol;case"object":return Array.isArray(n)?ge.array:n===null?ge.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?ge.promise:typeof Map!="undefined"&&n instanceof Map?ge.map:typeof Set!="undefined"&&n instanceof Set?ge.set:typeof Date!="undefined"&&n instanceof Date?ge.date:ge.object;default:return ge.unknown}}});var J,sYe,Zi,u_=y(()=>{TE();J=Pt.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),sYe=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),Zi=class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},r={_errors:[]},a=i=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(a);else if(s.code==="invalid_return_type")a(s.returnTypeError);else if(s.code==="invalid_arguments")a(s.argumentsError);else if(s.path.length===0)r._errors.push(t(s));else{let o=r,l=0;for(;lt.message){let t={},r=[];for(let a of this.issues)if(a.path.length>0){let i=a.path[0];t[i]=t[i]||[],t[i].push(e(a))}else r.push(e(a));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};Zi.create=n=>new Zi(n)});var oYe,du,dq=y(()=>{u_();TE();oYe=(n,e)=>{let t;switch(n.code){case J.invalid_type:n.received===ge.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case J.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,Pt.jsonStringifyReplacer)}`;break;case J.unrecognized_keys:t=`Unrecognized key(s) in object: ${Pt.joinValues(n.keys,", ")}`;break;case J.invalid_union:t="Invalid input";break;case J.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Pt.joinValues(n.options)}`;break;case J.invalid_enum_value:t=`Invalid enum value. Expected ${Pt.joinValues(n.options)}, received '${n.received}'`;break;case J.invalid_arguments:t="Invalid function arguments";break;case J.invalid_return_type:t="Invalid function return type";break;case J.invalid_date:t="Invalid date";break;case J.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:Pt.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case J.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case J.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case J.custom:t="Invalid input";break;case J.invalid_intersection_types:t="Intersection results could not be merged";break;case J.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case J.not_finite:t="Number must be finite";break;default:t=e.defaultError,Pt.assertNever(n)}return{message:t}},du=oYe});function lYe(n){pbe=n}function Hk(){return pbe}var pbe,p_=y(()=>{dq();pbe=du});function ue(n,e){let t=Hk(),r=bE({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===du?void 0:du].filter(a=>!!a)});n.common.issues.push(r)}var bE,cYe,Sa,Ye,Bh,Ga,m_,f_,lm,Vk,uq=y(()=>{p_();dq();bE=n=>{let{data:e,path:t,errorMaps:r,issueData:a}=n,i=[...t,...a.path||[]],s={...a,path:i};if(a.message!==void 0)return{...a,path:i,message:a.message};let o="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)o=c(s,{data:e,defaultError:o}).message;return{...a,path:i,message:o}},cYe=[];Sa=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let a of t){if(a.status==="aborted")return Ye;a.status==="dirty"&&e.dirty(),r.push(a.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let a of t){let i=await a.key,s=await a.value;r.push({key:i,value:s})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let a of t){let{key:i,value:s}=a;if(i.status==="aborted"||s.status==="aborted")return Ye;i.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof s.value!="undefined"||a.alwaysSet)&&(r[i.value]=s.value)}return{status:e.value,value:r}}},Ye=Object.freeze({status:"aborted"}),Bh=n=>({status:"dirty",value:n}),Ga=n=>({status:"valid",value:n}),m_=n=>n.status==="aborted",f_=n=>n.status==="dirty",lm=n=>n.status==="valid",Vk=n=>typeof Promise!="undefined"&&n instanceof Promise});var mbe=y(()=>{});var Ne,fbe=y(()=>{(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(Ne||(Ne={}))});function ut(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:a}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:a}:{errorMap:(s,o)=>{var c,d;let{message:l}=n;return s.code==="invalid_enum_value"?{message:l!=null?l:o.defaultError}:typeof o.data=="undefined"?{message:(c=l!=null?l:r)!=null?c:o.defaultError}:s.code!=="invalid_type"?{message:o.defaultError}:{message:(d=l!=null?l:t)!=null?d:o.defaultError}},description:a}}function vbe(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function EYe(n){return new RegExp(`^${vbe(n)}$`)}function kbe(n){let e=`${ybe}T${vbe(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function DYe(n,e){return!!((e==="v4"||!e)&&kYe.test(n)||(e==="v6"||!e)&&bYe.test(n))}function PYe(n,e){if(!hYe.test(n))return!1;try{let[t]=n.split(".");if(!t)return!1;let r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),a=JSON.parse(atob(r));return!(typeof a!="object"||a===null||"typ"in a&&(a==null?void 0:a.typ)!=="JWT"||!a.alg||e&&a.alg!==e)}catch(t){return!1}}function AYe(n,e){return!!((e==="v4"||!e)&&TYe.test(n)||(e==="v6"||!e)&&wYe.test(n))}function MYe(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,a=t>r?t:r,i=Number.parseInt(n.toFixed(a).replace(".","")),s=Number.parseInt(e.toFixed(a).replace(".",""));return i%s/10**a}function Wk(n){if(n instanceof Ji){let e={};for(let t in n.shape){let r=n.shape[t];e[t]=Qi.create(Wk(r))}return new Ji({...n._def,shape:()=>e})}else return n instanceof mu?new mu({...n._def,type:Wk(n.element)}):n instanceof Qi?Qi.create(Wk(n.unwrap())):n instanceof Fc?Fc.create(Wk(n.unwrap())):n instanceof _c?_c.create(n.items.map(e=>Wk(e))):n}function mq(n,e){let t=Rc(n),r=Rc(e);if(n===e)return{valid:!0,data:n};if(t===ge.object&&r===ge.object){let a=Pt.objectKeys(e),i=Pt.objectKeys(n).filter(o=>a.indexOf(o)!==-1),s={...n,...e};for(let o of i){let l=mq(n[o],e[o]);if(!l.valid)return{valid:!1};s[o]=l.data}return{valid:!0,data:s}}else if(t===ge.array&&r===ge.array){if(n.length!==e.length)return{valid:!1};let a=[];for(let i=0;i{var s,o;let i=n(r);if(i instanceof Promise)return i.then(l=>{var c,d;if(!l){let u=gbe(e,r),p=(d=(c=u.fatal)!=null?c:t)!=null?d:!0;a.addIssue({code:"custom",...u,fatal:p})}});if(!i){let l=gbe(e,r),c=(o=(s=l.fatal)!=null?s:t)!=null?o:!0;a.addIssue({code:"custom",...l,fatal:c})}}):dm.create()}var Po,hbe,ft,dYe,uYe,pYe,mYe,fYe,hYe,gYe,yYe,vYe,pq,kYe,TYe,bYe,wYe,SYe,CYe,ybe,xYe,cm,jh,$h,Uh,Hh,qk,Vh,Wh,dm,pu,vl,Gk,mu,Ji,qh,uu,h_,Gh,_c,g_,Yk,Kk,y_,Yh,Kh,Zh,Qh,um,Ao,Qi,Fc,Jh,Xh,Zk,IYe,wE,SE,eg,NYe,ee,RYe,wbe,Sbe,_Ye,FYe,Cbe,LYe,OYe,zYe,BYe,jYe,$Ye,UYe,HYe,VYe,fq,WYe,qYe,GYe,YYe,KYe,ZYe,QYe,JYe,XYe,e8e,t8e,r8e,n8e,a8e,i8e,s8e,o8e,l8e,c8e,d8e,u8e,p8e,m8e,f8e,xbe=y(()=>{u_();p_();fbe();uq();TE();Po=class{constructor(e,t,r,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},hbe=(n,e)=>{if(lm(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new Zi(n.common.issues);return this._error=t,this._error}}};ft=class{get description(){return this._def.description}_getType(e){return Rc(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Rc(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Sa,ctx:{common:e.parent.common,data:e.data,parsedType:Rc(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Vk(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var i;let r={common:{issues:[],async:(i=t==null?void 0:t.async)!=null?i:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rc(e)},a=this._parseSync({data:e,path:r.path,parent:r});return hbe(r,a)}"~validate"(e){var r,a;let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rc(e)};if(!this["~standard"].async)try{let i=this._parseSync({data:e,path:[],parent:t});return lm(i)?{value:i.value}:{issues:t.common.issues}}catch(i){(a=(r=i==null?void 0:i.message)==null?void 0:r.toLowerCase())!=null&&a.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>lm(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rc(e)},a=this._parse({data:e,path:r.path,parent:r}),i=await(Vk(a)?a:Promise.resolve(a));return hbe(r,i)}refine(e,t){let r=a=>typeof t=="string"||typeof t=="undefined"?{message:t}:typeof t=="function"?t(a):t;return this._refinement((a,i)=>{let s=e(a),o=()=>i.addIssue({code:J.custom,...r(a)});return typeof Promise!="undefined"&&s instanceof Promise?s.then(l=>l?!0:(o(),!1)):s?!0:(o(),!1)})}refinement(e,t){return this._refinement((r,a)=>e(r)?!0:(a.addIssue(typeof t=="function"?t(r,a):t),!1))}_refinement(e){return new Ao({schema:this,typeName:ee.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Qi.create(this,this._def)}nullable(){return Fc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return mu.create(this)}promise(){return um.create(this,this._def)}or(e){return qh.create([this,e],this._def)}and(e){return Gh.create(this,e,this._def)}transform(e){return new Ao({...ut(this._def),schema:this,typeName:ee.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Jh({...ut(this._def),innerType:this,defaultValue:t,typeName:ee.ZodDefault})}brand(){return new wE({typeName:ee.ZodBranded,type:this,...ut(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Xh({...ut(this._def),innerType:this,catchValue:t,typeName:ee.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return SE.create(this,e)}readonly(){return eg.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},dYe=/^c[^\s-]{8,}$/i,uYe=/^[0-9a-z]+$/,pYe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,mYe=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,fYe=/^[a-z0-9_-]{21}$/i,hYe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,gYe=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,yYe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,vYe="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",kYe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,TYe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,bYe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,wYe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,SYe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,CYe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ybe="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",xYe=new RegExp(`^${ybe}$`);cm=class n extends ft{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ge.string){let i=this._getOrReturnCtx(e);return ue(i,{code:J.invalid_type,expected:ge.string,received:i.parsedType}),Ye}let r=new Sa,a;for(let i of this._def.checks)if(i.kind==="min")e.data.lengthi.value&&(a=this._getOrReturnCtx(e,a),ue(a,{code:J.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let s=e.data.length>i.value,o=e.data.lengthe.test(a),{validation:t,code:J.invalid_string,...Ne.errToObj(r)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Ne.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Ne.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Ne.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Ne.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Ne.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Ne.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Ne.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Ne.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Ne.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Ne.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Ne.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Ne.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Ne.errToObj(e)})}datetime(e){var t,r;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)=="undefined"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!=null?t:!1,local:(r=e==null?void 0:e.local)!=null?r:!1,...Ne.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)=="undefined"?null:e==null?void 0:e.precision,...Ne.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...Ne.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...Ne.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...Ne.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...Ne.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...Ne.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...Ne.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...Ne.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...Ne.errToObj(t)})}nonempty(e){return this.min(1,Ne.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new cm({checks:[],typeName:ee.ZodString,coerce:(e=n==null?void 0:n.coerce)!=null?e:!1,...ut(n)})};jh=class n extends ft{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ge.number){let i=this._getOrReturnCtx(e);return ue(i,{code:J.invalid_type,expected:ge.number,received:i.parsedType}),Ye}let r,a=new Sa;for(let i of this._def.checks)i.kind==="int"?Pt.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),ue(r,{code:J.invalid_type,expected:"integer",received:"float",message:i.message}),a.dirty()):i.kind==="min"?(i.inclusive?e.datai.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),ue(r,{code:J.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),a.dirty()):i.kind==="multipleOf"?MYe(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),ue(r,{code:J.not_multiple_of,multipleOf:i.value,message:i.message}),a.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),ue(r,{code:J.not_finite,message:i.message}),a.dirty()):Pt.assertNever(i);return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,Ne.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Ne.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Ne.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Ne.toString(t))}setLimit(e,t,r,a){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Ne.toString(a)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Ne.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Ne.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:Ne.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.valuee.kind==="int"||e.kind==="multipleOf"&&Pt.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.valuenew jh({checks:[],typeName:ee.ZodNumber,coerce:(n==null?void 0:n.coerce)||!1,...ut(n)});$h=class n extends ft{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch(i){return this._getInvalidInput(e)}if(this._getType(e)!==ge.bigint)return this._getInvalidInput(e);let r,a=new Sa;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.datai.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),ue(r,{code:J.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),a.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),ue(r,{code:J.not_multiple_of,multipleOf:i.value,message:i.message}),a.dirty()):Pt.assertNever(i);return{status:a.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return ue(t,{code:J.invalid_type,expected:ge.bigint,received:t.parsedType}),Ye}gte(e,t){return this.setLimit("min",e,!0,Ne.toString(t))}gt(e,t){return this.setLimit("min",e,!1,Ne.toString(t))}lte(e,t){return this.setLimit("max",e,!0,Ne.toString(t))}lt(e,t){return this.setLimit("max",e,!1,Ne.toString(t))}setLimit(e,t,r,a){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:Ne.toString(a)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:Ne.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new $h({checks:[],typeName:ee.ZodBigInt,coerce:(e=n==null?void 0:n.coerce)!=null?e:!1,...ut(n)})};Uh=class extends ft{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ge.boolean){let r=this._getOrReturnCtx(e);return ue(r,{code:J.invalid_type,expected:ge.boolean,received:r.parsedType}),Ye}return Ga(e.data)}};Uh.create=n=>new Uh({typeName:ee.ZodBoolean,coerce:(n==null?void 0:n.coerce)||!1,...ut(n)});Hh=class n extends ft{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ge.date){let i=this._getOrReturnCtx(e);return ue(i,{code:J.invalid_type,expected:ge.date,received:i.parsedType}),Ye}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return ue(i,{code:J.invalid_date}),Ye}let r=new Sa,a;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()i.value&&(a=this._getOrReturnCtx(e,a),ue(a,{code:J.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):Pt.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:Ne.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:Ne.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.valuenew Hh({checks:[],coerce:(n==null?void 0:n.coerce)||!1,typeName:ee.ZodDate,...ut(n)});qk=class extends ft{_parse(e){if(this._getType(e)!==ge.symbol){let r=this._getOrReturnCtx(e);return ue(r,{code:J.invalid_type,expected:ge.symbol,received:r.parsedType}),Ye}return Ga(e.data)}};qk.create=n=>new qk({typeName:ee.ZodSymbol,...ut(n)});Vh=class extends ft{_parse(e){if(this._getType(e)!==ge.undefined){let r=this._getOrReturnCtx(e);return ue(r,{code:J.invalid_type,expected:ge.undefined,received:r.parsedType}),Ye}return Ga(e.data)}};Vh.create=n=>new Vh({typeName:ee.ZodUndefined,...ut(n)});Wh=class extends ft{_parse(e){if(this._getType(e)!==ge.null){let r=this._getOrReturnCtx(e);return ue(r,{code:J.invalid_type,expected:ge.null,received:r.parsedType}),Ye}return Ga(e.data)}};Wh.create=n=>new Wh({typeName:ee.ZodNull,...ut(n)});dm=class extends ft{constructor(){super(...arguments),this._any=!0}_parse(e){return Ga(e.data)}};dm.create=n=>new dm({typeName:ee.ZodAny,...ut(n)});pu=class extends ft{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ga(e.data)}};pu.create=n=>new pu({typeName:ee.ZodUnknown,...ut(n)});vl=class extends ft{_parse(e){let t=this._getOrReturnCtx(e);return ue(t,{code:J.invalid_type,expected:ge.never,received:t.parsedType}),Ye}};vl.create=n=>new vl({typeName:ee.ZodNever,...ut(n)});Gk=class extends ft{_parse(e){if(this._getType(e)!==ge.undefined){let r=this._getOrReturnCtx(e);return ue(r,{code:J.invalid_type,expected:ge.void,received:r.parsedType}),Ye}return Ga(e.data)}};Gk.create=n=>new Gk({typeName:ee.ZodVoid,...ut(n)});mu=class n extends ft{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),a=this._def;if(t.parsedType!==ge.array)return ue(t,{code:J.invalid_type,expected:ge.array,received:t.parsedType}),Ye;if(a.exactLength!==null){let s=t.data.length>a.exactLength.value,o=t.data.lengtha.maxLength.value&&(ue(t,{code:J.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((s,o)=>a.type._parseAsync(new Po(t,s,t.path,o)))).then(s=>Sa.mergeArray(r,s));let i=[...t.data].map((s,o)=>a.type._parseSync(new Po(t,s,t.path,o)));return Sa.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:Ne.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:Ne.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:Ne.toString(t)}})}nonempty(e){return this.min(1,e)}};mu.create=(n,e)=>new mu({type:n,minLength:null,maxLength:null,exactLength:null,typeName:ee.ZodArray,...ut(e)});Ji=class n extends ft{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=Pt.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==ge.object){let c=this._getOrReturnCtx(e);return ue(c,{code:J.invalid_type,expected:ge.object,received:c.parsedType}),Ye}let{status:r,ctx:a}=this._processInputParams(e),{shape:i,keys:s}=this._getCached(),o=[];if(!(this._def.catchall instanceof vl&&this._def.unknownKeys==="strip"))for(let c in a.data)s.includes(c)||o.push(c);let l=[];for(let c of s){let d=i[c],u=a.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new Po(a,u,a.path,c)),alwaysSet:c in a.data})}if(this._def.catchall instanceof vl){let c=this._def.unknownKeys;if(c==="passthrough")for(let d of o)l.push({key:{status:"valid",value:d},value:{status:"valid",value:a.data[d]}});else if(c==="strict")o.length>0&&(ue(a,{code:J.unrecognized_keys,keys:o}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let d of o){let u=a.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new Po(a,u,a.path,d)),alwaysSet:d in a.data})}}return a.common.async?Promise.resolve().then(async()=>{let c=[];for(let d of l){let u=await d.key,p=await d.value;c.push({key:u,value:p,alwaysSet:d.alwaysSet})}return c}).then(c=>Sa.mergeObjectSync(r,c)):Sa.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return Ne.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{var i,s,o,l;let a=(o=(s=(i=this._def).errorMap)==null?void 0:s.call(i,t,r).message)!=null?o:r.defaultError;return t.code==="unrecognized_keys"?{message:(l=Ne.errToObj(e).message)!=null?l:a}:{message:a}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ee.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};for(let r of Pt.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}omit(e){let t={};for(let r of Pt.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}deepPartial(){return Wk(this)}partial(e){let t={};for(let r of Pt.objectKeys(this.shape)){let a=this.shape[r];e&&!e[r]?t[r]=a:t[r]=a.optional()}return new n({...this._def,shape:()=>t})}required(e){let t={};for(let r of Pt.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Qi;)i=i._def.innerType;t[r]=i}return new n({...this._def,shape:()=>t})}keyof(){return Tbe(Pt.objectKeys(this.shape))}};Ji.create=(n,e)=>new Ji({shape:()=>n,unknownKeys:"strip",catchall:vl.create(),typeName:ee.ZodObject,...ut(e)});Ji.strictCreate=(n,e)=>new Ji({shape:()=>n,unknownKeys:"strict",catchall:vl.create(),typeName:ee.ZodObject,...ut(e)});Ji.lazycreate=(n,e)=>new Ji({shape:n,unknownKeys:"strip",catchall:vl.create(),typeName:ee.ZodObject,...ut(e)});qh=class extends ft{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function a(i){for(let o of i)if(o.result.status==="valid")return o.result;for(let o of i)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let s=i.map(o=>new Zi(o.ctx.common.issues));return ue(t,{code:J.invalid_union,unionErrors:s}),Ye}if(t.common.async)return Promise.all(r.map(async i=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(a);{let i,s=[];for(let l of r){let c={...t,common:{...t.common,issues:[]},parent:null},d=l._parseSync({data:t.data,path:t.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let o=s.map(l=>new Zi(l));return ue(t,{code:J.invalid_union,unionErrors:o}),Ye}}get options(){return this._def.options}};qh.create=(n,e)=>new qh({options:n,typeName:ee.ZodUnion,...ut(e)});uu=n=>n instanceof Yh?uu(n.schema):n instanceof Ao?uu(n.innerType()):n instanceof Kh?[n.value]:n instanceof Zh?n.options:n instanceof Qh?Pt.objectValues(n.enum):n instanceof Jh?uu(n._def.innerType):n instanceof Vh?[void 0]:n instanceof Wh?[null]:n instanceof Qi?[void 0,...uu(n.unwrap())]:n instanceof Fc?[null,...uu(n.unwrap())]:n instanceof wE||n instanceof eg?uu(n.unwrap()):n instanceof Xh?uu(n._def.innerType):[],h_=class n extends ft{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ge.object)return ue(t,{code:J.invalid_type,expected:ge.object,received:t.parsedType}),Ye;let r=this.discriminator,a=t.data[r],i=this.optionsMap.get(a);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(ue(t,{code:J.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ye)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let a=new Map;for(let i of t){let s=uu(i.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of s){if(a.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);a.set(o,i)}}return new n({typeName:ee.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...ut(r)})}};Gh=class extends ft{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),a=(i,s)=>{if(m_(i)||m_(s))return Ye;let o=mq(i.value,s.value);return o.valid?((f_(i)||f_(s))&&t.dirty(),{status:t.value,value:o.data}):(ue(r,{code:J.invalid_intersection_types}),Ye)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,s])=>a(i,s)):a(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Gh.create=(n,e,t)=>new Gh({left:n,right:e,typeName:ee.ZodIntersection,...ut(t)});_c=class n extends ft{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.array)return ue(r,{code:J.invalid_type,expected:ge.array,received:r.parsedType}),Ye;if(r.data.lengththis._def.items.length&&(ue(r,{code:J.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((s,o)=>{let l=this._def.items[o]||this._def.rest;return l?l._parse(new Po(r,s,r.path,o)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>Sa.mergeArray(t,s)):Sa.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};_c.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _c({items:n,typeName:ee.ZodTuple,rest:null,...ut(e)})};g_=class n extends ft{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.object)return ue(r,{code:J.invalid_type,expected:ge.object,received:r.parsedType}),Ye;let a=[],i=this._def.keyType,s=this._def.valueType;for(let o in r.data)a.push({key:i._parse(new Po(r,o,r.path,o)),value:s._parse(new Po(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?Sa.mergeObjectAsync(t,a):Sa.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof ft?new n({keyType:e,valueType:t,typeName:ee.ZodRecord,...ut(r)}):new n({keyType:cm.create(),valueType:e,typeName:ee.ZodRecord,...ut(t)})}},Yk=class extends ft{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.map)return ue(r,{code:J.invalid_type,expected:ge.map,received:r.parsedType}),Ye;let a=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([o,l],c)=>({key:a._parse(new Po(r,o,r.path,[c,"key"])),value:i._parse(new Po(r,l,r.path,[c,"value"]))}));if(r.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let l of s){let c=await l.key,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return Ye;(c.status==="dirty"||d.status==="dirty")&&t.dirty(),o.set(c.value,d.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let l of s){let c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return Ye;(c.status==="dirty"||d.status==="dirty")&&t.dirty(),o.set(c.value,d.value)}return{status:t.value,value:o}}}};Yk.create=(n,e,t)=>new Yk({valueType:e,keyType:n,typeName:ee.ZodMap,...ut(t)});Kk=class n extends ft{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.set)return ue(r,{code:J.invalid_type,expected:ge.set,received:r.parsedType}),Ye;let a=this._def;a.minSize!==null&&r.data.sizea.maxSize.value&&(ue(r,{code:J.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());let i=this._def.valueType;function s(l){let c=new Set;for(let d of l){if(d.status==="aborted")return Ye;d.status==="dirty"&&t.dirty(),c.add(d.value)}return{status:t.value,value:c}}let o=[...r.data.values()].map((l,c)=>i._parse(new Po(r,l,r.path,c)));return r.common.async?Promise.all(o).then(l=>s(l)):s(o)}min(e,t){return new n({...this._def,minSize:{value:e,message:Ne.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:Ne.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Kk.create=(n,e)=>new Kk({valueType:n,minSize:null,maxSize:null,typeName:ee.ZodSet,...ut(e)});y_=class n extends ft{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ge.function)return ue(t,{code:J.invalid_type,expected:ge.function,received:t.parsedType}),Ye;function r(o,l){return bE({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Hk(),du].filter(c=>!!c),issueData:{code:J.invalid_arguments,argumentsError:l}})}function a(o,l){return bE({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Hk(),du].filter(c=>!!c),issueData:{code:J.invalid_return_type,returnTypeError:l}})}let i={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof um){let o=this;return Ga(async function(...l){let c=new Zi([]),d=await o._def.args.parseAsync(l,i).catch(m=>{throw c.addIssue(r(l,m)),c}),u=await Reflect.apply(s,this,d);return await o._def.returns._def.type.parseAsync(u,i).catch(m=>{throw c.addIssue(a(u,m)),c})})}else{let o=this;return Ga(function(...l){let c=o._def.args.safeParse(l,i);if(!c.success)throw new Zi([r(l,c.error)]);let d=Reflect.apply(s,this,c.data),u=o._def.returns.safeParse(d,i);if(!u.success)throw new Zi([a(d,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:_c.create(e).rest(pu.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new n({args:e||_c.create([]).rest(pu.create()),returns:t||pu.create(),typeName:ee.ZodFunction,...ut(r)})}},Yh=class extends ft{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Yh.create=(n,e)=>new Yh({getter:n,typeName:ee.ZodLazy,...ut(e)});Kh=class extends ft{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return ue(t,{received:t.data,code:J.invalid_literal,expected:this._def.value}),Ye}return{status:"valid",value:e.data}}get value(){return this._def.value}};Kh.create=(n,e)=>new Kh({value:n,typeName:ee.ZodLiteral,...ut(e)});Zh=class n extends ft{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return ue(t,{expected:Pt.joinValues(r),received:t.parsedType,code:J.invalid_type}),Ye}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return ue(t,{received:t.data,code:J.invalid_enum_value,options:r}),Ye}return Ga(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};Zh.create=Tbe;Qh=class extends ft{_parse(e){let t=Pt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ge.string&&r.parsedType!==ge.number){let a=Pt.objectValues(t);return ue(r,{expected:Pt.joinValues(a),received:r.parsedType,code:J.invalid_type}),Ye}if(this._cache||(this._cache=new Set(Pt.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let a=Pt.objectValues(t);return ue(r,{received:r.data,code:J.invalid_enum_value,options:a}),Ye}return Ga(e.data)}get enum(){return this._def.values}};Qh.create=(n,e)=>new Qh({values:n,typeName:ee.ZodNativeEnum,...ut(e)});um=class extends ft{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==ge.promise&&t.common.async===!1)return ue(t,{code:J.invalid_type,expected:ge.promise,received:t.parsedType}),Ye;let r=t.parsedType===ge.promise?t.data:Promise.resolve(t.data);return Ga(r.then(a=>this._def.type.parseAsync(a,{path:t.path,errorMap:t.common.contextualErrorMap})))}};um.create=(n,e)=>new um({type:n,typeName:ee.ZodPromise,...ut(e)});Ao=class extends ft{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ee.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),a=this._def.effect||null,i={addIssue:s=>{ue(r,s),s.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),a.type==="preprocess"){let s=a.transform(r.data,i);if(r.common.async)return Promise.resolve(s).then(async o=>{if(t.value==="aborted")return Ye;let l=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return l.status==="aborted"?Ye:l.status==="dirty"?Bh(l.value):t.value==="dirty"?Bh(l.value):l});{if(t.value==="aborted")return Ye;let o=this._def.schema._parseSync({data:s,path:r.path,parent:r});return o.status==="aborted"?Ye:o.status==="dirty"?Bh(o.value):t.value==="dirty"?Bh(o.value):o}}if(a.type==="refinement"){let s=o=>{let l=a.refinement(o,i);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ye:(o.status==="dirty"&&t.dirty(),s(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?Ye:(o.status==="dirty"&&t.dirty(),s(o.value).then(()=>({status:t.value,value:o.value}))))}if(a.type==="transform")if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!lm(s))return Ye;let o=a.transform(s.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>lm(s)?Promise.resolve(a.transform(s.value,i)).then(o=>({status:t.value,value:o})):Ye);Pt.assertNever(a)}};Ao.create=(n,e,t)=>new Ao({schema:n,typeName:ee.ZodEffects,effect:e,...ut(t)});Ao.createWithPreprocess=(n,e,t)=>new Ao({schema:e,effect:{type:"preprocess",transform:n},typeName:ee.ZodEffects,...ut(t)});Qi=class extends ft{_parse(e){return this._getType(e)===ge.undefined?Ga(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Qi.create=(n,e)=>new Qi({innerType:n,typeName:ee.ZodOptional,...ut(e)});Fc=class extends ft{_parse(e){return this._getType(e)===ge.null?Ga(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Fc.create=(n,e)=>new Fc({innerType:n,typeName:ee.ZodNullable,...ut(e)});Jh=class extends ft{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===ge.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Jh.create=(n,e)=>new Jh({innerType:n,typeName:ee.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ut(e)});Xh=class extends ft{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Vk(a)?a.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Zi(r.common.issues)},input:r.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Zi(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Xh.create=(n,e)=>new Xh({innerType:n,typeName:ee.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ut(e)});Zk=class extends ft{_parse(e){if(this._getType(e)!==ge.nan){let r=this._getOrReturnCtx(e);return ue(r,{code:J.invalid_type,expected:ge.nan,received:r.parsedType}),Ye}return{status:"valid",value:e.data}}};Zk.create=n=>new Zk({typeName:ee.ZodNaN,...ut(n)});IYe=Symbol("zod_brand"),wE=class extends ft{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},SE=class n extends ft{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ye:i.status==="dirty"?(t.dirty(),Bh(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let a=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?Ye:a.status==="dirty"?(t.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:r.path,parent:r})}}static create(e,t){return new n({in:e,out:t,typeName:ee.ZodPipeline})}},eg=class extends ft{_parse(e){let t=this._def.innerType._parse(e),r=a=>(lm(a)&&(a.value=Object.freeze(a.value)),a);return Vk(t)?t.then(a=>r(a)):r(t)}unwrap(){return this._def.innerType}};eg.create=(n,e)=>new eg({innerType:n,typeName:ee.ZodReadonly,...ut(e)});NYe={object:Ji.lazycreate};(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(ee||(ee={}));RYe=(n,e={message:`Input not instance of ${n.name}`})=>bbe(t=>t instanceof n,e),wbe=cm.create,Sbe=jh.create,_Ye=Zk.create,FYe=$h.create,Cbe=Uh.create,LYe=Hh.create,OYe=qk.create,zYe=Vh.create,BYe=Wh.create,jYe=dm.create,$Ye=pu.create,UYe=vl.create,HYe=Gk.create,VYe=mu.create,fq=Ji.create,WYe=Ji.strictCreate,qYe=qh.create,GYe=h_.create,YYe=Gh.create,KYe=_c.create,ZYe=g_.create,QYe=Yk.create,JYe=Kk.create,XYe=y_.create,e8e=Yh.create,t8e=Kh.create,r8e=Zh.create,n8e=Qh.create,a8e=um.create,i8e=Ao.create,s8e=Qi.create,o8e=Fc.create,l8e=Ao.createWithPreprocess,c8e=SE.create,d8e=()=>wbe().optional(),u8e=()=>Sbe().optional(),p8e=()=>Cbe().optional(),m8e={string:(n=>cm.create({...n,coerce:!0})),number:(n=>jh.create({...n,coerce:!0})),boolean:(n=>Uh.create({...n,coerce:!0})),bigint:(n=>$h.create({...n,coerce:!0})),date:(n=>Hh.create({...n,coerce:!0}))},f8e=Ye});var N={};Xe(N,{BRAND:()=>IYe,DIRTY:()=>Bh,EMPTY_PATH:()=>cYe,INVALID:()=>Ye,NEVER:()=>f8e,OK:()=>Ga,ParseStatus:()=>Sa,Schema:()=>ft,ZodAny:()=>dm,ZodArray:()=>mu,ZodBigInt:()=>$h,ZodBoolean:()=>Uh,ZodBranded:()=>wE,ZodCatch:()=>Xh,ZodDate:()=>Hh,ZodDefault:()=>Jh,ZodDiscriminatedUnion:()=>h_,ZodEffects:()=>Ao,ZodEnum:()=>Zh,ZodError:()=>Zi,ZodFirstPartyTypeKind:()=>ee,ZodFunction:()=>y_,ZodIntersection:()=>Gh,ZodIssueCode:()=>J,ZodLazy:()=>Yh,ZodLiteral:()=>Kh,ZodMap:()=>Yk,ZodNaN:()=>Zk,ZodNativeEnum:()=>Qh,ZodNever:()=>vl,ZodNull:()=>Wh,ZodNullable:()=>Fc,ZodNumber:()=>jh,ZodObject:()=>Ji,ZodOptional:()=>Qi,ZodParsedType:()=>ge,ZodPipeline:()=>SE,ZodPromise:()=>um,ZodReadonly:()=>eg,ZodRecord:()=>g_,ZodSchema:()=>ft,ZodSet:()=>Kk,ZodString:()=>cm,ZodSymbol:()=>qk,ZodTransformer:()=>Ao,ZodTuple:()=>_c,ZodType:()=>ft,ZodUndefined:()=>Vh,ZodUnion:()=>qh,ZodUnknown:()=>pu,ZodVoid:()=>Gk,addIssueToContext:()=>ue,any:()=>jYe,array:()=>VYe,bigint:()=>FYe,boolean:()=>Cbe,coerce:()=>m8e,custom:()=>bbe,date:()=>LYe,datetimeRegex:()=>kbe,defaultErrorMap:()=>du,discriminatedUnion:()=>GYe,effect:()=>i8e,enum:()=>r8e,function:()=>XYe,getErrorMap:()=>Hk,getParsedType:()=>Rc,instanceof:()=>RYe,intersection:()=>YYe,isAborted:()=>m_,isAsync:()=>Vk,isDirty:()=>f_,isValid:()=>lm,late:()=>NYe,lazy:()=>e8e,literal:()=>t8e,makeIssue:()=>bE,map:()=>QYe,nan:()=>_Ye,nativeEnum:()=>n8e,never:()=>UYe,null:()=>BYe,nullable:()=>o8e,number:()=>Sbe,object:()=>fq,objectUtil:()=>cq,oboolean:()=>p8e,onumber:()=>u8e,optional:()=>s8e,ostring:()=>d8e,pipeline:()=>c8e,preprocess:()=>l8e,promise:()=>a8e,quotelessJson:()=>sYe,record:()=>ZYe,set:()=>JYe,setErrorMap:()=>lYe,strictObject:()=>WYe,string:()=>wbe,symbol:()=>OYe,transformer:()=>i8e,tuple:()=>KYe,undefined:()=>zYe,union:()=>qYe,unknown:()=>$Ye,util:()=>Pt,void:()=>HYe});var v_=y(()=>{p_();uq();mbe();TE();xbe();u_()});var k_=y(()=>{v_();v_()});function Mbe(n={}){return{...fu,...n,fieldMapping:{...Abe,...n.fieldMapping},statuses:n.statuses?n.statuses.map(e=>({...e})):fu.statuses.map(e=>({...e})),priorities:n.priorities?n.priorities.map(e=>({...e})):fu.priorities.map(e=>({...e})),defaults:{...fu.defaults,...n.defaults},taskIdentification:{...fu.taskIdentification,...n.taskIdentification},userFields:n.userFields?n.userFields.map(e=>({...e})):[],recurrence:{...fu.recurrence,...n.recurrence},occurrences:{...fu.occurrences,...n.occurrences},timeTracking:{...fu.timeTracking,...n.timeTracking},nlp:n.nlp?{triggers:n.nlp.triggers.map(e=>({...e}))}:void 0}}function Ebe(n,e=fu.statuses){return n?e.some(t=>t.value===n&&t.isCompleted):!1}function Ibe(n){let e=T8e(n),t=e.match(yq);if(t){let[,a,i,s]=t,o=Number(a),l=Number(i),c=Number(s);if(!Nbe(o,l,c))throw new Error(`Invalid date "${n}".`);return new Date(Date.UTC(o,l-1,c,0,0,0,0))}if(!b8e(e))throw new Error(`Invalid date "${n}".`);let r=new Date(e);if(!Rbe(r))throw new Error(`Invalid date "${n}".`);return r}function v8e(n){if(!Rbe(n))return"";let e=n.getUTCFullYear(),t=String(n.getUTCMonth()+1).padStart(2,"0"),r=String(n.getUTCDate()).padStart(2,"0");return`${e}-${t}-${r}`}function hq(n){if(!/^\d{4}-\d{2}-\d{2}$/.test(n))throw new Error(`Invalid date "${n}". Expected YYYY-MM-DD.`);return Ibe(n),n}function k8e(n){if(!n)return"";let e=n.trim();if(yq.test(e))return e;let t=e.indexOf("T");if(t>-1)return e.slice(0,t);let r=e.indexOf(" ");return r>-1&&yq.test(e.slice(0,r))?e.slice(0,r):v8e(Ibe(e))}function T8e(n,e="Date string cannot be empty"){if(!n||n.trim().length===0)throw new Error(e);return n.trim()}function b8e(n){let e=n.match(y8e);if(!e)return!1;let[,t,r,a,i,s,o,,l,c,d]=e;return Nbe(Number(t),Number(r),Number(a))&&w8e(Number(i),Number(s),Number(o))&&S8e(l,c,d)}function Nbe(n,e,t){let r=new Date(Date.UTC(n,e-1,t,0,0,0,0));return r.getUTCFullYear()===n&&r.getUTCMonth()===e-1&&r.getUTCDate()===t}function w8e(n,e,t){return n>=0&&n<=23&&e>=0&&e<=59&&t>=0&&t<=59}function S8e(n,e,t){if(!n)return!0;let r=Number(e),a=Number(t);return!(r>14||a>59||r===14&&a!==0)}function Rbe(n){return n instanceof Date&&!Number.isNaN(n.getTime())}function C8e(n,e=""){var c;let t=n.trim(),r="path",a=t.match(/^\[\[([^|\]#]+)(?:#[^|\]]*)?(?:\|[^\]]*)?\]\]$/);if(a)r="wikilink",t=a[1].trim();else{let d=t.match(/^\[[^\]]*\]\(([^)#]+)(?:#[^)]*)?\)$/);d&&(r="markdown",t=d[1].trim())}try{t=decodeURI(t)}catch(d){return}if(t=t.replace(/\\/g,"/"),!t||/^[A-Za-z][A-Za-z\d+.-]*:/.test(t))return;let i=t.startsWith("/")||r==="wikilink"&&!t.startsWith("./")&&!t.startsWith("../"),s=e.replace(/\\/g,"/").split("/").filter(Boolean);s.length>0&&s.pop();let o=i?[]:s;for(let d of t.replace(/^\/+/,"").split("/"))if(!(!d||d===".")){if(d===".."){if(o.length===0)return;o.pop();continue}if(d.includes("\0")||d.includes("[")||d.includes("]"))return;o.push(d)}if(o.length===0)return;let l=(c=o[o.length-1])!=null?c:"";if(/^.+\.[^.]+$/.test(l))return o.join("/")}function x8e(n,e=""){let t=[],r=new Set;for(let[a,i]of(n!=null?n:[]).entries()){let s=C8e(i,e);if(!s){t.push({code:"invalid_attachment_reference",message:"Attachment references must identify a collection file using an explicit extension",index:a,reference:i});continue}if(r.has(s)){t.push({code:"duplicate_attachment_reference",message:`Attachment target is listed more than once: ${s}`,index:a,reference:i});continue}r.add(s)}return{valid:t.length===0,issues:t}}function vq(n){let e=[],t=Fbe.partial().safeParse(n);if(!t.success)for(let r of t.error.issues)e.push({code:"schema_invalid",message:r.message,severity:"error",path:r.path.map(String)});for(let r of["due","scheduled","completedDate","dateCreated","dateModified"]){let a=n[r];if(a!==void 0&&typeof a=="string")try{hq(k8e(a))}catch(i){e.push({code:"invalid_date",message:`${r} must contain a valid date`,severity:"error",field:r})}}if(n.complete_instances)for(let r of n.complete_instances)try{hq(r)}catch(a){e.push({code:"invalid_complete_instance",message:`Invalid completed recurrence instance "${r}"`,severity:"warning",field:"complete_instances"})}if(n.skipped_instances)for(let r of n.skipped_instances)try{hq(r)}catch(a){e.push({code:"invalid_skipped_instance",message:`Invalid skipped recurrence instance "${r}"`,severity:"warning",field:"skipped_instances"})}n.timeEntries&&e.push(...A8e(n.timeEntries).issues);for(let r of x8e(n.attachments,n.path).issues)e.push({code:r.code,message:r.message,severity:"error",path:["attachments",String(r.index)],field:"attachments"});return{valid:!e.some(r=>r.severity==="error"),issues:e}}function A8e(n){let e=[];return Array.isArray(n)?(n.forEach((r,a)=>{let i=_be.safeParse(r);if(!i.success){for(let s of i.error.issues)e.push({code:"invalid_time_entry",message:s.message,severity:"error",path:["timeEntries",String(a),...s.path.map(String)]});return}M8e(i.data,a,e)}),n.filter(r=>r&&!r.endTime).length>1&&e.push({code:"multiple_active_time_entries",message:"Only one active time entry is allowed",severity:"warning",field:"timeEntries"}),{valid:!e.some(r=>r.severity==="error"),issues:e}):{valid:!1,issues:[{code:"time_entries_not_array",message:"timeEntries must be an array",severity:"error",field:"timeEntries"}]}}function Lbe(n,e){let t=vq(n);for(let r of["title","status","dateCreated","dateModified"]){let a=n[r];(typeof a!="string"||a.trim().length===0)&&t.issues.push({code:"missing_required",message:`${r} is required`,severity:"error",field:r})}if(n.status&&!e.some(r=>r.value===n.status)&&t.issues.push({code:"invalid_status",message:`Unknown status "${n.status}"`,severity:"error",field:"status"}),n.completedDate!==void 0&&!/^\d{4}-\d{2}-\d{2}$/.test(n.completedDate)&&t.issues.push({code:"invalid_date_value",message:"completedDate must be a YYYY-MM-DD date",severity:"error",field:"completedDate"}),n.status&&Ebe(n.status,e)&&!n.recurrence&&!n.completedDate&&t.issues.push({code:"missing_required",message:"completedDate is required for a completed non-recurring task",severity:"error",field:"completedDate"}),n.dateCreated&&n.dateModified){let r=Date.parse(n.dateCreated),a=Date.parse(n.dateModified);Number.isFinite(r)&&Number.isFinite(a)&&ar.severity==="error"),issues:t.issues}}function M8e(n,e,t){let r=new Date(n.startTime);if(Number.isNaN(r.getTime())){t.push({code:"invalid_time_entry_start",message:"Time entry startTime must be a valid datetime",severity:"error",path:["timeEntries",String(e),"startTime"]});return}if(!n.endTime)return;let a=new Date(n.endTime);if(Number.isNaN(a.getTime())){t.push({code:"invalid_time_entry_end",message:"Time entry endTime must be a valid datetime",severity:"error",path:["timeEntries",String(e),"endTime"]});return}a{k_();ny();cx();cx();Pbe="0.3.0-rc.3",Abe={title:"title",status:"status",priority:"priority",due:"due",scheduled:"scheduled",contexts:"contexts",projects:"projects",attachments:"attachments",timeEstimate:"timeEstimate",completedDate:"completedDate",dateCreated:"dateCreated",dateModified:"dateModified",recurrence:"recurrence",recurrenceAnchor:"recurrence_anchor",recurrenceParent:"recurrence_parent",occurrenceDate:"occurrence_date",occurrenceMaterialization:"occurrence_materialization",occurrenceNextTrigger:"occurrence_next_trigger",occurrenceTemplate:"occurrence_template",occurrencePastHorizon:"occurrence_past_horizon",occurrenceFutureHorizon:"occurrence_future_horizon",archiveTag:"archived",timeEntries:"timeEntries",completeInstances:"complete_instances",skippedInstances:"skipped_instances",blockedBy:"blockedBy",pomodoros:"pomodoros",icsEventId:"icsEventId",icsEventTag:"ics_event",googleCalendarEventId:"googleCalendarEventId",googleCalendarExceptionEventId:"googleCalendarExceptionEventId",googleCalendarExceptionOriginalScheduled:"googleCalendarExceptionOriginalScheduled",googleCalendarMovedOriginalDates:"googleCalendarMovedOriginalDates",reminders:"reminders",sortOrder:"tasknotes_manual_order"},h8e=[{id:"none",value:"none",label:"None",color:"#cccccc",isCompleted:!1,excludeFromCycle:!1,order:0,autoArchive:!1,autoArchiveDelay:5},{id:"open",value:"open",label:"Open",color:"#808080",isCompleted:!1,excludeFromCycle:!1,order:1,autoArchive:!1,autoArchiveDelay:5},{id:"in-progress",value:"in-progress",label:"In progress",color:"#0066cc",isCompleted:!1,excludeFromCycle:!1,order:2,autoArchive:!1,autoArchiveDelay:5},{id:"done",value:"done",label:"Done",color:"#00aa00",isCompleted:!0,excludeFromCycle:!1,order:3,autoArchive:!1,autoArchiveDelay:5}],g8e=[{id:"none",value:"none",label:"None",color:"#cccccc",weight:0},{id:"low",value:"low",label:"Low",color:"#00aa00",weight:1},{id:"normal",value:"normal",label:"Normal",color:"#ffaa00",weight:2},{id:"high",value:"high",label:"High",color:"#ff0000",weight:3}],fu={fieldMapping:Abe,statuses:h8e,priorities:g8e,defaults:{status:"open",priority:"normal",taskTag:"task"},taskIdentification:{method:"tag",tag:"task",propertyName:"isTask",propertyValue:"true"},storeTitleInFilename:!1,userFields:[],recurrence:{maintainDueDateOffset:!0,resetCheckboxesOnRecurrence:!1},occurrences:{defaultMaterialization:"manual",defaultNextTrigger:"completion",pastHorizon:"P0D",futureHorizon:"P14D"},timeTracking:{autoStopOnComplete:!1,autoStopNotification:!0,defaultSessionDescription:"Work session"}};yq=/^(\d{4})-(\d{2})-(\d{2})$/,y8e=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{1,3})?(?:Z|([+-])(\d{2}):(\d{2}))?$/;E8e=N.enum(["FINISHTOSTART","FINISHTOFINISH","STARTTOSTART","STARTTOFINISH"]),D8e=N.object({uid:N.string().min(1),reltype:E8e,gap:N.string().optional()}),_be=N.object({startTime:N.string().min(1),endTime:N.string().min(1).optional(),description:N.string().optional(),duration:N.number().optional()}),P8e=N.object({id:N.string().min(1),type:N.enum(["absolute","relative"]),relatedTo:N.enum(["due","scheduled"]).optional(),offset:N.string().optional(),absoluteTime:N.string().optional(),description:N.string().optional()}),btr=N.object({id:N.string().min(1),value:N.string().min(1),label:N.string().min(1),color:N.string().min(1),icon:N.string().optional(),isCompleted:N.boolean(),isSkipped:N.boolean().optional(),excludeFromCycle:N.boolean().optional(),nextStatus:N.string().optional(),order:N.number(),autoArchive:N.boolean(),autoArchiveDelay:N.number()}),wtr=N.object({id:N.string().min(1),value:N.string().min(1),label:N.string().min(1),color:N.string().min(1),icon:N.string().optional(),weight:N.number()}),Fbe=N.object({id:N.string().optional(),title:N.string(),status:N.string(),priority:N.string(),due:N.string().optional(),scheduled:N.string().optional(),path:N.string(),archived:N.boolean(),tags:N.array(N.string()).optional(),contexts:N.array(N.string()).optional(),projects:N.array(N.string()).optional(),attachments:N.array(N.string().min(1)).optional(),recurrence:N.string().optional(),recurrence_anchor:N.enum(["scheduled","completion"]).optional(),complete_instances:N.array(N.string()).optional(),skipped_instances:N.array(N.string()).optional(),recurrence_parent:N.string().optional(),occurrence_date:N.string().optional(),occurrence_materialization:N.enum(["manual","on_completion","rolling"]).optional(),occurrence_next_trigger:N.enum(["completion","completion_or_skip"]).optional(),occurrence_template:N.string().optional(),occurrence_past_horizon:N.string().optional(),occurrence_future_horizon:N.string().optional(),completedDate:N.string().optional(),timeEstimate:N.number().optional(),timeEntries:N.array(_be).optional(),totalTrackedTime:N.number().optional(),dateCreated:N.string().optional(),dateModified:N.string().optional(),icsEventId:N.array(N.string()).optional(),googleCalendarEventId:N.string().optional(),googleCalendarExceptionEventId:N.string().optional(),googleCalendarExceptionOriginalScheduled:N.string().optional(),googleCalendarMovedOriginalDates:N.array(N.string()).optional(),reminders:N.array(P8e).optional(),customProperties:N.record(N.unknown()).optional(),basesData:N.unknown().optional(),blockedBy:N.array(D8e).optional(),blocking:N.array(N.string()).optional(),isBlocked:N.boolean().optional(),isBlocking:N.boolean().optional(),hasSubtasks:N.boolean().optional(),details:N.string().optional(),sortOrder:N.string().optional()}),Str=N.object({frontmatter:N.record(N.unknown()),body:N.string(),task:Fbe.partial(),path:N.string().optional()}),gq=Reflect.get(Uu,"default"),Ctr=(Dbe=ye)!=null?Dbe:gq==null?void 0:gq.RRule});function I8e(n){return!n||n.length===0?0:n.reduce((e,t)=>{if(t.endTime){let r=new Date(t.endTime).getTime()-new Date(t.startTime).getTime();return e+Math.floor(r/(1e3*60))}else{let r=Date.now()-new Date(t.startTime).getTime();return e+Math.floor(r/(1e3*60))}},0)}function Qk(n,e){let t=[];for(let r of n){let a=e(r);if(a){let i=new Date(a.startTime),s=Math.floor((Date.now()-i.getTime())/(1e3*60));t.push({task:{id:r.path,title:r.title,status:r.status,priority:r.priority,tags:r.tags||[],projects:r.projects||[]},session:{startTime:a.startTime,description:a.description,elapsedMinutes:s},elapsedMinutes:s})}}return{activeSessions:t,totalActiveSessions:t.length,totalElapsedMinutes:t.reduce((r,a)=>r+a.elapsedMinutes,0)}}function N8e(n){let e,t=new Date;switch(n.period){case"today":e=new Date,e.setHours(0,0,0,0);break;case"week":e=new Date,e.setDate(e.getDate()-e.getDay()),e.setHours(0,0,0,0);break;case"month":e=new Date,e.setDate(1),e.setHours(0,0,0,0);break;case"all":e=new Date(0);break;default:n.fromDate?(e=n.fromDate,n.toDate&&(t=n.toDate)):(e=new Date,e.setHours(0,0,0,0))}return{startDate:e,endDate:t}}function Jk(n,e,t){let{startDate:r,endDate:a}=N8e(e),i=0,s=0,o=0,l=[],c=new Map,d=e.includeTags?new Map:null;for(let m of n){if(!m.timeEntries||m.timeEntries.length===0)continue;let f=0,h=!1;for(let g of m.timeEntries){let v=new Date(g.startTime);if(v>=r&&v<=a)if(!g.endTime)f+=Math.floor((Date.now()-v.getTime())/(1e3*60)),h=!0;else{let k=new Date(g.endTime);f+=Math.floor((k.getTime()-v.getTime())/(1e3*60))}}if(f>0){if(i+=f,l.push({task:m.path,title:m.title,minutes:f}),h?o++:t(m.status)&&s++,m.projects)for(let g of m.projects)c.set(g,(c.get(g)||0)+f);if(d&&m.tags)for(let g of m.tags)d.set(g,(d.get(g)||0)+f)}}l.sort((m,f)=>f.minutes-m.minutes);let u=Array.from(c.entries()).sort((m,f)=>f[1]-m[1]).slice(0,10).map(([m,f])=>({project:m,minutes:f})),p={period:e.period,dateRange:{from:r.toISOString(),to:a.toISOString()},summary:{totalMinutes:i,totalHours:Math.round(i/60*100)/100,tasksWithTime:l.length,activeTasks:o,completedTasks:s},topTasks:l.slice(0,10),topProjects:u};return d&&(p.topTags=Array.from(d.entries()).sort((m,f)=>f[1]-m[1]).slice(0,10).map(([m,f])=>({tag:m,minutes:f}))),p}function pm(n,e){let t=n.timeEntries||[],r=e(n),a=I8e(t),i=t.filter(l=>l.endTime).length,s=t.filter(l=>l.endTime),o=s.length>0?Math.round(s.reduce((l,c)=>l+Math.floor((new Date(c.endTime).getTime()-new Date(c.startTime).getTime())/(1e3*60)),0)/s.length*100)/100:0;return{task:{id:n.path,title:n.title,status:n.status,priority:n.priority},summary:{totalMinutes:a,totalHours:Math.round(a/60*100)/100,totalSessions:t.length,completedSessions:i,activeSessions:r?1:0,averageSessionMinutes:o},activeSession:r?{startTime:r.startTime,description:r.description,elapsedMinutes:Math.floor((Date.now()-new Date(r.startTime).getTime())/(1e3*60))}:null,timeEntries:t.map(l=>({startTime:l.startTime,endTime:l.endTime||null,description:l.description||null,duration:l.endTime?Math.floor((new Date(l.endTime).getTime()-new Date(l.startTime).getTime())/(1e3*60)):Math.floor((Date.now()-new Date(l.startTime).getTime())/(1e3*60)),isActive:!l.endTime}))}}var CE=y(()=>{});function kq(n){if(!n||typeof n!="object")return!1;let e=n;return e.name==="TaskNotesApiError"&&typeof e.message=="string"&&typeof e.status=="number"&&typeof e.code=="string"&&R8e.includes(e.code)}function $be(n){return n instanceof Hr||kq(n)}var zbe,Bbe,Lc,jbe,R8e,Hr,Ube,xE=y(()=>{zbe=["model.read","model.validate","catalog.read","extensions.read","extensions.register","tasks.read","tasks.write","tasks.delete","tasks.move","tasks.events","relationships.read","events.list","time.read","time.write","time.summary","pomodoro.read","pomodoro.write","pomodoro.events","recurring.write","recurring.materialize","recurring.events","settings.snapshot","bases.write","nlp.parse","ui.task-menu","query.tasks","query.validate","query.explain","query.filter-options","stats.tasks","system.health","lifecycle.events","errors.typed"],Bbe=[{name:"task.created",label:"Task created",description:"A TaskNotes task was created.",category:"task"},{name:"task.updated",label:"Task updated",description:"Any tracked TaskNotes task property changed.",category:"task"},{name:"task.deleted",label:"Task deleted",description:"A TaskNotes task was deleted.",category:"task"},{name:"task.moved",label:"Task moved",description:"A TaskNotes task note moved to a new path.",category:"task"},{name:"task.status.changed",label:"Task status changed",description:"A TaskNotes task status changed.",category:"task"},{name:"task.completed",label:"Task completed",description:"A TaskNotes task moved into a completed status.",category:"task"},{name:"task.uncompleted",label:"Task uncompleted",description:"A TaskNotes task moved out of a completed status.",category:"task"},{name:"task.archived",label:"Task archived",description:"A TaskNotes task was archived.",category:"task"},{name:"task.unarchived",label:"Task unarchived",description:"A TaskNotes task was unarchived.",category:"task"},{name:"task.scheduled.changed",label:"Task scheduled date changed",description:"A TaskNotes task scheduled date changed.",category:"task"},{name:"task.due.changed",label:"Task due date changed",description:"A TaskNotes task due date changed.",category:"task"},{name:"task.priority.changed",label:"Task priority changed",description:"A TaskNotes task priority changed.",category:"task"},{name:"task.tags.changed",label:"Task tags changed",description:"A TaskNotes task tag list changed.",category:"task"},{name:"task.contexts.changed",label:"Task contexts changed",description:"A TaskNotes task context list changed.",category:"task"},{name:"task.projects.changed",label:"Task projects changed",description:"A TaskNotes task project list changed.",category:"task"},{name:"task.attachments.changed",label:"Task attachments changed",description:"A TaskNotes task attachment list changed.",category:"task"},{name:"task.reminders.changed",label:"Task reminders changed",description:"A TaskNotes task reminder list changed.",category:"task"},{name:"task.dependencies.changed",label:"Task dependencies changed",description:"A TaskNotes task dependency list changed.",category:"task"},{name:"task.recurrence.changed",label:"Task recurrence changed",description:"A TaskNotes task recurrence rule changed.",category:"task"},{name:"time.started",label:"Time tracking started",description:"A time entry started on a TaskNotes task.",category:"time"},{name:"time.stopped",label:"Time tracking stopped",description:"A time entry stopped on a TaskNotes task.",category:"time"},{name:"pomodoro.started",label:"Pomodoro started",description:"A Pomodoro session started.",category:"pomodoro"},{name:"pomodoro.completed",label:"Pomodoro completed",description:"A Pomodoro session completed.",category:"pomodoro"},{name:"pomodoro.interrupted",label:"Pomodoro interrupted",description:"A Pomodoro session was interrupted.",category:"pomodoro"},{name:"recurring.instance.completed",label:"Recurring instance completed",description:"A recurring task instance was completed.",category:"recurring"},{name:"recurring.instance.skipped",label:"Recurring instance skipped",description:"A recurring task instance was skipped.",category:"recurring"}],Lc={ready:"tasknotes:runtime.ready","layout.ready":"tasknotes:runtime.layout-ready","settings.changed":"settings-changed","cache.changed":"tasknotes:cache.changed","cache.rebuilt":"tasknotes:cache.rebuilt","extension.registered":"tasknotes:extension.registered","extension.unregistered":"tasknotes:extension.unregistered",unloading:"tasknotes:runtime.unloading"},jbe=[{name:"ready",label:"Runtime ready",description:"TaskNotes loaded its runtime API.",category:"runtime"},{name:"layout.ready",label:"Layout ready",description:"TaskNotes completed post-layout initialization.",category:"runtime"},{name:"settings.changed",label:"Settings changed",description:"TaskNotes settings were saved or reloaded.",category:"settings"},{name:"cache.changed",label:"Cache changed",description:"TaskNotes task data changed or was invalidated.",category:"cache"},{name:"cache.rebuilt",label:"Cache rebuilt",description:"TaskNotes cache was explicitly rebuilt.",category:"cache"},{name:"extension.registered",label:"Extension registered",description:"A companion plugin registered a runtime API extension namespace.",category:"extension"},{name:"extension.unregistered",label:"Extension unregistered",description:"A companion plugin unregistered a runtime API extension namespace.",category:"extension"},{name:"unloading",label:"Runtime unloading",description:"TaskNotes started unloading.",category:"runtime"}],R8e=["invalid_input","invalid_task_path","invalid_status","task_not_found","task_file_not_found","file_already_exists","extension_invalid","extension_namespace_reserved","extension_namespace_conflict","extension_not_registered","operation_failed"],Hr=class extends Error{constructor(t,r,a={}){var i;super(r);this.name="TaskNotesApiError";this.code=t,this.status=(i=a.status)!=null?i:500,this.details=a.details,a.cause!==void 0&&(this.cause=a.cause)}toJSON(){return{name:this.name,code:this.code,message:this.message,status:this.status,details:this.details}}};Ube=["eq","ne","contains","notContains","in","notIn","exists","missing","lt","lte","gt","gte","isTrue","isFalse"]});function $8e(n){let e=vt(n).trim();return e?(0,vi.normalizePath)(e):null}function xn(n,e,t,r,a,i,s={}){var l,c,d,u,p;let o=_X.find(m=>m.id===e);return{id:n,internalProperty:e,label:t,category:r,valueType:a,source:i,queryable:!0,sortable:(l=s.sortable)!=null?l:!1,groupable:(c=s.groupable)!=null?c:!1,supportedOperators:H8e((d=o==null?void 0:o.supportedOperators)!=null?d:b_(a)),aliases:s.aliases,valueInputType:(p=(u=s.valueInputType)!=null?u:o==null?void 0:o.valueInputType)!=null?p:"text"}}function U8e(n){return bq.find(e=>e.internalProperty===n)}function H8e(n){let e=n.map(t=>Qbe(t)).filter(Oc);return e.includes("eq")&&e.push("in"),e.includes("ne")&&e.push("notIn"),Array.from(new Set(e))}function b_(n){return n==="boolean"?["isTrue","isFalse"]:n==="number"?["eq","ne","in","notIn","lt","lte","gt","gte","exists","missing"]:n==="date"||n==="datetime"?["eq","ne","in","notIn","lt","lte","gt","gte","exists","missing"]:n.endsWith("[]")?["contains","notContains","exists","missing"]:["eq","ne","in","notIn","contains","notContains","exists","missing"]}function Vbe(n){return n==="number"?"number":n==="date"?"date":n==="boolean"?"none":n==="list"?"multi-select":"text"}function Qbe(n){if(typeof n!="string")return null;let e=n.trim(),t=z8e.get(e);return t||(Ube.includes(e)?e:null)}function V8e(n){return!["exists","missing","isTrue","isFalse"].includes(n)}function Wbe(){return{sort:[],offset:0,group:[],scope:{includeArchived:!0}}}function W8e(n,e,t){if(!(typeof n=="undefined"||n===null)){if(typeof n!="number"||!Number.isInteger(n)||n<=0){t.push({path:e,code:"limit_invalid",message:"Runtime query limit must be a positive integer."});return}return n}}function q8e(n,e,t){return typeof n=="undefined"||n===null?0:typeof n!="number"||!Number.isInteger(n)||n<0?(t.push({path:e,code:"offset_invalid",message:"Runtime query offset must be a non-negative integer."}),0):n}function G8e(n,e){return typeof n=="undefined"||n===null?{includeArchived:!0}:hu(n)?{includeArchived:n.includeArchived!==!1,folders:qbe(n.folders,"$.scope.folders",e),excludeFolders:qbe(n.excludeFolders,"$.scope.excludeFolders",e)}:(e.push({path:"$.scope",code:"scope_not_object",message:"Runtime query scope must be an object."}),{includeArchived:!0})}function qbe(n,e,t){if(typeof n=="undefined")return;if(!Array.isArray(n)){t.push({path:e,code:"folder_list_invalid",message:"Runtime query folder scope must be an array of folder paths."});return}let r=n.map((a,i)=>typeof a!="string"||a.trim().length===0?(t.push({path:`${e}.${i}`,code:"folder_invalid",message:"Runtime query folder path must be a non-empty string."}),null):(0,vi.normalizePath)(a)).filter(Oc);return r.length>0?r:void 0}function S_(n){if(Array.isArray(n))return n.map(S_);if(hu(n)){let e=n.fn;if(e==="today")return{fn:"today"};if(e==="now")return{fn:"now"};if(e==="date"&&typeof n.value=="string")return{fn:"date",value:n.value};if(e==="dateAdd"&&Number.isFinite(n.amount)&&(n.unit==="day"||n.unit==="week"||n.unit==="month"))return{fn:"dateAdd",value:S_(n.value),amount:Number(n.amount),unit:n.unit}}return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||n===null?n:Jbe(n)}function C_(n){if(typeof n=="undefined")return null;if(Array.isArray(n))return n.map(e=>String(C_(e)));if(hu(n)){if(n.fn==="today")return"today";if(n.fn==="now")return new Date().toISOString();if(n.fn==="date"&&typeof n.value=="string")return n.value;if(n.fn==="dateAdd")return Y8e(n)}return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||n===null?n:Jbe(n)}function Jbe(n){var e;if(typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="bigint")return String(n);try{return(e=JSON.stringify(n))!=null?e:""}catch(t){return""}}function Y8e(n){let e=C_(n.value),t=e==="today"?new Date:typeof e=="string"?new Date(e):new Date;return n.unit==="day"&&t.setDate(t.getDate()+n.amount),n.unit==="week"&&t.setDate(t.getDate()+n.amount*7),n.unit==="month"&&t.setMonth(t.getMonth()+n.amount),t.toISOString().slice(0,10)}function wq(n){if("all"in n)return{any:n.all.map(wq).filter(Oc)};if("any"in n)return{all:n.any.map(wq).filter(Oc)};if("not"in n)return n.not;let e=K8e(n.op);return e?{...n,op:e}:null}function K8e(n){var t;return(t={eq:"ne",ne:"eq",contains:"notContains",notContains:"contains",in:"notIn",notIn:"in",exists:"missing",missing:"exists",lt:"gte",lte:"gt",gt:"lte",gte:"lt",isTrue:"isFalse",isFalse:"isTrue"}[n])!=null?t:null}function Z8e(n,e){return n.filter(t=>{var r;return!(!e.includeArchived&&t.archived||e.folders&&!e.folders.some(a=>Gbe(t,a))||(r=e.excludeFolders)!=null&&r.some(a=>Gbe(t,a)))})}function Gbe(n,e){let t=(0,vi.normalizePath)(e);return t?n.path===t||n.path.startsWith(`${t}/`):!0}function Q8e(n,e){let t=[];for(let[r,a]of n.entries()){let i=a.map(s=>s.path).filter(s=>e.has(s));i.length>0&&t.push({key:r,label:r,taskPaths:i})}return t}function EE(n){return`runtime:${n.replace(/[^a-z0-9._-]+/giu,"-")}`}function Oc(n){return n!==null&&typeof n!="undefined"}function J8e(n){let e=(0,vi.normalizePath)(n),t=[e];return/\.md$/iu.test(e)||t.push(`${e}.md`),t}function Tq(n){let e=new Set,t=[];for(let r of n)e.has(r.path)||(e.add(r.path),t.push(r));return t}function X8e(n){return{...n}}function DE(n){switch(n){case"number":return"number";case"date":return"date";case"boolean":return"boolean";case"list":return"string[]";case"text":default:return"string"}}function Ybe(n){return n?n instanceof Date?n:new Date(n):null}function hu(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function eKe(n,e){let t={},r=new Set([...Object.keys(n!=null?n:{}),...Object.keys(e!=null?e:{})]);for(let a of r){if(a==="basesData")continue;let i=n==null?void 0:n[a],s=e==null?void 0:e[a];tg(i,s)||(t[a]={before:i,after:s})}return t}function tg(n,e){if(Object.is(n,e))return!0;if(typeof n!="object"||n===null||typeof e!="object"||e===null)return!1;try{return JSON.stringify(n)===JSON.stringify(e)}catch(t){return!1}}function T_(n){var e;return((e=n.timeEntries)!=null?e:[]).filter(t=>!t.endTime).length}function Kbe(n,e){let t=new Set(n!=null?n:[]);return(e!=null?e:[]).some(r=>!t.has(r))}function tKe(n){return n==="task.deleted"?Di:n==="pomodoro.started"?cd:n==="pomodoro.completed"?dd:n==="pomodoro.interrupted"?ud:rt}function cr(n){let e={...n};return n.tags&&(e.tags=[...n.tags]),n.contexts&&(e.contexts=[...n.contexts]),n.projects&&(e.projects=[...n.projects]),n.complete_instances&&(e.complete_instances=[...n.complete_instances]),n.skipped_instances&&(e.skipped_instances=[...n.skipped_instances]),n.icsEventId&&(e.icsEventId=[...n.icsEventId]),n.googleCalendarMovedOriginalDates&&(e.googleCalendarMovedOriginalDates=[...n.googleCalendarMovedOriginalDates]),n.reminders&&(e.reminders=n.reminders.map(t=>({...t}))),n.timeEntries&&(e.timeEntries=n.timeEntries.map(t=>({...t}))),n.blockedBy&&(e.blockedBy=n.blockedBy.map(t=>({...t}))),n.blocking&&(e.blocking=[...n.blocking]),n.customProperties&&(e.customProperties={...n.customProperties}),e}var vi,F8e,L8e,O8e,Zbe,z8e,bq,Hbe,B8e,j8e,w_,Xbe=y(()=>{vi=require("obsidian");Obe();Wl();Pr();yt();Cn();CE();DC();xE();xE();F8e=new Set(["apiversion","capabilities","events","extensions","hascapability","nlp","pomodoro","relationships","recurring","settings","tasks","time"]),L8e=[{id:"title",label:"Title",valueType:"string",source:"model",writable:!0,required:!0},{id:"status",label:"Status",valueType:"string",source:"model",writable:!0,required:!0},{id:"priority",label:"Priority",valueType:"string",source:"model",writable:!0,required:!0},{id:"due",label:"Due",valueType:"date",source:"model",writable:!0},{id:"scheduled",label:"Scheduled",valueType:"date",source:"model",writable:!0},{id:"archived",label:"Archived",valueType:"boolean",source:"model",writable:!0},{id:"tags",label:"Tags",valueType:"string[]",source:"model",writable:!0},{id:"contexts",label:"Contexts",valueType:"string[]",source:"model",writable:!0},{id:"projects",label:"Projects",valueType:"string[]",source:"model",writable:!0},{id:"recurrence",label:"Recurrence",valueType:"string",source:"model",writable:!0},{id:"recurrence_anchor",label:"Recurrence anchor",valueType:"string",source:"model",writable:!0},{id:"complete_instances",label:"Complete instances",valueType:"string[]",source:"model",writable:!0},{id:"skipped_instances",label:"Skipped instances",valueType:"string[]",source:"model",writable:!0},{id:"recurrence_parent",label:"Recurrence parent",valueType:"string",source:"model",writable:!0},{id:"occurrence_date",label:"Occurrence date",valueType:"date",source:"model",writable:!0},{id:"occurrence_materialization",label:"Occurrence materialization",valueType:"string",source:"model",writable:!0},{id:"occurrence_next_trigger",label:"Occurrence next trigger",valueType:"string",source:"model",writable:!0},{id:"occurrence_template",label:"Occurrence template",valueType:"string",source:"model",writable:!0},{id:"occurrence_past_horizon",label:"Occurrence past horizon",valueType:"string",source:"model",writable:!0},{id:"occurrence_future_horizon",label:"Occurrence future horizon",valueType:"string",source:"model",writable:!0},{id:"completedDate",label:"Completed date",valueType:"date",source:"model",writable:!0},{id:"timeEstimate",label:"Time estimate",valueType:"number",source:"model",writable:!0},{id:"timeEntries",label:"Time entries",valueType:"timeEntry[]",source:"model",writable:!0},{id:"attachments",label:"Attachments",valueType:"string[]",source:"model",writable:!0},{id:"dateCreated",label:"Date created",valueType:"datetime",source:"model",writable:!0},{id:"dateModified",label:"Date modified",valueType:"datetime",source:"model",writable:!0},{id:"reminders",label:"Reminders",valueType:"reminder[]",source:"model",writable:!0},{id:"blockedBy",label:"Blocked by",valueType:"dependency[]",source:"model",writable:!0},{id:"details",label:"Details",valueType:"string",source:"model",writable:!0},{id:"sortOrder",label:"Sort order",valueType:"string",source:"model",writable:!0},{id:"path",label:"Path",valueType:"string",source:"model",writable:!1},{id:"totalTrackedTime",label:"Total tracked time",valueType:"number",source:"computed",writable:!1},{id:"blocking",label:"Blocking",valueType:"string[]",source:"computed",writable:!1},{id:"isBlocked",label:"Is blocked",valueType:"boolean",source:"computed",writable:!1},{id:"isBlocking",label:"Is blocking",valueType:"boolean",source:"computed",writable:!1},{id:"hasSubtasks",label:"Has subtasks",valueType:"boolean",source:"computed",writable:!1}],O8e={title:"title",status:"status",priority:"priority",due:"due",scheduled:"scheduled",contexts:"contexts",projects:"projects",attachments:"attachments",recurrence:"recurrence",recurrence_anchor:"recurrenceAnchor",complete_instances:"completeInstances",skipped_instances:"skippedInstances",recurrence_parent:"recurrenceParent",occurrence_date:"occurrenceDate",occurrence_materialization:"occurrenceMaterialization",occurrence_next_trigger:"occurrenceNextTrigger",occurrence_template:"occurrenceTemplate",occurrence_past_horizon:"occurrencePastHorizon",occurrence_future_horizon:"occurrenceFutureHorizon",completedDate:"completedDate",timeEstimate:"timeEstimate",timeEntries:"timeEntries",dateCreated:"dateCreated",dateModified:"dateModified",reminders:"reminders",blockedBy:"blockedBy",sortOrder:"sortOrder"},Zbe=[{id:"eq",label:"equals",valueRequired:!0,appliesTo:["string","number","boolean","date","datetime","string[]"],aliases:["is"]},{id:"ne",label:"does not equal",valueRequired:!0,appliesTo:["string","number","boolean","date","datetime","string[]"],aliases:["is-not"]},{id:"contains",label:"contains",valueRequired:!0,appliesTo:["string","string[]","dependency[]"]},{id:"notContains",label:"does not contain",valueRequired:!0,appliesTo:["string","string[]","dependency[]"],aliases:["does-not-contain"]},{id:"in",label:"is one of",valueRequired:!0,appliesTo:["string","number","boolean","date","datetime"]},{id:"notIn",label:"is not one of",valueRequired:!0,appliesTo:["string","number","boolean","date","datetime"]},{id:"exists",label:"exists",valueRequired:!1,appliesTo:["string","number","boolean","date","datetime","string[]"],aliases:["is-not-empty"]},{id:"missing",label:"is missing",valueRequired:!1,appliesTo:["string","number","boolean","date","datetime","string[]"],aliases:["is-empty"]},{id:"lt",label:"is less than",valueRequired:!0,appliesTo:["number","date","datetime"],aliases:["is-before","is-less-than"]},{id:"lte",label:"is less than or equal",valueRequired:!0,appliesTo:["number","date","datetime"],aliases:["is-on-or-before","is-less-than-or-equal"]},{id:"gt",label:"is greater than",valueRequired:!0,appliesTo:["number","date","datetime"],aliases:["is-after","is-greater-than"]},{id:"gte",label:"is greater than or equal",valueRequired:!0,appliesTo:["number","date","datetime"],aliases:["is-on-or-after","is-greater-than-or-equal"]},{id:"isTrue",label:"is true",valueRequired:!1,appliesTo:["boolean"],aliases:["is-checked"]},{id:"isFalse",label:"is false",valueRequired:!1,appliesTo:["boolean"],aliases:["is-not-checked"]}],z8e=new Map(Zbe.flatMap(n=>{var e;return[[n.id,n.id],...((e=n.aliases)!=null?e:[]).map(t=>[t,n.id])]})),bq=[xn("task.title","title","Title","text","string","model",{aliases:["title","note.title"],sortable:!0}),xn("file.path","path","Path","file","string","file",{aliases:["path","task.path","note.path"]}),xn("task.status","status","Status","select","string","model",{aliases:["status","note.status"],sortable:!0,groupable:!0}),xn("task.priority","priority","Priority","select","string","model",{aliases:["priority","note.priority"],sortable:!0,groupable:!0}),xn("task.tags","tags","Tags","select","string[]","model",{aliases:["tags","file.tags","note.tags"],sortable:!0,groupable:!0}),xn("task.contexts","contexts","Contexts","select","string[]","model",{aliases:["contexts"],groupable:!0}),xn("task.projects","projects","Projects","select","string[]","model",{aliases:["projects"],groupable:!0}),xn("task.blockedBy","blockedBy","Blocked by","select","dependency[]","model",{aliases:["blockedBy"]}),xn("task.blocking","blocking","Blocking","select","string[]","computed",{aliases:["blocking"]}),xn("task.due","due","Due date","date","date","model",{aliases:["due","note.due"],sortable:!0,groupable:!0}),xn("task.scheduled","scheduled","Scheduled date","date","date","model",{aliases:["scheduled","note.scheduled"],sortable:!0,groupable:!0}),xn("task.completedDate","completedDate","Completed date","date","date","model",{aliases:["completedDate"],sortable:!0,groupable:!0}),xn("task.dateCreated","dateCreated","Created date","date","datetime","model",{aliases:["dateCreated","file.ctime"],sortable:!0}),xn("task.dateModified","dateModified","Modified date","date","datetime","model",{aliases:["dateModified","file.mtime"]}),xn("task.archived","archived","Archived","boolean","boolean","model",{aliases:["archived"]}),xn("task.hasSubtasks","hasSubtasks","Has subtasks","boolean","boolean","computed",{aliases:["hasSubtasks"]}),xn("task.isBlocked","dependencies.isBlocked","Blocked","boolean","boolean","computed",{aliases:["dependencies.isBlocked","isBlocked"]}),xn("task.isBlocking","dependencies.isBlocking","Blocking others","boolean","boolean","computed",{aliases:["dependencies.isBlocking","isBlocking"]}),xn("task.timeEstimate","timeEstimate","Time estimate","numeric","number","model",{aliases:["timeEstimate"],sortable:!0}),xn("task.recurrence","recurrence","Recurrence","special","string","model",{aliases:["recurrence"]}),xn("task.isCompleted","status.isCompleted","Completed","boolean","boolean","computed",{aliases:["status.isCompleted","completed"]})],Hbe={eq:"is",ne:"is-not",contains:"contains",notContains:"does-not-contain",in:"is",notIn:"is-not",exists:"is-not-empty",missing:"is-empty",lt:"is-before",lte:"is-on-or-before",gt:"is-after",gte:"is-on-or-after",isTrue:"is-checked",isFalse:"is-not-checked"},B8e=[{id:"parents",label:"Parents",description:"Tasks referenced from this task's projects."},{id:"subtasks",label:"Subtasks",description:"Tasks that reference this task as a project."},{id:"dependencies",label:"Dependencies",description:"Tasks this task is blocked by."},{id:"blocking",label:"Blocking",description:"Tasks blocked by this task."}],j8e=[{value:"FINISHTOSTART",label:"Finish to start",description:"The blocking task should finish before this task starts."},{value:"FINISHTOFINISH",label:"Finish to finish",description:"The blocking task should finish before this task finishes."},{value:"STARTTOSTART",label:"Start to start",description:"The blocking task should start before this task starts."},{value:"STARTTOFINISH",label:"Start to finish",description:"The blocking task should start before this task finishes."}],w_=class{constructor(e){this.plugin=e;this.apiVersion=1;this.model={info:()=>({packageName:"@tasknotes/model",specVersion:Pbe,runtimeApiVersion:this.apiVersion}),config:()=>this.getModelConfig(),validateTask:e=>this.validateTask(e),validatePatch:e=>this.validateTaskPatch(e)};this.catalog={statuses:()=>this.getStatuses(),priorities:()=>this.getPriorities(),userFields:()=>this.getUserFields(),fields:()=>this.getFieldDefinitions(),writableFields:()=>this.getFieldDefinitions().filter(e=>e.writable),filterProperties:()=>this.getFilterPropertyDefinitions(),filterOperators:()=>Zbe.map(e=>({...e})),relationships:()=>B8e.map(e=>({...e})),dependencyRelTypes:()=>j8e.map(e=>({...e})),events:()=>this.events.list()};this.tasks={get:e=>this.getTask(e),list:e=>this.listTasks(e),create:(e,t)=>this.createTask(e,t),update:(e,t,r)=>this.updateTask(e,t,r),patch:(e,t,r)=>this.updateTask(e,t,r),delete:(e,t)=>this.deleteTask(e,t),complete:(e,t,r)=>this.completeTask(e,t,r),uncomplete:(e,t,r)=>this.uncompleteTask(e,t,r),setStatus:(e,t,r)=>this.setTaskProperty(e,"status",t,r),setPriority:(e,t,r)=>this.setTaskProperty(e,"priority",t,r),setDue:(e,t,r)=>this.setTaskProperty(e,"due",t,r),clearDue:(e,t)=>this.setTaskProperty(e,"due",void 0,t),setScheduled:(e,t,r)=>this.setTaskProperty(e,"scheduled",t,r),clearScheduled:(e,t)=>this.setTaskProperty(e,"scheduled",void 0,t),reschedule:(e,t,r)=>this.rescheduleTask(e,t,r),archive:(e,t,r)=>this.archiveTask(e,t,r),move:(e,t,r)=>this.moveTask(e,t,r),addTag:(e,t,r)=>this.updateStringList(e,"tags",t,"add",r),removeTag:(e,t,r)=>this.updateStringList(e,"tags",t,"remove",r),addProject:(e,t,r)=>this.updateStringList(e,"projects",t,"add",r),removeProject:(e,t,r)=>this.updateStringList(e,"projects",t,"remove",r),addContext:(e,t,r)=>this.updateStringList(e,"contexts",t,"add",r),removeContext:(e,t,r)=>this.updateStringList(e,"contexts",t,"remove",r),setReminders:(e,t,r)=>this.updateTask(e,{reminders:t.map(a=>({...a}))},r),addReminder:(e,t,r)=>this.addReminder(e,t,r),removeReminder:(e,t,r)=>this.removeReminder(e,t,r),addDependency:(e,t,r)=>this.addDependency(e,t,r),removeDependency:(e,t,r)=>this.removeDependency(e,t,r)};this.relationships={parents:e=>this.getParentTasks(e),subtasks:e=>this.getSubtasks(e),dependencies:e=>this.getTaskDependencies(e),blocking:e=>this.getBlockingTasks(e),all:e=>this.getTaskRelationships(e)};this.time={start:(e,t,r)=>this.startTime(e,t,r),stop:(e,t)=>this.stopTime(e,t),active:()=>this.getActiveTimeEntries(),summary:e=>this.getTimeSummary(e),task:e=>this.getTaskTimeData(e),append:(e,t,r)=>this.appendTimeEntry(e,t,r),deleteEntry:(e,t,r)=>this.deleteTimeEntry(e,t,r)};this.pomodoro={status:()=>Promise.resolve(this.copyPomodoroState(this.plugin.pomodoroService.getState())),start:(e,t)=>this.startPomodoro(e,t),stop:e=>this.stopPomodoro(e),pause:e=>this.pausePomodoro(e),resume:e=>this.resumePomodoro(e),assignTask:(e,t)=>this.assignPomodoroTask(e,t),sessions:e=>this.getPomodoroSessions(e),stats:e=>this.getPomodoroStats(e)};this.recurring={toggleCompleteInstance:(e,t,r)=>this.toggleRecurringComplete(e,t,r),toggleSkippedInstance:(e,t,r)=>this.toggleRecurringSkipped(e,t,r),materializeOccurrence:(e,t,r)=>this.materializeOccurrence(e,t,r)};this.events={on:(e,t)=>this.on(e,t),off:e=>this.off(e),list:()=>Bbe.map(e=>({...e}))};this.settings={snapshot:()=>this.getSettingsSnapshot()};this.bases={updateDefaultFiles:()=>this.updateDefaultBasesFiles()};this.nlp={parse:e=>this.parseNaturalLanguage(e)};this.query={tasks:e=>this.queryTasks(e),validate:e=>this.validateRuntimeQuery(e),normalize:e=>this.normalizeRuntimeQueryOrThrow(e),explain:e=>this.explainRuntimeQuery(e),filterOptions:()=>this.getFilterOptions()};this.stats={tasks:e=>this.getTaskStats(e)};this.system={health:()=>this.getHealth()};this.ui={taskMenu:{show:e=>this.showTaskMenu(e),showAtElement:e=>this.showTaskMenuAtElement(e),populate:(e,t)=>this.populateTaskMenu(e,t)}};this.lifecycle={ready:()=>this.plugin.onReady(),isReady:()=>this.plugin.initializationComplete===!0,on:(e,t)=>this.onLifecycle(e,t),off:e=>this.off(e),list:()=>jbe.map(e=>({...e}))};this.errors={isApiError:e=>$be(e),normalize:e=>this.normalizeError(e),toResult:async e=>{try{return{ok:!0,value:await e()}}catch(t){return{ok:!1,error:this.normalizeError(t)}}}};this.extensions={register:e=>this.registerExtension(e),get:e=>this.getExtension(e),require:e=>this.requireExtension(e),has:e=>this.hasExtension(e),list:()=>this.listExtensions(),capabilities:()=>this.getExtensionCapabilities()};this.mutationContextByPath=new Map;this.mutationContextStack=[];this.extensionRegistry=new Map}get capabilities(){return[...zbe,...this.getExtensionCapabilities()]}hasCapability(e){return this.capabilities.includes(e)}parseNaturalLanguage(e){if(typeof e!="string")throw new Hr("invalid_input","TaskNotes API parseNaturalLanguage expects a string",{status:400});return Nn.fromPlugin(this.plugin).parseInput(e)}getModelConfig(){var t,r,a,i,s,o,l,c,d,u,p,m,f,h;let e=this.plugin.settings;return Mbe({fieldMapping:e.fieldMapping,statuses:e.customStatuses,priorities:e.customPriorities,defaults:{status:(t=e.defaultTaskStatus)!=null?t:"open",priority:(r=e.defaultTaskPriority)!=null?r:"normal",taskTag:(a=e.taskTag)!=null?a:"task"},taskIdentification:{method:(i=e.taskIdentificationMethod)!=null?i:"tag",tag:(s=e.taskTag)!=null?s:"task",propertyName:(o=e.taskPropertyName)!=null?o:"type",propertyValue:(l=e.taskPropertyValue)!=null?l:"task",excludedFolders:(c=e.excludedFolders)!=null?c:""},storeTitleInFilename:(d=e.storeTitleInFilename)!=null?d:!1,userFields:(u=e.userFields)!=null?u:[],recurrence:{maintainDueDateOffset:(p=e.maintainDueDateOffsetInRecurring)!=null?p:!0,resetCheckboxesOnRecurrence:(m=e.resetCheckboxesOnRecurrence)!=null?m:!0},timeTracking:{autoStopOnComplete:(f=e.autoStopTimeTrackingOnComplete)!=null?f:!1,autoStopNotification:(h=e.autoStopTimeTrackingNotification)!=null?h:!0,defaultSessionDescription:""}})}validateTask(e){var t;return Lbe(e,(t=this.plugin.settings.customStatuses)!=null?t:[])}validateTaskPatch(e){return vq(e)}normalizeError(e){return e instanceof Hr?e.toJSON():kq(e)?e:new Hr("operation_failed",e instanceof Error?e.message:String(e),{status:500,cause:e}).toJSON()}async updateDefaultBasesFiles(){return this.plugin.updateDefaultBasesFiles()}getStatuses(){var e;return((e=this.plugin.settings.customStatuses)!=null?e:[]).map(t=>({...t}))}getPriorities(){var e;return((e=this.plugin.settings.customPriorities)!=null?e:[]).map(t=>({...t}))}getUserFields(){var e;return((e=this.plugin.settings.userFields)!=null?e:[]).map(t=>({...t}))}getFieldDefinitions(){var a;let e=(a=this.plugin.settings.fieldMapping)!=null?a:{},t=L8e.map(i=>{var l,c,d;let s=O8e[i.id],o=U8e(i.id);return{...i,frontmatterKey:s?e[s]:void 0,queryable:!!o,sortable:(l=o==null?void 0:o.sortable)!=null?l:!1,groupable:(c=o==null?void 0:o.groupable)!=null?c:!1,supportedOperators:o==null?void 0:o.supportedOperators,aliases:o?[o.id,...(d=o.aliases)!=null?d:[]]:void 0}}),r=this.getUserFields().map(i=>({id:`user:${i.id||i.key}`,label:i.displayName||i.key,valueType:DE(i.type),source:"user",writable:!0,queryable:!0,sortable:!0,groupable:!0,supportedOperators:b_(DE(i.type)),aliases:[`user.${i.id||i.key}`,`user:${i.id||i.key}`],frontmatterKey:i.key,description:`User-defined field ${i.key}`}));return[...t,...r]}getFilterPropertyDefinitions(){let e=this.getUserFields().map(t=>({id:`user.${t.id||t.key}`,label:t.displayName||t.key,category:"user",valueType:DE(t.type),source:"user",queryable:!0,sortable:!0,groupable:!0,supportedOperators:b_(DE(t.type)),aliases:[`user:${t.id||t.key}`,`user.${t.key}`,`user:${t.key}`],frontmatterKey:t.key,valueInputType:Vbe(t.type)}));return[...bq.map(({internalProperty:t,...r})=>({...r,aliases:r.aliases?[...r.aliases]:void 0,supportedOperators:[...r.supportedOperators]})),...e]}async queryTasks(e){let t=this.normalizeRuntimeQueryForExecution(e);if(!t.validation.valid)throw new Hr("invalid_input","TaskNotes runtime query is invalid",{status:400,details:{issues:t.validation.issues}});let r=await this.plugin.cacheManager.getAllTasks(),a=Z8e(r,t.normalized.scope),i=new Set(a.map(m=>m.path)),s=await this.plugin.filterService.getGroupedTasks(t.filterQuery),o=new Map;for(let m of s.values())for(let f of m)i.has(f.path)&&!o.has(f.path)&&o.set(f.path,f);let l=Array.from(o.values()),c=t.normalized.offset,d=t.normalized.limit,u=typeof d=="number"?l.slice(c,c+d):l.slice(c),p=new Set(u.map(m=>m.path));return{tasks:u.map(cr),total:a.length,matched:l.length,returned:u.length,groups:t.normalized.group.length>0?Q8e(s,p):void 0,query:t.normalized,warnings:t.validation.warnings}}validateRuntimeQuery(e){return this.normalizeRuntimeQueryForExecution(e).validation}normalizeRuntimeQueryOrThrow(e){let t=this.normalizeRuntimeQueryForExecution(e);if(!t.validation.valid)throw new Hr("invalid_input","TaskNotes runtime query is invalid",{status:400,details:{issues:t.validation.issues}});return t.normalized}async explainRuntimeQuery(e){var i;let t=this.normalizeRuntimeQueryForExecution(e);if(!t.validation.valid)return{valid:!1,issues:t.validation.issues,warnings:t.validation.warnings,notes:["Query validation failed before execution."]};let r=await this.queryTasks(e),a=[];return t.normalized.sort.length>1&&a.push("Only the first sort is currently applied by the TaskNotes filter engine."),t.normalized.group.length>1&&a.push("Only the first group is currently applied by the TaskNotes filter engine."),{valid:!0,query:r.query,issues:[],warnings:(i=r.warnings)!=null?i:[],total:r.total,matched:r.matched,returned:r.returned,groups:r.groups,appliedSort:r.query.sort.slice(0,1),appliedLimit:r.query.limit,appliedOffset:r.query.offset,notes:a}}async getFilterOptions(){return this.plugin.filterService.getFilterOptions()}normalizeRuntimeQueryForExecution(e){let t=[],r=[],a=this.normalizeRuntimeTaskQuery(e,t,r);return{filterQuery:this.runtimeQueryToFilterQuery(a,t,r),normalized:a,validation:{valid:t.length===0,issues:t,warnings:r,normalized:t.length===0?a:void 0}}}normalizeRuntimeTaskQuery(e,t,r){if(e==null)return Wbe();if(!hu(e))return t.push({path:"$",code:"query_not_object",message:"Runtime task query must be an object."}),Wbe();let a=typeof e.where=="undefined"?void 0:this.normalizeRuntimePredicate(e.where,"$.where",t),i=this.normalizeRuntimeSorts(e.sort,t,r),s=this.normalizeRuntimeGroups(e.group,t,r),o=W8e(e.limit,"$.limit",t),l=q8e(e.offset,"$.offset",t),c=G8e(e.scope,t);return{where:a,sort:i,limit:o,offset:l,group:s,scope:c}}normalizeRuntimePredicate(e,t,r){if(!hu(e)){r.push({path:t,code:"predicate_not_object",message:"Runtime query predicate must be an object."});return}if(Array.isArray(e.all))return{all:e.all.map((a,i)=>this.normalizeRuntimePredicate(a,`${t}.all.${i}`,r)).filter(Oc)};if(Array.isArray(e.any))return{any:e.any.map((a,i)=>this.normalizeRuntimePredicate(a,`${t}.any.${i}`,r)).filter(Oc)};if(typeof e.not!="undefined"){let a=this.normalizeRuntimePredicate(e.not,`${t}.not`,r);return a?{not:a}:void 0}return this.normalizeRuntimeCondition(e,t,r)}normalizeRuntimeCondition(e,t,r){if(typeof e.field!="string"||e.field.trim().length===0){r.push({path:`${t}.field`,code:"field_required",message:"Runtime query condition requires a field."});return}let a=this.resolveRuntimeQueryField(e.field);if(!a){r.push({path:`${t}.field`,code:"field_unknown",message:`Unsupported runtime query field: ${e.field}`});return}let i=Qbe(e.op);if(!i){r.push({path:`${t}.op`,code:"operator_unknown",message:`Unsupported runtime query operator: ${String(e.op)}`});return}if(!a.definition.supportedOperators.includes(i)){r.push({path:`${t}.op`,code:"operator_unsupported",message:`Operator ${i} is not supported for ${a.definition.id}.`});return}let s=V8e(i);if(s&&typeof e.value=="undefined"){r.push({path:`${t}.value`,code:"value_required",message:`Operator ${i} requires a value.`});return}if((i==="in"||i==="notIn")&&!Array.isArray(e.value)){r.push({path:`${t}.value`,code:"value_array_required",message:`Operator ${i} requires an array value.`});return}return{field:a.definition.id,op:i,value:s?S_(e.value):void 0}}normalizeRuntimeSorts(e,t,r){if(typeof e=="undefined")return[];if(!Array.isArray(e))return t.push({path:"$.sort",code:"sort_not_array",message:"Runtime query sort must be an array."}),[];let a=e.map((i,s)=>{if(!hu(i)||typeof i.field!="string")return t.push({path:`$.sort.${s}`,code:"sort_invalid",message:"Runtime query sort entries require a field."}),null;let o=this.resolveRuntimeQueryField(i.field);if(!o||!o.definition.sortable)return t.push({path:`$.sort.${s}.field`,code:"sort_field_unsupported",message:`Runtime query field is not sortable: ${i.field}`}),null;let l=i.direction==="desc"?"desc":"asc";return{field:o.definition.id,direction:l}}).filter(Oc);return a.length>1&&r.push({path:"$.sort",code:"multiple_sorts",message:"Only the first sort is currently applied by TaskNotes."}),a}normalizeRuntimeGroups(e,t,r){if(typeof e=="undefined")return[];if(!Array.isArray(e))return t.push({path:"$.group",code:"group_not_array",message:"Runtime query group must be an array."}),[];let a=e.map((i,s)=>{if(!hu(i)||typeof i.field!="string")return t.push({path:`$.group.${s}`,code:"group_invalid",message:"Runtime query group entries require a field."}),null;let o=this.resolveRuntimeQueryField(i.field);return!o||!o.definition.groupable?(t.push({path:`$.group.${s}.field`,code:"group_field_unsupported",message:`Runtime query field is not groupable: ${i.field}`}),null):{field:o.definition.id}}).filter(Oc);return a.length>1&&r.push({path:"$.group",code:"multiple_groups",message:"Only the first group is currently applied by TaskNotes."}),a}runtimeQueryToFilterQuery(e,t,r){var c;let a=this.runtimePredicateToFilterNode(e.where,"$.where",t),s={type:"group",id:"runtime-query-root",conjunction:"and",children:a?a.type==="group"&&a.conjunction==="and"?a.children:[a]:[]},o=e.sort[0];if(o){let d=this.runtimeFieldToSortKey(o.field);d?(s.sortKey=d,s.sortDirection=(c=o.direction)!=null?c:"asc"):r.push({path:"$.sort.0.field",code:"sort_not_applied",message:`Sort field ${o.field} could not be mapped to TaskNotes sorting.`})}let l=e.group[0];if(l){let d=this.runtimeFieldToGroupKey(l.field);d?s.groupKey=d:r.push({path:"$.group.0.field",code:"group_not_applied",message:`Group field ${l.field} could not be mapped to TaskNotes grouping.`})}return s}runtimePredicateToFilterNode(e,t,r){if(!e)return null;if("all"in e)return{type:"group",id:EE(t),conjunction:"and",children:e.all.map((a,i)=>this.runtimePredicateToFilterNode(a,`${t}.all.${i}`,r)).filter(Oc)};if("any"in e)return{type:"group",id:EE(t),conjunction:"or",children:e.any.map((a,i)=>this.runtimePredicateToFilterNode(a,`${t}.any.${i}`,r)).filter(Oc)};if("not"in e){let a=wq(e.not);return a?this.runtimePredicateToFilterNode(a,`${t}.not`,r):(r.push({path:`${t}.not`,code:"not_unsupported",message:"Unable to invert runtime query predicate."}),null)}return this.runtimeConditionToFilterNode(e,t)}runtimeConditionToFilterNode(e,t){var i;let r=this.resolveRuntimeQueryField(e.field),a=Array.isArray(e.value)&&(e.op==="in"||e.op==="notIn")?e.value:null;return a?{type:"group",id:EE(t),conjunction:e.op==="in"?"or":"and",children:a.map((s,o)=>{var l;return{type:"condition",id:EE(`${t}.value.${o}`),property:(l=r==null?void 0:r.internalProperty)!=null?l:e.field,operator:Hbe[e.op],value:C_(S_(s))}})}:{type:"condition",id:EE(t),property:(i=r==null?void 0:r.internalProperty)!=null?i:e.field,operator:Hbe[e.op],value:C_(e.value)}}resolveRuntimeQueryField(e){let t=e.trim(),r=this.resolveRuntimeUserField(t);if(r)return r;let a=bq.find(i=>{var s;return i.id===t||((s=i.aliases)!=null?s:[]).includes(t)});return a?{definition:a,internalProperty:a.internalProperty}:null}resolveRuntimeUserField(e){if(!e.startsWith("user.")&&!e.startsWith("user:"))return null;let t=e.slice(5),r=this.getUserFields().find(s=>s.id===t||s.key===t);if(!r)return null;let a=r.id||r.key,i=DE(r.type);return{internalProperty:`user:${a}`,definition:{id:`user.${a}`,label:r.displayName||r.key,category:"user",valueType:i,source:"user",queryable:!0,sortable:!0,groupable:!0,supportedOperators:b_(i),aliases:[`user:${a}`,`user.${r.key}`,`user:${r.key}`],frontmatterKey:r.key,valueInputType:Vbe(r.type)}}}runtimeFieldToSortKey(e){let t=this.resolveRuntimeQueryField(e);if(!t)return null;let r=t.internalProperty;return r.startsWith("user:")||r==="due"||r==="scheduled"||r==="priority"||r==="status"||r==="title"||r==="dateCreated"||r==="completedDate"||r==="tags"?r:null}runtimeFieldToGroupKey(e){let t=this.resolveRuntimeQueryField(e);if(!t)return null;let r=t.internalProperty;return r.startsWith("user:")||r==="priority"||r==="due"||r==="scheduled"||r==="status"||r==="tags"||r==="completedDate"?r:r==="contexts"?"context":r==="projects"?"project":null}async getTaskStats(e){var a,i;let t=e?(await this.queryTasks(e)).tasks:await this.plugin.cacheManager.getAllTasks(),r=(i=(a=this.plugin.taskStatsService)==null?void 0:a.getStats(t))!=null?i:this.computeTaskStats(t);return{total:r.total,statusCounts:{...r.statusCounts},priorityCounts:{...r.priorityCounts},completed:r.completed,active:r.active,overdue:r.overdue,archived:r.archived,withTimeEntries:r.withTimeEntries,totalTrackedMinutes:r.totalTrackedMinutes,totalTrackedHours:r.totalTrackedHours}}async getTimeSummary(e={}){var r,a;let t=await this.plugin.cacheManager.getAllTasks();return Jk(t,{period:(r=e.period)!=null?r:"today",fromDate:Ybe(e.from),toDate:Ybe(e.to),includeTags:(a=e.includeTags)!=null?a:!0},i=>this.plugin.statusManager.isCompletedStatus(i))}async getTaskTimeData(e){let t=await this.requireTask(e);return pm(t,r=>this.plugin.getActiveTimeSession(r))}async getHealth(){let e=await this.plugin.cacheManager.getAllTasks();return{status:"ok",timestamp:new Date().toISOString(),apiVersion:this.apiVersion,capabilities:this.capabilities,vault:this.getVaultInfo(),tasks:{total:e.length}}}async showTaskMenu(e){(await this.buildTaskContextMenu(e)).show(e.event)}async showTaskMenuAtElement(e){(await this.buildTaskContextMenu(e)).showAtElement(e.element)}async populateTaskMenu(e,t){var a,i;let r=await this.requireTask(t.taskPath);ll.addToMenu(e,{task:r,plugin:this.plugin,targetDate:(a=t.targetDate)!=null?a:new Date,promoteOccurrenceControls:t.promoteOccurrenceControls,onUpdate:(i=t.onUpdate)!=null?i:this.defaultTaskMenuUpdateHandler()})}async buildTaskContextMenu(e){var r,a;let t=await this.requireTask(e.taskPath);return new ll({task:t,plugin:this.plugin,targetDate:(r=e.targetDate)!=null?r:new Date,promoteOccurrenceControls:e.promoteOccurrenceControls,onUpdate:(a=e.onUpdate)!=null?a:this.defaultTaskMenuUpdateHandler()})}defaultTaskMenuUpdateHandler(){return()=>{this.plugin.app.workspace.trigger("tasknotes:refresh-views")}}getVaultInfo(){let e=this.plugin.app.vault.adapter,t=null;try{typeof e.basePath=="string"?t=e.basePath:typeof e.path=="string"&&(t=e.path)}catch(r){t=null}return{name:this.plugin.app.vault.getName(),path:t}}computeTaskStats(e){var u,p,m,f,h;let t={},r={},a=0,i=0,s=0,o=0,l=0,c=0,d=(u=new Date().toISOString().split("T")[0])!=null?u:"";for(let g of e){t[g.status]=((p=t[g.status])!=null?p:0)+1,r[g.priority]=((m=r[g.priority])!=null?m:0)+1;let v=this.plugin.statusManager.isCompletedStatus(g.status);v&&a++,g.archived&&o++,!v&&!g.archived&&i++,g.due&&g.due{var a;return this.plugin.taskService.createTask({...e,creationContext:(a=e.creationContext)!=null?a:"api"},{applyDefaults:!0})});return cr(r.taskInfo)}async updateTask(e,t,r){let a=await this.requireTask(e),i=await this.withMutationContext([a.path],r,()=>this.plugin.taskService.updateTask(a,t));return cr(i)}async completeTask(e,t,r){var o,l;let a=await this.requireTask(e),i=(l=(o=t==null?void 0:t.status)!=null?o:this.plugin.statusManager.getCompletedStatuses()[0])!=null?l:"done";if(!this.plugin.statusManager.isCompletedStatus(i))throw new Hr("invalid_status",`Status "${i}" is not configured as a completed status`,{status:400,details:{status:i}});if(!(t!=null&&t.status)&&this.plugin.statusManager.isCompletedStatus(a.status))return cr(a);let s=await this.withMutationContext([a.path],r,()=>this.plugin.taskService.updateProperty(a,"status",i));return cr(s)}async rescheduleTask(e,t,r){let a=await this.requireTask(e),i=await this.withMutationContext([a.path],r,()=>this.plugin.taskService.updateProperty(a,"scheduled",t!=null?t:void 0));return cr(i)}async archiveTask(e,t,r){let a=await this.requireTask(e);if(a.archived===t)return cr(a);let i=await this.withMutationContext([a.path],r,()=>this.plugin.taskService.toggleArchive(a));return cr(i)}async moveTask(e,t,r){let a=await this.requireTask(e),i=this.requireTaskFile(a.path),s=(0,vi.normalizePath)(t),o=s?`${s}/${i.name}`:i.name;return o===a.path?cr(a):this.withMutationContext([a.path,o],r,async()=>{if(s&&await qu(this.plugin.app.vault,s),this.plugin.app.vault.getAbstractFileByPath(o))throw new Hr("file_already_exists",`Cannot move task to "${o}" because a file already exists`,{status:409,details:{path:o}});await this.plugin.app.fileManager.renameFile(i,o);let c=cr({...a,id:a.id&&a.id!==a.path?a.id:o,path:o});return this.plugin.cacheManager.clearCacheEntry(a.path),this.plugin.cacheManager.updateTaskInfoInCache(o,c),this.plugin.emitter.trigger(rt,{path:o,originalTask:a,updatedTask:c}),c})}async deleteTask(e,t){let r=await this.requireTask(e);await this.withMutationContext([r.path],t,()=>this.plugin.taskService.deleteTask(r))}async uncompleteTask(e,t,r){var o,l;let a=await this.requireTask(e),i=(l=(o=t==null?void 0:t.status)!=null?o:this.plugin.settings.defaultTaskStatus)!=null?l:"open";if(!this.plugin.statusManager.isCompletedStatus(a.status)&&!(t!=null&&t.status))return cr(a);let s=await this.withMutationContext([a.path],r,()=>this.plugin.taskService.updateProperty(a,"status",i));return cr(s)}async startTimeEntry(e,t){await this.startTime(e,void 0,t)}async stopTimeEntry(e,t){await this.stopTime(e,t)}async setTaskProperty(e,t,r,a){let i=await this.requireTask(e),s=await this.withMutationContext([i.path],a,()=>this.plugin.taskService.updateProperty(i,t,r));return cr(s)}async updateStringList(e,t,r,a,i){var d;let s=await this.requireTask(e),o=(d=s[t])!=null?d:[],l=r.trim();if(!l)throw new Hr("invalid_input",`TaskNotes API ${a} ${t} expects a non-empty value`,{status:400,details:{operation:a,property:t}});let c=a==="add"?Array.from(new Set([...o,l])):o.filter(u=>u!==l);return this.updateTask(s.path,{[t]:c},i)}async addReminder(e,t,r){var s;let a=await this.requireTask(e),i=[...(s=a.reminders)!=null?s:[],{...t}];return this.updateTask(a.path,{reminders:i},r)}async removeReminder(e,t,r){var s;let a=await this.requireTask(e),i=((s=a.reminders)!=null?s:[]).filter(o=>o.id!==t);return this.updateTask(a.path,{reminders:i},r)}async addDependency(e,t,r){var l;let a=await this.requireTask(e),i=(l=a.blockedBy)!=null?l:[],s=i.findIndex(c=>c.uid===t.uid),o=s>=0?i.map((c,d)=>d===s?{...t}:{...c}):[...i.map(c=>({...c})),{...t}];return this.updateTask(a.path,{blockedBy:o},r)}async removeDependency(e,t,r){var s;let a=await this.requireTask(e),i=((s=a.blockedBy)!=null?s:[]).filter(o=>o.uid!==t);return this.updateTask(a.path,{blockedBy:i.length>0?i:void 0},r)}async startTime(e,t,r){var s;let a=await this.requireTask(e),i=await this.withMutationContext([a.path],r,()=>this.plugin.taskService.startTimeTracking(a));if(t!=null&&t.description&&((s=i.timeEntries)!=null&&s.length)){let o=i.timeEntries.map(c=>({...c})),l=-1;for(let c=o.length-1;c>=0;c--)if(!o[c].endTime){l=c;break}l>=0&&(o[l]={...o[l],description:t.description},i=await this.updateTask(i.path,{timeEntries:o},r))}return cr(i)}async stopTime(e,t){let r=await this.requireTask(e),a=await this.withMutationContext([r.path],t,()=>this.plugin.taskService.stopTimeTracking(r));return cr(a)}async appendTimeEntry(e,t,r){var s;let a=await this.requireTask(e),i=[...((s=a.timeEntries)!=null?s:[]).map(o=>({...o})),{...t}];return this.updateTask(a.path,{timeEntries:i},r)}async deleteTimeEntry(e,t,r){let a=await this.requireTask(e),i=await this.withMutationContext([a.path],r,()=>this.plugin.taskService.deleteTimeEntry(a,t));return cr(i)}async getActiveTimeEntries(){var r;let e=await this.plugin.cacheManager.getAllTasks(),t=[];for(let a of e)for(let[i,s]of((r=a.timeEntries)!=null?r:[]).entries())s.endTime||t.push({taskPath:a.path,task:cr(a),entry:{...s},index:i});return t}getSettingsSnapshot(){return JSON.parse(JSON.stringify(this.plugin.settings))}registerExtension(e){var o;if(!e||typeof e!="object")throw new Hr("extension_invalid","TaskNotes API extension registration expects an object",{status:400});if(typeof e.id!="string"||e.id.trim().length===0)throw new Hr("extension_invalid","TaskNotes API extension registration expects a non-empty id",{status:400});if(e.api===null||typeof e.api=="undefined")throw new Hr("extension_invalid","TaskNotes API extension registration expects an api object",{status:400});let t=e.id.trim(),r=this.normalizeExtensionNamespace(e.namespace);if(F8e.has(r))throw new Hr("extension_namespace_reserved",`Cannot register TaskNotes API extension namespace "${r}"`,{status:400,details:{namespace:r}});if(this.extensionRegistry.has(r))throw new Hr("extension_namespace_conflict",`TaskNotes API extension namespace "${r}" is already registered`,{status:409,details:{namespace:r}});let a=Symbol(r),i=Array.from(new Set(((o=e.capabilities)!=null?o:[]).map(l=>this.normalizeExtensionCapability(l)))),s={id:t,namespace:r,api:e.api,displayName:e.displayName,version:e.version,capabilities:i,token:a};return this.extensionRegistry.set(r,s),this.emitLifecycle("extension.registered",{extension:this.extensionInfo(s)}),{id:t,namespace:r,unregister:()=>{let l=this.extensionRegistry.get(r);(l==null?void 0:l.token)===a&&(this.extensionRegistry.delete(r),this.emitLifecycle("extension.unregistered",{extension:this.extensionInfo(l)}))}}}getExtension(e){var t;return(t=this.extensionRegistry.get(this.normalizeExtensionNamespace(e)))==null?void 0:t.api}requireExtension(e){let t=this.normalizeExtensionNamespace(e),r=this.extensionRegistry.get(t);if(!r)throw new Hr("extension_not_registered",`TaskNotes API extension namespace "${t}" is not registered`,{status:404,details:{namespace:t}});return r.api}hasExtension(e){return this.extensionRegistry.has(this.normalizeExtensionNamespace(e))}listExtensions(){return Array.from(this.extensionRegistry.values()).map(e=>this.extensionInfo(e))}extensionInfo(e){return{id:e.id,namespace:e.namespace,displayName:e.displayName,version:e.version,capabilities:[...e.capabilities]}}getExtensionCapabilities(){return Array.from(this.extensionRegistry.values()).flatMap(e=>[...e.capabilities])}normalizeExtensionNamespace(e){if(typeof e!="string"||e.trim().length===0)throw new Hr("extension_invalid","TaskNotes API extension namespace must be a non-empty string",{status:400});let t=e.trim().toLowerCase();if(!/^[a-z][a-z0-9._-]*$/.test(t))throw new Hr("extension_invalid",`TaskNotes API extension namespace "${e}" must use letters, numbers, dots, underscores, or dashes`,{status:400,details:{namespace:e}});return t}normalizeExtensionCapability(e){if(typeof e!="string"||e.trim().length===0)throw new Hr("extension_invalid","TaskNotes API extension capabilities must be non-empty strings",{status:400});let t=e.trim().toLowerCase();if(!/^[a-z][a-z0-9._:-]*$/.test(t))throw new Hr("extension_invalid",`TaskNotes API extension capability "${e}" must use letters, numbers, dots, underscores, dashes, or colons`,{status:400,details:{capability:e}});return t}async startPomodoro(e,t){let r=e!=null&&e.taskPath?await this.requireTask(e.taskPath):void 0;return await this.withMutationContext(r?[r.path]:[],t,()=>this.plugin.pomodoroService.startPomodoro(r,e==null?void 0:e.duration)),this.copyPomodoroState(this.plugin.pomodoroService.getState())}async stopPomodoro(e){return await this.withMutationContext([],e,()=>this.plugin.pomodoroService.stopPomodoro()),this.copyPomodoroState(this.plugin.pomodoroService.getState())}async pausePomodoro(e){return await this.withMutationContext([],e,()=>this.plugin.pomodoroService.pausePomodoro()),this.copyPomodoroState(this.plugin.pomodoroService.getState())}async resumePomodoro(e){return await this.withMutationContext([],e,()=>this.plugin.pomodoroService.resumePomodoro()),this.copyPomodoroState(this.plugin.pomodoroService.getState())}async assignPomodoroTask(e,t){let r=e?await this.requireTask(e):void 0;return await this.withMutationContext(r?[r.path]:[],t,()=>this.plugin.pomodoroService.assignTaskToCurrentSession(r)),this.copyPomodoroState(this.plugin.pomodoroService.getState())}async getPomodoroSessions(e){let t=await this.plugin.pomodoroService.getSessionHistory();return e!=null&&e.date&&(t=t.filter(r=>new Date(r.startTime).toISOString().split("T")[0]===e.date)),e!=null&&e.limit&&e.limit>0&&(t=t.slice(-e.limit)),t.map(r=>({...r}))}getPomodoroStats(e){return e?this.plugin.pomodoroService.getStatsForDate(new Date(e)):this.plugin.pomodoroService.getTodayStats()}copyPomodoroState(e){return JSON.parse(JSON.stringify(e))}async toggleRecurringComplete(e,t,r){let a=await this.requireTask(e),i=t?new Date(t):void 0,s=await this.withMutationContext([a.path],r,()=>this.plugin.taskService.toggleRecurringTaskCompleteWithOccurrenceNotes(a,i));return cr(s)}async materializeOccurrence(e,t,r){let a=await this.requireTask(e),i=await this.withMutationContext([a.path],r,()=>this.plugin.taskService.materializeOccurrence(a,t));return cr(i)}async toggleRecurringSkipped(e,t,r){let a=await this.requireTask(e),i=t?new Date(t):void 0,s=await this.withMutationContext([a.path],r,()=>this.plugin.taskService.toggleRecurringTaskSkipped(a,i));return cr(s)}on(e,t){let r=tKe(e);return this.plugin.emitter.on(r,a=>{let i=this.normalizeRawEvent(r,a);for(let s of i)s.event===e&&t(s)})}onLifecycle(e,t){let r=Lc[e],a=this.plugin.emitter.on(r,i=>{t(this.normalizeLifecycleEvent(e,r,i))});return e==="ready"&&this.plugin.onReady().then(()=>{t(this.normalizeLifecycleEvent(e,r,void 0))}),a}emitLifecycle(e,t={}){this.plugin.emitter.trigger(Lc[e],{...t,timestamp:new Date().toISOString()})}off(e){this.plugin.emitter.offref(e)}async resolveTaskReference(e,t){let r=await this.resolveTaskReferencePath(e,t);return r?await this.plugin.cacheManager.getTaskInfo(r):null}async taskReferenceMatches(e,t,r){return await this.resolveTaskReferencePath(e,t)===(0,vi.normalizePath)(r)}async resolveTaskReferencePath(e,t){var s;let r=$8e(e);if(!r)return null;let a=this.plugin.app.metadataCache,i=(s=a==null?void 0:a.getFirstLinkpathDest)==null?void 0:s.call(a,r,t);if(i instanceof vi.TFile)return(0,vi.normalizePath)(i.path);for(let o of J8e(r)){let l=await this.plugin.cacheManager.getTaskInfo(o);if(l)return l.path}return(0,vi.normalizePath)(r)}async requireTask(e){let t=this.normalizeTaskPath(e),r=await this.plugin.cacheManager.getTaskInfo(t);if(!r)throw new Hr("task_not_found",`Task not found: ${t}`,{status:404,details:{path:t}});return r}requireTaskFile(e){let t=this.plugin.app.vault.getAbstractFileByPath(e);if(!(t instanceof vi.TFile))throw new Hr("task_file_not_found",`Cannot find task file: ${e}`,{status:404,details:{path:e}});return t}normalizeTaskPath(e){if(typeof e!="string"||e.trim().length===0)throw new Hr("invalid_task_path","TaskNotes API expects a non-empty task path",{status:400});return(0,vi.normalizePath)(e)}async withMutationContext(e,t,r){var i;if(!t)return r();let a=e.map(s=>(0,vi.normalizePath)(s));for(let s of a){let o=(i=this.mutationContextByPath.get(s))!=null?i:[];o.push(t),this.mutationContextByPath.set(s,o)}this.mutationContextStack.push(t);try{return await r()}finally{for(let s of a){let o=this.mutationContextByPath.get(s);o==null||o.pop(),o!=null&&o.length||this.mutationContextByPath.delete(s)}this.mutationContextStack.pop()}}normalizeUpdatedEvent(e){var c,d,u,p,m,f,h,g,v,k,T,b,w,S,C;let t=e.originalTask?cr(e.originalTask):void 0,r=e.updatedTask?cr(e.updatedTask):void 0,a=(u=(d=(c=r==null?void 0:r.path)!=null?c:t==null?void 0:t.path)!=null?d:e.path)!=null?u:"",i=eKe(t,r),s=this.getMutationContext(e),o=this.buildEventPayloadBase({taskPath:a,before:t,after:r,task:r,changes:i,context:s,rawEvent:rt}),l=[];if(!t&&r&&l.push({...o,event:"task.created"}),l.push({...o,event:"task.updated"}),t&&r&&t.path!==r.path&&l.push({...o,event:"task.moved"}),t&&r&&t.status!==r.status){l.push({...o,event:"task.status.changed"});let x=this.plugin.statusManager.isCompletedStatus(t.status),E=this.plugin.statusManager.isCompletedStatus(r.status);!x&&E?l.push({...o,event:"task.completed"}):x&&!E&&l.push({...o,event:"task.uncompleted"})}return t&&r&&t.archived!==r.archived&&l.push({...o,event:r.archived?"task.archived":"task.unarchived"}),t&&r&&t.scheduled!==r.scheduled&&l.push({...o,event:"task.scheduled.changed"}),t&&r&&t.due!==r.due&&l.push({...o,event:"task.due.changed"}),t&&r&&t.priority!==r.priority&&l.push({...o,event:"task.priority.changed"}),t&&r&&!tg((p=t.tags)!=null?p:[],(m=r.tags)!=null?m:[])&&l.push({...o,event:"task.tags.changed"}),t&&r&&!tg((f=t.contexts)!=null?f:[],(h=r.contexts)!=null?h:[])&&l.push({...o,event:"task.contexts.changed"}),t&&r&&!tg((g=t.projects)!=null?g:[],(v=r.projects)!=null?v:[])&&l.push({...o,event:"task.projects.changed"}),t&&r&&!tg((k=t.attachments)!=null?k:[],(T=r.attachments)!=null?T:[])&&l.push({...o,event:"task.attachments.changed"}),t&&r&&!tg((b=t.reminders)!=null?b:[],(w=r.reminders)!=null?w:[])&&l.push({...o,event:"task.reminders.changed"}),t&&r&&!tg((S=t.blockedBy)!=null?S:[],(C=r.blockedBy)!=null?C:[])&&l.push({...o,event:"task.dependencies.changed"}),t&&r&&t.recurrence!==r.recurrence&&l.push({...o,event:"task.recurrence.changed"}),t&&r&&Kbe(t.complete_instances,r.complete_instances)&&l.push({...o,event:"recurring.instance.completed"}),t&&r&&Kbe(t.skipped_instances,r.skipped_instances)&&l.push({...o,event:"recurring.instance.skipped"}),t&&r&&T_(t)!==T_(r)&&l.push({...o,event:T_(r)>T_(t)?"time.started":"time.stopped"}),l}normalizeDeletedEvent(e){var i,s;let t=e.deletedTask?cr(e.deletedTask):void 0,r=(s=(i=t==null?void 0:t.path)!=null?i:e.path)!=null?s:"",a=this.getMutationContext(e);return[this.buildEventPayloadBase({event:"task.deleted",taskPath:r,deletedTask:t,task:t,changes:{},context:a,rawEvent:Di})]}normalizeLifecycleEvent(e,t,r){var s;let a=hu(r)?r:{},i=hu(a.extension)?a.extension:void 0;return{event:e,timestamp:typeof a.timestamp=="string"?a.timestamp:new Date().toISOString(),data:(s=a.data)!=null?s:r,settings:e==="settings.changed"?this.getSettingsSnapshot():void 0,extension:i,filePath:typeof a.filePath=="string"?a.filePath:void 0,force:typeof a.force=="boolean"?a.force:void 0,rawEvent:t}}buildEventPayloadBase(e){var t,r,a,i;return{event:(t=e.event)!=null?t:"task.updated",timestamp:new Date().toISOString(),taskPath:e.taskPath,task:e.task,before:e.before,after:e.after,deletedTask:e.deletedTask,changes:e.changes,data:e.data,context:e.context,source:(r=e.context)==null?void 0:r.source,correlationId:(a=e.context)==null?void 0:a.correlationId,reason:(i=e.context)==null?void 0:i.reason,rawEvent:e.rawEvent}}getMutationContext(e){var r,a,i;let t=[e.path,"originalTask"in e?(r=e.originalTask)==null?void 0:r.path:void 0,"updatedTask"in e?(a=e.updatedTask)==null?void 0:a.path:void 0,"deletedTask"in e?(i=e.deletedTask)==null?void 0:i.path:void 0].filter(s=>!!s).map(s=>(0,vi.normalizePath)(s));for(let s of t){let o=this.mutationContextByPath.get(s),l=o==null?void 0:o[o.length-1];if(l)return l}return this.mutationContextStack[this.mutationContextStack.length-1]}normalizeRawEvent(e,t){return e===Di?this.normalizeDeletedEvent(t):e===cd?this.normalizePomodoroEvent("pomodoro.started",e,t):e===dd?this.normalizePomodoroEvent("pomodoro.completed",e,t):e===ud?this.normalizePomodoroEvent("pomodoro.interrupted",e,t):this.normalizeUpdatedEvent(t)}normalizePomodoroEvent(e,t,r){var l,c;let a=r,i=a.task?cr(a.task):void 0,s=(c=i==null?void 0:i.path)!=null?c:(l=a.session)==null?void 0:l.taskPath,o=this.mutationContextStack[this.mutationContextStack.length-1];return[this.buildEventPayloadBase({event:e,taskPath:s,task:i,changes:{},data:r,context:o,rawEvent:t})]}}});function x_(n,e=ewe.Platform.isMobile){return e&&n.disableCalendarOnMobile}var ewe,Sq=y(()=>{ewe=require("obsidian")});var rwe={};Xe(rwe,{TaskSelectionService:()=>Cq});var twe,Cq,nwe=y(()=>{q();twe=M({tag:"Services/TaskSelectionService"}),Cq=class{constructor(e){this.selectedTaskPaths=new Set;this.lastSelectedPath=null;this.primarySelectedPath=null;this.selectionModeActive=!1;this.selectionModeListeners=[];this.selectionChangeListeners=[];this.plugin=e}isSelectionModeActive(){return this.selectionModeActive}enterSelectionMode(){this.selectionModeActive||(this.selectionModeActive=!0,this.notifySelectionModeChange(!0))}exitSelectionMode(e=!1){this.selectionModeActive&&(this.selectionModeActive=!1,e&&this.clearSelection(),this.notifySelectionModeChange(!1))}toggleSelectionMode(){this.selectionModeActive?this.exitSelectionMode():this.enterSelectionMode()}isSelected(e){return this.selectedTaskPaths.has(e)}toggleSelection(e){this.selectedTaskPaths.has(e)?(this.selectedTaskPaths.delete(e),this.primarySelectedPath===e&&(this.primarySelectedPath=this.selectedTaskPaths.size>0?Array.from(this.selectedTaskPaths)[0]:null)):(this.selectedTaskPaths.size===0&&(this.primarySelectedPath=e),this.selectedTaskPaths.add(e)),this.lastSelectedPath=e,this.selectedTaskPaths.size>0&&!this.selectionModeActive&&this.enterSelectionMode(),this.selectedTaskPaths.size===0&&this.selectionModeActive&&this.exitSelectionMode(),this.notifySelectionChange()}selectTask(e){this.selectedTaskPaths.clear(),this.selectedTaskPaths.add(e),this.lastSelectedPath=e,this.primarySelectedPath=e,this.notifySelectionChange()}addToSelection(e){this.selectedTaskPaths.size===0&&(this.primarySelectedPath=e),this.selectedTaskPaths.add(e),this.lastSelectedPath=e,this.notifySelectionChange()}removeFromSelection(e){this.selectedTaskPaths.delete(e),this.notifySelectionChange()}selectRange(e,t){if(!this.lastSelectedPath){this.selectTask(e);return}let r=t.indexOf(this.lastSelectedPath),a=t.indexOf(e);if(r===-1||a===-1){this.toggleSelection(e);return}let i=Math.min(r,a),s=Math.max(r,a);for(let o=i;o<=s;o++)this.selectedTaskPaths.add(t[o]);this.lastSelectedPath=e,this.notifySelectionChange()}selectAdjacentRange(e,t){var s;if(t.length===0)return;let r=this.lastSelectedPath;if((!r||!t.includes(r))&&(r=(s=t.find(o=>this.selectedTaskPaths.has(o)))!=null?s:null),!r){this.selectTask(e>0?t[0]:t[t.length-1]);return}let a=t.indexOf(r);if(a===-1)return;let i=Math.max(0,Math.min(t.length-1,a+e));i!==a&&(this.lastSelectedPath=r,this.selectRange(t[i],t))}selectAll(e){this.selectedTaskPaths.size===0&&e.length>0&&(this.primarySelectedPath=e[0]);for(let t of e)this.selectedTaskPaths.add(t);e.length>0&&(this.lastSelectedPath=e[e.length-1]),this.notifySelectionChange()}clearSelection(){this.selectedTaskPaths.clear(),this.lastSelectedPath=null,this.primarySelectedPath=null,this.notifySelectionChange()}getSelectedPaths(){return Array.from(this.selectedTaskPaths)}getPrimarySelectedPath(){return this.primarySelectedPath}getSelectionCount(){return this.selectedTaskPaths.size}async getSelectedTasks(){let e=[];for(let t of this.selectedTaskPaths){let r=await this.plugin.cacheManager.getTaskInfo(t);r&&e.push(r)}return e}onSelectionModeChange(e){return this.selectionModeListeners.push(e),()=>{let t=this.selectionModeListeners.indexOf(e);t!==-1&&this.selectionModeListeners.splice(t,1)}}onSelectionChange(e){return this.selectionChangeListeners.push(e),()=>{let t=this.selectionChangeListeners.indexOf(e);t!==-1&&this.selectionChangeListeners.splice(t,1)}}notifySelectionModeChange(e){for(let t of this.selectionModeListeners)try{t(e)}catch(r){twe.error("[TaskSelectionService] Error in selection mode listener:",{category:"persistence",operation:"selection-mode-listener",error:r})}}notifySelectionChange(){let e=this.getSelectedPaths();for(let t of this.selectionChangeListeners)try{t(e)}catch(r){twe.error("[TaskSelectionService] Error in selection change listener:",{category:"persistence",operation:"selection-change-listener",error:r})}}destroy(){this.selectedTaskPaths.clear(),this.selectionModeListeners=[],this.selectionChangeListeners=[]}}});var awe={};Xe(awe,{BasesFilterConverter:()=>Eq});function rKe(n){return n instanceof Error?n.message:String(n)}function nKe(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}var xq,Eq,iwe=y(()=>{dr();q();xq=M({tag:"Services/BasesFilterConverter"});Eq=class{constructor(e){this.plugin=e,this.statusManager=e.statusManager,this.priorityManager=e.priorityManager}convertToBasesFilter(e){try{let t=this.convertNodeToObject(e);return t||null}catch(t){throw xq.error("Error converting TaskNotes filter to Bases:",{category:"validation",operation:"converting-tasknotes-filter-bases",error:t}),new Error(`Failed to convert filter: ${rKe(t)}`)}}convertNodeToObject(e){return e.type=="group"?this.convertGroupToObject(e):e.type=="condition"?this.convertConditionToString(e):null}convertGroupToObject(e){let t=e.children.filter(i=>i.type=="condition"?this.isConditionComplete(i):!0);if(t.length==0)return null;let r=t.map(i=>this.convertNodeToObject(i)).filter(i=>i!==null);return r.length==0?null:r.length===1?r[0]:{[e.conjunction=="and"?"and":"or"]:r}}convertConditionToString(e){let{property:t,operator:r,value:a}=e;if(t=="status.isCompleted")return this.convertCompletedStatusCondition(r,a);if(t=="archived")return this.convertArchivedCondition(r);if(t=="dependencies.isBlocked")return this.convertIsBlockedCondition(r);if(t.startsWith("user:"))return this.convertUserFieldCondition(t,r,a);let i=this.getBasesPropertyPath(t);return this.convertOperator(i,r,a,t)}isConditionComplete(e){let{property:t,operator:r,value:a}=e;return!t||!r?!1:["is-empty","is-not-empty","is-checked","is-not-checked"].includes(r)?!0:a!=null&&a!==""}convertCompletedStatusCondition(e,t){let r=this.statusManager.getCompletedStatuses(),a=this.plugin.fieldMapper,i=a.toUserField("status"),s=r.map(u=>`note.${i} == "${this.escapeString(u)}"`).join(" || "),o=r.length>1?`(${s})`:s,l=a.toUserField("completeInstances"),c=`note.${l} && note.${l}.map(date(value).format("YYYY-MM-DD")).contains(today().format("YYYY-MM-DD"))`,d=`(${o}) || (${c})`;return e=="is-not-checked"||e=="is-not"?`!(${d})`:d}convertArchivedCondition(e){let r=this.plugin.fieldMapper.toUserField("archiveTag"),a=`file.tags.contains("${this.escapeString(r)}")`;return e=="is-not-checked"||e=="is-not"?`!${a}`:a}convertIsBlockedCondition(e){let r=this.plugin.fieldMapper.toUserField("blockedBy"),a=`(note.${r} && list(note.${r}).length > 0)`;return e=="is-not-checked"||e=="is-not"?`!(${a})`:a}convertUserFieldCondition(e,t,r){let a=e.slice(5),s=(this.plugin.settings.userFields||[]).find(l=>(l.id||l.key)===a||l.key===a);if(!s)return xq.warn(`User field not found: ${a}`,{category:"validation",operation:"user-field-not-found"}),"true";let o=`note.${s.key}`;return this.convertOperator(o,t,r,e,s.type)}getBasesPropertyPath(e){let t=this.plugin.fieldMapper,r;switch(e){case"title":return"file.name";case"status":r=t.toUserField("status");break;case"priority":r=t.toUserField("priority");break;case"due":r=t.toUserField("due");break;case"scheduled":r=t.toUserField("scheduled");break;case"contexts":r=t.toUserField("contexts");break;case"projects":r=t.toUserField("projects");break;case"tags":return"file.tags";case"path":return"file.path";case"dateCreated":return"file.ctime";case"dateModified":return"file.mtime";case"timeEstimate":r=t.toUserField("timeEstimate");break;case"completedDate":r=t.toUserField("completedDate");break;case"recurrence":r=t.toUserField("recurrence");break;case"blockedBy":r=t.toUserField("blockedBy");break;case"blocking":r="blocking";break;default:r=e}return`note.${r}`}convertOperator(e,t,r,a,i){switch(t){case"is":return this.convertIsOperator(e,r,i);case"is-not":return`!(${this.convertIsOperator(e,r,i)})`;case"contains":return this.convertContainsOperator(e,r,a);case"does-not-contain":return`!(${this.convertContainsOperator(e,r,a)})`;case"is-before":return`${e} < "${this.escapeString(String(r))}"`;case"is-after":return`${e} > "${this.escapeString(String(r))}"`;case"is-on-or-before":return`${e} <= "${this.escapeString(String(r))}"`;case"is-on-or-after":return`${e} >= "${this.escapeString(String(r))}"`;case"is-empty":return`${e}.isEmpty()`;case"is-not-empty":return`!${e}.isEmpty()`;case"is-checked":return`${e} == true`;case"is-not-checked":return`${e} != true`;case"is-greater-than":return`${e} > ${this.formatNumericValue(r)}`;case"is-less-than":return`${e} < ${this.formatNumericValue(r)}`;case"is-greater-than-or-equal":return`${e} >= ${this.formatNumericValue(r)}`;case"is-less-than-or-equal":return`${e} <= ${this.formatNumericValue(r)}`;default:return xq.warn("Unknown operator:",{category:"validation",operation:"unknown-operator",details:{value:t}}),"true"}}convertIsOperator(e,t,r){if(Array.isArray(t)){if(t.length==0)return`(!${e} || ${e}.length == 0)`;let a=t.map(i=>`${e}.contains("${this.escapeString(Y(i))}")`);return a.length>1?`(${a.join(" || ")})`:a[0]}if(r=="list")return`${e}.contains("${this.escapeString(Y(t))}")`;if(typeof t=="boolean"||r=="boolean"){let a=typeof t=="boolean"?t?"true":"false":Y(t);return`${e} == ${a}`}return typeof t=="number"||r=="number"?`${e} == ${this.formatNumericValue(t)}`:t==null||t==""?`(!${e} || ${e} == "" || ${e} == null)`:`${e} == "${this.escapeString(Y(t))}"`}convertContainsOperator(e,t,r){if(["tags","contexts","projects"].includes(r)){if(Array.isArray(t)){let i=t.map(s=>`${e}.contains("${this.escapeString(String(s))}")`);return i.length>1?`(${i.join(" || ")})`:i[0]}if(r=="projects"){let i=String(t);return i.startsWith("[[")&&i.endsWith("]]")?`${e}.contains("${this.escapeString(i)}")`:`(${e}.contains("[[${this.escapeString(i)}]]") || ${e}.contains("${this.escapeString(i)}"))`}return`${e}.contains("${this.escapeString(Y(t))}")`}return`${e}.lower().contains("${this.escapeString(Y(t).toLowerCase())}")`}formatNumericValue(e){if(typeof e=="number")return String(e);let t=parseFloat(Y(e));return isNaN(t)?"0":String(t)}escapeString(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}filterObjectToYAML(e,t=0){let r=" ".repeat(t);if(typeof e=="string")return`'${e.replace(/'/g,"\\'")}'`;if(Array.isArray(e))return e.map(a=>` +${r}- ${this.filterObjectToYAML(a,t+1)}`).join("");if(nKe(e)){let a=Object.keys(e)[0],i=e[a];return Array.isArray(i)?` +${r}${a}:${i.map(s=>` +${r} - ${this.filterObjectToYAML(s,t+2)}`).join("")}`:` +${r}${a}: ${this.filterObjectToYAML(i,t+1)}`}return String(e)}convertSavedViewToBasesFile(e,t="tasknotesTaskList"){let r=this.convertToBasesFilter(e.query),a=`# ${e.name} + +`;if(r&&(a+=`filters:${this.filterObjectToYAML(r,1)} + +`),a+=`views: +`,a+=` - type: ${t} +`,a+=` name: "${e.name}" +`,e.query.sortKey){let i=this.mapSortKeyToBasesColumn(e.query.sortKey),s=(e.query.sortDirection||"asc").toUpperCase();a+=` sort: +`,a+=` - column: ${i} +`,a+=` direction: ${s} +`}if(e.query.groupKey&&e.query.groupKey!=="none"){let i=this.mapGroupKeyToBasesColumn(e.query.groupKey),s=(e.query.sortDirection||"asc").toUpperCase();a+=` groupBy: +`,a+=` property: ${i} +`,a+=` direction: ${s} +`}return e.viewOptions&&Object.keys(e.viewOptions).length>0&&(a+=` options: +`,Object.entries(e.viewOptions).forEach(([i,s])=>{let o;typeof s=="boolean"||typeof s=="number"?o=String(s):typeof s=="string"?o=`"${this.escapeString(s)}"`:o=JSON.stringify(s),a+=` ${i}: ${o} +`})),a}mapSortKeyToBasesColumn(e){let t=this.plugin.fieldMapper;switch(e){case"due":return t.toUserField("due");case"scheduled":return t.toUserField("scheduled");case"priority":return t.toUserField("priority");case"status":return t.toUserField("status");case"title":return t.toUserField("title");case"dateCreated":return"file.ctime";case"dateModified":return"file.mtime";case"completedDate":return t.toUserField("completedDate");case"tags":return"file.tags";case"path":return"file.path";case"timeEstimate":return t.toUserField("timeEstimate");case"recurrence":return t.toUserField("recurrence");default:if(e.startsWith("user:")){let r=e.slice(5),i=(this.plugin.settings.userFields||[]).find(s=>(s.id||s.key)===r||s.key===r);return(i==null?void 0:i.key)||e}return e}}mapGroupKeyToBasesColumn(e){return this.mapSortKeyToBasesColumn(e)}convertAllSavedViewsToBasesFile(e){if(!e||e.length==0)return"";let t=`# All Saved Views +`;t+=`# Converted from TaskNotes saved views + +`;let r=[];for(let a of e){let i=this.detectViewType(a),s=this.convertToBasesFilter(a.query),o=` - type: ${i} +`;if(o+=` name: "${a.name}" +`,s&&(o+=` filters:${this.filterObjectToYAML(s,3)} +`),a.query.sortKey){let l=this.mapSortKeyToBasesColumn(a.query.sortKey),c=(a.query.sortDirection||"asc").toUpperCase();o+=` sort: +`,o+=` - column: ${l} +`,o+=` direction: ${c} +`}if(a.query.groupKey&&a.query.groupKey!=="none"){let l=this.mapGroupKeyToBasesColumn(a.query.groupKey),c=(a.query.sortDirection||"asc").toUpperCase();o+=` groupBy: +`,o+=` property: ${l} +`,o+=` direction: ${c} +`}a.viewOptions&&Object.keys(a.viewOptions).length>0&&(o+=` options: +`,Object.entries(a.viewOptions).forEach(([l,c])=>{let d;typeof c=="boolean"||typeof c=="number"?d=String(c):typeof c=="string"?d=`"${this.escapeString(c)}"`:d=JSON.stringify(c),o+=` ${l}: ${d} +`})),r.push(o)}return t+=`views: +`,t+=r.join(` +`),t}detectViewType(e){let t=e.viewOptions||{};return["showScheduled","showDue","showRecurring","showTimeEntries","showTimeblocks","showPropertyBasedEvents","calendarView","customDayCount","firstDay","slotMinTime","slotMaxTime","slotDuration","snapDuration"].some(o=>o in t)?"tasknotesCalendar":["columnWidth","hideEmptyColumns","pinnedColumns","cardLayout"].some(o=>o in t)?"tasknotesKanban":"tasknotesTaskList"}}});var owe={};Xe(owe,{MdbaseSpecService:()=>Pq});function gu(n){return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function aKe(n){return gu(n)}function iKe(n){let e=n.toLowerCase();return e==="true"||e==="false"?e:gu(n)}var swe,Dq,PE,Pq,lwe=y(()=>{swe=require("obsidian");cx();q();Dq=M({tag:"Services/MdbaseSpecService"}),PE="_types",Pq=class{constructor(e){this.plugin=e}async onSettingsChanged(){this.plugin.settings.enableMdbaseSpec&&await this.generate()}async generate(){try{let e=this.plugin.app.vault,t=await this.getTypesFolder(),r=`${t}/task.md`;await this.ensureFolderPath(t);let a=this.buildTaskTypeDef();if(await this.writeFile(r,a),!await e.adapter.exists("mdbase.yaml")){let s=this.buildMdbaseYaml(t);await this.writeFile("mdbase.yaml",s)}Dq.debug(`[TaskNotes][mdbase-spec] Generated mdbase.yaml and ${r}`,{category:"configuration",operation:"generated-mdbase-yaml-and"})}catch(e){Dq.error("[TaskNotes][mdbase-spec] Failed to generate files:",{category:"configuration",operation:"generate-files",error:e})}}async getTypesFolder(){var r,a;let e=this.plugin.app.vault;if(!await e.adapter.exists("mdbase.yaml"))return PE;try{let i=await e.adapter.read("mdbase.yaml"),s=Yv.parse(i);return(a=this.normalizeTypesFolder((r=s==null?void 0:s.settings)==null?void 0:r.types_folder))!=null?a:PE}catch(i){return Dq.warn("[TaskNotes][mdbase-spec] Failed to read mdbase.yaml:",{category:"configuration",operation:"read-mdbase-yaml",error:i}),PE}}normalizeTypesFolder(e){if(typeof e!="string")return null;let t=e.trim();if(!t||t.startsWith("/")||t==="."||t==="..")return null;let r=(0,swe.normalizePath)(t);return!r||r==="."||r===".."||r.startsWith("../")||r.includes("/../")?null:r}async ensureFolderPath(e){let t=this.plugin.app.vault,r=e.split("/").filter(Boolean),a="";for(let i of r)a=a?`${a}/${i}`:i,await t.adapter.exists(a)||await t.createFolder(a)}async writeFile(e,t){let r=this.plugin.app.vault;await r.adapter.exists(e)?await r.adapter.write(e,t):await r.create(e,t)}buildMdbaseYaml(e=PE){var r;let t=(r=this.normalizeTypesFolder(e))!=null?r:PE;return['spec_version: "0.2.0"','name: "TaskNotes"','description: "Task collection managed by TaskNotes for Obsidian"',"settings:",` types_folder: ${gu(t)}`," default_strict: false"," exclude:",` - ${gu(t)}`,""].join(` +`)}buildTaskTypeDef(){var i,s;let e=this.plugin.settings,t=this.plugin.fieldMapper,r=[];if(r.push("---"),r.push("name: task"),r.push("description: A task managed by the TaskNotes plugin for Obsidian."),r.push(`display_name_key: ${t.toUserField("title")}`),r.push("strict: false"),r.push(`path_pattern: ${gu(this.buildPathPattern())}`),r.push(""),r.push("match:"),this.addMatchRules(r),r.push(""),r.push("fields:"),this.addRoleField(r,"title",{type:"string",required:!0,description:"Short summary of the task."}),this.addRoleField(r,"status",{type:"enum",required:!0,values:e.customStatuses.map(o=>o.value),default:e.defaultTaskStatus,tn_completed_values:e.customStatuses.filter(o=>o.isCompleted).map(o=>o.value)}),this.addRoleField(r,"priority",{type:"enum",values:e.customPriorities.map(o=>o.value),default:e.defaultTaskPriority}),this.addRoleField(r,"due",{type:"date"}),this.addRoleField(r,"scheduled",{type:"date"}),this.addRoleField(r,"contexts",{type:"list",items:{type:"string"}}),this.addRoleField(r,"projects",{type:"list",items:{type:"link"},description:"Wikilinks to related project notes."}),this.addRoleField(r,"timeEstimate",{type:"integer",min:0,description:"Estimated time in minutes."}),this.addRoleField(r,"completedDate",{type:"date"}),this.addRoleField(r,"dateCreated",{type:"datetime",required:!0,generated:"now"}),this.addRoleField(r,"dateModified",{type:"datetime",generated:"now_on_write"}),this.addRoleField(r,"recurrence",{type:"string"}),this.addRoleField(r,"recurrenceAnchor",{type:"enum",values:["scheduled","completion"],default:"scheduled"}),this.addRoleField(r,"occurrenceMaterialization",{type:"enum",values:["manual","on_completion","rolling"],default:"manual",description:"How occurrence task notes are materialized for a recurring parent task."}),this.addRoleField(r,"occurrenceNextTrigger",{type:"enum",values:["completion","completion_or_skip"],default:"completion",description:"Which occurrence state changes should materialize the next occurrence."}),this.addRoleField(r,"occurrenceTemplate",{type:"link",description:"Optional template note used when materializing occurrences."}),this.addRoleField(r,"occurrencePastHorizon",{type:"string",description:"ISO 8601 duration controlling rolling materialization before today."}),this.addRoleField(r,"occurrenceFutureHorizon",{type:"string",description:"ISO 8601 duration controlling rolling materialization after today."}),this.addRoleField(r,"recurrenceParent",{type:"link",description:"Parent recurring task for a materialized occurrence note."}),this.addRoleField(r,"occurrenceDate",{type:"date",description:"Target recurrence date for a materialized occurrence note."}),this.addField(r,"tags",{type:"list",items:{type:"string"},tn_role:"tags"}),this.addRoleField(r,"timeEntries",{type:"list",items:{type:"object",fields:{startTime:{type:"datetime"},endTime:{type:"datetime"},description:{type:"string"},duration:{type:"integer"}}}}),this.addRoleField(r,"reminders",{type:"list",items:{type:"object",fields:{id:{type:"string",required:!0},type:{type:"enum",values:["absolute","relative"]},description:{type:"string"},relatedTo:{type:"enum",values:["due","scheduled"],description:"Field the reminder is relative to (e.g. 'due')."},offset:{type:"string",description:"ISO 8601 duration offset (e.g. '-PT1H')."},absoluteTime:{type:"datetime"}}},description:"Reminder objects with id, type, offset, etc."}),this.addRoleField(r,"blockedBy",{type:"list",items:{type:"object",fields:{uid:{type:"link",required:!0},reltype:{type:"string"},gap:{type:"string"}}}}),this.addRoleField(r,"completeInstances",{type:"list",items:{type:"date"}}),this.addRoleField(r,"skippedInstances",{type:"list",items:{type:"date"}}),this.addRoleField(r,"icsEventId",{type:"list",items:{type:"string"}}),this.addRoleField(r,"googleCalendarEventId",{type:"string"}),this.addRoleField(r,"googleCalendarExceptionEventId",{type:"string"}),this.addRoleField(r,"googleCalendarExceptionOriginalScheduled",{type:"date"}),this.addRoleField(r,"googleCalendarMovedOriginalDates",{type:"list",items:{type:"date"}}),e.userFields&&e.userFields.length>0)for(let o of e.userFields)this.addField(r,o.key,this.mapUserFieldType(o));r.push(""),r.push("x-tasknotes:"),r.push(" nlp:");let a=(s=(i=e.nlpTriggers)==null?void 0:i.triggers)!=null?s:[];if(a.length===0)r.push(" triggers: []");else{r.push(" triggers:");for(let o of a)r.push(` - property_id: ${gu(o.propertyId)}`),r.push(` trigger: ${gu(o.trigger)}`),r.push(` enabled: ${o.enabled===!0}`)}return r.push("---"),r.push(""),r.push("# Task"),r.push(""),r.push("This type definition describes the data schema for tasks managed by"),r.push("[TaskNotes](https://github.com/callumalpass/tasknotes), an Obsidian plugin"),r.push("for note-based task management."),r.push(""),r.push("It conforms to [mdbase-spec](https://github.com/callumalpass/mdbase-spec) v0.2.0,"),r.push("a specification for typed markdown collections."),r.push(""),r.push("TaskNotes also adds a non-standard `tn_role` field annotation on schema"),r.push("fields. This maps each field to its TaskNotes semantic role so custom"),r.push("frontmatter field names can still be interpreted consistently."),r.push("The status field also includes `tn_completed_values`, listing"),r.push("which status values count as completed."),r.push(""),r.push("This file is automatically generated from TaskNotes settings and should not be"),r.push("edited manually. Changes to TaskNotes settings (statuses, priorities, field"),r.push("mappings, user fields) will cause this file to be regenerated."),r.push(""),r.join(` +`)}addField(e,t,r,a=2){let i=" ".repeat(a);e.push(`${i}${t}:`),this.writeFieldProps(e,r,a+2)}addRoleField(e,t,r,a=2){let i=this.plugin.fieldMapper.toUserField(t);this.addField(e,i,{...r,tn_role:t},a)}writeFieldProps(e,t,r){let a=" ".repeat(r);if(e.push(`${a}type: ${t.type}`),t.required&&e.push(`${a}required: true`),t.generated&&e.push(`${a}generated: ${t.generated}`),t.values&&e.push(`${a}values: [${t.values.join(", ")}]`),t.tn_completed_values&&t.tn_completed_values.length>0&&e.push(`${a}tn_completed_values: [${t.tn_completed_values.join(", ")}]`),t.default!==void 0&&e.push(`${a}default: ${t.default}`),t.min!==void 0&&e.push(`${a}min: ${t.min}`),t.description&&e.push(`${a}description: ${gu(t.description)}`),t.tn_role&&e.push(`${a}tn_role: ${t.tn_role}`),t.items)if(t.items.type==="object"&&t.items.fields){e.push(`${a}items:`),e.push(`${a} type: object`),e.push(`${a} fields:`);for(let[i,s]of Object.entries(t.items.fields))this.addField(e,i,s,r+4)}else e.push(`${a}items:`),e.push(`${a} type: ${t.items.type}`)}mapUserFieldType(e){switch(e.type){case"text":return{type:"string"};case"number":return{type:"number"};case"date":return{type:"date"};case"boolean":return{type:"boolean"};case"list":return{type:"list",items:{type:"string"}};default:return{type:"string"}}}addMatchRules(e){var r,a;let t=this.plugin.settings;if(t.taskIdentificationMethod==="property"){let i=(r=t.taskPropertyName)==null?void 0:r.trim(),s=(a=t.taskPropertyValue)==null?void 0:a.trim();if(!i){this.addTagMatchRule(e);return}e.push(" where:"),e.push(` ${aKe(i)}:`),s?e.push(` eq: ${iKe(s)}`):e.push(" exists: true");return}this.addTagMatchRule(e)}addTagMatchRule(e){var r;let t=((r=this.plugin.settings.taskTag)==null?void 0:r.trim())||"task";e.push(" where:"),e.push(" tags:"),e.push(` contains: ${gu(t)}`)}buildPathPattern(){let e=this.toMdbaseTemplate(this.plugin.settings.tasksFolder||""),t=this.getFilenameTemplate(),r=this.toMdbaseTemplate(t)||`{${this.plugin.fieldMapper.toUserField("title")}}`,a=r.endsWith(".md")?r:`${r}.md`;return e?`${e}/${a}`:a}getFilenameTemplate(){var t;let e=this.plugin.settings;if(e.storeTitleInFilename||e.taskFilenameFormat==="title")return"{{title}}";switch(e.taskFilenameFormat){case"timestamp":return"{{timestamp}}";case"uuid":return"{{uuid}}";case"custom":return((t=e.customFilenameTemplate)==null?void 0:t.trim())||"{{title}}";case"zettel":default:return"{{zettel}}"}}toMdbaseTemplate(e){let t=(e||"").trim();if(!t)return"";let r=this.getPathVariableMap();return t.replace(/\{\{(\w+)\}\}|\{(\w+)\}/g,(i,s,o)=>{let l=String(s!=null?s:o);return`{${r[l]||l}}`}).replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+|\/+$/g,"")}getPathVariableMap(){let e=this.plugin.fieldMapper;return{title:e.toUserField("title"),priority:e.toUserField("priority"),status:e.toUserField("status"),dueDate:e.toUserField("due"),scheduledDate:e.toUserField("scheduled"),due:e.toUserField("due"),scheduled:e.toUserField("scheduled")}}}});function rg(n){var i,s;if(n==null)return null;let e=n;if(((i=e.constructor)==null?void 0:i.name)==="NullValue"||dwe(e))return null;if(typeof e.data!="undefined")return e.data;let t=pwe(e);if(t)return t;let r=uwe(e);if(r!==void 0)return r;if(e.date instanceof Date)return e.date.toISOString();if(((s=e.constructor)==null?void 0:s.name)==="DateValue"&&e.toISOString)return e.toISOString();if(e.file)return e.file.path;let a=Reflect.get(e,"toString");if(typeof a=="function"&&a!==Object.prototype.toString){let o=Reflect.apply(a,e,[]);if(o!=="[object Object]")return o}return n}function cwe(n){var r;if(n==null)return"Unknown";let e=n;if(((r=e.constructor)==null?void 0:r.name)==="NullValue")return"Unknown";if(dwe(e))return"None";let t=sKe(e);return oKe(t)}function sKe(n){if(n.file&&typeof n.file=="object")return n.file.path;if(n.date instanceof Date)return n.date;let e=pwe(n);if(e)return e;if(typeof n.data!="undefined")return n.data;let t=uwe(n);return t!==void 0?t:n}function dwe(n){return n.icon==="lucide-file-question"&&typeof n.data=="undefined"&&typeof n.display=="undefined"&&typeof n.label=="undefined"&&!(n.date instanceof Date)&&!n.file&&!Array.isArray(n.value)&&typeof n.get!="function"&&typeof n.at!="function"&&typeof n.length!="function"&&typeof n.toISOString!="function"}function uwe(n){for(let e of[n.value,n.display,n.label])if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e}function oKe(n){if(n==null)return"None";if(n instanceof Date){let e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),r=String(n.getDate()).padStart(2,"0");return`${e}-${t}-${r}`}return typeof n=="string"?n||"None":typeof n=="number"?String(n):typeof n=="boolean"?n?"True":"False":Array.isArray(n)?n.length>0?n.map(Y).join(", "):"None":Y(n)||"None"}function pwe(n){let e=typeof n.get=="function"?n.get.bind(n):typeof n.at=="function"?n.at.bind(n):null;if(typeof n.length=="function"&&e){let t=n.length(),r=[];for(let a=0;arg(t)):null}var Aq=y(()=>{dr()});function mwe(n){let t={...n.frontmatter||n.properties||{}},r=n.file;return r&&(r.name!==void 0&&(t["file.name"]=r.name),r.basename!==void 0&&(t["file.basename"]=r.basename),r.extension!==void 0&&(t["file.extension"]=r.extension),r.path!==void 0&&(t["file.path"]=r.path),r.stat&&(r.stat.size!==void 0&&(t["file.size"]=r.stat.size),r.stat.ctime!==void 0&&(t["file.ctime"]=r.stat.ctime),r.stat.mtime!==void 0&&(t["file.mtime"]=r.stat.mtime))),t}var fwe=y(()=>{});var E_,hwe=y(()=>{q();Aq();fwe();E_=class{constructor(e,t=M({tag:"Bases/DataAdapter"})){this.basesView=e;this.logger=t}extractDataItems(){return this.basesView.data.data.map(t=>({key:t.file.path,data:t,file:t.file,path:t.file.path,properties:this.extractEntryProperties(t),basesData:t}))}getGroupedData(){return this.basesView.data.groupedData}isGrouped(){let e=this.basesView.data.groupedData;return e.length!==1?!0:e[0].hasKey()}getSortConfig(){return this.basesView.config.getSort()}getVisiblePropertyIds(){return this.basesView.config.getOrder()}getPropertyDisplayName(e){return this.basesView.config.getDisplayName(e)}getPropertyValue(e,t){try{let r=e.getValue(t);return rg(r)}catch(r){return this.logger.warn("Failed to get property value",{category:"provider",operation:"get-property-value",details:{propertyId:t},error:r}),null}}convertGroupKeyToString(e){return cwe(e)}extractEntryProperties(e){return mwe(e)}getComputedProperty(e,t){if(!e||typeof e!="object")return null;try{let r=e.getValue;if(typeof r!="function")return null;let a=r.call(e,t);return rg(a)}catch(r){return null}}}});var AE,Mq=y(()=>{AE=class{constructor(e,t){this.fieldMapper=t!=null?t:e}basesToTaskCardProperty(e){if(this.fieldMapper&&this.fieldMapper.isRecognizedProperty(e))return this.applySpecialTransformations(e);if(e.startsWith("note.")){let t=e.substring(5);return this.fieldMapper&&this.fieldMapper.isRecognizedProperty(t)?this.applySpecialTransformations(t):t==="dateCreated"?"dateCreated":t==="dateModified"?"dateModified":t==="completedDate"?"completedDate":this.applySpecialTransformations(t)}if(e.startsWith("task.")){let t=e.substring(5);return this.fieldMapper&&this.fieldMapper.isRecognizedProperty(t)?this.applySpecialTransformations(t):this.applySpecialTransformations(t)}return e.startsWith("file.")?e==="file.ctime"?"dateCreated":e==="file.mtime"?"dateModified":e==="file.tasks"?"checklistProgress":e:e.startsWith("formula.")?e==="formula.checklistProgress"?"checklistProgress":e:this.applySpecialTransformations(e)}internalToUserProperty(e){let t=this.fieldMapper.getMapping();return e in t?this.fieldMapper.toUserField(e):e}userPropertyToInternal(e){return this.fieldMapper.lookupMappingKey(e)||e}basesToUserProperty(e){let t=this.basesToTaskCardProperty(e);return this.internalToUserProperty(t)}applySpecialTransformations(e){return e==="timeEntries"?"totalTrackedTime":e==="blockedBy"?"blocked":e==="file.tasks"||e==="formula.checklistProgress"?"checklistProgress":e}basesToInternal(e){return this.basesToTaskCardProperty(e)}basesToTaskInfoProperty(e){var a;let t=e.replace(/^(note\.|file\.|task\.)/,""),r=(a=this.fieldMapper)==null?void 0:a.lookupMappingKey(t);return r||(t==="ctime"||e==="file.ctime"?"dateCreated":t==="mtime"||e==="file.mtime"?"dateModified":t==="name"||t==="basename"?"title":t)}mapVisibleProperties(e){let t=new Set,r=[];for(let a of e){let i=this.basesToTaskCardProperty(a);t.has(i)||(t.add(i),r.push(i))}return r}}});function mm(n){if(n!=null)return L0(n)}function ca(n){if(n!=null)return Y(n)}function dKe(n){if(typeof n=="number")return n;if(typeof n=="string"&&n.trim()!==""){let e=Number(n);return Number.isNaN(e)?void 0:e}}function uKe(n){let e=ca(n);return e==="manual"||e==="on_completion"||e==="rolling"?e:void 0}function pKe(n){let e=ca(n);return e==="completion"||e==="completion_or_skip"?e:void 0}function mKe(n){return Array.isArray(n)?n:void 0}function fKe(n){return Array.isArray(n)?n:void 0}function hKe(n){return n===void 0?void 0:yf(n)}function gwe(n,e,t){var d,u,p;let r=new Set(["title","status","priority","archived","due","scheduled","contexts","projects","tags","timeEstimate","completedDate","recurrence","recurrence_parent","occurrence_date","occurrence_materialization","occurrence_next_trigger","occurrence_template","occurrence_past_horizon","occurrence_future_horizon","dateCreated","dateModified","timeEntries","reminders","icsEventId","complete_instances","skipped_instances","googleCalendarExceptionOriginalScheduled","googleCalendarMovedOriginalDates","blockedBy","blocking","sortOrder","customProperties"]),a={};Object.keys(n).forEach(m=>{r.has(m)||(a[m]=n[m])});let i=mKe(n.timeEntries),s=i?oi(i):0,o=!1,l=[],c=!1;return t!=null&&t.dependencyCache&&e.path?(o=t.dependencyCache.isTaskBlocked(e.path),l=t.dependencyCache.getBlockedTaskPaths(e.path),c=l.length>0):o=Array.isArray(n.blockedBy)&&n.blockedBy.length>0,{title:ca(n.title)||e.name||((u=(d=e.path)==null?void 0:d.split("/").pop())==null?void 0:u.replace(".md",""))||"Untitled",status:ca(n.status)||((p=t==null?void 0:t.settings)==null?void 0:p.defaultTaskStatus)||"open",priority:ca(n.priority)||"normal",path:e.path||"",archived:n.archived===!0,due:ca(n.due),scheduled:ca(n.scheduled),contexts:mm(n.contexts),projects:mm(n.projects),attachments:mm(n.attachments),tags:mm(n.tags),timeEstimate:dKe(n.timeEstimate),completedDate:ca(n.completedDate),recurrence:ca(n.recurrence),recurrence_parent:ca(n.recurrence_parent),occurrence_date:ca(n.occurrence_date),occurrence_materialization:uKe(n.occurrence_materialization),occurrence_next_trigger:pKe(n.occurrence_next_trigger),occurrence_template:ca(n.occurrence_template),occurrence_past_horizon:ca(n.occurrence_past_horizon),occurrence_future_horizon:ca(n.occurrence_future_horizon),dateCreated:ca(n.dateCreated),dateModified:ca(n.dateModified),timeEntries:i,totalTrackedTime:s,reminders:fKe(n.reminders),icsEventId:mm(n.icsEventId),complete_instances:mm(n.complete_instances),skipped_instances:mm(n.skipped_instances),googleCalendarExceptionOriginalScheduled:ca(n.googleCalendarExceptionOriginalScheduled),googleCalendarMovedOriginalDates:mm(n.googleCalendarMovedOriginalDates),blockedBy:hKe(n.blockedBy),blocking:l.length>0?l:void 0,isBlocked:o,isBlocking:c,sortOrder:ca(n.sortOrder),customProperties:Object.keys(a).length>0?a:void 0,basesData:e.basesData}}function gKe(n,e){let t={...n!=null?n:{},...e!=null?e:{}};return Object.keys(t).length>0?t:void 0}function ywe(n,e){var r,a;let t=(a=(r=e==null?void 0:e.cacheManager)==null?void 0:r.getCachedTaskInfoSync)==null?void 0:a.call(r,n.path);return t?{...t,basesData:n.basesData,customProperties:gKe(t.customProperties,n.customProperties)}:n}function yKe(n,e){if(!(n!=null&&n.path))return null;let t=n.properties||n.frontmatter||{};if(e!=null&&e.fieldMapper){let r=e.fieldMapper.mapFromFrontmatter(t,n.path,e.settings.storeTitleInFilename),a=gwe(r,n,e),i={};return Object.keys(t).forEach(s=>{s.startsWith("file.")&&(i[s]=t[s])}),ywe({...a,customProperties:{...r.customProperties,...a.customProperties,...i}},e)}else return ywe(gwe(t,n,e),e)}async function yu(n,e,t){let r=t||yKe,a=[];for(let i of n)if(i!=null&&i.path)try{let s=r(i,e);s&&a.push(s)}catch(s){cKe.warn("[TaskNotes][BasesPOC] Error converting Bases item to TaskInfo:",{category:"validation",operation:"converting-bases-item-taskinfo",error:s})}return a}var lKe,cKe,ME=y(()=>{lKe=require("obsidian");yt();Yl();jf();Mq();Zs();dr();q();Li();cKe=M({tag:"Bases/Helpers"})});function Iq(n){return Array.isArray(n)?n.map(String):[String(n)]}function Mo(n,e,t){return n[e.toUserField(t)]}function fm(n){return Y(n)}function kKe(n,e){return new Set([...vKe.map(t=>n.toUserField(t)),n.toUserField("archiveTag"),"tags",...e.map(t=>t.key)])}function vwe(n,e,t=[]){let r={},a={},i=Mo(n,e,"title");i!==void 0&&(r.title=fm(i));let s=Mo(n,e,"status");s!==void 0&&(r.status=fm(s));let o=Mo(n,e,"priority");o!==void 0&&(r.priority=fm(o));let l=Mo(n,e,"due");l!==void 0&&(r.due=fm(l));let c=Mo(n,e,"scheduled");c!==void 0&&(r.scheduled=fm(c));let d=Mo(n,e,"contexts");d!==void 0&&(r.contexts=Iq(d));let u=Mo(n,e,"projects");u!==void 0&&(r.projects=Iq(u)),n.tags!==void 0&&(r.tags=Iq(n.tags)),Array.isArray(n.tags)&&(r.archived=n.tags.includes(e.toUserField("archiveTag")));let p=Mo(n,e,"timeEstimate");p!==void 0&&(r.timeEstimate=Number(p));let m=Mo(n,e,"recurrence");m!==void 0&&(r.recurrence=fm(m));let f=Mo(n,e,"completedDate");f!==void 0&&(r.completedDate=fm(f));let h=Mo(n,e,"dateCreated");h!==void 0&&(r.dateCreated=fm(h));let g=Mo(n,e,"blockedBy");g!==void 0&&(r.blockedBy=yf(g));for(let T of t)n[T.key]!==void 0&&(a[T.key]=n[T.key]);let v=kKe(e,t);for(let[T,b]of Object.entries(n))v.has(T)||(a[T]=b);let k={...r};return Object.keys(a).length>0&&(k.customFrontmatter=a),k}var vKe,kwe=y(()=>{Zs();dr();vKe=["title","status","priority","due","scheduled","contexts","projects","timeEstimate","recurrence","completedDate","dateCreated","blockedBy"]});function P_(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Nq(n){try{return JSON.parse(`"${n}"`)}catch(e){return n}}function Twe(n){let e={},t=P_(n.config)?n.config:{},r=P_(t.query)?t.query:void 0;return _q(r==null?void 0:r.filters,e,n),_q(t.filters,e,n),e}function _q(n,e,t){if(!P_(n))return;let r=n,a=Array.isArray(r.filters)?r.filters:[];if(a.length>0){if(r.conjunction!==void 0&&r.conjunction!=="and")return;for(let s of a)_q(s,e,t);return}let i=P_(r.rule)?r.rule.text:void 0;typeof i=="string"&&TKe(i,e,t)}function TKe(n,e,t){let r=n.trim(),a=r.match(/^file\.hasTag\("((?:\\.|[^"\\])*)"\)$/);if(a){let l=Nq(a[1]);l!==t.taskTag&&D_(e,"tags",l,t.fieldMapper);return}let i=r.match(/^(.+?)\s*==\s*"((?:\\.|[^"\\])*)"$/);if(i){let l=Rq(i[1],t);l&&D_(e,l,Nq(i[2]),t.fieldMapper);return}let s=r.match(/^(.+?)\.contains\("((?:\\.|[^"\\])*)"\)$/);if(s){let l=Rq(s[1],t);l&&D_(e,l,Nq(s[2]),t.fieldMapper);return}let o=r.match(/^(.+?)\.contains\(this\.file\.asLink\(\)\)$/);if(o){let l=o[1].trim(),c=`.map(${vb("value")})`;l.endsWith(c)&&(l=l.slice(0,-c.length).replace(/^file\.hasLink\(this\.file\)\s*&&\s*/,""));let d=Rq(l,t),u=bKe(t.currentFileLink);d&&u&&D_(e,d,u,t.fieldMapper)}}function bKe(n){return typeof n=="function"?n():n!=null?n:null}function Rq(n,e){var a;let t=n.trim(),r=t.match(/^list\((.+)\)$/);if(r&&(t=r[1].trim()),t=t.replace(/^(note|task)\./,""),t==="tags"||t==="file.tags")return"tags";for(let i of wKe){let s=e.fieldMapper.toUserField(i);if(t===i||t===s)return s}return(a=e.userFields)!=null&&a.some(i=>i.key===t)?t:null}function D_(n,e,t,r){if(!new Set(["tags",r.toUserField("contexts"),r.toUserField("projects"),r.toUserField("blockedBy")]).has(e)){n[e]===void 0&&(n[e]=t);return}let i=n[e],s=Array.isArray(i)?i.filter(o=>typeof o=="string"):typeof i=="string"?[i]:[];s.includes(t)||(n[e]=[...s,t])}var wKe,bwe=y(()=>{G1();wKe=["title","status","priority","due","scheduled","contexts","projects","timeEstimate","completedDate","dateCreated","recurrence","blockedBy"]});function wwe({config:n,fieldMapper:e,taskTag:t,userFields:r=[],currentFileLink:a,frontmatterProcessor:i}){let s=Twe({config:n,fieldMapper:e,taskTag:t,userFields:r,currentFileLink:a});return i==null||i(s),vwe(s,e,r)}function Swe(n){let e=n.workspace.getActiveFile();return!e||e.extension==="base"?null:n.fileManager.generateMarkdownLink(e,e.path)}var Cwe=y(()=>{kwe();bwe()});function Ewe(n,e){let t=SKe(e),r=n.map(a=>t.map(i=>{var s,o;return i.id==="file"?(o=(s=a.file)==null?void 0:s.path)!=null?o:"":CKe(e.getPropertyValue(a,i.id))}));return{columns:t,rows:r}}function SKe(n){let e=n.getVisiblePropertyIds();return[{id:"file",label:"File"},...e.map(t=>({id:t,label:n.getPropertyDisplayName(t)||t}))]}function CKe(n){return Y(n).replace(/\r?\n/g," ")}function Dwe(n){return[n.columns.map(e=>xwe(e.label)),...n.rows].map(e=>e.map(xwe).join(" ")).join(` +`)}function Pwe(n){return[n.columns.map(e=>e.label),...n.rows].map(e=>e.map(xKe).join(",")).join(` +`)}function Awe(n,e){let r=Y(n)||e||"tasknotes-bases-export";return`${EKe(r)}.csv`}function xwe(n){return n.replace(/\t/g," ")}function xKe(n){return/[",\r\n]/.test(n)?`"${n.replace(/"/g,'""')}"`:n}function EKe(n){return n.trim().replace(/[\\/:*?"<>|]+/g,"-").replace(/\s+/g,"-").replace(/^-+|-+$/g,"")||"tasknotes-bases-export"}var Mwe=y(()=>{dr()});function Iwe(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Nwe(n,e){var o,l,c,d;let t=Iwe(n)?n:{},r=(l=(o=t.updatedTask)!=null?o:t.task)!=null?l:t.taskInfo;if(!(r!=null&&r.path))return{action:"ignore"};let a=r.path,i=(d=(c=t.originalTask)==null?void 0:c.path)!=null?d:typeof t.path=="string"?t.path:void 0;return e.has(a)||(i?e.has(i):!1)?i&&i!==a?{action:"refresh-renamed-task",removePath:i,addPath:a}:{action:"handle-task",task:r,source:PKe(t)}:DKe(t)?{action:"refresh-view"}:{action:"ignore"}}function DKe(n){return n.originalTask?!0:!(n.task!==void 0||n.taskInfo!==void 0)}function PKe(n){return n.task!==void 0||n.taskInfo!==void 0?"metadata-cache":"tasknotes-service"}function Rwe(n,e){var s,o,l,c;let t=Iwe(n)?n:{},r=typeof t.path=="string"?t.path:(s=t.deletedTask)==null?void 0:s.path,a=typeof r=="string"&&e.renderedTaskPaths.has(r),i=((c=(l=(o=t.deletedTask)==null?void 0:o.projects)==null?void 0:l.length)!=null?c:0)>0||AKe(t.prevCache,e.projectsField);return{deletedPath:r,shouldRefresh:a||i}}function _we(n){let e=new Set;if(!n)return e;let t=n.querySelectorAll(".task-card[data-task-path]");for(let r of Array.from(t))r.dataset.taskPath&&e.add(r.dataset.taskPath);return e}function AKe(n,e){let t=n==null?void 0:n.frontmatter;if(!t)return!1;let r=t[e];return Array.isArray(r)?r.length>0:typeof r=="string"&&r.trim().length>0}var Fq=y(()=>{});function Owe(n){var r;let e=n.closest(".bases-view"),t=e==null?void 0:e.parentElement;(r=t==null?void 0:t.querySelector(`.${Lq}`))==null||r.remove(),t==null||t.classList.remove(Lwe)}function zwe(n){var d;let e=n.containerEl.closest(".bases-view");if(!e)return"missing-bases-view";let t=e.parentElement;if(!t)return"missing-parent";t.classList.add(Lwe);let r=t.querySelector(".bases-toolbar");if(!r)return"missing-toolbar";(d=r.querySelector(`.${Lq}`))==null||d.remove();let a=n.containerEl.ownerDocument,i=Ie(a,"div");i.className=`bases-toolbar-item ${Lq}`;let s=Ie(a,"button");s.className="text-icon-button",s.type="button",s.setAttribute("aria-label",n.label);let o=Ie(a,"span");o.className="text-button-icon",(0,Fwe.setIcon)(o,"plus"),s.appendChild(o);let l=Ie(a,"span");l.className="text-button-label",l.textContent=n.label,s.appendChild(l),i.appendChild(s),i.addEventListener("click",n.onClick);let c=r.querySelector(".bases-toolbar-new-item-menu");return c?c.before(i):r.appendChild(i),"injected"}var Fwe,Lwe,Lq,Bwe=y(()=>{Fwe=require("obsidian");Li();Lwe="tasknotes-view-active",Lq="tn-bases-new-task-btn"});function jwe({basesPropertyIds:n,propertyMapper:e,fallbackInternalProperties:t,toUserProperties:r}){let a=e.mapVisibleProperties([...n]);return a.length>0?a:r(t)}function $we({basesPropertyIds:n,propertyMapper:e,getDisplayName:t}){let r={};for(let a of n){let i=e.basesToTaskCardProperty(a),s=t(a);i&&typeof s=="string"&&s.trim()!==""&&(r[i]=s)}return r}var Uwe=y(()=>{});var Hwe,A_,Vwe=y(()=>{Hwe=require("obsidian");tc();Li();A_=class{constructor(e,t,r=300){this.searchBoxEl=null;this.inputEl=null;this.clearBtnEl=null;this.debouncedSearch=null;this.destroyed=!1;this.handleInput=()=>{if(!this.inputEl)return;let e=this.inputEl.value;this.updateClearButtonVisibility(),this.debouncedSearch&&this.debouncedSearch(e)};this.handleKeydown=e=>{e.key==="Escape"&&(this.clear(),this.debouncedSearch&&this.debouncedSearch(""))};this.handleClear=()=>{var e;this.clear(),this.debouncedSearch&&this.debouncedSearch(""),(e=this.inputEl)==null||e.focus()};this.container=e,this.onSearch=t,this.debounceMs=r,this.debouncedSearch=iv(a=>{this.destroyed||this.onSearch(a)},this.debounceMs,!1)}render(){let e=this.container.ownerDocument;this.searchBoxEl=Ie(e,"div"),this.searchBoxEl.className="tn-search-box";let t=Ie(e,"div");t.className="tn-search-box__input-wrapper";let r=Ie(e,"div");r.className="tn-search-box__icon",(0,Hwe.setIcon)(r,"search"),this.inputEl=Ie(e,"input"),this.inputEl.type="text",this.inputEl.className="tn-search-box__input",this.inputEl.placeholder="Search tasks...",this.inputEl.setAttribute("aria-label","Search tasks");let a=Ie(e,"button");return a.type="button",a.className="tn-search-box__clear",a.textContent="×",a.setAttribute("aria-label","Clear search"),this.clearBtnEl=a,t.appendChild(r),t.appendChild(this.inputEl),t.appendChild(this.clearBtnEl),this.searchBoxEl.appendChild(t),this.container.appendChild(this.searchBoxEl),this.attachEventListeners(),this.searchBoxEl}attachEventListeners(){!this.inputEl||!this.clearBtnEl||(this.inputEl.addEventListener("input",this.handleInput),this.inputEl.addEventListener("keydown",this.handleKeydown),this.clearBtnEl.addEventListener("click",this.handleClear))}updateClearButtonVisibility(){if(!this.inputEl||!this.clearBtnEl)return;this.inputEl.value.length>0?this.clearBtnEl.classList.add("is-visible"):this.clearBtnEl.classList.remove("is-visible")}getValue(){var e;return((e=this.inputEl)==null?void 0:e.value)||""}setValue(e){this.inputEl&&(this.inputEl.value=e,this.updateClearButtonVisibility())}clear(){this.inputEl&&(this.inputEl.value="",this.updateClearButtonVisibility())}destroy(){this.destroyed=!0,this.inputEl&&(this.inputEl.removeEventListener("input",this.handleInput),this.inputEl.removeEventListener("keydown",this.handleKeydown)),this.clearBtnEl&&this.clearBtnEl.removeEventListener("click",this.handleClear),this.inputEl=null,this.clearBtnEl=null,this.searchBoxEl=null,this.debouncedSearch=null}}});var M_,Wwe=y(()=>{dr();M_=class{constructor(e){this.visibleProperties=e||[]}filterTasks(e,t){let a=this.normalizeSearchTerm(t).split(/\s+/).filter(Boolean);return a.length===0?e:e.filter(i=>{let s=this.extractSearchableText(i);return a.some(o=>s.includes(o))})}extractSearchableText(e){let t=[];if(t.push(e.title||""),t.push(e.status||""),t.push(e.priority||""),e.tags&&Array.isArray(e.tags)&&t.push(e.tags.join(" ")),e.contexts&&Array.isArray(e.contexts)&&t.push(e.contexts.join(" ")),e.projects&&Array.isArray(e.projects)&&t.push(e.projects.join(" ")),e.customProperties&&this.visibleProperties.length>0)for(let r of this.visibleProperties){let a=e.customProperties[r];a!=null&&(Array.isArray(a)?t.push(a.join(" ")):t.push(Y(a)))}return t.join(" ").toLowerCase()}normalizeSearchTerm(e){return e.trim().toLowerCase()}}});function qwe({container:n,visibleProperties:e,currentSearchTerm:t,onSearch:r,debounceMs:a=300}){let i=n.ownerDocument,s=Ie(i,"div");s.className="tn-search-container",n.firstChild?n.insertBefore(s,n.firstChild):n.appendChild(s);let o=new M_([...e]),l=new A_(s,r,a);return l.render(),t&&l.setValue(t),{searchContainer:s,searchBox:l,searchFilter:o}}function Gwe(n,e,t){return n.length>0&&e===0&&t>0}function Ywe(n,e){let t=n.ownerDocument,r=Ie(t,"div");r.className="tn-search-no-results";let a=Ie(t,"div");a.className="tn-search-no-results__text",a.textContent=`No tasks match "${e}"`;let i=Ie(t,"div");return i.className="tn-search-no-results__hint",i.textContent="Try a different search term or clear the search",r.appendChild(a),r.appendChild(i),n.appendChild(r),r}var Kwe=y(()=>{Vwe();Wwe();Li()});function Jwe(n,e){if(e){n.classList.add("tn-selection-mode"),n.setAttribute("data-selection-mode","true");return}n.classList.remove("tn-selection-mode"),n.removeAttribute("data-selection-mode"),I_(n)}function Xwe(n,e){if(!e){I_(n);return}let t=e.getPrimarySelectedPath(),r=n.querySelectorAll(".task-card");for(let i of r)Qwe({element:i,path:i.dataset.taskPath,selected:i.dataset.taskPath?e.isSelected(i.dataset.taskPath):!1,primary:i.dataset.taskPath===t,selectedClass:"task-card--selected",primaryClass:"task-card--selected-primary"});let a=n.querySelectorAll(".kanban-view__card-wrapper");for(let i of a)Qwe({element:i,path:i.dataset.taskPath,selected:i.dataset.taskPath?e.isSelected(i.dataset.taskPath):!1,primary:i.dataset.taskPath===t,selectedClass:"kanban-view__card-wrapper--selected",primaryClass:"kanban-view__card-wrapper--selected-primary"})}function I_(n){let e=n.querySelectorAll(".task-card--selected");for(let r of e)r.classList.remove("task-card--selected"),r.classList.remove("task-card--selected-primary");let t=n.querySelectorAll(".kanban-view__card-wrapper--selected");for(let r of t)r.classList.remove("kanban-view__card-wrapper--selected"),r.classList.remove("kanban-view__card-wrapper--selected-primary")}function eSe({rootElement:n,indicatorEl:e,count:t,onClearSelection:r}){if(t<=0)return e&&Zwe(e,"tn-static-display-none-6b99de8b"),e;let a=e!=null?e:IKe(n);return a.onclick=()=>{r()},a.onkeydown=i=>{i.key!=="Enter"&&i.key!==" "||(i.preventDefault(),r())},a.textContent=`${t} selected`,a.setAttribute("aria-label",`${t} selected. Activate to clear selection.`),Zwe(a,"tn-static-display-block-2a1b75c9"),a}function tSe({event:n,taskPath:e,selectionService:t,getVisibleTaskPaths:r,updateSelectionVisuals:a}){return!t||!t.isSelectionModeActive()&&!n.shiftKey&&!n.ctrlKey&&!n.metaKey?!1:(n.shiftKey&&!t.isSelectionModeActive()&&t.enterSelectionMode(),n.shiftKey?t.selectRange(e,r()):(n.ctrlKey||n.metaKey||t.isSelectionModeActive())&&t.toggleSelection(e),a(),!0)}function rSe({event:n,selectionService:e,getVisibleTaskPaths:t,updateSelectionModeUi:r,updateSelectionVisuals:a}){if(!(e!=null&&e.isSelectionModeActive())||RKe(n.target))return!1;if(n.key==="Escape")return e.exitSelectionMode(!0),r(!1),!0;if((n.ctrlKey||n.metaKey)&&n.key.toLowerCase()==="a")return n.preventDefault(),e.selectAll(t()),a(),!0;let i=NKe(n);return i!==null?(n.preventDefault(),e.selectAdjacentRange(i,t()),a(),!0):!1}function nSe(n){if(!n)return[];let e=n.querySelectorAll(".task-card[data-task-path]"),t=[];for(let r of e){let a=r.dataset.taskPath;a&&t.push(a)}return t}function IKe(n){let e=n.ownerDocument,t=Ie(e,"div");return t.className="tn-selection-indicator",t.setAttribute("role","button"),t.tabIndex=0,n.appendChild(t),t}function Zwe(n,e){n.classList.remove(...MKe),n.classList.add(e)}function Qwe({element:n,path:e,selected:t,primary:r,selectedClass:a,primaryClass:i}){if(!e||!t){n.classList.remove(a),n.classList.remove(i);return}n.classList.add(a),r?n.classList.add(i):n.classList.remove(i)}function NKe(n){return n.shiftKey?n.key==="ArrowUp"||n.key==="ArrowLeft"?-1:n.key==="ArrowDown"||n.key==="ArrowRight"?1:null:null}function RKe(n){if(!(n instanceof HTMLElement))return!1;if(n.isContentEditable)return!0;let e=n.tagName.toLowerCase();return e==="input"||e==="textarea"||e==="select"}var MKe,aSe=y(()=>{Li();MKe=["tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"]});function _Ke(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function FKe(n,e,t){let r=n;if(r&&typeof r.then=="function"){r.then(e,e);return}t(e,0)}function iSe({controller:n,view:e,isConnected:t,refresh:r,scheduleTimeout:a}){if(!_Ke(n)||typeof n.onConfigChanged!="function")return null;let i=n,s=i.onConfigChanged;if(!s)return null;let o=()=>{i.view&&i.view!==e||t()&&r()},l=(...c)=>{let d=s.apply(i,c);return FKe(d,o,a),d};return i.onConfigChanged=l,()=>{i.onConfigChanged===l&&(i.onConfigChanged=s)}}function sSe({currentTimer:n,scheduler:e,isConnected:t,beforeRender:r,render:a,onTimerCleared:i,onRenderError:s,delayMs:o=500}){return t()?(n&&e.clearTimeout(n),e.setTimeout(()=>{i();try{r(),a()}catch(l){s(l)}},o)):n}function oSe({currentTimer:n,scheduler:e,render:t,onTimerCleared:r,delayMs:a=300}){return n&&e.clearTimeout(n),e.setTimeout(()=>{try{t()}finally{r()}},a)}var lSe=y(()=>{});function dSe(n){return[{name:"Copy task filenames",icon:"lucide-file-text",callback:()=>n("filenames")},{name:"Copy task links",icon:"lucide-link",callback:()=>n("markdown-links")},{name:"Copy task titles",icon:"lucide-text",callback:()=>n("titles")}]}async function uSe({dataItems:n,format:e,identifyTaskNotes:t,filterTasks:r,resolveLinkText:a,writeText:i}){let s=await t(n),l=r(s).map(d=>({path:d.path,title:d.title}));if(l.length===0)return{status:"empty"};let c=UA(l,e,a);return await i(c),{status:"copied",count:l.length}}function pSe(n,e){let t=n.vault.getAbstractFileByPath(e);return t instanceof cSe.TFile?n.metadataCache.fileToLinktext(t,""):e}var cSe,mSe=y(()=>{cSe=require("obsidian");T$()});async function LKe({eventData:n,isConnected:e,relevantPathsCache:t,handleTaskUpdate:r,debouncedRefresh:a,onError:i}){try{if(!e())return;let s=Nwe(n,t);if(s.action==="refresh-view"){a();return}if(s.action==="refresh-renamed-task"){t.delete(s.removePath),t.add(s.addPath),a();return}s.action==="handle-task"&&await r(s.task,s.source)}catch(s){i(s),a()}}function fSe({emitter:n,isConnected:e,relevantPathsCache:t,handleTaskUpdate:r,handleTaskDeleted:a,debouncedRefresh:i,onError:s}){let o=n.on(rt,d=>LKe({eventData:d,isConnected:e,relevantPathsCache:t,handleTaskUpdate:r,debouncedRefresh:i,onError:s})),l=n.on(Di,d=>{a(d)}),c=n.on("file-deleted",d=>{a(d)});return[o,l,c]}function hSe(n,e){for(let t of e)n.offref(t)}var gSe=y(()=>{Pr();Fq()});function OKe(n,e){return e!==n||n.trim().startsWith("[[")}function zKe(n,e,t){if(!Array.isArray(n.projects)||n.projects.length===0)return!1;for(let r of n.projects){if(typeof r!="string"||r.trim().length===0)continue;let a=vt(r);if(!OKe(r,a))continue;let i=t(a,n.path);if(i!=null&&i.path&&e.has(i.path))return!0}return!1}function ySe(n,e){let t=new Set(n.map(r=>r.path));return n.filter(r=>!zKe(r,t,e))}var vSe=y(()=>{Cn()});function BKe(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}var zc,Bc,IE=y(()=>{zc=require("obsidian");hwe();Mq();Yl();jf();w$();ME();Cwe();Mwe();Fq();Bwe();Uwe();Kwe();aSe();Li();lSe();mSe();gSe();vSe();q();Bc=class extends zc.Component{constructor(t,r,a){super();this.app=void 0;this.config=void 0;this.data=void 0;this.allProperties=[];this.rootElement=null;this.taskUpdateListener=null;this.updateDebounceTimer=null;this.dataUpdateDebounceTimer=null;this.restoreConfigChangeHook=null;this.relevantPathsCache=new Set;this.enableSearch=!1;this.searchBox=null;this.searchContainerEl=null;this.searchFilter=null;this.currentSearchTerm="";this.selectionModeCleanup=null;this.selectionIndicatorEl=null;this.plugin=a,this.containerEl=r,this.logger=M({tag:()=>`Bases/${this.type}`,isDebugEnabled:()=>this.plugin.settings.enableDebugLogging}),this.dataAdapter=new E_(this,this.logger.child("DataAdapter")),this.propertyMapper=new AE(a.fieldMapper),this.createFileForView=this.createFileForView.bind(this),this.setupConfigChangeHook(t)}setupConfigChangeHook(t){let r=iSe({controller:t,view:this,isConnected:()=>{var a;return!!((a=this.rootElement)!=null&&a.isConnected)},refresh:()=>this.debouncedRefresh(),scheduleTimeout:(a,i)=>{this.getTimeoutScheduler().setTimeout(a,i)}});r&&(this.restoreConfigChangeHook=r,typeof this.register=="function"&&this.register(()=>{var a;(a=this.restoreConfigChangeHook)==null||a.call(this),this.restoreConfigChangeHook=null}))}getTimeoutScheduler(){let t=this.containerEl.ownerDocument.defaultView||window;return{setTimeout:(r,a)=>t.setTimeout(r,a),clearTimeout:r=>t.clearTimeout(r)}}onload(){this.setupContainer(),this.setupTaskUpdateListener(),this.setupSelectionHandling(),this.updateRelevantPathsCache(),this.render()}onDataUpdated(){var t;(t=this.rootElement)!=null&&t.isConnected&&(this.dataUpdateDebounceTimer=sSe({currentTimer:this.dataUpdateDebounceTimer,scheduler:this.getTimeoutScheduler(),isConnected:()=>{var r;return!!((r=this.rootElement)!=null&&r.isConnected)},beforeRender:()=>this.updateRelevantPathsCache(),render:async()=>{let r=this.getEphemeralState();try{await this.render()}finally{this.setEphemeralState(r)}},onTimerCleared:()=>{this.dataUpdateDebounceTimer=null},onRenderError:r=>{this.logger.error("Render error during data update",{category:"internal",operation:"data-update-render",error:r}),this.renderError(r)},delayMs:500}))}updateRelevantPathsCache(){this.relevantPathsCache.clear();try{let t=this.dataAdapter.extractDataItems();for(let r of t)r.path&&this.relevantPathsCache.add(r.path)}catch(t){}}getEphemeralState(){var t;return{scrollTop:((t=this.rootElement)==null?void 0:t.scrollTop)||0,containerScrollTop:this.containerEl.scrollTop||0}}setEphemeralState(t){if(!(!BKe(t)||!this.rootElement||!this.rootElement.isConnected))try{let r=t;typeof r.scrollTop=="number"&&(this.rootElement.scrollTop=r.scrollTop),typeof r.containerScrollTop=="number"&&(this.containerEl.scrollTop=r.containerScrollTop)}catch(r){this.logger.debug("Failed to restore ephemeral state",{category:"stale-data",operation:"restore-ephemeral-state",error:r})}}focus(){var t;try{(t=this.rootElement)!=null&&t.isConnected&&typeof this.rootElement.focus=="function"&&this.rootElement.focus()}catch(r){this.logger.debug("Failed to focus view",{category:"internal",operation:"focus-view",error:r})}}refresh(){this.render()}copyToClipboard(){this.copyBasesTableToClipboard()}exportTable(){this.exportBasesTableAsCsv()}getViewActions(){return dSe(t=>{this.copyCurrentViewTasks(t)})}onResize(){}setupContainer(){this.containerEl.empty();let t=this.containerEl.ownerDocument,r=Ie(t,"div");r.className=`tn-bases-integration tasknotes-plugin tasknotes-container tn-${this.type}`,r.tabIndex=-1,this.containerEl.appendChild(r),this.rootElement=r,this.setupNewTaskButton()}setupNewTaskButton(){window.setTimeout(()=>this.injectNewTaskButton(),100),this.register(()=>this.cleanupNewTaskButton())}cleanupNewTaskButton(){Owe(this.containerEl)}injectNewTaskButton(){let t=zwe({containerEl:this.containerEl,label:this.plugin.i18n.translate("common.new"),onClick:r=>{r.preventDefault(),r.stopPropagation(),this.createFileForView("New Task")}});if(t==="missing-bases-view"){this.logger.debug("No .bases-view element found",{category:"provider",operation:"inject-new-task-button"});return}if(t==="missing-parent"){this.logger.debug("No parent element found for Bases view",{category:"provider",operation:"inject-new-task-button"});return}if(t==="missing-toolbar"){this.logger.debug("No .bases-toolbar element found",{category:"provider",operation:"inject-new-task-button"});return}this.logger.debug("Injected New Task button into toolbar",{category:"provider",operation:"inject-new-task-button"})}setupTaskUpdateListener(){this.taskUpdateListener||(this.taskUpdateListener=fSe({emitter:this.plugin.emitter,isConnected:()=>{var t;return!!((t=this.rootElement)!=null&&t.isConnected)},relevantPathsCache:this.relevantPathsCache,handleTaskUpdate:(t,r)=>this.handleTaskUpdate(t,r),handleTaskDeleted:t=>this.handleTaskDeletedEvent(t),debouncedRefresh:()=>this.debouncedRefresh(),onError:t=>{this.logger.error("Error in task update handler",{category:"internal",operation:"task-update-handler",error:t})}}),this.register(()=>{this.taskUpdateListener&&(hSe(this.plugin.emitter,this.taskUpdateListener),this.taskUpdateListener=null)}))}handleTaskDeletedEvent(t){var a,i;let r=Rwe(t,{projectsField:this.plugin.fieldMapper.toUserField("projects"),renderedTaskPaths:_we(this.rootElement)});r.deletedPath&&this.relevantPathsCache.delete(r.deletedPath),(a=this.plugin.projectSubtasksService)==null||a.invalidateIndex(),(i=this.rootElement)!=null&&i.isConnected&&r.shouldRefresh&&this.debouncedRefresh()}debouncedRefresh(){this.updateDebounceTimer=oSe({currentTimer:this.updateDebounceTimer,scheduler:this.getTimeoutScheduler(),render:async()=>{let t=this.getEphemeralState();try{await this.render()}finally{this.setEphemeralState(t)}},onTimerCleared:()=>{this.updateDebounceTimer=null},delayMs:300})}async createFileForView(t,r){let{TaskCreationModal:a}=await Promise.resolve().then(()=>(UM(),Sue)),i=this.app||this.plugin.app,s=wwe({config:this.config,fieldMapper:this.plugin.fieldMapper,taskTag:this.plugin.settings.taskTag,userFields:this.plugin.settings.userFields||[],currentFileLink:()=>Swe(i),frontmatterProcessor:r});new a(i,this.plugin,{prePopulatedValues:s,onTaskCreated:l=>{this.refresh()}}).open()}getVisibleProperties(){let t=this.plugin.settings.defaultVisibleProperties||[...oC,"tags"];return jwe({basesPropertyIds:this.config.getOrder(),propertyMapper:this.propertyMapper,fallbackInternalProperties:t,toUserProperties:r=>di([...r],this.plugin)})}getVisiblePropertyLabels(){return $we({basesPropertyIds:this.config.getOrder(),propertyMapper:this.propertyMapper,getDisplayName:t=>{var r,a;return(a=(r=this.config).getDisplayName)==null?void 0:a.call(r,t)}})}buildTaskCardOptions(t={}){return{propertyLabels:this.getVisiblePropertyLabels(),...t}}filterTopLevelSubtasks(t){return ySe(t,(r,a)=>this.plugin.app.metadataCache.getFirstLinkpathDest(r,a))}setupSearch(t){if(this.searchBox&&!this.enableSearch){this.teardownSearch();return}if(this.searchBox){this.currentSearchTerm&&this.searchBox.getValue()!==this.currentSearchTerm&&this.searchBox.setValue(this.currentSearchTerm);return}if(!this.enableSearch)return;let r=[];try{this.config&&(r=this.getVisibleProperties())}catch(i){this.logger.debug("Could not get visible properties during search setup",{category:"provider",operation:"setup-search",error:i})}let a=qwe({container:t,visibleProperties:r,currentSearchTerm:this.currentSearchTerm,onSearch:i=>this.handleSearch(i)});this.searchFilter=a.searchFilter,this.searchBox=a.searchBox,this.searchContainerEl=a.searchContainer,this.register(()=>this.teardownSearch())}teardownSearch(){var t;this.searchBox&&(this.searchBox.destroy(),this.searchBox=null),(t=this.searchContainerEl)==null||t.remove(),this.searchContainerEl=null,this.searchFilter=null,this.currentSearchTerm=""}handleSearch(t){let r=performance.now();this.currentSearchTerm=t,this.render();let a=performance.now()-r;a>200&&this.logger.warn("Slow search",{category:"internal",operation:"search",details:{elapsedMs:a,term:t}})}applySearchFilter(t){if(!this.searchFilter||!this.currentSearchTerm)return t;let r=performance.now(),a=this.searchFilter.filterTasks(t,this.currentSearchTerm),i=performance.now()-r;return i>100&&this.logger.warn("Slow filter operation",{category:"internal",operation:"filter",details:{elapsedMs:i,taskCount:t.length}}),a}async copyCurrentViewTasks(t){try{let r=this.app||this.plugin.app,a=await uSe({dataItems:this.dataAdapter.extractDataItems(),format:t,identifyTaskNotes:i=>yu(i,this.plugin),filterTasks:i=>this.applySearchFilter(i),resolveLinkText:i=>pSe(r,i.path),writeText:i=>navigator.clipboard.writeText(i)});if(a.status==="empty"){new zc.Notice("No tasks to copy");return}new zc.Notice(`Copied ${a.count} tasks`)}catch(r){this.logger.error("Failed to copy current view tasks",{category:"provider",operation:"copy-current-view-tasks",error:r}),new zc.Notice("Failed to copy tasks")}}getBasesExportTable(){var t,r;return Ewe((r=(t=this.data)==null?void 0:t.data)!=null?r:[],this.dataAdapter)}getBasesExportFileName(){var r;let t=typeof((r=this.config)==null?void 0:r.get)=="function"?this.config.get("name"):"";return Awe(t,this.type)}async copyBasesTableToClipboard(){try{let t=this.getBasesExportTable(),r=Dwe(t);await navigator.clipboard.writeText(r),new zc.Notice(`Copied ${t.rows.length} rows`)}catch(t){this.logger.error("Failed to copy Bases table",{category:"provider",operation:"copy-bases-table",error:t}),new zc.Notice("Failed to copy table")}}async exportBasesTableAsCsv(){var t;try{let r=this.getBasesExportTable(),a=Pwe(r),i=new Blob([a],{type:"text/csv;charset=utf-8"}),s=(t=this.containerEl.ownerDocument.defaultView)!=null?t:window,o=s.URL.createObjectURL(i),l=Ie(this.containerEl.ownerDocument,"a");l.href=o,l.download=this.getBasesExportFileName(),l.click(),s.URL.revokeObjectURL(o),new zc.Notice(`Exported ${r.rows.length} rows`)}catch(r){this.logger.error("Failed to export Bases table",{category:"provider",operation:"export-bases-table",error:r}),new zc.Notice("Failed to export table")}}isSearchWithNoResults(t,r){return Gwe(this.currentSearchTerm,t.length,r)}renderSearchNoResults(t){Ywe(t,this.currentSearchTerm)}setupSelectionHandling(){if(!this.rootElement)return;let t=this.plugin.taskSelectionService;if(!t)return;let r=s=>{rSe({event:s,selectionService:t,getVisibleTaskPaths:()=>this.getVisibleTaskPaths(),updateSelectionModeUi:o=>this.updateSelectionModeUI(o),updateSelectionVisuals:()=>this.updateSelectionVisuals()})};this.rootElement.addEventListener("keydown",r);let a=t.onSelectionChange(s=>{this.updateSelectionVisuals(),this.updateSelectionIndicator(s.length)}),i=t.onSelectionModeChange(s=>{this.updateSelectionModeUI(s)});this.register(()=>{var s;(s=this.rootElement)==null||s.removeEventListener("keydown",r),a(),i()})}updateSelectionModeUI(t){this.rootElement&&Jwe(this.rootElement,t)}updateSelectionVisuals(){if(!this.rootElement)return;let t=this.plugin.taskSelectionService;t&&Xwe(this.rootElement,t)}clearSelectionVisuals(){this.rootElement&&I_(this.rootElement)}updateSelectionIndicator(t){this.rootElement&&(this.selectionIndicatorEl=eSe({rootElement:this.rootElement,indicatorEl:this.selectionIndicatorEl,count:t,onClearSelection:()=>{var r,a;(r=this.plugin.taskSelectionService)==null||r.clearSelection(),(a=this.plugin.taskSelectionService)==null||a.exitSelectionMode()}}))}handleSelectionClick(t,r){var s;let a=this.plugin.taskSelectionService,i=tSe({event:t,taskPath:r,selectionService:a,getVisibleTaskPaths:()=>this.getVisibleTaskPaths(),updateSelectionVisuals:()=>this.updateSelectionVisuals()});return i&&((s=this.rootElement)==null||s.focus({preventScroll:!0})),i}showBatchContextMenu(t){let r=this.plugin.taskSelectionService;if(!r)return;let a=r.getSelectedPaths();if(a.length===0)return;new Gy({plugin:this.plugin,selectedPaths:a,onUpdate:()=>{this.render()}}).show(t)}getVisibleTaskPaths(){return nSe(this.rootElement)}}});function TSe(n,e,t){var c,d;let r=(c=t.sourcePath)!=null?c:"",a=vt(n),i=t.metadataCache.getFirstLinkpathDest(a,r)||t.metadataCache.getFirstLinkpathDest(a,"");if(!(i instanceof NE.TFile))return e;let s=t.metadataCache.getCache(i.path),o=(d=s==null?void 0:s.frontmatter)==null?void 0:d.title,l=jKe(e,i,a);if(typeof o=="string"&&o.trim().length>0)return l?o:e;if(l){let u=(e==null?void 0:e.trim())||"";return u&&!u.includes("/")?u:i.basename}return e}function jKe(n,e,t){let r=(n==null?void 0:n.trim())||"",a=e.path.replace(/\.md$/i,""),i=t.replace(/\.md$/i,"");return new Set(["",e.name,e.basename,e.path,a,t,i]).has(r)}function bSe(n){let e=n.match(/^\[\[([^\]]+)\]\]$/);if(!e)return null;let t=e[1];if(t.includes("|")){let a=t.split("|");return{filePath:a[0].trim(),displayText:a[1].trim()}}let r=(0,NE.parseLinktext)(t);return{filePath:r.path,displayText:r.path}}function wSe(n){let e=n.match(/^\[([^\]]*)\]\(([^)]+)\)$/);return e?{displayText:e[1].trim(),filePath:vt(n)}:null}function $Ke(n){return bSe(n)||wSe(n)}function UKe(n,e){let t=n.slice(e),r=t.match(/^\[\[([^\]]+)\]\]/);if(r){let i=bSe(r[0]);return i?{segment:i,endIndex:e+r[0].length}:null}let a=t.match(/^\[([^\]]*)\]\(([^)]+)\)/);if(a){let i=wSe(a[0]);return i?{segment:i,endIndex:e+a[0].length}:null}return null}function HKe(n){var a,i,s,o,l;let e=[],t=0,r=0;for(;t=n.length)break;let p=(l=n.slice(t).match(/^,\s*/))==null?void 0:l[0];if(!p)return null;e.push(p),t+=p.length}return r>1?e:null}function kSe(n,e,t){let r=TSe(e.filePath,e.displayText,t);nl(n,e.filePath,r,t,{cssClass:"internal-link task-group-link",hoverSource:"tasknotes-bases-group",showErrorNotices:!1})}function N_(n,e,t){let r=$Ke(e);if(r){kSe(n,r,t);return}let a=HKe(e);if(a){for(let o of a)typeof o=="string"?n.appendChild(activeDocument.createTextNode(o)):kSe(n,o,t);return}let i=e.endsWith(".md")?e.replace(/\.md$/,""):e,s=t.metadataCache.getFirstLinkpathDest(i,"");if(s instanceof NE.TFile){let o=s.basename,l=TSe(i,o,t);nl(n,i,l,t,{cssClass:"internal-link task-group-link",hoverSource:"tasknotes-bases-group",showErrorNotices:!1});return}n.textContent=e}var NE,Oq=y(()=>{NE=require("obsidian");cp();Cn()});var VKe,hm,zq=y(()=>{q();VKe=M({tag:"Utils/VirtualScroller"}),hm=class{constructor(e){this.items=[];this.state={startIndex:0,endIndex:0,totalItems:0,offsetY:0};this.renderedElements=new Map;this.scrollRAF=null;this.itemHeights=new Map;this.positionCache=[];this.totalHeight=0;this.resizeObserver=null;this.measurementRAF=null;this.pendingMeasurements=new Set;this.invalidatedKeys=new Set;this.handleScroll=()=>{this.scrollRAF===null&&(this.scrollRAF=window.requestAnimationFrame(()=>{this.updateVisibleRange(),this.scrollRAF=null}))};var t,r,a;this.container=e.container,this.items=e.items,this.estimatedHeight=(t=e.itemHeight)!=null?t:0,this.overscan=(r=e.overscan)!=null?r:5,this.renderItem=e.renderItem,this.getItemKey=(a=e.getItemKey)!=null?a:((i,s)=>String(s)),this.setupDOM(),this.attachScrollListener(),this.setupResizeObserver(),!e.itemHeight&&this.items.length>0&&this.calculateEstimatedHeight(),this.rebuildPositionCache(),this.updateVisibleRange()}setupDOM(){this.container.empty(),this.container.classList.remove("tn-static-margin-top-12px-91e0f558"),this.container.classList.add("tn-static-position-relative-d461c96d"),this.spacer=this.container.createDiv({cls:"virtual-scroller__spacer"}),this.spacer.style.cssText=` + position: absolute; + top: 0; + left: 0; + right: 0; + pointer-events: none; + `,this.updateSpacerHeight(),this.contentContainer=this.container.createDiv({cls:"virtual-scroller__content"}),this.contentContainer.style.cssText=` + position: relative; + `,this.scrollContainer=this.findScrollContainer(this.container)}calculateEstimatedHeight(){let e=Math.min(5,this.items.length),t=[],r=this.contentContainer.createDiv({cls:"virtual-scroller__sample"});r.style.cssText=` + position: absolute; + visibility: hidden; + pointer-events: none; + `;for(let a=0;a0&&t.push(s)}if(r.remove(),t.length>0){let a=t.reduce((i,s)=>i+s,0);this.estimatedHeight=Math.ceil(a/t.length)}else this.estimatedHeight=60}findScrollContainer(e){let t=e;for(;t;){let a=window.getComputedStyle(t).overflowY;if(a==="scroll"||a==="auto")return t;t=t.parentElement}return e}getContainerBottomPadding(){var a;let e=this.container.ownerDocument.defaultView,t=(a=e==null?void 0:e.getComputedStyle(this.container).paddingBottom)!=null?a:"",r=Number.parseFloat(t);return Number.isFinite(r)?r:0}updateSpacerHeight(){this.spacer.style.height=`${this.totalHeight+this.getContainerBottomPadding()}px`}binarySearchPosition(e){if(this.positionCache.length===0)return 0;let t=0,r=this.positionCache.length-1;for(;t=this.positionCache.length?0:this.positionCache[e]}rebuildPositionCache(){this.positionCache=[];let e=0;for(let t=0;t({item:e,key:this.getItemKey(e,t),height:this.itemHeights.get(t)}))}hasUniqueStableKeys(e){let t=new Set;for(let r of e){if(t.has(r.key))return!1;t.add(r.key)}return!0}applyItemEntries(e){this.items=e.map(r=>r.item),this.state.totalItems=this.items.length;let t=new Map;e.forEach((r,a)=>{r.height!==void 0&&t.set(a,r.height)}),this.itemHeights=t,this.pendingMeasurements.clear(),this.rebuildPositionCache()}forceVisibleRangeUpdate(){this.state.startIndex=-1,this.state.endIndex=-1,this.updateVisibleRange()}getUniqueCurrentEntries(){let e=this.getItemEntries();return this.hasUniqueStableKeys(e)?e:null}buildEntriesAfterRemoval(e){let t=new Set(e);if(e.length===0||t.size!==e.length)return null;let r=this.getUniqueCurrentEntries();if(!r)return null;let a=new Set(r.map(o=>o.key));if(!e.every(o=>a.has(o)))return null;let i=r.filter(o=>!t.has(o.key));return i.every((o,l)=>this.getItemKey(o.item,l)===o.key)?i:null}buildEntriesAfterInsertion(e){var l;if(e.items.length===0)return null;let t=this.getUniqueCurrentEntries();if(!t)return null;let r=(l=e.position)!=null?l:"end";if(r!=="end"&&!e.targetKey)return null;let a=t.length;if(r!=="end"){let c=t.findIndex(d=>d.key===e.targetKey);if(c===-1)return null;a=r==="before"?c:c+1}let i=e.items.map((c,d)=>({item:c,key:this.getItemKey(c,a+d)})),s=[...t.slice(0,a),...i,...t.slice(a)];return this.hasUniqueStableKeys(s)&&s.every((c,d)=>this.getItemKey(c.item,d)===c.key)?s:null}setupResizeObserver(){this.resizeObserver=new ResizeObserver(e=>{for(let t of e){let r=t.target,a=parseInt(r.dataset.virtualIndex||"-1",10);a>=0&&a{this.processPendingMeasurements(),this.measurementRAF=null}))})}processPendingMeasurements(){if(this.pendingMeasurements.size===0)return;let e=!1;for(let t of this.pendingMeasurements){let r=this.contentContainer.querySelector(`[data-virtual-index="${t}"]`);if(r){let a=r.getBoundingClientRect().height;this.itemHeights.get(t)!==a&&a>0&&(this.itemHeights.set(t,a),e=!0)}}this.pendingMeasurements.clear(),e&&this.rebuildPositionCache()}measureRenderedItems(){let e=this.contentContainer.querySelectorAll("[data-virtual-index]"),t=!1;for(let r of e){let a=parseInt(r.dataset.virtualIndex||"-1",10);if(a>=0&&a0&&(this.itemHeights.set(a,i),t=!0)}}t&&this.rebuildPositionCache()}attachScrollListener(){this.scrollContainer.addEventListener("scroll",this.handleScroll)}updateVisibleRange(){var o;let e=this.scrollContainer.scrollTop,t=this.scrollContainer.clientHeight;t===0&&(t=((o=this.scrollContainer.parentElement)==null?void 0:o.clientHeight)||0),t===0&&(t=window.innerHeight,VKe.warn("[VirtualScroller] Using window height as fallback:",{category:"configuration",operation:"using-window-height-as-fallback",details:{value:t}}));let r=Math.max(0,this.binarySearchPosition(e)-this.overscan),a=r,i=e+t;for(;ai);)a++;a=Math.min(this.items.length-1,a+this.overscan);let s=this.getItemPosition(r);(r!==this.state.startIndex||a!==this.state.endIndex||this.items.length!==this.state.totalItems)&&(this.state={startIndex:r,endIndex:a,totalItems:this.items.length,offsetY:s},this.renderVisibleItems())}renderVisibleItems(){let{startIndex:e,endIndex:t,offsetY:r}=this.state,a=new Set;this.contentContainer.style.transform=`translateY(${r}px)`;let i=new Map;for(let[o,l]of this.renderedElements)l.parentElement===this.contentContainer&&i.set(o,l);let s=null;for(let o=e;o<=t;o++){let l=this.items[o],c=this.getItemKey(l,o);a.add(c);let d=this.renderedElements.get(c);d&&this.invalidatedKeys.has(c)&&(this.resizeObserver&&this.resizeObserver.unobserve(d),d.remove(),this.renderedElements.delete(c),d=void 0),d?d.dataset.virtualIndex=String(o):(d=this.renderItem(l,o),d.dataset.virtualIndex=String(o),this.renderedElements.set(c,d),this.resizeObserver&&this.resizeObserver.observe(d)),this.invalidatedKeys.delete(c),s?d.previousElementSibling!==s&&s.after(d):this.contentContainer.firstChild!==d&&this.contentContainer.prepend(d),s=d}for(let[o,l]of this.renderedElements)a.has(o)||(this.resizeObserver&&this.resizeObserver.unobserve(l),l.remove(),this.renderedElements.delete(o),this.invalidatedKeys.delete(o));window.requestAnimationFrame(()=>{this.measureRenderedItems()})}updateItems(e){let t=this.scrollContainer.scrollTop;this.items=e,this.state.totalItems=e.length;let r=this.itemHeights.size;for(let a=e.length;a[m.key,m]));if(!i.has(e.targetKey)||!t.every(m=>i.has(m)))return!1;let s=a.filter(m=>!r.has(m.key)),o=s.findIndex(m=>m.key===e.targetKey);if(o===-1)return!1;let l=[];for(let m of t){let f=i.get(m);if(!f)return!1;l.push(f)}let c=e.position==="before"?o:o+1,d=[...s.slice(0,c),...l,...s.slice(c)];if(!d.every((m,f)=>this.getItemKey(m.item,f)===m.key))return!1;let p=this.scrollContainer.scrollTop;return this.applyItemEntries(d),this.scrollContainer.scrollTop=p,this.forceVisibleRangeUpdate(),!0}canRemoveItems(e){return this.buildEntriesAfterRemoval(e)!==null}removeItems(e){let t=this.buildEntriesAfterRemoval(e);if(!t)return!1;let r=this.scrollContainer.scrollTop;for(let a of e){let i=this.renderedElements.get(a);i&&(this.resizeObserver&&this.resizeObserver.unobserve(i),i.remove(),this.renderedElements.delete(a)),this.invalidatedKeys.delete(a)}return this.applyItemEntries(t),this.scrollContainer.scrollTop=r,this.forceVisibleRangeUpdate(),!0}canInsertItems(e){return this.buildEntriesAfterInsertion(e)!==null}insertItems(e){let t=this.buildEntriesAfterInsertion(e);if(!t)return!1;let r=this.scrollContainer.scrollTop;return this.applyItemEntries(t),this.scrollContainer.scrollTop=r,this.forceVisibleRangeUpdate(),!0}invalidateItems(e,t={}){if(e.length===0)return;let r=new Set(e);if(t.invalidateHeights){for(let a of r){let i=this.renderedElements.get(a);if(!i)continue;let s=parseInt(i.dataset.virtualIndex||"-1",10);s>=0&&this.itemHeights.delete(s)}this.rebuildPositionCache()}for(let a of r)this.invalidatedKeys.add(a);this.forceVisibleRangeUpdate()}scrollToIndex(e,t="smooth"){let r=this.getItemPosition(e);this.scrollContainer.scrollTo({top:r,behavior:t})}recalculate(){this.state.startIndex=-1,this.state.endIndex=-1,this.updateSpacerHeight(),this.updateVisibleRange()}invalidateItem(e){this.invalidateItems([e],{invalidateHeights:!0})}invalidateHeights(e){for(let t of e)this.itemHeights.delete(t);this.rebuildPositionCache()}getState(){return{...this.state}}destroy(){this.scrollRAF!==null&&cancelAnimationFrame(this.scrollRAF),this.measurementRAF!==null&&cancelAnimationFrame(this.measurementRAF),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.scrollContainer.removeEventListener("scroll",this.handleScroll),this.renderedElements.clear(),this.contentContainer.empty(),this.itemHeights.clear(),this.positionCache=[],this.pendingMeasurements.clear(),this.invalidatedKeys.clear()}}});var SSe=te(R_=>{"use strict";Object.defineProperty(R_,"__esModule",{value:!0});R_.lexoHelper=void 0;R_.lexoHelper={arrayCopy:WKe};function WKe(n,e,t,r,a){let i=r,s=e+a;for(let o=e;o{"use strict";Object.defineProperty(jq,"__esModule",{value:!0});var Bq=class{constructor(e=""){this.str=e}get length(){return this.str.length}set length(e){this.str=this.str.substring(0,e)}append(e){return this.str=this.str+e,this}remove(e,t){return this.str=this.str.substr(0,e)+this.str.substr(e+t),this}insert(e,t){return this.str=this.str.substr(0,e)+t+this.str.substr(e),this}toString(){return this.str}};jq.default=Bq});var O_=te(L_=>{"use strict";Object.defineProperty(L_,"__esModule",{value:!0});L_.LexoInteger=void 0;var F_=SSe(),qKe=__(),gm=class n{constructor(e,t,r){this.sys=e,this.sign=t,this.mag=r}static parse(e,t){let r=e,a=1;e.indexOf(t.getPositiveChar())===0?r=e.substring(1):e.indexOf(t.getNegativeChar())===0&&(r=e.substring(1),a=-1);let i=new Array(r.length),s=i.length-1;for(let o=0;s>=0;++o)i[o]=t.toDigit(r.charAt(s)),--s;return n.make(t,a,i)}static zero(e){return new n(e,0,n.ZERO_MAG)}static one(e){return n.make(e,1,n.ONE_MAG)}static make(e,t,r){let a;for(a=r.length;a>0&&r[a-1]===0;--a);if(a===0)return n.zero(e);if(a===r.length)return new n(e,t,r);let i=new Array(a).fill(0);return F_.lexoHelper.arrayCopy(r,0,i,0,a),new n(e,t,i)}static add(e,t,r){let a=Math.max(t.length,r.length),i=new Array(a).fill(0),s=0;for(let o=0;o=e.getBase();d-=e.getBase())++s;i[o]=d}return n.extendWithCarry(i,s)}static extendWithCarry(e,t){if(t>0){let r=new Array(e.length+1).fill(0);return F_.lexoHelper.arrayCopy(e,0,r,0,e.length),r[r.length-1]=t,r}return e}static subtract(e,t,r){let a=n.complement(e,r,t.length),i=n.add(e,t,a);return i[i.length-1]=0,n.add(e,i,n.ONE_MAG)}static multiply(e,t,r){let a=new Array(t.length+r.length).fill(0);for(let i=0;i=e.getBase();a[o]-=e.getBase())++a[o+1]}return a}static complement(e,t,r){if(r<=0)throw new Error("Expected at least 1 digit");let a=new Array(r).fill(e.getBase()-1);for(let i=0;it.length)return 1;for(let r=e.length-1;r>=0;--r){if(e[r]t[r])return 1}return 0}add(e){if(this.checkSystem(e),this.isZero())return e;if(e.isZero())return this;if(this.sign!==e.sign){let r;return this.sign===-1?(r=this.negate(),r.subtract(e).negate()):(r=e.negate(),this.subtract(r))}let t=n.add(this.sys,this.mag,e.mag);return n.make(this.sys,this.sign,t)}subtract(e){if(this.checkSystem(e),this.isZero())return e.negate();if(e.isZero())return this;if(this.sign!==e.sign){let r;return this.sign===-1?(r=this.negate(),r.add(e).negate()):(r=e.negate(),this.add(r))}let t=n.compare(this.mag,e.mag);return t===0?n.zero(this.sys):t<0?n.make(this.sys,this.sign===-1?1:-1,n.subtract(this.sys,e.mag,this.mag)):n.make(this.sys,this.sign===-1?-1:1,n.subtract(this.sys,this.mag,e.mag))}multiply(e){if(this.checkSystem(e),this.isZero())return this;if(e.isZero())return e;if(this.isOneish())return this.sign===e.sign?n.make(this.sys,1,e.mag):n.make(this.sys,-1,e.mag);if(e.isOneish())return this.sign===e.sign?n.make(this.sys,1,this.mag):n.make(this.sys,-1,this.mag);let t=n.multiply(this.sys,this.mag,e.mag);return this.sign===e.sign?n.make(this.sys,1,t):n.make(this.sys,-1,t)}negate(){return this.isZero()?this:n.make(this.sys,this.sign===1?-1:1,this.mag)}shiftLeft(e=1){if(e===0)return this;if(e<0)return this.shiftRight(Math.abs(e));let t=new Array(this.mag.length+e).fill(0);return F_.lexoHelper.arrayCopy(this.mag,0,t,e,this.mag.length),n.make(this.sys,this.sign,t)}shiftRight(e=1){if(this.mag.length-e<=0)return n.zero(this.sys);let t=new Array(this.mag.length-e).fill(0);return F_.lexoHelper.arrayCopy(this.mag,e,t,0,t.length),n.make(this.sys,this.sign,t)}complement(){return this.complementDigits(this.mag.length)}complementDigits(e){return n.make(this.sys,this.sign,n.complement(this.sys,this.mag,e))}isZero(){return this.sign===0&&this.mag.length===1&&this.mag[0]===0}isOne(){return this.sign===1&&this.mag.length===1&&this.mag[0]===1}getMag(e){return this.mag[e]}compareTo(e){if(this===e)return 0;if(!e)return 1;if(this.sign===-1){if(e.sign===-1){let t=n.compare(this.mag,e.mag);return t===-1?1:t===1?-1:0}return-1}return this.sign===1?e.sign===1?n.compare(this.mag,e.mag):1:e.sign===-1?1:e.sign===1?-1:0}getSystem(){return this.sys}format(){if(this.isZero())return""+this.sys.toChar(0);let e=new qKe.default,t=this.mag,r=t.length;for(let a=0;a{"use strict";Object.defineProperty(z_,"__esModule",{value:!0});z_.LexoDecimal=void 0;var RE=O_(),GKe=__(),$q=class n{constructor(e,t){this.mag=e,this.sig=t}static half(e){let t=e.getBase()/2|0;return n.make(RE.LexoInteger.make(e,1,[t]),1)}static parse(e,t){let r=e.indexOf(t.getRadixPointChar());if(e.lastIndexOf(t.getRadixPointChar())!==r)throw new Error("More than one "+t.getRadixPointChar());if(r<0)return n.make(RE.LexoInteger.parse(e,t),0);let a=e.substring(0,r)+e.substring(r+1);return n.make(RE.LexoInteger.parse(a,t),e.length-1-r)}static from(e){return n.make(e,0)}static make(e,t){if(e.isZero())return new n(e,0);let r=0;for(let s=0;si;)a=a.shiftLeft(),++i;return n.make(t.add(a),r)}subtract(e){let t=this.mag,r=this.sig,a=e.mag,i;for(i=e.sig;ri;)a=a.shiftLeft(),++i;return n.make(t.subtract(a),r)}multiply(e){return n.make(this.mag.multiply(e.mag),this.sig+e.sig)}floor(){return this.mag.shiftRight(this.sig)}ceil(){if(this.isExact())return this.mag;let e=this.floor();return e.add(RE.LexoInteger.one(e.getSystem()))}isExact(){if(this.sig===0)return!0;for(let e=0;e=this.sig)return this;e<0&&(e=0);let r=this.sig-e,a=this.mag.shiftRight(r);return t&&(a=a.add(RE.LexoInteger.one(a.getSystem()))),n.make(a,e)}compareTo(e){if(this===e)return 0;if(!e)return 1;let t=this.mag,r=e.mag;return this.sig>e.sig?r=r.shiftLeft(this.sig-e.sig):this.sig{"use strict";Object.defineProperty(Vq,"__esModule",{value:!0});var CSe=O_(),xSe=qq(),Hq=class n{constructor(e){this.value=CSe.LexoInteger.parse(e,xSe.LexoRank.NUMERAL_SYSTEM)}static get BUCKET_0(){return this._BUCKET_0||(this._BUCKET_0=new n("0")),this._BUCKET_0}static get BUCKET_1(){return this._BUCKET_1||(this._BUCKET_1=new n("1")),this._BUCKET_1}static get BUCKET_2(){return this._BUCKET_2||(this._BUCKET_2=new n("2")),this._BUCKET_2}static get VALUES(){return this._VALUES||(this._VALUES=[n.BUCKET_0,n.BUCKET_1,n.BUCKET_2]),this._VALUES}static max(){return n.VALUES[n.VALUES.length-1]}static from(e){let t=CSe.LexoInteger.parse(e,xSe.LexoRank.NUMERAL_SYSTEM),r=n.VALUES,a=r.length;for(let i=0;i{"use strict";Object.defineProperty(ESe,"__esModule",{value:!0})});var PSe=te(B_=>{"use strict";Object.defineProperty(B_,"__esModule",{value:!0});B_.LexoNumeralSystem10=void 0;var Gq=class{getBase(){return 10}getPositiveChar(){return"+"}getNegativeChar(){return"-"}getRadixPointChar(){return"."}toDigit(e){if(e>="0"&&e<="9")return e.charCodeAt(0)-48;throw new Error("Not valid digit: "+e)}toChar(e){return String.fromCharCode(e+48)}};B_.LexoNumeralSystem10=Gq});var ASe=te(j_=>{"use strict";Object.defineProperty(j_,"__esModule",{value:!0});j_.LexoNumeralSystem36=void 0;var Yq=class{constructor(){this.DIGITS="0123456789abcdefghijklmnopqrstuvwxyz".split("")}getBase(){return 36}getPositiveChar(){return"+"}getNegativeChar(){return"-"}getRadixPointChar(){return":"}toDigit(e){if(e>="0"&&e<="9")return e.charCodeAt(0)-48;if(e>="a"&&e<="z")return e.charCodeAt(0)-97+10;throw new Error("Not valid digit: "+e)}toChar(e){return this.DIGITS[e]}};j_.LexoNumeralSystem36=Yq});var MSe=te($_=>{"use strict";Object.defineProperty($_,"__esModule",{value:!0});$_.LexoNumeralSystem64=void 0;var Kq=class{constructor(){this.DIGITS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_abcdefghijklmnopqrstuvwxyz".split("")}getBase(){return 64}getPositiveChar(){return"+"}getNegativeChar(){return"-"}getRadixPointChar(){return":"}toDigit(e){if(e>="0"&&e<="9")return e.charCodeAt(0)-48;if(e>="A"&&e<="Z")return e.charCodeAt(0)-65+10;if(e==="^")return 36;if(e==="_")return 37;if(e>="a"&&e<="z")return e.charCodeAt(0)-97+38;throw new Error("Not valid digit: "+e)}toChar(e){return this.DIGITS[e]}};$_.LexoNumeralSystem64=Kq});var Zq=te(jc=>{"use strict";var YKe=jc&&jc.__createBinding||(Object.create?(function(n,e,t,r){r===void 0&&(r=t);var a=Object.getOwnPropertyDescriptor(e,t);(!a||("get"in a?!e.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,r,a)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]})),U_=jc&&jc.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&YKe(e,n,t)};Object.defineProperty(jc,"__esModule",{value:!0});U_(DSe(),jc);U_(PSe(),jc);U_(ASe(),jc);U_(MSe(),jc)});var qq=te(V_=>{"use strict";Object.defineProperty(V_,"__esModule",{value:!0});V_.LexoRank=void 0;var $c=Uq(),H_=Wq(),KKe=__(),ZKe=Zq(),Qq=class n{constructor(e,t){this.value=e.format()+"|"+n.formatDecimal(t),this.bucket=e,this.decimal=t}static get NUMERAL_SYSTEM(){return this._NUMERAL_SYSTEM||(this._NUMERAL_SYSTEM=new ZKe.LexoNumeralSystem36),this._NUMERAL_SYSTEM}static get ZERO_DECIMAL(){return this._ZERO_DECIMAL||(this._ZERO_DECIMAL=$c.LexoDecimal.parse("0",n.NUMERAL_SYSTEM)),this._ZERO_DECIMAL}static get ONE_DECIMAL(){return this._ONE_DECIMAL||(this._ONE_DECIMAL=$c.LexoDecimal.parse("1",n.NUMERAL_SYSTEM)),this._ONE_DECIMAL}static get EIGHT_DECIMAL(){return this._EIGHT_DECIMAL||(this._EIGHT_DECIMAL=$c.LexoDecimal.parse("8",n.NUMERAL_SYSTEM)),this._EIGHT_DECIMAL}static get MIN_DECIMAL(){return this._MIN_DECIMAL||(this._MIN_DECIMAL=n.ZERO_DECIMAL),this._MIN_DECIMAL}static get MAX_DECIMAL(){return this._MAX_DECIMAL||(this._MAX_DECIMAL=$c.LexoDecimal.parse("1000000",n.NUMERAL_SYSTEM).subtract(n.ONE_DECIMAL)),this._MAX_DECIMAL}static get MID_DECIMAL(){return this._MID_DECIMAL||(this._MID_DECIMAL=n.between(n.MIN_DECIMAL,n.MAX_DECIMAL)),this._MID_DECIMAL}static get INITIAL_MIN_DECIMAL(){return this._INITIAL_MIN_DECIMAL||(this._INITIAL_MIN_DECIMAL=$c.LexoDecimal.parse("100000",n.NUMERAL_SYSTEM)),this._INITIAL_MIN_DECIMAL}static get INITIAL_MAX_DECIMAL(){return this._INITIAL_MAX_DECIMAL||(this._INITIAL_MAX_DECIMAL=$c.LexoDecimal.parse(n.NUMERAL_SYSTEM.toChar(n.NUMERAL_SYSTEM.getBase()-2)+"00000",n.NUMERAL_SYSTEM)),this._INITIAL_MAX_DECIMAL}static min(){return n.from(H_.default.BUCKET_0,n.MIN_DECIMAL)}static middle(){let e=n.min();return e.between(n.max(e.bucket))}static max(e=H_.default.BUCKET_0){return n.from(e,n.MAX_DECIMAL)}static initial(e){return e===H_.default.BUCKET_0?n.from(e,n.INITIAL_MIN_DECIMAL):n.from(e,n.INITIAL_MAX_DECIMAL)}static between(e,t){if(e.getSystem().getBase()!==t.getSystem().getBase())throw new Error("Expected same system");let r=e,a=t,i;if(e.getScale()=0)return n.mid(e,t);a=i}if(e.getScale()>a.getScale()){if(i=e.setScale(a.getScale(),!0),i.compareTo(a)>=0)return n.mid(e,t);r=i}let s;for(let c=r.getScale();c>0;a=s){let d=c-1,u=r.setScale(d,!0);if(s=a.setScale(d,!1),u.compareTo(s)===0)return n.checkMid(e,t,u);if(u.compareTo(s)>0)break;c=d,r=u}let o=n.middleInternal(e,t,r,a),l;for(let c=o.getScale();c>0;c=l){l=c-1;let d=o.setScale(l);if(e.compareTo(d)>=0||d.compareTo(t)>=0)break;o=d}return o}static parse(e){let t=e.split("|"),r=H_.default.from(t[0]),a=$c.LexoDecimal.parse(t[1],n.NUMERAL_SYSTEM);return new n(r,a)}static from(e,t){if(t.getSystem().getBase()!==n.NUMERAL_SYSTEM.getBase())throw new Error("Expected different system");return new n(e,t)}static middleInternal(e,t,r,a){let i=n.mid(r,a);return n.checkMid(e,t,i)}static checkMid(e,t,r){return e.compareTo(r)>=0||r.compareTo(t)>=0?n.mid(e,t):r}static mid(e,t){let a=e.add(t).multiply($c.LexoDecimal.half(e.getSystem())),i=e.getScale()>t.getScale()?e.getScale():t.getScale();if(a.getScale()>i){let s=a.setScale(i,!1);if(s.compareTo(e)>0)return s;let o=a.setScale(i,!0);if(o.compareTo(t)<0)return o}return a}static formatDecimal(e){let t=e.format(),r=new KKe.default(t),a=t.indexOf(n.NUMERAL_SYSTEM.getRadixPointChar()),i=n.NUMERAL_SYSTEM.toChar(0);for(a<0&&(a=t.length,r.append(n.NUMERAL_SYSTEM.getRadixPointChar()));a<6;)r.insert(0,i),++a;for(;r[r.length-1]===i;)r.length=r.length-1;return r.toString()}genPrev(){if(this.isMax())return new n(this.bucket,n.INITIAL_MAX_DECIMAL);let e=this.decimal.floor(),r=$c.LexoDecimal.from(e).subtract(n.EIGHT_DECIMAL);return r.compareTo(n.MIN_DECIMAL)<=0&&(r=n.between(n.MIN_DECIMAL,this.decimal)),new n(this.bucket,r)}genNext(){if(this.isMin())return new n(this.bucket,n.INITIAL_MIN_DECIMAL);let e=this.decimal.ceil(),r=$c.LexoDecimal.from(e).add(n.EIGHT_DECIMAL);return r.compareTo(n.MAX_DECIMAL)>=0&&(r=n.between(this.decimal,n.MAX_DECIMAL)),new n(this.bucket,r)}between(e){if(!this.bucket.equals(e.bucket))throw new Error("Between works only within the same bucket");let t=this.decimal.compareTo(e.decimal);if(t>0)return new n(this.bucket,n.between(e.decimal,this.decimal));if(t===0)throw new Error("Try to rank between issues with same rank this="+this+" other="+e+" this.decimal="+this.decimal+" other.decimal="+e.decimal);return new n(this.bucket,n.between(this.decimal,e.decimal))}getBucket(){return this.bucket}getDecimal(){return this.decimal}inNextBucket(){return n.from(this.bucket.next(),this.decimal)}inPrevBucket(){return n.from(this.bucket.prev(),this.decimal)}isMin(){return this.decimal.equals(n.MIN_DECIMAL)}isMax(){return this.decimal.equals(n.MAX_DECIMAL)}format(){return this.value}equals(e){return this===e?!0:e?this.value===e.value:!1}toString(){return this.value}compareTo(e){return this===e?0:e?this.value.localeCompare(e.value):1}};V_.LexoRank=Qq});var ISe=te(Uc=>{"use strict";var QKe=Uc&&Uc.__createBinding||(Object.create?(function(n,e,t,r){r===void 0&&(r=t);var a=Object.getOwnPropertyDescriptor(e,t);(!a||("get"in a?!e.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,r,a)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]})),W_=Uc&&Uc.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&QKe(e,n,t)};Object.defineProperty(Uc,"__esModule",{value:!0});W_(qq(),Uc);W_(Wq(),Uc);W_(Uq(),Uc);W_(O_(),Uc)});var RSe=te(ym=>{"use strict";var JKe=ym&&ym.__createBinding||(Object.create?(function(n,e,t,r){r===void 0&&(r=t);var a=Object.getOwnPropertyDescriptor(e,t);(!a||("get"in a?!e.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(n,r,a)}):(function(n,e,t,r){r===void 0&&(r=t),n[r]=e[t]})),NSe=ym&&ym.__exportStar||function(n,e){for(var t in n)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&JKe(e,n,t)};Object.defineProperty(ym,"__esModule",{value:!0});NSe(ISe(),ym);NSe(Zq(),ym)});function GSe(n){let e=Math.max(0,Math.min(Xk,Math.floor(n))),t=Array(Jq);for(let r=Jq-1;r>=0;r--)t[r]=String.fromCharCode(97+e%Y_),e=Math.floor(e/Y_);return`${qSe}${t.join("")}`}function Z_(n){if(!t7e.test(n))return null;let e=0;for(let t of n.slice(qSe.length))e=e*Y_+(t.charCodeAt(0)-97);return e}function r7e(n,e,t){let r=Math.max(1,Math.floor(Xk/(e+1))),a=t==="asc"?n+1:e-n;return GSe(r*a)}function Io(n,e){let t=e7e.compare(n,e);return t!==0?t:n.localeCompare(e)}function _Se(n,e,t){return t==="asc"?Io(n,e):Io(e,n)}function q_(n,e,t,r){return!(e&&_Se(e,n,r)>=0||t&&_Se(n,t,r)>=0)}function K_(n){return VSe.LexoRank.parse(n)}function FSe(){return new eT(Math.floor(Xk/2))}function Ya(n){let e=n.split("."),t=0;for(;t0?e.slice(t).join("."):n}function _E(n,e){try{let t=n.getSortConfig();return t?(Array.isArray(t)?t:[t]).some(a=>{if(!a||typeof a!="object")return!1;let i=a.property||a.column||a.field||a.id||a.name||"";return Y(i).replace(/^(note\.|file\.|task\.)/,"")===e}):!1}catch(t){return!1}}function vu(n){if(typeof n!="string"||n.length===0)return null;let e=Z_(n);if(e!==null)return new eT(e);try{return K_(n)}catch(t){return null}}function n7e(n){return vu(n.sortOrder)!==null}function G_(n){return n?n.isMax()||n.toString().length>XKe:!1}function LSe(n){return n==null||n===""?"None":typeof n=="string"?n:typeof n=="boolean"?n?"True":"False":typeof n=="number"?String(n):Y(n)||"None"}function a7e(n){return n==null||n===""?["None"]:Array.isArray(n)?n.length>0?n.map(e=>LSe(e)):["None"]:[LSe(n)]}function OSe(n,e){return e===null?!0:a7e(n).includes(e)}function i7e(n){let e=new Map;return n&&n.forEach((t,r)=>{e.set(t,r)}),e}function s7e(n,e,t){if(!e||e.length===0)return n.filter(i=>i.path!==t);let r=new Map(n.map(i=>[i.path,i])),a=e.filter(i=>i!==t).map(i=>r.get(i)).filter(i=>!!i);return a.length>0?a:n.filter(i=>i.path!==t)}function o7e(n){for(let e=1;e0)return"desc"}return"asc"}function zSe(n,e,t){return t==="asc"?Io(n.toString(),e.toString()):Io(e.toString(),n.toString())}function BSe(n,e){return e==="asc"?e4(n):Xq(n)}function jSe(n,e){return e==="asc"?Xq(n):e4(n)}function $Se(n,e,t){return t==="asc"?USe(n,e):USe(e,n)}function Xq(n){let e=n.toString();try{let c=n.genNext();if(c.toString()>e)return c}catch(c){}if(Z_(e)!==null)return new eT(Xk);let r=e.indexOf("|"),a=e.indexOf(":"),i=e.substring(0,r),s=e.substring(r+1,a),o=e.substring(a+1),l=s.charAt(0);if(l!=="z"){let c=l>="0"&&l<="8"?String.fromCharCode(l.charCodeAt(0)+1):l==="9"?"a":l>="a"&&l<="y"?String.fromCharCode(l.charCodeAt(0)+1):"z",d=`${i}|${c}${s.slice(1)}:`,u=n.between(K_(d));if(u.toString()>e)return u}return K_(`${i}|${s}:${o}i`)}function e4(n){let e=n.toString();try{let c=n.genPrev();if(c.toString()="1"&&o<="9"?String.fromCharCode(o.charCodeAt(0)-1):o==="a"?"9":o>="b"&&o<="z"?String.fromCharCode(o.charCodeAt(0)-1):"0";l=`${i}|${c}${s.slice(1)}:`}return K_(l).between(n)}function USe(n,e){let t=n.toString(),r=e.toString();try{let s=n.between(e).toString();if(Io(s,t)>0&&Io(s,r)<0)return s}catch(s){}let a=Xq(n).toString();if(Io(a,t)>0&&Io(a,r)<0)return a;let i=e4(e).toString();return Io(i,t)>0&&Io(i,r)<0?i:a}function ng(n,e,t,r){let a=t?e:e+1,i=n.map(l=>l.path);i.splice(a,0,null);let s=[],o=null;for(let l=0;l!OSe(m[v.property],v.value)))continue;let f=m[a],h=f!==void 0?String(f):void 0,g=(u=r.taskInfoCache)==null?void 0:u.get(p.path);if(g){g.sortOrder=h,l.push(g);continue}l.push({path:p.path,title:p.basename,status:m.status||"open",priority:m.priority||"",archived:m.archived||!1,sortOrder:h})}return l.sort((p,m)=>{let f=vu(p.sortOrder),h=vu(m.sortOrder);if(f&&h){let k=Io(f.toString(),h.toString());if(k!==0)return k}if(f&&!h)return-1;if(!f&&h)return 1;let g=i.get(p.path),v=i.get(m.path);return g!==void 0&&v!==void 0?g-v:g!==void 0?-1:v!==void 0?1:p.path.localeCompare(m.path)}),l}async function HSe(n,e,t){let r=t.app.vault.getAbstractFileByPath(n);if(!(r instanceof WSe.TFile))return;let a=t.settings.fieldMapping.sortOrder;await yr(t.app,r,i=>{i[a]=e})}async function Q_(n,e,t,r,a,i,s={}){var b;let o=l7e(t,r,i,s).filter(w=>w.path!==a),l=s7e(o,s.visibleTaskPaths,a),c=o7e(l);if(o.length===0)return{sortOrder:FSe().toString(),additionalWrites:[],reason:"boundary"};let d=l.findIndex(w=>w.path===n);if(d===-1){let w=[...l].reverse().find(C=>n7e(C)),S=w?vu(w.sortOrder):null;if(S&&!G_(S)){let C=jSe(S,c).toString();if(q_(C,S.toString(),null,c))return{sortOrder:C,additionalWrites:[],reason:"boundary"}}return l.length>0?ng(l,l.length-1,!1,c):{sortOrder:FSe().toString(),additionalWrites:[],reason:"boundary"}}let u=l[d],p=d>0?l[d-1]:null,m=d=0:!1,k=g?zSe(f,g,c)>=0:!1;if(e&&v||!e&&k||G_(h)||G_(f)||G_(g))return ng(l,d,e,c);if(e){let w=d===0?BSe(f,c).toString():h?$Se(h,f,c):BSe(f,c).toString();return q_(w,(b=h==null?void 0:h.toString())!=null?b:null,f.toString(),c)?{sortOrder:w,additionalWrites:[],reason:d===0?"boundary":"midpoint"}:ng(l,d,e,c)}if(!m||!g){let w=jSe(f,c).toString();return q_(w,f.toString(),null,c)?{sortOrder:w,additionalWrites:[],reason:"boundary"}:ng(l,d,e,c)}let T=$Se(f,g,c);return q_(T,f.toString(),g.toString(),c)?{sortOrder:T,additionalWrites:[],reason:"midpoint"}:ng(l,d,e,c)}async function J_(n,e,t,r={}){if(e.sortOrder){for(let a of e.additionalWrites)await HSe(a.path,a.sortOrder,t);r.includeDragged!==!1&&await HSe(n,e.sortOrder,t)}}var VSe,WSe,XKe,e7e,qSe,Jq,Y_,Xk,t7e,eT,tT,FE=y(()=>{VSe=tt(RSe()),WSe=require("obsidian");dr();ya();XKe=32,e7e=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),qSe="tn",Jq=10,Y_=26,Xk=Math.pow(Y_,Jq)-1,t7e=/^tn[a-z]{10}$/,eT=class n{constructor(e){this.value=e}toString(){return GSe(this.value)}genPrev(){if(this.value<=0)throw new Error("Cannot generate rank before minimum alpha rank");return new n(this.value-1)}genNext(){if(this.value>=Xk)throw new Error("Cannot generate rank after maximum alpha rank");return new n(this.value+1)}between(e){let t=Z_(e.toString());if(t===null)throw new Error("Cannot generate alpha midpoint against a non-alpha rank");let r=Math.min(this.value,t),a=Math.max(this.value,t),i=Math.floor((r+a)/2);if(i<=r||i>=a)throw new Error("No alpha rank gap available");return new n(i)}isMax(){return this.value>=Xk}};tT=class{constructor(){this.queues=new Map}async enqueue(e,t){var i;let a=((i=this.queues.get(e))!=null?i:Promise.resolve()).then(t,t);this.queues.set(e,a);try{await a}finally{this.queues.get(e)===a&&this.queues.delete(e)}}}});function vm(n){n.classList.remove(...c7e),n.removeAttribute("style")}var c7e,X_=y(()=>{c7e=["tn-static-align-items-baseline-4b95b5c7","tn-static-align-items-center-7c619740","tn-static-align-items-flex-start-0486f781","tn-static-background-color-var-background-mo-94b219f0","tn-static-background-color-var-background-se-9087a23e","tn-static-background-color-var-color-base-40-ef5f175e","tn-static-background-color-var-color-red-134bc721","tn-static-background-color-var-text-accent-a954c70f","tn-static-border-1px-solid-var-background-mo-b65b5121","tn-static-border-none-2eda1daa","tn-static-border-radius-4px-c290c56e","tn-static-border-radius-6px-0dc8408c","tn-static-border-style-dashed-12296c91","tn-static-border-style-solid-11080b69","tn-static-border-top-1px-solid-var-backgroun-aab7c2ca","tn-static-border-width-2px-a1222254","tn-static-color-var-color-accent-d2cad743","tn-static-color-var-text-accent-65b47ee3","tn-static-color-var-text-muted-5872de20","tn-static-color-var-text-on-accent-f3e1679d","tn-static-color-var-text-warning-783d5f03","tn-static-color-var-tn-text-muted-a90fb6f3","tn-static-color-white-0a43e56a","tn-static-cursor-grab-dad79857","tn-static-cursor-pointer-2723efcc","tn-static-cursor-pointer-3b6a3a65","tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-flex-1-14e3b769","tn-static-flex-1-97445a8d","tn-static-flex-direction-column-06c8b5ed","tn-static-flex-shrink-0-6ee0661e","tn-static-font-size-0-75em-948e16e5","tn-static-font-size-0-8em-19dc7c13","tn-static-font-size-0-9em-65025e95","tn-static-font-size-1-2em-3a352995","tn-static-font-size-12px-65574819","tn-static-font-size-12px-b0cc7e05","tn-static-font-size-var-tn-font-size-sm-0274a31d","tn-static-font-weight-500-02a2d333","tn-static-font-weight-600-eed0f8fb","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-gap-0-5rem-ce2fca4d","tn-static-gap-10px-f3d7ce77","tn-static-gap-12px-ed7b3d87","tn-static-gap-6px-f0abc1db","tn-static-gap-8px-33fcd4c3","tn-static-height-0-7a31cef0","tn-static-height-100-62264068","tn-static-height-12px-06c0747e","tn-static-height-16px-30de4aee","tn-static-height-24px-29a11d37","tn-static-justify-content-center-03c4bb6f","tn-static-justify-content-flex-end-455f8cca","tn-static-justify-content-space-between-a562f4fd","tn-static-margin-0-11696618","tn-static-margin-0-auto-266e9b04","tn-static-margin-0-db0d5f36","tn-static-margin-0-var-size-4-2-77f7dc08","tn-static-margin-2px-0-edce9b14","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-margin-bottom-0-75rem-c05a3c6e","tn-static-margin-bottom-20px-49f14f8f","tn-static-margin-bottom-8px-fdf33f23","tn-static-margin-left-4px-46cec891","tn-static-margin-right-4px-c6b76b85","tn-static-margin-right-8px-539fa9a0","tn-static-margin-top-0-5rem-3dc98b5e","tn-static-margin-top-0-d462248a","tn-static-margin-top-12px-91e0f558","tn-static-margin-top-16px-1b0f4999","tn-static-margin-top-1rem-2239d6d5","tn-static-margin-top-20px-a26bda7d","tn-static-margin-top-30px-2fbbbcd4","tn-static-margin-top-4px-96ad6099","tn-static-margin-top-8px-8a77e5a3","tn-static-margin-top-8px-f4f01e68","tn-static-max-height-400px-f0787633","tn-static-max-width-900px-1d34c094","tn-static-min-height-800px-997b4c8c","tn-static-min-width-0-3922d326","tn-static-min-width-2px-709d7da0","tn-static-opacity-0-6-d95b59ac","tn-static-opacity-0-8d919cb5","tn-static-opacity-1-c6e7979d","tn-static-overflow-hidden-69824400","tn-static-overflow-y-auto-03df744e","tn-static-overflow-y-clip-c5043043","tn-static-padding-0-16px-16px-16px-f1aa998c","tn-static-padding-0-41d7d7e2","tn-static-padding-12px-43bef435","tn-static-padding-16px-287f770e","tn-static-padding-20px-769fed37","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c","tn-static-padding-2px-8px-c8eea84a","tn-static-padding-2rem-42aa6d9c","tn-static-padding-top-20px-49826953","tn-static-position-relative-d461c96d","tn-static-text-align-center-91a87015","tn-static-text-decoration-line-through-7059a4e5","tn-static-text-decoration-none-80d654f9","tn-static-transform-translatey-0-1b976432","tn-static-transform-translatey-10px-5b91bf02","tn-static-transition-background-color-0-2s-8142f01e","tn-static-vertical-align-baseline-657d9c46","tn-static-width-100-0466783d","tn-static-width-12px-fbf353fb","tn-static-width-16px-7375d50b","tn-static-width-1px-aa77e27e","tn-static-width-200px-2acaf3b5","tn-static-width-60px-bd09c419","tn-static-width-80px-8573bae3"]});function eF(n){return typeof n=="object"&&n!==null}function tF(n,e){let t=t4(n,e);return typeof t=="string"&&d7e.has(t)}function t4(n,e){var i,s;let t=n.metadataTypeManager,r=(i=t==null?void 0:t.properties)==null?void 0:i[e.toLowerCase()],a=(s=r==null?void 0:r.type)!=null?s:r==null?void 0:r.widget;return typeof a=="string"?a:null}function u7e(n){if(!(!eF(n)||!eF(n.ctx)||!eF(n.ctx.formulas)))return n.ctx.formulas}function YSe(n){return eF(n.basesData)?n.basesData:void 0}function p7e(n){return typeof(n==null?void 0:n.getValue)=="function"}function m7e(n,e,t){let r=e.frontmatter;if(r&&Object.keys(t).length>0){e.frontmatter={...r,...t};try{return n.getValue(e)}finally{e.frontmatter=r}}return n.getValue(e)}function f7e(n,e){var r,a;let t=(a=(r=YSe(e))==null?void 0:r.formulaResults)==null?void 0:a.cachedFormulaOutputs;if(!(!t||typeof t!="object"))for(let[i,s]of Object.entries(t))n[`formula.${i}`]=s}function h7e(n){var e,t,r;return(e=n.formulaResults)!=null||(n.formulaResults={}),(r=(t=n.formulaResults).cachedFormulaOutputs)!=null||(t.cachedFormulaOutputs={}),n.formulaResults.cachedFormulaOutputs}function rF(n){let e=new Map;for(let t of n){if(!t.path)continue;let r={...t.properties||{}};f7e(r,t),e.set(t.path,r)}return e}function KSe(n,e,t){if(t.startsWith("formula."))for(let r of n){if(!r.path||!r.data||typeof r.data!="object")continue;let a=r.data.getValue;if(typeof a=="function")try{let i=a.call(r.data,t),s=e.get(r.path);s&&(s[t]=rg(i))}catch(i){}}}function LE(n,e){let t=u7e(n);if(!(!t||e.length===0))for(let r of e){let a=YSe(r);if(!a)continue;let i=h7e(a);for(let s of Object.keys(t)){let o=t[s];if(p7e(o))try{let l=r.properties||{},c=m7e(o,a,l);c!==void 0&&(i[s]=c)}catch(l){}}}}var d7e,OE=y(()=>{Aq();d7e=new Set(["multitext","tags","aliases"])});function v7e(n,e){var i;let t=n==null?void 0:n.find(s=>s.key===e);if(t)return t.type;let r=e.toLowerCase(),a=n==null?void 0:n.find(s=>s.key.toLowerCase()===r);return(i=a==null?void 0:a.type)!=null?i:null}function k7e(n,e,t){var r;return(r=v7e(t,e))!=null?r:t4(n,e)}function T7e(n,e){if(!e)return n;let t=e.toLowerCase(),r=n.trim();if(t==="number"&&y7e.test(r)){let a=Number(r);return Number.isFinite(a)?a:n}if(g7e.has(t)){if(r.toLowerCase()==="true")return!0;if(r.toLowerCase()==="false")return!1}return n}function nF(n,e,t,r){let a=k7e(n,e,r);return T7e(t,a)}var g7e,y7e,r4=y(()=>{OE();g7e=new Set(["boolean","checkbox"]),y7e=/^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i});function ZSe(n){if(n.length===0)return[];let e=[];for(let t of n){let r=e[e.length-1];if(!r||r.groupKey!==t.groupKey){e.push({groupKey:t.groupKey,cards:[t]});continue}r.cards.push(t)}return e}function QSe(n,e,t){let r=n[e];if(!r||r.cards.length===0)return null;let a=Math.max(0,Math.min(t,r.cards.length));return a===0?{taskPath:r.cards[0].path,above:!0}:{taskPath:r.cards[a-1].path,above:!1}}function JSe(n,e){if(n.length===0)return null;let t=n.length-1;for(let s=0;s0?n[s-1]:null,c=s=p||s===0)){t=s;break}}let r=n[t],a=r.cards,i=a.findIndex(s=>e{});function zE(n){return rF(n)}function b7e(n,e){var r,a;if(!e)return null;if(e.startsWith("formula."))return(r=n[e])!=null?r:null;let t=e.replace(/^(note\.|task\.|file\.)/,"");return(a=n[t])!=null?a:null}function n4(n){var e,t;if(n==null)return"None";if(typeof n=="object"&&n!==null&&typeof n.toString=="function"){let r=n;if(((e=r.constructor)==null?void 0:e.name)==="NullValue"||r.isTruthy&&!r.isTruthy())return"None";if(((t=r.constructor)==null?void 0:t.name)==="ListValue"||Array.isArray(r.value)){let a=r.value||[];return a.length>0?a.map(i=>n4(i)).join(", "):"None"}return r.toString()||"None"}return typeof n=="string"?n||"None":typeof n=="number"?String(n):typeof n=="boolean"?n?"True":"False":Array.isArray(n)?n.length>0?n.map(r=>n4(r)).join(", "):"None":Y(n)||"None"}function rT(n,e,t){let r=new Map;for(let a of n){let i=t.get(a.path)||{},s=b7e(i,e),o=n4(s),l=r.get(o)||[];l.push(a),r.set(o,l)}return r}function eCe(n,e,t){let r=new Set(e.map(i=>i.path)),a=new Map;for(let i of n){let s=t(i.key),o=i.entries.map(l=>{var c;return(c=l.file)==null?void 0:c.path}).filter(l=>!!l&&r.has(l));a.set(s,o)}return a}function tCe(n){let e=new Map;for(let[t,r]of n)e.set(t,r.map(a=>a.path));return e}function a4(n){let e=[];for(let t of n.groups){let r=n.convertGroupKeyToString(t.key),a=new Set(t.entries.map(o=>{var l;return(l=o.file)==null?void 0:l.path})),i=n.taskNotes.filter(o=>a.has(o.path));if(i.length===0)continue;let s=n.collapsedGroups.has(r);if(e.push({type:"primary-header",groupKey:r,groupTitle:r,taskCount:i.length,groupEntries:t.entries,isCollapsed:s}),!s){if(n.subGroupPropertyId){let o=rT(i,n.subGroupPropertyId,n.pathToProps);for(let[l,c]of o){if(c.length===0)continue;let d=`${r}:${l}`,u=n.collapsedSubGroups.has(d);if(e.push({type:"sub-header",groupKey:r,subGroupKey:l,subGroupTitle:l,taskCount:c.length,isCollapsed:u,parentKey:r}),!u)for(let p of c)e.push({type:"task",task:p,groupKey:r,subGroupKey:l})}continue}for(let o of i)e.push({type:"task",task:o,groupKey:r})}}return e}function i4(n,e){let t=[];for(let[r,a]of n){if(a.length===0)continue;let i=e.has(r);if(t.push({type:"primary-header",groupKey:r,groupTitle:r,taskCount:a.length,groupEntries:[],isCollapsed:i}),!i)for(let s of a)t.push({type:"task",task:s,groupKey:r})}return t}var rCe=y(()=>{dr();OE()});function nCe({groupByPropertyId:n,sourceGroupKey:e,targetGroupKey:t,lookupMappingKey:r,isListTypeProperty:a}){let i=n?Ya(n):null,s=!!(n!=null&&n.startsWith("formula.")),o=t==="None"?null:t,l=!!n&&o!==e,c=i?r(i):null,d=!!i&&a(i),u=n?n.replace(/^(note\.|file\.|task\.)/,""):null;return{groupByPropertyId:n,cleanGroupBy:i,frontmatterKey:u,groupByTaskProp:c,isFormulaGrouping:s,isListGrouping:d,needsGroupUpdate:l,normalizedTargetGroupKey:o,sourceGroupKey:e}}function aCe({frontmatter:n,plan:e,sortOrderField:t,sortOrder:r,isRecurring:a,dateModifiedField:i,coerceGroupKeyForFrontmatter:s,updateCompletedDateInFrontmatter:o,getTimestamp:l}){if(e.needsGroupUpdate&&e.frontmatterKey){if(e.isListGrouping){let c=n[e.frontmatterKey],u=(Array.isArray(c)?c:c?[c]:[]).filter(p=>p!==e.sourceGroupKey);e.normalizedTargetGroupKey!==null&&!u.includes(e.normalizedTargetGroupKey)&&u.push(e.normalizedTargetGroupKey),u.length>0?n[e.frontmatterKey]=u:delete n[e.frontmatterKey]}else e.normalizedTargetGroupKey===null?delete n[e.frontmatterKey]:n[e.frontmatterKey]=s(e.frontmatterKey,e.normalizedTargetGroupKey);e.groupByTaskProp==="status"&&e.normalizedTargetGroupKey!==null&&(o(n,e.normalizedTargetGroupKey,a),n[i]=l())}r!==null&&(n[t]=r)}function iCe(n,{plan:e,isCompletedStatus:t,getTimestamp:r,getCompletedDate:a}){if(!e.needsGroupUpdate||!e.groupByTaskProp)return null;let i={...n},s=n,o=i,l=e.groupByTaskProp;if(e.isListGrouping){let c=s[l],u=(Array.isArray(c)?[...c]:c?[Y(c)]:[]).filter(p=>p!==e.sourceGroupKey);e.normalizedTargetGroupKey!==null&&!u.includes(e.normalizedTargetGroupKey)&&u.push(e.normalizedTargetGroupKey),o[l]=u}else o[l]=e.normalizedTargetGroupKey;return i.dateModified=r(),l==="status"&&!n.recurrence&&(e.normalizedTargetGroupKey!==null&&t(e.normalizedTargetGroupKey)?i.completedDate=a():i.completedDate=void 0),i}var sCe=y(()=>{dr();FE()});function BE(n,e){let t=new Map;e.sortOrder&&t.set(n,e.sortOrder);for(let r of e.additionalWrites)t.set(r.path,r.sortOrder);return t}function jE(n,e,t){for(let[r,a]of e){let i=n.get(r);i&&(i.sortOrder=a,t==null||t(i))}}function $E(n,e,t,r){for(let a of n){let i=e(a);if(!i)continue;let s=t.get(i.path);s!==void 0&&(i.sortOrder=s,r==null||r(i))}}function UE(n,e,t,r){if(e.length===0||e.includes(t))return null;let a=new Set(n),i=new Set(e);if(!e.every(c=>a.has(c)))return null;let s=n.filter(c=>!i.has(c)),o=s.indexOf(t);if(o===-1)return null;let l=r?o:o+1;return[...s.slice(0,l),...e,...s.slice(l)]}function oCe(n,e,t,r,a){if(t.length===0||t.includes(r))return null;let i=new Set(t),s=new Map,o=[];for(let u of n){let p=e(u);p&&i.has(p)?s.set(p,u):o.push(u)}if(!t.every(u=>s.has(u)))return null;let l=o.findIndex(u=>e(u)===r);if(l===-1)return null;let c=[];for(let u of t){let p=s.get(u);if(!p)return null;c.push(p)}let d=a?l:l+1;return[...o.slice(0,d),...c,...o.slice(d)]}var s4=y(()=>{});function cCe(n){return typeof n=="object"&&n!==null}function w7e(n){return cCe(n)}function lCe(n){if(typeof n=="number")return n===1?"show-all":"inherit";let e=Y(n).trim().toLowerCase().replace(/^['"]|['"]$/g,"").replace(/[_\s]+/g,"-");return e==="show-all"||e==="1"?"show-all":"inherit"}function dCe(n){return function(e,t){if(!t)throw Fs.error("[TaskNotes][TaskListView] No containerEl provided",{category:"stale-data",operation:"no-containerel-provided"}),new Error("TaskListView requires a containerEl");return new o4(e,t,n)}}var Qn,Fs,o4,uCe=y(()=>{Qn=require("obsidian");IE();ME();Ua();D$();Oq();Uy();fC();Qy();Fi();Jy();xe();dr();zq();FE();X_();Li();OE();r4();XSe();rCe();sCe();s4();q();ya();Fs=M({tag:"Bases/TaskListView"});o4=class extends Bc{constructor(t,r,a){super(t,r,a);this.type="tasknotesTaskList";this.configLoaded=!1;this.itemsContainer=null;this.currentTaskElements=new Map;this.lastRenderWasGrouped=!1;this.lastFlatPaths=[];this.lastVirtualItems=[];this.lastTaskSignatures=new Map;this.lastCardRenderSignature="";this.taskInfoCache=new Map;this.clickTimeouts=new Map;this.currentTargetDate=Br(new Date);this.containerListenersRegistered=!1;this.virtualScroller=null;this.useVirtualScrolling=!1;this.collapsedGroups=new Set;this.collapsedSubGroups=new Set;this.subGroupPropertyId=null;this.defaultCollapsedState="Expanded";this.expandedRelationshipFilterMode="inherit";this.currentVisibleTaskPaths=new Set;this.currentVisibleTaskOrder=new Map;this.expandedRelationshipTaskPaths=new Set;this.expandedRelationshipTaskOrder=new Map;this.hideTopLevelSubtasks=!1;this.currentPrimaryGroupKeys=[];this.currentSubGroupKeysByParent=new Map;this.initializedPrimaryGroupKeys=new Set;this.initializedSubGroupKeys=new Set;this.deferCollapseDefaultForNextSnapshot=!1;this.draggedTaskPath=null;this.dragGroupKey=null;this.currentInsertionGroupKey=null;this.currentInsertionSegmentIndex=-1;this.currentInsertionIndex=-1;this.pendingDragClientY=null;this.pendingRender=!1;this.taskGroupKeys=new Map;this.sortScopeTaskPaths=new Map;this.sortScopeCandidateTaskPaths=new Map;this.dragOverRafId=0;this.dragContainer=null;this.currentDropSlotElement=null;this.currentDropSlotPosition=null;this.dragBaselineCards=[];this.dropQueue=new tT;this.VIRTUAL_SCROLL_THRESHOLD=100;this.LARGE_REORDER_WARNING_THRESHOLD=10;this.UNGROUPED_SORT_SCOPE_KEY="__ungrouped__";this.CARD_NO_DRAG_SELECTOR='[data-tn-no-drag="true"], a, button, input, select, textarea, [contenteditable="true"]';this.CARD_DRAG_HANDLE_SELECTOR='[data-tn-drag-handle="true"]';this.handleItemClick=async t=>{let r=t.target,a=r.closest(".task-group-header");if(a){let i=a.closest(".task-group"),s=i==null?void 0:i.dataset.groupKey;if(s){if(r.closest("a"))return;t.preventDefault(),t.stopPropagation(),await this.handleGroupToggle(s);return}}};this.handleItemContextMenu=async t=>{let r=this.getTaskContextFromEvent(t);if(!r)return;t.preventDefault(),t.stopPropagation();let a=this.plugin.taskSelectionService;if(a&&a.getSelectionCount()>1){a.isSelected(r.task.path)||a.addToSelection(r.task.path),this.showBatchContextMenu(t);return}await uo(t,r.task.path,this.plugin,this.currentTargetDate)};this.handleItemPointerOver=t=>{if("pointerType"in t&&t.pointerType!=="mouse")return;let r=this.getTaskContextFromEvent(t);if(!r)return;let a=t.relatedTarget;if(a&&r.card.contains(a))return;let i=this.app||this.plugin.app;i.vault.getAbstractFileByPath(r.task.path)&&i.workspace.trigger("hover-link",{event:t,source:"tasknotes-task-card",hoverParent:r.card,targetEl:r.card,linktext:r.task.path,sourcePath:r.task.path})};this.basesController=t,this.dataAdapter.basesView=this}onload(){this.readViewOptions(),super.onload(),this.registerGroupContextMenuListeners()}registerGroupContextMenuListeners(){this.rootElement&&this.rootElement.addEventListener("contextmenu",t=>{let r=t.target,a=r.closest(".task-group-header");if(a){let s=a.closest(".task-group"),o=s==null?void 0:s.dataset.groupKey;if(o&&!this.isSubGroupKey(o)){t.preventDefault(),this.showGroupHeaderContextMenu(t,o);return}}!r.closest(".task-card")&&!a&&this.currentPrimaryGroupKeys.length>0&&(t.preventDefault(),this.showContainerContextMenu(t))})}showGroupHeaderContextMenu(t,r){let a=this.currentSubGroupKeysByParent.get(r);if(!a||a.length===0)return;let i=a.every(o=>this.collapsedSubGroups.has(o)),s=new Qn.Menu;s.addItem(o=>{o.setTitle(i?"Expand subgroups":"Collapse subgroups").setIcon(i?"list-tree":"list-collapse").onClick(()=>void this.setSubGroupsCollapsed(r,!i))}),s.showAtMouseEvent(t)}showContainerContextMenu(t){let r=new Qn.Menu;r.addItem(a=>{a.setTitle("Expand all groups").setIcon("chevrons-down").onClick(()=>void this.setAllPrimaryGroupsCollapsed(!1))}),r.addItem(a=>{a.setTitle("Collapse all groups").setIcon("chevrons-up").onClick(()=>void this.setAllPrimaryGroupsCollapsed(!0))}),r.addItem(a=>{a.setTitle("Expand all groups and subgroups").setIcon("list-tree").onClick(()=>void this.setAllGroupsAndSubGroupsCollapsed(!1))}),r.addItem(a=>{a.setTitle("Collapse all groups and subgroups").setIcon("list-collapse").onClick(()=>void this.setAllGroupsAndSubGroupsCollapsed(!0))}),r.showAtMouseEvent(t)}readViewOptions(){if(!this.config||typeof this.config.get!="function"){Fs.debug("[TaskListView] Config not available yet in readViewOptions",{category:"configuration",operation:"config-not-yet-readviewoptions"});return}try{this.subGroupPropertyId=this.config.getAsPropertyId("subGroup");let t=this.config.get("enableSearch");this.enableSearch=t!=null?t:!1;let r=this.config.get("defaultCollapsedState");this.defaultCollapsedState=r==="Collapsed"||r==="1"?"Collapsed":"Expanded";let a=this.config.get("expandedRelationshipFilterMode");this.expandedRelationshipFilterMode=lCe(a),this.hideTopLevelSubtasks=this.config.get("hideTopLevelSubtasks")===!0,this.configLoaded=!0}catch(t){Fs.warn("[TaskListView] Failed to parse config:",{category:"configuration",operation:"parse-config",error:t})}}clearGroupingSnapshot(){this.currentPrimaryGroupKeys=[],this.currentSubGroupKeysByParent.clear()}initializeCollapseStateForSnapshot(t,r){let a=this.defaultCollapsedState==="Collapsed"&&!this.deferCollapseDefaultForNextSnapshot;for(let i of t)this.initializedPrimaryGroupKeys.has(i)||(this.initializedPrimaryGroupKeys.add(i),a&&this.collapsedGroups.add(i));for(let i of r.values())for(let s of i)this.initializedSubGroupKeys.has(s)||(this.initializedSubGroupKeys.add(s),a&&this.collapsedSubGroups.add(s));this.deferCollapseDefaultForNextSnapshot=!1}applyGroupingSnapshot(t){let r=new Map;for(let[a,i]of t.subGroupKeysByParent.entries())r.set(a,[...i]);this.initializeCollapseStateForSnapshot(t.primaryGroupKeys,r),this.currentPrimaryGroupKeys=[...t.primaryGroupKeys],this.currentSubGroupKeysByParent=r}createGroupedHierarchySnapshot(t,r){let a={primaryGroupKeys:[],subGroupKeysByParent:new Map},i=this.subGroupPropertyId?zE(this.dataAdapter.extractDataItems()):new Map;for(let s of t){let o=this.dataAdapter.convertGroupKeyToString(s.key),l=new Set(s.entries.map(p=>{var m;return(m=p.file)==null?void 0:m.path})),c=r.filter(p=>l.has(p.path));if(c.length===0||(a.primaryGroupKeys.push(o),!this.subGroupPropertyId))continue;let d=[],u=rT(c,this.subGroupPropertyId,i);for(let[p,m]of u)m.length!==0&&d.push(`${o}:${p}`);d.length>0&&a.subGroupKeysByParent.set(o,d)}return a}createSubPropertyHierarchySnapshot(t){return{primaryGroupKeys:Array.from(t.keys()),subGroupKeysByParent:new Map}}setupContainer(){var a;super.setupContainer(),this.rootElement&&(this.rootElement.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-flex-direction-column-06c8b5ed","tn-static-height-0-7a31cef0","tn-static-height-100-62264068","tn-static-height-12px-06c0747e","tn-static-height-16px-30de4aee","tn-static-height-24px-29a11d37","tn-static-min-height-800px-997b4c8c"),this.rootElement.classList.add("tn-static-display-flex-4d51fc62"));let t=this.containerEl.ownerDocument,r=Ie(t,"div");r.className="tn-bases-items-container",r.classList.remove("tn-static-flex-1-14e3b769","tn-static-flex-1-97445a8d","tn-static-font-size-12px-b0cc7e05","tn-static-margin-top-0-5rem-3dc98b5e","tn-static-margin-top-0-d462248a","tn-static-margin-top-16px-1b0f4999","tn-static-margin-top-1rem-2239d6d5","tn-static-margin-top-20px-a26bda7d","tn-static-margin-top-30px-2fbbbcd4","tn-static-margin-top-4px-96ad6099","tn-static-margin-top-8px-8a77e5a3","tn-static-margin-top-8px-f4f01e68","tn-static-max-height-400px-f0787633","tn-static-overflow-y-auto-03df744e","tn-static-overflow-y-clip-c5043043","tn-static-position-relative-d461c96d"),r.classList.add("tn-static-margin-top-12px-91e0f558"),(a=this.rootElement)==null||a.appendChild(r),this.itemsContainer=r,this.registerContainerListeners(),this.setupContainerDragHandlers()}async render(){var t;if(!(!this.itemsContainer||!this.rootElement)){if(this.draggedTaskPath){this.pendingRender=!0;return}this.config&&this.readViewOptions(),this.rootElement&&this.setupSearch(this.rootElement);try{if(!((t=this.data)!=null&&t.data)){this.clearGroupingSnapshot();return}let r=this.dataAdapter.extractDataItems();LE(this.data,r);let a=await yu(r,this.plugin);if(a.length===0){this.clearAllTaskElements(),this.sortScopeTaskPaths.clear(),this.sortScopeCandidateTaskPaths.clear(),this.clearGroupingSnapshot(),this.renderEmptyState(),this.lastRenderWasGrouped=!1;return}let i=this.dataAdapter.isGrouped();!i&&this.subGroupPropertyId?(this.lastRenderWasGrouped||this.clearAllTaskElements(),await this.renderGroupedBySubProperty(a),this.lastRenderWasGrouped=!0):i?(this.lastRenderWasGrouped||this.clearAllTaskElements(),await this.renderGrouped(a),this.lastRenderWasGrouped=!0):(this.lastRenderWasGrouped&&this.clearAllTaskElements(),this.clearGroupingSnapshot(),await this.renderFlat(a),this.lastRenderWasGrouped=!1)}catch(r){Fs.error("[TaskNotes][TaskListView] Error rendering:",{category:"persistence",operation:"rendering",error:r}),this.clearAllTaskElements(),this.sortScopeTaskPaths.clear(),this.sortScopeCandidateTaskPaths.clear(),this.renderError(r instanceof Error?r:new Error(String(r)))}}}getGroupByPropertyId(){var r;let t=this.basesController;if((r=t==null?void 0:t.query)!=null&&r.views&&(t!=null&&t.viewName)){for(let a of t.query.views)if((a==null?void 0:a.name)===t.viewName){if(a.groupBy){if(typeof a.groupBy=="object"&&a.groupBy.property)return a.groupBy.property;if(typeof a.groupBy=="string")return a.groupBy}return null}}return null}getSortScopeKey(t){return t!=null?t:this.UNGROUPED_SORT_SCOPE_KEY}getVisibleSortScopePaths(t){return this.sortScopeTaskPaths.get(this.getSortScopeKey(t))}getCandidateSortScopePaths(t){return this.sortScopeCandidateTaskPaths.get(this.getSortScopeKey(t))}setSortScopePaths(t){this.sortScopeTaskPaths.clear();for(let[r,a]of t)this.sortScopeTaskPaths.set(this.getSortScopeKey(r),[...a])}setSortScopeCandidatePaths(t){this.sortScopeCandidateTaskPaths.clear();for(let[r,a]of t)this.sortScopeCandidateTaskPaths.set(this.getSortScopeKey(r),[...a])}getVirtualItemTask(t){return"type"in t?t.type==="task"?t.task:null:t}getVirtualItemPath(t){var r,a;return(a=(r=this.getVirtualItemTask(t))==null?void 0:r.path)!=null?a:null}getVirtualItemGroupKey(t){return"type"in t&&t.type==="task"?t.groupKey:null}rebuildSortScopesFromVirtualItems(t){var i;let r=new Map,a=[];for(let s of t){let o=this.getVirtualItemTask(s);if(!o)continue;a.push(o.path);let l=this.getVirtualItemGroupKey(s),c=(i=r.get(l))!=null?i:[];c.push(o.path),r.set(l,c)}r.size>0?this.setSortScopePaths(r):this.setSortScopePaths([[null,a]])}applyOptimisticSortOrderResult(t,r,a,i,s,o){var u,p;if(s!==i)return!1;let l=BE(t,o);if(jE(this.taskInfoCache,l,m=>{this.lastTaskSignatures.set(m.path,this.buildTaskSignature(m))}),this.virtualScroller&&this.lastVirtualItems.length>0){let m=oCe(this.lastVirtualItems,f=>this.getVirtualItemPath(f),[t],r,a);return m?($E(m,f=>this.getVirtualItemTask(f),l,f=>{this.taskInfoCache.set(f.path,f),this.lastTaskSignatures.set(f.path,this.buildTaskSignature(f))}),this.lastVirtualItems=m,this.virtualScroller.updateItems(m),this.rebuildSortScopesFromVirtualItems(m),this.setCurrentVisibleTaskPaths(m.map(f=>this.getVirtualItemTask(f)).filter(f=>!!f)),this.lastFlatPaths=m.map(f=>this.getVirtualItemPath(f)).filter(f=>!!f),!0):!1}let c=(u=this.itemsContainer)==null?void 0:u.querySelector(`.task-card[data-task-path="${CSS.escape(t)}"]`),d=(p=this.itemsContainer)==null?void 0:p.querySelector(`.task-card[data-task-path="${CSS.escape(r)}"]`);return!c||!d?!1:(a?d.before(c):d.after(c),!0)}isListTypeProperty(t){if(tF(this.plugin.app,t))return!0;let r=this.plugin.fieldMapper.toUserField("contexts"),a=this.plugin.fieldMapper.toUserField("projects");return new Set(["contexts",r,"projects",a,"tags","aliases"]).has(t)}coerceGroupKeyForFrontmatter(t,r){return nF(this.plugin.app,t,r,this.plugin.settings.userFields)}async confirmLargeReorder(t,r){let a=this.plugin.settings.fieldMapping.sortOrder,i=r===null?this.plugin.i18n.translate("views.taskList.reorder.scope.ungrouped"):this.plugin.i18n.translate("views.taskList.reorder.scope.group",{group:r});return ur(this.plugin.app,{title:this.plugin.i18n.translate("common.reorder.confirmLargeTitle"),message:this.plugin.i18n.translate("common.reorder.confirmLargeMessage",{field:a,count:t,scope:i}),confirmText:this.plugin.i18n.translate("common.reorder.confirmButton"),cancelText:this.plugin.i18n.translate("common.cancel")})}getEventTargetElement(t){let r=t;return!r||typeof r.nodeType!="number"?null:r.nodeType===Node.ELEMENT_NODE?r:r.parentElement}shouldSuppressCardDrag(t,r){let a=this.getEventTargetElement(t);if(!a||!r.contains(a))return!1;let i=a.closest(this.CARD_NO_DRAG_SELECTOR);return i&&r.contains(i)?!0:this.isMobileDragHandleOnlyMode(r)&&!a.closest(this.CARD_DRAG_HANDLE_SELECTOR)}isMobileDragHandleOnlyMode(t){return t.ownerDocument.body.classList.contains("is-mobile")}setupCardDragHandle(t){t.classList.add("task-card--reorderable"),t.classList.toggle("task-card--drag-handle-only",this.isMobileDragHandleOnlyMode(t));let r=t.querySelector(this.CARD_DRAG_HANDLE_SELECTOR);if(r){r.setAttribute("draggable","true");return}let a=Ie(t.ownerDocument,"div");a.className="task-card__drag-handle",a.dataset.tnDragHandle="true",a.setAttribute("draggable","true"),a.setAttribute("aria-label","Drag to reorder"),a.setAttribute("title","Drag to reorder"),(0,Qn.setIcon)(a,"grip-vertical"),a.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation()}),t.insertBefore(a,t.firstChild)}setupCardDragHandlers(t,r,a){let i=null,s=!1,o=()=>{t.setAttribute("draggable",this.isMobileDragHandleOnlyMode(t)?"false":"true"),i=null,s=!1},l=d=>typeof d.button!="number"||d.button===0,c=d=>{i=d.target,s=this.shouldSuppressCardDrag(d.target,t),t.setAttribute("draggable",s?"false":"true"),!(s||!l(d))&&d.stopPropagation()};this.setupCardDragHandle(t),o(),t.addEventListener("pointerdown",c,{capture:!0}),t.addEventListener("mousedown",c,{capture:!0}),t.addEventListener("mouseup",d=>{!s&&l(d)&&d.stopPropagation(),o()}),t.addEventListener("click",o,{capture:!0}),t.addEventListener("dragstart",d=>{if(this.shouldSuppressCardDrag(i!=null?i:d.target,t)){d.preventDefault(),d.stopPropagation(),o();return}d.stopPropagation(),this.draggedTaskPath=r.path,this.dragGroupKey=a,t.classList.add("task-card--dragging"),d.dataTransfer&&(d.dataTransfer.effectAllowed="move",d.dataTransfer.setData("text/plain",r.path)),this.containerEl.ownerDocument.body.classList.add("tn-drag-active");let u=t.getBoundingClientRect().height,p=this.itemsContainer;window.requestAnimationFrame(()=>{if(t.classList.remove("tn-static-display-flex-4d51fc62","tn-static-height-100-62264068","tn-static-height-12px-06c0747e","tn-static-height-16px-30de4aee","tn-static-height-24px-29a11d37","tn-static-min-height-800px-997b4c8c"),t.classList.add("tn-static-height-0-7a31cef0"),t.classList.remove("tn-static-flex-1-14e3b769"),t.classList.add("tn-static-overflow-hidden-69824400"),t.classList.remove("tn-static-margin-8px-0-0-0-a2eb8382","tn-static-padding-0-16px-16px-16px-f1aa998c","tn-static-padding-12px-43bef435","tn-static-padding-16px-287f770e","tn-static-padding-20px-769fed37","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c","tn-static-padding-2px-8px-c8eea84a","tn-static-padding-2rem-42aa6d9c"),t.classList.add("tn-static-padding-0-41d7d7e2"),t.classList.remove("tn-static-margin-0-auto-266e9b04","tn-static-margin-0-db0d5f36","tn-static-margin-0-var-size-4-2-77f7dc08","tn-static-margin-2px-0-edce9b14","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-padding-12px-43bef435","tn-static-padding-20px-ebe8e48c"),t.classList.add("tn-static-margin-0-11696618"),t.classList.remove("tn-static-border-1px-solid-var-background-mo-b65b5121","tn-static-padding-12px-43bef435"),t.classList.add("tn-static-border-none-2eda1daa"),t.classList.remove("tn-static-opacity-0-6-d95b59ac","tn-static-opacity-1-c6e7979d"),t.classList.add("tn-static-opacity-0-8d919cb5"),p){let m=getComputedStyle(p).gap,f=parseFloat(m)||4;p.style.setProperty("--tn-drag-gap",`${u+f}px`),this.dragContainer=p,this.currentInsertionGroupKey=a,this.currentInsertionSegmentIndex=-1,this.currentInsertionIndex=-1,this.currentDropSlotElement=null,this.currentDropSlotPosition=null,this.captureDropBaseline()}})}),t.addEventListener("dragend",()=>{o(),vm(t),t.classList.remove("task-card--dragging"),this.cleanupDragShift(),this.containerEl.ownerDocument.body.classList.remove("tn-drag-active"),this.draggedTaskPath=null,this.dragGroupKey=null,this.currentInsertionGroupKey=null,this.currentInsertionSegmentIndex=-1,this.currentInsertionIndex=-1,this.dragOverRafId&&(cancelAnimationFrame(this.dragOverRafId),this.dragOverRafId=0),this.pendingDragClientY=null,this.pendingRender&&(this.containerEl.ownerDocument.defaultView||window).setTimeout(()=>{this.pendingRender&&(this.pendingRender=!1,this.debouncedRefresh())},200)})}shouldEnableManualReordering(){return _E(this.dataAdapter,this.plugin.settings.fieldMapping.sortOrder)}configureCardForManualReordering(t,r,a){this.shouldEnableManualReordering()&&(t.setAttribute("draggable","true"),this.setupCardDragHandlers(t,r,a))}clearDropIndicators(){var t;(t=this.itemsContainer)==null||t.querySelectorAll(".task-card--drop-above, .task-card--drop-below, .task-list-view__drop-slot-before, .task-list-view__drop-slot-after").forEach(r=>{r.classList.remove("task-card--drop-above","task-card--drop-below","task-list-view__drop-slot-before","task-list-view__drop-slot-after")}),this.currentDropSlotElement=null,this.currentDropSlotPosition=null}cleanupDragShift(){var t;this.dragContainer&&this.dragContainer.style.removeProperty("--tn-drag-gap"),(t=this.itemsContainer)==null||t.querySelectorAll(".task-card--drag-shift, .task-card--shift-down, .task-list-view__drop-slot-before, .task-list-view__drop-slot-after").forEach(r=>{r.classList.remove("task-card--drag-shift","task-card--shift-down","task-list-view__drop-slot-before","task-list-view__drop-slot-after")}),this.dragContainer=null,this.currentDropSlotElement=null,this.currentDropSlotPosition=null,this.currentInsertionGroupKey=null,this.currentInsertionSegmentIndex=-1,this.currentInsertionIndex=-1,this.dragBaselineCards=[]}getDropSegments(){return ZSe(this.getDropBaselineCards())}reconstructDropTargetFromInsertionSlot(t,r){return QSe(this.getDropSegments(),t,r)}getCurrentInsertionTarget(){return this.currentInsertionSegmentIndex<0||this.currentInsertionIndex<0?null:this.reconstructDropTargetFromInsertionSlot(this.currentInsertionSegmentIndex,this.currentInsertionIndex)}getVisibleSortScopePathsForDrag(t){return this.getVisibleSortScopePaths(t)}getReorderScopeQueueKey(t,r){return r?`manual-sort:${r}:${this.getSortScopeKey(t)}`:"manual-sort:list"}syncGroupedDragMetadata(t){this.taskGroupKeys.clear();let r=new Map;for(let a of t){if(a.type!=="task")continue;this.taskGroupKeys.set(a.task.path,a.groupKey);let i=r.get(a.groupKey)||[];i.push(a.task.path),r.set(a.groupKey,i)}this.setSortScopePaths(r)}updateDropSlotPreview(t){let{element:r,position:a}=t;r===this.currentDropSlotElement&&a===this.currentDropSlotPosition||(this.clearDropIndicators(),r.classList.add(a==="before"?"task-list-view__drop-slot-before":"task-list-view__drop-slot-after"),this.currentDropSlotElement=r,this.currentDropSlotPosition=a)}updateResolvedInsertionSlot(t){let r=this.resolveClosestInsertionSlot(t);return r?(this.currentInsertionGroupKey=r.groupKey,this.currentInsertionSegmentIndex=r.segmentIndex,this.currentInsertionIndex=r.insertionIndex,this.updateDropSlotPreview(r),!0):!1}flushPendingInsertionSlot(t){return this.dragOverRafId&&(cancelAnimationFrame(this.dragOverRafId),this.dragOverRafId=0),this.pendingDragClientY=null,this.updateResolvedInsertionSlot(t)}getVisibleDropCards(){return this.itemsContainer?Array.from(this.itemsContainer.querySelectorAll(".task-card[data-task-path]")).filter(t=>{var a;return t.dataset.taskPath===this.draggedTaskPath?!1:!((a=t.parentElement)==null?void 0:a.closest(".task-card[data-task-path]"))}):[]}captureDropBaseline(t=this.getVisibleDropCards()){if(!this.itemsContainer){this.dragBaselineCards=[];return}let r=this.itemsContainer.getBoundingClientRect(),a=this.itemsContainer.scrollTop;this.dragBaselineCards=t.map(i=>{var c;let s=i.dataset.taskPath;if(!s)return null;let o=i.getBoundingClientRect(),l=o.top-r.top+a;return{path:s,groupKey:(c=this.taskGroupKeys.get(s))!=null?c:null,card:i,top:l,bottom:l+o.height,midpoint:l+o.height/2}}).filter(i=>!!i)}getDropBaselineCards(){let t=this.getVisibleDropCards(),r=t.map(s=>{var o;return(o=s.dataset.taskPath)!=null?o:""}),a=this.dragBaselineCards.map(s=>s.path);return r.length===a.length&&r.every((s,o)=>s===a[o])||this.captureDropBaseline(t),this.dragBaselineCards}getContainerLocalY(t){if(!this.itemsContainer)return t;let r=this.itemsContainer.getBoundingClientRect();return t-r.top+this.itemsContainer.scrollTop}resolveClosestInsertionSlot(t){let r=this.getDropSegments(),a=this.getContainerLocalY(t);return JSe(r,a)}setupContainerDragHandlers(){this.itemsContainer&&(this.itemsContainer.addEventListener("dragenter",t=>{this.draggedTaskPath&&(t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="move"))}),this.itemsContainer.addEventListener("dragover",t=>{this.draggedTaskPath&&(t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="move"),this.pendingDragClientY=t.clientY,this.dragOverRafId||(this.dragOverRafId=window.requestAnimationFrame(()=>{this.dragOverRafId=0;let r=this.pendingDragClientY;this.pendingDragClientY=null,r!==null&&this.updateResolvedInsertionSlot(r)})))}),this.itemsContainer.addEventListener("dragleave",t=>{var a;let r=t.relatedTarget;(!r||!((a=this.itemsContainer)!=null&&a.contains(r)))&&this.clearDropIndicators()}),this.itemsContainer.addEventListener("drop",t=>{(async()=>{if(t.preventDefault(),!this.draggedTaskPath||!this.flushPendingInsertionSlot(t.clientY)&&this.currentInsertionIndex<0)return;let r=this.draggedTaskPath,a=this.dragGroupKey,i=this.currentInsertionGroupKey,s=this.getVisibleSortScopePathsForDrag(i),o=this.currentInsertionSegmentIndex,l=this.currentInsertionIndex,c=o>=0&&l>=0?this.reconstructDropTargetFromInsertionSlot(o,l):null;!r||!c||(this.clearDropIndicators(),this.cleanupDragShift(),this.draggedTaskPath=null,this.dragGroupKey=null,this.currentInsertionGroupKey=null,this.currentInsertionSegmentIndex=-1,this.currentInsertionIndex=-1,this.pendingDragClientY=null,await this.handleSortOrderDrop(r,c.taskPath,c.above,i,a,s))})()}))}async handleSortOrderDrop(t,r,a,i,s,o){let l=this.getGroupByPropertyId(),c=this.getReorderScopeQueueKey(i,l);await this.dropQueue.enqueue(c,async()=>{var v;let d=nCe({groupByPropertyId:l,sourceGroupKey:s,targetGroupKey:i,lookupMappingKey:k=>this.plugin.fieldMapper.lookupMappingKey(k),isListTypeProperty:k=>this.isListTypeProperty(k)});if(d.isFormulaGrouping){new Qn.Notice(this.plugin.i18n.translate("views.taskList.errors.formulaGroupingReadOnly"));return}let u=await Q_(r,a,i,d.cleanGroupBy,t,this.plugin,{taskInfoCache:this.taskInfoCache,visibleTaskPaths:o!=null?o:this.getVisibleSortScopePaths(i),candidateTaskPaths:this.getCandidateSortScopePaths(i)});if(u.sortOrder===null)return;let p=u.additionalWrites.length+1;if(p>this.LARGE_REORDER_WARNING_THRESHOLD&&!await this.confirmLargeReorder(p,i))return;if(!(d.needsGroupUpdate||u!==null)){this.debouncedRefresh();return}let f=this.plugin.app.vault.getAbstractFileByPath(t);if(!f||!(f instanceof Qn.TFile)){this.debouncedRefresh();return}let h=this.plugin.settings.fieldMapping.sortOrder;if(await J_(t,u,this.plugin,{includeDragged:!1}),await yr(this.plugin.app,f,k=>{var T;aCe({frontmatter:k,plan:d,sortOrderField:h,sortOrder:u.sortOrder,isRecurring:!!((T=this.taskInfoCache.get(t))!=null&&T.recurrence),dateModifiedField:this.plugin.fieldMapper.toUserField("dateModified"),coerceGroupKeyForFrontmatter:(b,w)=>this.coerceGroupKeyForFrontmatter(b,w),updateCompletedDateInFrontmatter:(b,w,S)=>this.plugin.taskService.updateCompletedDateInFrontmatter(b,w,S),getTimestamp:qe})}),d.needsGroupUpdate&&d.groupByTaskProp)try{let k=(v=this.taskInfoCache.get(t))!=null?v:await this.plugin.cacheManager.getTaskInfo(t);if(k){let T=iCe(k,{plan:d,isCompletedStatus:b=>this.plugin.statusManager.isCompletedStatus(b),getTimestamp:qe,getCompletedDate:()=>new Date().toISOString().split("T")[0]});T&&await this.plugin.taskService.applyPropertyChangeSideEffects(f,k,T,d.groupByTaskProp,d.sourceGroupKey,d.normalizedTargetGroupKey)}}catch(k){Fs.warn("[TaskNotes][TaskListView] Side-effect error after drop:",{category:"persistence",operation:"side-effect-drop",error:k})}this.applyOptimisticSortOrderResult(t,r,a,i,s,u)||this.debouncedRefresh()})}async renderFlat(t){let r=this.getVisibleProperties();this.setSortScopeCandidatePaths([[null,t.map(c=>c.path)]]);let a=this.applySearchFilter(t);this.setExpandedRelationshipTaskScope(a);let i=this.getTopLevelRenderTasks(a);if(this.setCurrentVisibleTaskPaths(i),this.isSearchWithNoResults(a,t.length)){this.clearAllTaskElements(),this.sortScopeTaskPaths.clear(),this.sortScopeCandidateTaskPaths.clear(),this.itemsContainer&&this.renderSearchNoResults(this.itemsContainer);return}let s=Br(new Date);this.currentTargetDate=s;let o=this.getCardOptions(s),l=i.length>=this.VIRTUAL_SCROLL_THRESHOLD;l&&!this.useVirtualScrolling?(this.cleanupNonVirtualRendering(),this.useVirtualScrolling=!0):!l&&this.useVirtualScrolling&&(this.destroyVirtualScroller(),this.useVirtualScrolling=!1),this.useVirtualScrolling?await this.renderFlatVirtual(i,r,o):await this.renderFlatNormal(i,r,o)}async renderFlatVirtual(t,r,a){if(this.itemsContainer){if(this.taskGroupKeys.clear(),this.setSortScopePaths([[null,t.map(i=>i.path)]]),!this.virtualScroller)this.resetVirtualScrollerIfCardRenderChanged(this.buildCardRenderSignature(r,a)),this.virtualScroller=new hm({container:this.itemsContainer,items:t,overscan:5,renderItem:i=>{if("type"in i)throw new Error("Unexpected grouped item in flat renderer");let s=i,o=pr(i,this.plugin,r,a);return this.configureCardForManualReordering(o,s,null),this.taskInfoCache.set(s.path,s),this.lastTaskSignatures.set(s.path,this.buildTaskSignature(s)),o},getItemKey:i=>"type"in i?`grouped-${i.groupKey}`:i.path}),window.setTimeout(()=>{var i;(i=this.virtualScroller)==null||i.recalculate()},0);else{if(this.resetVirtualScrollerIfCardRenderChanged(this.buildCardRenderSignature(r,a)),!this.virtualScroller){await this.renderFlatVirtual(t,r,a);return}this.virtualScroller.updateItems(t)}this.lastVirtualItems=t,this.lastFlatPaths=t.map(i=>i.path),this.lastCardRenderSignature=this.buildCardRenderSignature(r,a)}}async renderFlatNormal(t,r,a){if(!this.itemsContainer)return;this.lastVirtualItems=[],this.taskGroupKeys.clear(),this.setSortScopePaths([[null,t.map(c=>c.path)]]);let i=new Set,s=!this.arePathArraysEqual(t,this.lastFlatPaths),o=this.buildCardRenderSignature(r,a),l=o!==this.lastCardRenderSignature;s&&(this.itemsContainer.empty(),this.currentTaskElements.clear());for(let c of t){let d=s?null:this.currentTaskElements.get(c.path)||null,u=this.buildTaskSignature(c,r),p=this.lastTaskSignatures.get(c.path),m=l||u!==p||!d;if(!d||m){let f=pr(c,this.plugin,r,a);d&&d.isConnected&&d.replaceWith(f),d=f}d.isConnected||this.itemsContainer.appendChild(d),m&&this.configureCardForManualReordering(d,c,null),this.currentTaskElements.set(c.path,d),this.taskInfoCache.set(c.path,c),this.lastTaskSignatures.set(c.path,u),i.add(c.path)}if(!s&&i.size!==this.currentTaskElements.size){for(let[c,d]of this.currentTaskElements)if(!i.has(c)){d.remove(),this.currentTaskElements.delete(c);let u=this.clickTimeouts.get(c);u&&(window.clearTimeout(u),this.clickTimeouts.delete(c)),this.taskInfoCache.delete(c),this.lastTaskSignatures.delete(c)}}this.lastFlatPaths=t.map(c=>c.path),this.lastCardRenderSignature=o}async renderGroupedBySubProperty(t){let r=this.getVisibleProperties(),a=this.applySearchFilter(t);this.setExpandedRelationshipTaskScope(a);let i=this.getTopLevelRenderTasks(a),s=this.getTopLevelRenderTasks(t);if(this.setCurrentVisibleTaskPaths(i),this.isSearchWithNoResults(a,t.length)){this.clearAllTaskElements(),this.sortScopeTaskPaths.clear(),this.sortScopeCandidateTaskPaths.clear(),this.itemsContainer&&this.renderSearchNoResults(this.itemsContainer);return}let o=Br(new Date);this.currentTargetDate=o;let l=this.getCardOptions(o),c=zE(this.dataAdapter.extractDataItems()),d=rT(i,this.subGroupPropertyId,c),u=rT(s,this.subGroupPropertyId,c);this.setSortScopeCandidatePaths(tCe(u)),this.applyGroupingSnapshot(this.createSubPropertyHierarchySnapshot(d));let p=i4(d,this.collapsedGroups),m=p.length>=this.VIRTUAL_SCROLL_THRESHOLD;if(this.useVirtualScrolling&&m&&this.virtualScroller){await this.renderGroupedVirtual(p,r,l),this.lastFlatPaths=t.map(f=>f.path);return}this.itemsContainer.empty(),this.currentTaskElements.clear(),this.clearClickTimeouts(),this.taskInfoCache.clear(),this.lastTaskSignatures.clear(),m&&!this.useVirtualScrolling?(this.cleanupNonVirtualRendering(),this.useVirtualScrolling=!0):!m&&this.useVirtualScrolling&&(this.destroyVirtualScroller(),this.useVirtualScrolling=!1),this.useVirtualScrolling?await this.renderGroupedVirtual(p,r,l):await this.renderGroupedNormal(p,r,l),this.lastFlatPaths=t.map(f=>f.path)}async renderGrouped(t){let r=this.getVisibleProperties(),a=this.dataAdapter.getGroupedData(),i=this.applySearchFilter(t);this.setExpandedRelationshipTaskScope(i);let s=this.getTopLevelRenderTasks(i),o=this.getTopLevelRenderTasks(t);if(this.setCurrentVisibleTaskPaths(s),this.isSearchWithNoResults(i,t.length)){this.clearAllTaskElements(),this.sortScopeTaskPaths.clear(),this.sortScopeCandidateTaskPaths.clear(),this.itemsContainer&&this.renderSearchNoResults(this.itemsContainer);return}let l=Br(new Date);this.currentTargetDate=l;let c=this.getCardOptions(l);this.applyGroupingSnapshot(this.createGroupedHierarchySnapshot(a,s));let d=this.subGroupPropertyId?zE(this.dataAdapter.extractDataItems()):new Map,u=a4({groups:a,taskNotes:s,subGroupPropertyId:this.subGroupPropertyId,pathToProps:d,collapsedGroups:this.collapsedGroups,collapsedSubGroups:this.collapsedSubGroups,convertGroupKeyToString:m=>this.dataAdapter.convertGroupKeyToString(m)});this.setSortScopeCandidatePaths(eCe(a,o,m=>this.dataAdapter.convertGroupKeyToString(m)));let p=u.length>=this.VIRTUAL_SCROLL_THRESHOLD;if(this.useVirtualScrolling&&p&&this.virtualScroller){await this.renderGroupedVirtual(u,r,c),this.lastFlatPaths=t.map(m=>m.path);return}this.itemsContainer.empty(),this.currentTaskElements.clear(),this.clearClickTimeouts(),this.taskInfoCache.clear(),this.lastTaskSignatures.clear(),p&&!this.useVirtualScrolling?(this.cleanupNonVirtualRendering(),this.useVirtualScrolling=!0):!p&&this.useVirtualScrolling&&(this.destroyVirtualScroller(),this.useVirtualScrolling=!1),this.useVirtualScrolling?await this.renderGroupedVirtual(u,r,c):await this.renderGroupedNormal(u,r,c),this.lastFlatPaths=t.map(m=>m.path)}async renderGroupedVirtual(t,r,a){if(this.syncGroupedDragMetadata(t),!this.virtualScroller)this.virtualScroller=new hm({container:this.itemsContainer,items:t,overscan:5,renderItem:i=>{if(!("type"in i))throw new Error("Unexpected flat task item in grouped renderer");if(i.type==="primary-header"||i.type==="sub-header")return this.createGroupHeader(i);{let s=pr(i.task,this.plugin,r,a);return this.configureCardForManualReordering(s,i.task,i.groupKey),this.taskInfoCache.set(i.task.path,i.task),this.lastTaskSignatures.set(i.task.path,this.buildTaskSignature(i.task)),s}},getItemKey:i=>"type"in i?i.type==="primary-header"?`primary-${i.groupKey}`:i.type==="sub-header"?`sub-${i.groupKey}:${i.subGroupKey}`:i.task.path:i.path}),window.setTimeout(()=>{var i;(i=this.virtualScroller)==null||i.recalculate()},0);else{if(this.resetVirtualScrollerIfCardRenderChanged(this.buildCardRenderSignature(r,a)),!this.virtualScroller){await this.renderGroupedVirtual(t,r,a);return}this.virtualScroller.updateItems(t)}this.lastVirtualItems=t,this.lastCardRenderSignature=this.buildCardRenderSignature(r,a)}async renderGroupedNormal(t,r,a){this.lastVirtualItems=[],this.syncGroupedDragMetadata(t);for(let i of t)if(i.type==="primary-header"||i.type==="sub-header"){let s=this.createGroupHeader(i);this.itemsContainer.appendChild(s)}else{let s=pr(i.task,this.plugin,r,a);this.configureCardForManualReordering(s,i.task,i.groupKey),this.itemsContainer.appendChild(s),this.currentTaskElements.set(i.task.path,s),this.taskInfoCache.set(i.task.path,i.task),this.lastTaskSignatures.set(i.task.path,this.buildTaskSignature(i.task))}this.lastCardRenderSignature=this.buildCardRenderSignature(r,a)}createGroupHeader(t){let r=this.containerEl.ownerDocument,a=Ie(r,"div");a.className="task-section task-group";let i=t.type==="sub-header",s=i?"sub":"primary";a.dataset.level=s;let o=i?`${t.groupKey}:${t.subGroupKey}`:t.groupKey;i?(a.dataset.groupKey=o,a.dataset.parentKey=t.parentKey):a.dataset.groupKey=o,t.isCollapsed&&a.classList.add("is-collapsed");let l=Ie(r,"h3");l.className="task-group-header task-list-view__group-header",a.appendChild(l);let c=Ie(r,"button");c.className="task-group-toggle",c.type="button",c.setAttribute("aria-label","Toggle group"),c.setAttribute("aria-expanded",String(!t.isCollapsed)),c.dataset.groupKey=o,l.appendChild(c),(0,Qn.setIcon)(c,"chevron-right");let d=c.querySelector("svg");d&&(d.classList.add("chevron"),d.setAttribute("width","16"),d.setAttribute("height","16"));let u=l.createSpan({cls:"task-group-title"}),p=i?t.subGroupTitle:t.groupTitle;return this.renderGroupTitle(u,p),l.createSpan({text:` (${t.taskCount})`,cls:"agenda-view__item-count"}),a}async handleTaskUpdate(t){var r;if(this.taskInfoCache.set(t.path,t),this.lastTaskSignatures.set(t.path,this.buildTaskSignature(t)),this.useVirtualScrolling)this.debouncedRefresh();else{let a=this.currentTaskElements.get(t.path);if(a&&a.isConnected){let i=this.getVisibleProperties(),s=pr(t,this.plugin,i,this.getCardOptions(this.currentTargetDate));this.configureCardForManualReordering(s,t,(r=this.taskGroupKeys.get(t.path))!=null?r:null),a.replaceWith(s),s.classList.add("task-card--updated"),(this.containerEl.ownerDocument.defaultView||window).setTimeout(()=>{s.classList.remove("task-card--updated")},1e3),this.currentTaskElements.set(t.path,s)}else this.debouncedRefresh()}}renderEmptyState(){let t=this.containerEl.ownerDocument,r=Ie(t,"div");r.className="tn-bases-empty",r.classList.remove("tn-static-color-var-color-accent-d2cad743","tn-static-color-var-text-accent-65b47ee3","tn-static-color-var-text-muted-5872de20","tn-static-color-var-text-on-accent-f3e1679d","tn-static-color-var-text-warning-783d5f03","tn-static-color-var-tn-text-muted-a90fb6f3","tn-static-color-white-0a43e56a","tn-static-cursor-pointer-2723efcc","tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-2px-0-edce9b14","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-padding-0-16px-16px-16px-f1aa998c","tn-static-padding-0-41d7d7e2","tn-static-padding-12px-43bef435","tn-static-padding-16px-287f770e","tn-static-padding-20px-769fed37","tn-static-padding-20px-ebe8e48c","tn-static-padding-2px-8px-c8eea84a","tn-static-padding-2rem-42aa6d9c","tn-static-text-align-center-91a87015"),r.classList.add("tn-static-padding-20px-7a035d95"),r.textContent="No tasknotes tasks found for this base.",this.itemsContainer.appendChild(r)}renderError(t){let r=this.containerEl.ownerDocument,a=Ie(r,"div");a.className="tn-bases-error",a.classList.remove("tn-static-border-radius-4px-c290c56e","tn-static-border-radius-6px-0dc8408c","tn-static-color-var-color-accent-d2cad743","tn-static-color-var-text-accent-65b47ee3","tn-static-color-var-text-muted-5872de20","tn-static-color-var-text-on-accent-f3e1679d","tn-static-color-var-text-warning-783d5f03","tn-static-color-var-tn-text-muted-a90fb6f3","tn-static-color-white-0a43e56a","tn-static-cursor-pointer-2723efcc","tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-0-11696618","tn-static-margin-0-auto-266e9b04","tn-static-margin-0-db0d5f36","tn-static-margin-0-var-size-4-2-77f7dc08","tn-static-margin-2px-0-edce9b14","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-padding-0-16px-16px-16px-f1aa998c","tn-static-padding-0-41d7d7e2","tn-static-padding-12px-43bef435","tn-static-padding-16px-287f770e","tn-static-padding-20px-769fed37","tn-static-padding-20px-7a035d95","tn-static-padding-2px-8px-c8eea84a","tn-static-padding-2rem-42aa6d9c"),a.classList.add("tn-static-padding-20px-ebe8e48c"),a.textContent=`Error loading tasks: ${t.message||"Unknown error"}`,this.itemsContainer.appendChild(a)}renderGroupTitle(t,r){let a=this.app||this.plugin.app,i={metadataCache:a.metadataCache,workspace:a.workspace};N_(t,r,i)}onunload(){this.unregisterContainerListeners(),this.destroyVirtualScroller(),this.currentTaskElements.clear(),this.itemsContainer=null,this.lastRenderWasGrouped=!1,this.clearClickTimeouts(),this.taskInfoCache.clear(),this.lastTaskSignatures.clear(),this.lastFlatPaths=[],this.useVirtualScrolling=!1,this.collapsedGroups.clear(),this.collapsedSubGroups.clear(),this.clearGroupingSnapshot(),this.initializedPrimaryGroupKeys.clear(),this.initializedSubGroupKeys.clear(),this.taskGroupKeys.clear(),this.sortScopeTaskPaths.clear()}getEphemeralState(){var a,i;let t=super.getEphemeralState();return{...cCe(t)?t:{},scrollTop:((a=this.rootElement)==null?void 0:a.scrollTop)||0,itemsContainerScrollTop:((i=this.itemsContainer)==null?void 0:i.scrollTop)||0,collapsedGroups:Array.from(this.collapsedGroups),collapsedSubGroups:Array.from(this.collapsedSubGroups)}}hasInitializedCollapseState(){return this.initializedPrimaryGroupKeys.size>0||this.initializedSubGroupKeys.size>0}restoreCollapsedStateFromEphemeral(t){let r=!1;if(t.collapsedGroups&&Array.isArray(t.collapsedGroups)){let a=t.collapsedGroups.filter(i=>typeof i=="string");this.collapsedGroups=new Set(a),r=r||a.length>0}if(t.collapsedSubGroups&&Array.isArray(t.collapsedSubGroups)){let a=t.collapsedSubGroups.filter(i=>typeof i=="string");this.collapsedSubGroups=new Set(a),r=r||a.length>0}this.deferCollapseDefaultForNextSnapshot=r}setEphemeralState(t){if(w7e(t)){if(super.setEphemeralState(t),this.hasInitializedCollapseState()||this.restoreCollapsedStateFromEphemeral(t),typeof t.scrollTop=="number"&&this.rootElement){let r=t.scrollTop;window.requestAnimationFrame(()=>{this.rootElement&&this.rootElement.isConnected&&(this.rootElement.scrollTop=r)})}if(typeof t.itemsContainerScrollTop=="number"){let r=t.itemsContainerScrollTop;window.requestAnimationFrame(()=>{var a;this.itemsContainer&&this.itemsContainer.isConnected&&(this.itemsContainer.scrollTop=r,(a=this.virtualScroller)==null||a.recalculate())})}}}clearAllTaskElements(){var t;this.useVirtualScrolling&&(this.destroyVirtualScroller(),this.useVirtualScrolling=!1),(t=this.itemsContainer)==null||t.empty(),this.currentTaskElements.forEach(r=>r.remove()),this.currentTaskElements.clear(),this.lastFlatPaths=[],this.lastTaskSignatures.clear(),this.taskInfoCache.clear(),this.clearClickTimeouts(),this.taskGroupKeys.clear(),this.sortScopeTaskPaths.clear(),this.expandedRelationshipTaskPaths.clear(),this.expandedRelationshipTaskOrder.clear()}getCardOptions(t){return this.buildTaskCardOptions({targetDate:t,expandedRelationshipFilterMode:this.expandedRelationshipFilterMode,resolveExpandedRelationshipFilterMode:()=>{var r;return lCe((r=this.config)==null?void 0:r.get("expandedRelationshipFilterMode"))},expandedRelationshipTaskPaths:this.expandedRelationshipTaskPaths,expandedRelationshipTaskOrder:this.expandedRelationshipTaskOrder})}getTopLevelRenderTasks(t){return this.hideTopLevelSubtasks?this.filterTopLevelSubtasks(t):[...t]}setExpandedRelationshipTaskScope(t){this.expandedRelationshipTaskPaths.clear(),this.expandedRelationshipTaskOrder.clear(),t.forEach((r,a)=>{this.expandedRelationshipTaskPaths.add(r.path),this.expandedRelationshipTaskOrder.set(r.path,a)})}setCurrentVisibleTaskPaths(t){this.currentVisibleTaskPaths.clear(),this.currentVisibleTaskOrder.clear(),t.forEach((r,a)=>{this.currentVisibleTaskPaths.add(r.path),this.currentVisibleTaskOrder.set(r.path,a)})}clearClickTimeouts(){for(let t of this.clickTimeouts.values())t&&window.clearTimeout(t);this.clickTimeouts.clear()}registerContainerListeners(){!this.itemsContainer||this.containerListenersRegistered||(this.registerDomEvent(this.itemsContainer,"click",this.handleItemClick),this.containerListenersRegistered=!0)}unregisterContainerListeners(){this.containerListenersRegistered=!1}getTaskContextFromEvent(t){let r=t.target;if(!r)return null;let a=r.closest(".task-card");if(!a)return null;let i=a.dataset.taskPath;if(!i)return null;let s=this.taskInfoCache.get(i);return s?{task:s,card:a}:null}isSubGroupKey(t){return t.includes(":")}setSetEntry(t,r,a){if(a){t.add(r);return}t.delete(r)}getCurrentSubGroupKeys(){let t=[];for(let r of this.currentSubGroupKeysByParent.values())t.push(...r);return t}async setSubGroupsCollapsed(t,r){for(let a of this.currentSubGroupKeysByParent.get(t)||[])this.setSetEntry(this.collapsedSubGroups,a,r);this.lastRenderWasGrouped&&await this.refreshGroupedView()}async setAllPrimaryGroupsCollapsed(t){for(let r of this.currentPrimaryGroupKeys)this.setSetEntry(this.collapsedGroups,r,t);this.lastRenderWasGrouped&&await this.refreshGroupedView()}async setAllGroupsAndSubGroupsCollapsed(t){for(let r of this.currentPrimaryGroupKeys)this.setSetEntry(this.collapsedGroups,r,t);for(let r of this.getCurrentSubGroupKeys())this.setSetEntry(this.collapsedSubGroups,r,t);this.lastRenderWasGrouped&&await this.refreshGroupedView()}async handleGroupToggle(t){this.isSubGroupKey(t)?this.setSetEntry(this.collapsedSubGroups,t,!this.collapsedSubGroups.has(t)):this.setSetEntry(this.collapsedGroups,t,!this.collapsedGroups.has(t)),this.lastRenderWasGrouped&&await this.refreshGroupedView()}async refreshGroupedView(){var l;if(!((l=this.data)!=null&&l.data))return;let t=this.dataAdapter.extractDataItems();LE(this.data,t);let r=await yu(t,this.plugin),a=this.applySearchFilter(r);this.setExpandedRelationshipTaskScope(a);let i=this.getTopLevelRenderTasks(a);this.setCurrentVisibleTaskPaths(i);let s=this.subGroupPropertyId?zE(t):new Map,o;if(!this.dataAdapter.isGrouped()&&this.subGroupPropertyId){let c=rT(i,this.subGroupPropertyId,s);this.applyGroupingSnapshot(this.createSubPropertyHierarchySnapshot(c)),o=i4(c,this.collapsedGroups)}else{let c=this.dataAdapter.getGroupedData();this.applyGroupingSnapshot(this.createGroupedHierarchySnapshot(c,i)),o=a4({groups:c,taskNotes:i,subGroupPropertyId:this.subGroupPropertyId,pathToProps:s,collapsedGroups:this.collapsedGroups,collapsedSubGroups:this.collapsedSubGroups,convertGroupKeyToString:d=>this.dataAdapter.convertGroupKeyToString(d)})}this.useVirtualScrolling&&this.virtualScroller?(this.syncGroupedDragMetadata(o),this.virtualScroller.updateItems(o)):await this.render()}async handleActionClick(t,r,a,i){switch(t){case"toggle-status":await this.handleToggleStatus(r,i);return;case"priority-menu":this.showPriorityMenu(r,i);return;case"recurrence-menu":this.showRecurrenceMenu(r,i);return;case"reminder-menu":this.showReminderModal(r);return;case"task-context-menu":await uo(i,r.path,this.plugin,this.getTaskActionDate(r));return;case"edit-date":await this.openDateContextMenu(r,a.dataset.tnDateType,i);return;case"toggle-subtasks":await this.toggleSubtasks(r,a);return;case"toggle-blocking-tasks":await this.toggleBlockingTasks(r,a);return;default:await this.handleCardClick(r,i)}}async handleToggleStatus(t,r){try{if(t.recurrence){let a=this.getTaskActionDate(t);await this.plugin.toggleRecurringTaskComplete(t,a)}else await this.plugin.toggleTaskStatus(t)}catch(a){let i=a instanceof Error?a.message:String(a);Fs.error("[TaskNotes][TaskListView] Failed to toggle status",{category:"persistence",operation:"toggle-status",details:{taskPath:t.path},error:i}),new Qn.Notice(`Failed to toggle task status: ${i}`)}}getTaskActionDate(t){let r=re(t.scheduled||t.due||"");return r?st(r):this.currentTargetDate}showPriorityMenu(t,r){new Ud({currentValue:t.priority,onSelect:i=>{(async()=>{try{await this.plugin.updateTaskProperty(t,"priority",i)}catch(s){Fs.error("[TaskNotes][TaskListView] Failed to update priority",{category:"validation",operation:"update-priority",error:s}),new Qn.Notice("Failed to update priority")}})()},plugin:this.plugin}).show(r)}showRecurrenceMenu(t,r){new il({currentValue:typeof t.recurrence=="string"?t.recurrence:void 0,currentAnchor:t.recurrence_anchor||"scheduled",scheduledDate:t.scheduled,onSelect:(i,s)=>{(async()=>{try{await this.plugin.updateTaskProperty(t,"recurrence",i||void 0),s!==void 0&&await this.plugin.updateTaskProperty(t,"recurrence_anchor",s)}catch(o){Fs.error("[TaskNotes][TaskListView] Failed to update recurrence",{category:"validation",operation:"update-recurrence",error:o}),new Qn.Notice("Failed to update recurrence")}})()},app:this.plugin.app,plugin:this.plugin}).show(r)}showReminderModal(t){new sl(this.plugin.app,this.plugin,t,a=>{(async()=>{try{await this.plugin.updateTaskProperty(t,"reminders",a.length>0?a:void 0)}catch(i){Fs.error("[TaskNotes][TaskListView] Failed to update reminders",{category:"validation",operation:"update-reminders",error:i}),new Qn.Notice("Failed to update reminders")}})()}).open()}async openDateContextMenu(t,r,a){if(!r)return;let i=r==="due"?t.due:t.scheduled;new rl({currentValue:re(i||""),currentTime:si(i||""),onSelect:(o,l)=>{(async()=>{try{let c;o?l?c=`${o}T${l}`:c=o:c=void 0,await this.plugin.updateTaskProperty(t,r,c)}catch(c){let d=c instanceof Error?c.message:String(c);Fs.error("[TaskNotes][TaskListView] Failed to update date",{category:"validation",operation:"update-date",details:{taskPath:t.path,dateType:r},error:d}),new Qn.Notice(`Failed to update ${r} date: ${d}`)}})()},dateRole:r,plugin:this.plugin,app:this.app||this.plugin.app}).show(a)}async handleCardClick(t,r){if(this.handleSelectionClick(r,t.path))return;if(this.plugin.settings.doubleClickAction==="none"){await this.executeSingleClickAction(t,r);return}let a=this.clickTimeouts.get(t.path);if(a)window.clearTimeout(a),this.clickTimeouts.delete(t.path),await this.executeDoubleClickAction(t,r);else{let s=(this.containerEl.ownerDocument.defaultView||window).setTimeout(()=>{(async()=>(this.clickTimeouts.delete(t.path),await this.executeSingleClickAction(t,r)))()},250);this.clickTimeouts.set(t.path,s)}}async executeSingleClickAction(t,r){if(r.ctrlKey||r.metaKey){this.openTaskNote(t,!0);return}switch(this.plugin.settings.singleClickAction){case"edit":await this.editTask(t);break;case"openNote":this.openTaskNote(t,!1);break;default:break}}async executeDoubleClickAction(t,r){switch(this.plugin.settings.doubleClickAction){case"edit":await this.editTask(t);break;case"openNote":this.openTaskNote(t,!1);break;default:break}}async editTask(t){await this.plugin.openTaskEditModal(t)}openTaskNote(t,r){let a=this.app||this.plugin.app,i=a.vault.getAbstractFileByPath(t.path);i instanceof Qn.TFile&&(r?a.workspace.openLinkText(t.path,"",!0):a.workspace.getLeaf(!1).openFile(i))}async toggleSubtasks(t,r){var a;try{if(!this.plugin.expandedProjectsService){Fs.error("[TaskNotes][TaskListView] ExpandedProjectsService not initialized",{category:"stale-data",operation:"expandedprojectsservice-not-initialized"}),new Qn.Notice("Service not available. Please try reloading the plugin.");return}let i=this.plugin.expandedProjectsService.toggle(t.path,((a=this.plugin.settings)==null?void 0:a.expandSubtasksByDefault)===!0);r.classList.toggle("task-card__chevron--expanded",i),r.setAttribute("aria-label",i?"Collapse subtasks":"Expand subtasks");let s=r.closest(".task-card");if(s){let{toggleSubtasks:o}=await Promise.resolve().then(()=>(Ua(),fv));await o(s,t,this.plugin,i)}}catch(i){Fs.error("[TaskNotes][TaskListView] Failed to toggle subtasks",{category:"persistence",operation:"toggle-subtasks",error:i}),new Qn.Notice("Failed to toggle subtasks")}}async toggleBlockingTasks(t,r){try{let a=r.classList.toggle("task-card__blocking-toggle--expanded"),i=r.closest(".task-card");if(i){let{toggleBlockingTasks:s}=await Promise.resolve().then(()=>(Ua(),fv));await s(i,t,this.plugin,a)}}catch(a){Fs.error("[TaskNotes][TaskListView] Failed to toggle blocking tasks",{category:"persistence",operation:"toggle-blocking-tasks",error:a}),new Qn.Notice("Failed to toggle blocking tasks")}}arePathArraysEqual(t,r){if(t.length!==r.length)return!1;for(let a=0;adC(t,a,this.plugin))})}buildCardRenderSignature(t,r){var i,s,o;let a=r.propertyLabels?Object.entries(r.propertyLabels).sort(([l],[c])=>l.localeCompare(c)):[];return JSON.stringify({visibleProperties:t!=null?t:null,propertyLabels:a,expandedRelationshipFilterMode:(i=r.expandedRelationshipFilterMode)!=null?i:null,targetDate:(o=(s=r.targetDate)==null?void 0:s.toISOString().slice(0,10))!=null?o:null})}}});async function l4({action:n,task:e,target:t,event:r,plugin:a,app:i}){let[{DateContextMenu:s},{PriorityContextMenu:o},{RecurrenceContextMenu:l},{ReminderModal:c},{showTaskContextMenu:d,toggleBlockingTasks:u,toggleSubtasks:p}]=await Promise.all([Promise.resolve().then(()=>(Uy(),rle)),Promise.resolve().then(()=>(fC(),Rle)),Promise.resolve().then(()=>(Qy(),jle)),Promise.resolve().then(()=>(Jy(),$le)),Promise.resolve().then(()=>(Ua(),fv))]);switch(n){case"toggle-status":await S7e(e,r,a);return;case"priority-menu":C7e(e,r,a,o);return;case"recurrence-menu":x7e(e,r,a,l);return;case"reminder-menu":E7e(e,a,c);return;case"task-context-menu":await d(r,e.path,a,VE(e));return;case"edit-date":await D7e(e,t.dataset.tnDateType,r,a,i,s);return;case"toggle-subtasks":await P7e(e,t,a,p);return;case"toggle-blocking-tasks":await A7e(e,t,a,u);return}}async function S7e(n,e,t){try{n.recurrence?await t.toggleRecurringTaskComplete(n,VE(n)):await t.toggleTaskStatus(n)}catch(r){HE.error("[TaskNotes][KanbanView] Failed to toggle status",{category:"internal",operation:"toggle-status",error:r})}}function VE(n){let e=re(n.scheduled||n.due||"");return e?st(e):Br(new Date)}function C7e(n,e,t,r){new r({currentValue:n.priority,onSelect:i=>{(async()=>{try{await t.updateTaskProperty(n,"priority",i)}catch(s){HE.error("[TaskNotes][KanbanView] Failed to update priority",{category:"validation",operation:"update-priority",error:s})}})()},plugin:t}).show(e)}function x7e(n,e,t,r){new r({currentValue:typeof n.recurrence=="string"?n.recurrence:void 0,currentAnchor:n.recurrence_anchor||"scheduled",scheduledDate:n.scheduled,onSelect:(i,s)=>{(async()=>{try{await t.updateTaskProperty(n,"recurrence",i||void 0),s!==void 0&&await t.updateTaskProperty(n,"recurrence_anchor",s)}catch(o){HE.error("[TaskNotes][KanbanView] Failed to update recurrence",{category:"validation",operation:"update-recurrence",error:o})}})()},app:t.app,plugin:t}).show(e)}function E7e(n,e,t){new t(e.app,e,n,a=>{(async()=>{try{await e.updateTaskProperty(n,"reminders",a.length>0?a:void 0)}catch(i){HE.error("[TaskNotes][KanbanView] Failed to update reminders",{category:"validation",operation:"update-reminders",error:i})}})()}).open()}async function D7e(n,e,t,r,a,i){if(!e)return;let{getDatePart:s,getTimePart:o}=await Promise.resolve().then(()=>(xe(),Gz)),l=e==="due"?n.due:n.scheduled;new i({currentValue:s(l||""),currentTime:o(l||""),onSelect:(d,u)=>{(async()=>{try{let p;d?u?p=`${d}T${u}`:p=d:p=void 0,await r.updateTaskProperty(n,e,p)}catch(p){HE.error("[TaskNotes][KanbanView] Failed to update date",{category:"validation",operation:"update-date",error:p})}})()},dateRole:e,plugin:r,app:a}).show(t)}async function P7e(n,e,t,r){var o,l;let a=e.closest(".task-card");if(!a)return;let s=!(((o=t.expandedProjectsService)==null?void 0:o.isExpanded(n.path))||!1);(l=t.expandedProjectsService)==null||l.setExpanded(n.path,s),e.classList.toggle("is-rotated",s),await r(a,n,t,s)}async function A7e(n,e,t,r){let a=e.closest(".task-card");if(!a)return;let i=e.classList.toggle("task-card__blocking-toggle--expanded");await r(a,n,t,i)}var HE,pCe=y(()=>{xe();q();HE=M({tag:"Bases/KanbanCardActions"})});function mCe(n,e,t){return Math.min(Math.max(n,e),t)}function M7e(n,e,t){let r=Math.max(0,n.width),a=Math.max(0,n.height);return{x:mCe(e-n.left,0,r),y:mCe(t-n.top,0,a)}}function fCe(n,e,t){let r=n.dataTransfer;if(!r||typeof r.setDragImage!="function")return null;let a=e.ownerDocument,i=a.body;if(!i)return null;let s=e.getBoundingClientRect(),o=e.cloneNode(!0);o.classList.add("tasknotes-plugin"),t&&o.classList.add(t),o.setAttribute("aria-hidden","true"),o.style.width=`${Math.max(0,s.width)}px`,o.style.height=`${Math.max(0,s.height)}px`,i.appendChild(o);let l=M7e(s,n.clientX,n.clientY);r.setDragImage(o,l.x,l.y);let c=a.defaultView;return(c!=null?c:window).setTimeout(()=>{o.remove()},0),o}var hCe=y(()=>{});function I7e(n){let e=n;return!e||typeof e.nodeType!="number"?null:e.nodeType===Node.ELEMENT_NODE?e:e.parentElement}function c4(n,e){let t=I7e(n);if(!t||!e.contains(t))return null;let r=t.closest(".task-card__subtasks .task-card[data-task-path]");if(!r||!e.contains(r))return null;let a=r.dataset.taskPath;return a?{taskPath:a,sourceElement:r}:null}function iF(n,e){return n?{taskPath:n,above:e}:void 0}function WE(n,e){return n.length>0?[...n]:[e]}function d4({dropTarget:n,isCrossScope:e,targetInDropScope:t,fallbackDropTarget:r}){if(!(n&&e&&!t))return!n&&!e?r:n}function yCe(n,e,t){let r=n.getBoundingClientRect();return{taskPath:e,above:t{let o=s.dataset.taskPath;return!!o&&!e.includes(o)});if(a.length===0)return;if(r!==void 0&&Number.isFinite(r)){let s=a.findIndex(o=>{let l=o.getBoundingClientRect();return r=0?Math.min(t,a.length):a.length;return i===0?{taskPath:a[0].dataset.taskPath,above:!0}:{taskPath:a[i-1].dataset.taskPath,above:!1}}function vCe(n,e,t){n.classList.remove("kanban-view__cards--drop-marker-end");for(let a of e)a.classList.remove("kanban-view__card-wrapper--drop-marker");let r=e[t];if(r){r.classList.add("kanban-view__card-wrapper--drop-marker");return}e.length>0&&t>=e.length&&n.classList.add("kanban-view__cards--drop-marker-end")}function p4(n){n.nodeType===Node.ELEMENT_NODE&&n.classList.remove("kanban-view__card-wrapper--drop-marker","kanban-view__cards--drop-marker-end"),n.querySelectorAll(".kanban-view__card-wrapper--drop-marker").forEach(e=>{e.classList.remove("kanban-view__card-wrapper--drop-marker")}),n.querySelectorAll(".kanban-view__cards--drop-marker-end").forEach(e=>{e.classList.remove("kanban-view__cards--drop-marker-end")})}function kCe({draggedPaths:n,dropTarget:e,targetContainer:t,currentTaskElements:r,removeEmptyCellHint:a,log:i}){var d,u;if(n.length===0)return i==null||i("OPTIMISTIC-REORDER: bail — no dragged paths"),!1;let s=()=>{let p=[];for(let m of n){let f=r.get(m);if(!f)return i==null||i("OPTIMISTIC-REORDER: bail — element not in currentTaskElements",{path:m.split("/").pop()}),null;p.push(f)}return p};if(!e){if(!t)return i==null||i("OPTIMISTIC-REORDER: bail — no dropTarget AND no targetContainer"),!1;let p=s();if(!p)return!1;a==null||a(t),i==null||i("OPTIMISTIC-REORDER: cross-column append path",{paths:n.map(m=>m.split("/").pop()),containerChildCount:t.childElementCount,containerClass:t.className});for(let m of p){let f=m.parentElement;i==null||i("OPTIMISTIC-REORDER: moving element",{path:(d=m.dataset.taskPath)==null?void 0:d.split("/").pop(),oldParentClass:f==null?void 0:f.className,oldParentChildCount:f==null?void 0:f.childElementCount,sameContainer:f===t,elCurrentStyles:m.style.cssText.slice(0,120)}),vm(m),m.classList.remove("kanban-view__card--dragging"),t.appendChild(m)}return i==null||i("OPTIMISTIC-REORDER: cross-column append SUCCESS",{containerChildCount:t.childElementCount}),!0}i==null||i("OPTIMISTIC-REORDER: drop-on-card path",{paths:n.map(p=>p.split("/").pop()),targetCard:e.taskPath.split("/").pop(),above:e.above,hasContainer:!!t});let o=r.get(e.taskPath);if(!o)return i==null||i("OPTIMISTIC-REORDER: bail — target element not in currentTaskElements",{target:e.taskPath.split("/").pop()}),!1;let l=t||o.parentElement;if(!l)return i==null||i("OPTIMISTIC-REORDER: bail — no container resolved"),!1;if(!l.contains(o))return i==null||i("OPTIMISTIC-REORDER: bail — targetEl not in container",{containerClass:l.className,targetElParentClass:(u=o.parentElement)==null?void 0:u.className}),!1;let c=s();if(!c)return!1;a==null||a(l);for(let p of c)vm(p),p.classList.remove("kanban-view__card--dragging"),e.above?l.insertBefore(p,o):l.insertBefore(p,o.nextSibling);return i==null||i("OPTIMISTIC-REORDER: drop-on-card SUCCESS"),!0}function gCe(n){return n.replace(/^(note\.|file\.|task\.)/,"")}function TCe({path:n,sourceColumn:e,sourceSwimlane:t,newGroupValue:r,newSwimLaneValue:a,groupByPropertyId:i,swimLanePropertyId:s,groupByTaskProp:o,swimlaneTaskProp:l,isGroupByListProperty:c,isSwimlaneListProperty:d}){let u=e!==r,p=a!==null&&!!s&&t!==a,m=u?o:p?l:null,f=u?e:t,h=u?r:a;return{path:n,sourceColumn:e,sourceSwimlane:t,needsGroupUpdate:u,needsSwimlaneUpdate:p,groupByFrontmatterKey:gCe(i),swimlaneFrontmatterKey:s?gCe(s):void 0,groupByTaskProp:o,swimlaneTaskProp:l,changedTaskProp:m,oldPropValue:f,newPropValue:h,newGroupValue:r,newSwimLaneValue:a,isGroupByListProperty:c,isSwimlaneListProperty:d}}function bCe(n,e){return n.needsGroupUpdate||n.needsSwimlaneUpdate||e}function N7e(n){return Array.isArray(n)?n:n?[n]:[]}function aF(n,e,t){let r=N7e(n).filter(a=>a!==e);return!r.includes(t)&&t!=="None"&&r.push(t),r.length>0?r:[]}function wCe(n,e,t){e.needsGroupUpdate&&(e.isGroupByListProperty&&e.sourceColumn?n[e.groupByFrontmatterKey]=aF(n[e.groupByFrontmatterKey],e.sourceColumn,e.newGroupValue):n[e.groupByFrontmatterKey]=t.coerceGroupValue(e.groupByFrontmatterKey,e.newGroupValue)),e.needsSwimlaneUpdate&&e.swimlaneFrontmatterKey&&e.newSwimLaneValue!==null&&(e.isSwimlaneListProperty&&e.sourceSwimlane?n[e.swimlaneFrontmatterKey]=aF(n[e.swimlaneFrontmatterKey],e.sourceSwimlane,e.newSwimLaneValue):n[e.swimlaneFrontmatterKey]=t.coerceGroupValue(e.swimlaneFrontmatterKey,e.newSwimLaneValue))}function SCe({plan:n,task:e,dateModifiedField:t,dateModifiedValue:r}){let a=n.needsGroupUpdate&&n.groupByTaskProp==="status"?n.newGroupValue:n.needsSwimlaneUpdate&&n.swimlaneTaskProp==="status"&&n.newSwimLaneValue!==null?n.newSwimLaneValue:null;return a===null?null:{statusValue:a,isRecurring:!!(e!=null&&e.recurrence),dateModifiedField:t,dateModifiedValue:r}}function CCe({plan:n,originalTask:e,dateModifiedValue:t,isCompletedStatus:r}){if(!n.changedTaskProp||!e)return null;let a=n.changedTaskProp,i=R7e(n,e,a),s={...e,[a]:i,dateModified:t};return a==="status"&&!e.recurrence&&(s.completedDate=typeof i=="string"&&r(i)?new Date().toISOString().split("T")[0]:void 0),{changedTaskProp:a,oldPropValue:n.oldPropValue,newPropValue:i,updatedTask:s}}function R7e(n,e,t){let r=e[t];return n.needsGroupUpdate&&n.isGroupByListProperty?aF(r,n.sourceColumn,n.newGroupValue):n.needsSwimlaneUpdate&&n.isSwimlaneListProperty&&n.newSwimLaneValue!==null?aF(r,n.sourceSwimlane,n.newSwimLaneValue):n.newPropValue}var xCe=y(()=>{X_()});function ECe(n){let{frontmatter:e,propertyId:t,groupKey:r}=n;if(!t||!r||r==="None")return;let a=F7e({propertyId:t,propertyMapper:n.propertyMapper,fieldMapper:n.fieldMapper,userFields:n.userFields});if(a){if(L7e({property:a,fieldMapper:n.fieldMapper,userFields:n.userFields,isListTypeProperty:n.isListTypeProperty})){z7e(e,a,r);return}e[a]=n.coerceGroupKeyForFrontmatter(a,r)}}function F7e(n){var r;if(n.propertyId.startsWith("file.")||n.propertyId.startsWith("formula."))return null;let e=n.propertyMapper.basesToUserProperty(n.propertyId);return new Set([..._7e.map(a=>n.fieldMapper.toUserField(a)),"tags"]).has(e)||(r=n.userFields)!=null&&r.some(a=>a.key===e)?e:null}function L7e(n){var t;if(O7e(n.fieldMapper).has(n.property))return!0;let e=(t=n.userFields)==null?void 0:t.find(r=>r.key===n.property);return(e==null?void 0:e.type)==="list"||n.isListTypeProperty(n.property)}function O7e(n){return new Set(["tags",n.toUserField("contexts"),n.toUserField("projects"),n.toUserField("blockedBy")])}function z7e(n,e,t){let r=n[e],a=Array.isArray(r)?r.filter(i=>typeof i=="string"):typeof r=="string"?[r]:[];a.includes(t)||(n[e]=[...a,t])}var _7e,DCe=y(()=>{_7e=["status","priority","due","scheduled","contexts","projects","timeEstimate","recurrence","blockedBy"]});function RCe(n){return typeof n=="object"&&n!==null}function sF(n){let e=new Set,t=[];for(let r of n){let a=Y(r).trim();!a||e.has(a)||(e.add(a),t.push(a))}return t}function m4(n){if(n==null)return{};let e=n;if(typeof n=="string"){let r=n.trim();if(!r)return{};try{e=JSON.parse(r)}catch(a){return{}}}if(!RCe(e))return{};let t={};for(let[r,a]of Object.entries(e)){if(!Array.isArray(a))continue;let i=sF(a);i.length>0&&(t[r]=i)}return t}function _Ce(n){let e=typeof n=="number"?n:typeof n=="string"&&n.trim()?Number(n):Number.NaN;return!Number.isFinite(e)||e<=0?null:Math.floor(e)}function f4(n){if(n==null)return{};let e=n;if(typeof n=="string"){let r=n.trim();if(!r)return{};try{e=JSON.parse(r)}catch(a){return{}}}if(!RCe(e))return{};let t={};for(let[r,a]of Object.entries(e)){let i=Y(r).trim(),s=_Ce(a);i&&s!==null&&(t[i]=s)}return t}function oF(n,e){let t=_Ce(e);return t===null?{text:` (${n})`,isExceeded:!1}:{text:` (${n}/${t})`,isExceeded:n>t}}function h4(n){if(n==null)return[];if(Array.isArray(n))return sF(n);if(typeof n!="string")return[];let e=n.trim();if(!e)return[];if(e.startsWith("["))try{let t=JSON.parse(e);if(Array.isArray(t))return sF(t)}catch(t){}return sF(e.split(","))}function FCe(n,e){for(let t of e)n.has(t)||n.set(t,[])}function LCe(n,e){let t=new Set(e),r=new Set(n),a=e.filter(s=>r.has(s)),i=n.filter(s=>!t.has(s)).sort();return[...a,...i]}function g4(n,e,t,r){return!n||t.length>0||r.includes(e)}function B7e(n,e){var r;if(e.startsWith("formula."))return(r=n[e])!=null?r:null;let t=Ya(e);return n[e]!==void 0?n[e]:n[t]!==void 0?n[t]:null}function OCe(n,e,t){return t(n)?!0:new Set(["contexts",e.contextsField,"projects",e.projectsField,"tags","aliases"]).has(n)}function zCe(n,e,t,r){return e==="contexts"||e===r.contextsField?n.contexts:e==="projects"||e===r.projectsField?n.projects:e==="tags"?n.tags:(t.get(n.path)||{})[e]}function lF(n,e){return n?Ya(n)===e:!1}function y4(n,e){return n?Ya(n)===e:!1}function BCe(n,e=()=>null){let t=new Set;for(let r of[n.value,n.label]){let a=r.trim();if(!a)continue;t.add(a);let i=e(a);i&&t.add(i)}return t}function v4(n,e,t,r){let a=n.trim();if(!a||a==="None")return;let i=e.find(d=>d.value===a);if(i)return i;let s=t(a),o=e.find(d=>d.value===s);if(o)return o;let l=e.filter(d=>d.label===a);if(l.length===1)return l[0];let c=e.filter(d=>r(d).has(a));return c.length===1?c[0]:void 0}function jCe(n){var e,t;return n.groupKey.trim()==="None"?n.groupKey:lF(n.propertyId,n.fields.statusField)?(t=(e=v4(n.groupKey,n.statuses,n.normalizeStatusValue,n.getStatusGroupKeyAliases))==null?void 0:e.value)!=null?t:n.groupKey:y4(n.propertyId,n.fields.priorityField)?n.normalizePriorityValue(n.groupKey):n.groupKey}function j7e(n,e,t){let r=t(e);for(let a of n.keys())if(r.has(a.trim()))return!0;return!1}function $7e(n,e,t,r,a){if(r(e))for(let i of t)j7e(n,i,a)||n.set(i.value,[])}function U7e(n,e,t,r){if(r(e))for(let a of t)n.has(a.value)||n.set(a.value,[])}function qE(n){var e,t;if(n==null)return"None";if(typeof n=="object"&&n!==null&&typeof n.toString=="function"){let r=n;if(((e=r.constructor)==null?void 0:e.name)==="NullValue"||r.isTruthy&&!r.isTruthy())return"None";if(((t=r.constructor)==null?void 0:t.name)==="ListValue"||Array.isArray(r.value)){let i=r.value||[];return i.length===0?"None":i.map(s=>qE(s)).join(", ")}return r.toString()||"None"}return typeof n=="string"?n||"None":typeof n=="number"?String(n):typeof n=="boolean"?n?"True":"False":Array.isArray(n)?n.length>0?n.map(r=>qE(r)).join(", "):"None":Y(n)||"None"}function $Ce(n){let e;Array.isArray(n)?e=n:n==null?e=[]:typeof n=="object"&&n!==null&&Array.isArray(n.value)?e=n.value||[]:e=[n];let t=e.map(r=>qE(r)).filter(r=>r!=="None");return t.length>0?Array.from(new Set(t)):["None"]}function H7e(n,e){for(let t of n.values())t.sort((r,a)=>{var i,s;return((i=e.get(r.path))!=null?i:Number.MAX_SAFE_INTEGER)-((s=e.get(a.path))!=null?s:Number.MAX_SAFE_INTEGER)})}function V7e(n,e){if(e)for(let t of n.values())t.sort((r,a)=>{let i=e.get(r.path),s=e.get(a.path);return i!=null&&s!=null?Y(i).localeCompare(Y(s)):i!=null?-1:s!=null?1:0})}function PCe(n,e,t){var r;n.has(e)||n.set(e,[]),(r=n.get(e))==null||r.push(t)}function UCe(n){if(!n.swimLanePropertyId)return["None"];let e=Ya(n.swimLanePropertyId);if(n.explodeListColumns&&n.isListTypeProperty(e)){let a=n.getListPropertyValue(n.task,e);return $Ce(a)}let t=n.pathToProps.get(n.task.path)||{},r=qE(B7e(t,n.swimLanePropertyId));return[n.canonicalizeGroupKey(r,n.swimLanePropertyId)]}function HCe(n){let e=new Map,t=new Map(n.taskNotes.map((o,l)=>[o.path,l])),r=Ya(n.groupByPropertyId),a=n.isStatusGroupingProperty(n.groupByPropertyId),i=n.isPriorityGroupingProperty(n.groupByPropertyId);if(n.explodeListColumns&&n.isListTypeProperty(r))for(let o of n.taskNotes){let l=n.getListPropertyValue(o,r),c=$Ce(l);for(let d of c)PCe(e,d,o)}else if(a||i)for(let o of n.taskNotes){let l=a?o.status:o.priority,c=qE(l),d=n.canonicalizeGroupKey(c,n.groupByPropertyId);PCe(e,d,o)}else{let o=new Map(n.taskNotes.map(l=>[l.path,l]));for(let l of n.groupedData){let c=n.convertGroupKeyToString(l.key),d=n.canonicalizeGroupKey(c,n.groupByPropertyId),u=e.get(d)||[];for(let p of l.entries){let m=o.get(p.file.path);m&&u.push(m)}e.has(d)||e.set(d,u)}}return H7e(e,t),V7e(e,n.sortOrderValues),$7e(e,n.groupByPropertyId,n.statusConfigs,n.isStatusGroupingProperty,n.getStatusGroupKeyAliases),U7e(e,n.groupByPropertyId,n.priorityConfigs,n.isPriorityGroupingProperty),FCe(e,n.pinnedColumns),e}function k4(n,e,t){var i;let r=new Set;for(let s of n)for(let o of t(s))r.add(o);let a=new Map;for(let s of r){let o=new Map;a.set(s,o);for(let[l]of e)o.set(l,[])}for(let[s,o]of e)for(let l of o)for(let c of t(l)){let d=a.get(c);d&&d.has(s)&&((i=d.get(s))==null||i.push(l))}return a}function T4(n,e){var r,a,i;let t=new Map(e.map(s=>[s,0]));for(let s of n.values())for(let o of e)t.set(o,((r=t.get(o))!=null?r:0)+((i=(a=s.get(o))==null?void 0:a.length)!=null?i:0));return t}function VCe(n,e,t,r){if(!t)return[...n];let a=T4(e,n);return n.filter(i=>{var s;return((s=a.get(i))!=null?s:0)>0||r.includes(i)})}function ACe(n,e){return n==="None"&&e!=="None"?1:e==="None"&&n!=="None"?-1:n.localeCompare(e)}function WCe(n,e){var t;if(e)return(t=n[e])!=null?t:n[Ya(e)]}function MCe(n,e){let t=new Set(n),r=new Set(e),a=e.filter(s=>t.has(s)),i=n.filter(s=>!r.has(s));return[...a,...i]}function ICe(n){let e=[...n.actualKeys];return n.isPriorityField(n.groupBy)?MCe(e.sort((t,r)=>n.getPriorityWeight(r)-n.getPriorityWeight(t)||ACe(t,r)),n.pinnedColumns):n.isStatusField(n.groupBy)?MCe(e.sort((t,r)=>{let a=n.findStatusConfig(t),i=n.findStatusConfig(r);return a&&i?a.order-i.order||t.localeCompare(r):a?-1:i?1:ACe(t,r)}),n.pinnedColumns):LCe([...n.actualKeys],n.pinnedColumns)}function qCe(n){let e=WCe(n.columnOrders,n.groupBy);if(!e||e.length===0)return ICe(n);let t=[],r=[],a=new Set(n.actualKeys);for(let i of e)(!n.hideEmptyColumns||a.has(i))&&t.push(i);for(let i of n.actualKeys)e.includes(i)||r.push(i);return[...t,...ICe({...n,actualKeys:r})]}function NCe(n){let e=[...n.actualKeys];return n.isPriorityField(n.swimLanePropertyId)?e.sort((t,r)=>n.getPriorityWeight(r)-n.getPriorityWeight(t)||t.localeCompare(r)):n.isStatusField(n.swimLanePropertyId)?e.sort((t,r)=>n.getStatusOrder(t)-n.getStatusOrder(r)||t.localeCompare(r)):e}function b4(n){let e=WCe(n.swimLaneOrders,n.swimLanePropertyId);if(!e||e.length===0)return NCe(n);let t=new Set(n.actualKeys),r=e.filter(i=>t.has(i)||!n.hideEmptySwimLanes),a=NCe({...n,actualKeys:n.actualKeys.filter(i=>!e.includes(i))});return[...r,...a]}function W7e(n){return new Map(n.map(e=>[e,[]]))}function q7e(n){return Array.from(n.values()).reduce((e,t)=>e+t.length,0)}function GCe(n){var a;let e=Array.from(n.swimLanes.keys());if(!n.hideEmptySwimLanes&&n.isPriorityField(n.swimLanePropertyId))for(let i of n.priorityKeys)n.swimLanes.has(i)||e.push(i);let t=b4({swimLanePropertyId:n.swimLanePropertyId,actualKeys:e,swimLaneOrders:n.swimLaneOrders,hideEmptySwimLanes:n.hideEmptySwimLanes,isPriorityField:n.isPriorityField,isStatusField:n.isStatusField,getPriorityWeight:n.getPriorityWeight,getStatusOrder:n.getStatusOrder}),r=new Map;for(let i of t){let s=(a=n.swimLanes.get(i))!=null?a:W7e(n.columnKeys);n.hideEmptySwimLanes&&q7e(s)===0||r.set(i,s instanceof Map?s:new Map(Array.from(s.entries()).map(([o,l])=>[o,[...l]])))}return r}var w4=y(()=>{dr();FE()});function C4(n){return typeof n=="object"&&n!==null}function G7e(n){return C4(n)}function cF(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Y7e(n){if(!C4(n.columnScroll))return null;let e={};for(let[t,r]of Object.entries(n.columnScroll))typeof r=="number"&&(e[t]=r);return e}function YCe(n){if(typeof n=="number")return n===1?"show-all":"inherit";let e=Y(n).trim().toLowerCase().replace(/^['"]|['"]$/g,"").replace(/[_\s]+/g,"-");return e==="show-all"||e==="1"?"show-all":"inherit"}function KCe(n,e=navigator,t=window){var r,a,i,s;return n||typeof(e==null?void 0:e.maxTouchPoints)=="number"&&e.maxTouchPoints>0?!0:!!((a=(r=t==null?void 0:t.matchMedia)==null?void 0:r.call(t,"(any-pointer: coarse)"))!=null&&a.matches||(s=(i=t==null?void 0:t.matchMedia)==null?void 0:i.call(t,"(pointer: coarse)"))!=null&&s.matches)}function K7e(n){return n==="compact"?"compact":"default"}function ZCe(n){return function(e,t){if(!t)throw ag.error("[TaskNotes][KanbanView] No containerEl provided",{category:"stale-data",operation:"no-containerel-provided"}),new Error("KanbanView requires a containerEl");return new S4(e,t,n)}}var En,ag,nT,S4,QCe=y(()=>{En=require("obsidian");IE();ME();Ua();Oq();Fi();zq();xe();Cn();dr();FE();s4();pCe();X_();hCe();Li();xCe();OE();DCe();r4();w4();q();ya();w4();ag=M({tag:"Bases/KanbanView"});nT=class nT extends Bc{constructor(t,r,a){super(t,r,a);this.type="tasknotesKanban";this.boardEl=null;this.currentTaskElements=new Map;this.draggedTaskPath=null;this.draggedTaskPaths=[];this.draggedFromColumn=null;this.draggedFromSwimlane=null;this.dropTargetPath=null;this.pendingRender=!1;this.dropAbove=!0;this.dragOverRafId=0;this.dragContainer=null;this.currentInsertionIndex=-1;this.dragSourceColumnEl=null;this.dragTargetColumnEl=null;this.activeDragSourceElement=null;this.floatingDragPreviewEl=null;this.floatingDragPreviewDocument=null;this.floatingDragPreviewMoveHandler=null;this.floatingDragPreviewRafId=null;this.floatingDragPreviewWidth=280;this.floatingDragPreviewHeight=40;this.floatingDragPreviewPendingX=0;this.floatingDragPreviewPendingY=0;this.draggedSourceColumns=new Map;this.draggedSourceSwimlanes=new Map;this.taskInfoCache=new Map;this.sortScopeTaskPaths=new Map;this.sortScopeCandidateTaskPaths=new Map;this.containerListenersRegistered=!1;this.columnScrollers=new Map;this.expandedRelationshipFilterMode="inherit";this.currentVisibleTaskPaths=new Set;this.currentVisibleTaskOrder=new Map;this.expandedRelationshipTaskPaths=new Set;this.expandedRelationshipTaskOrder=new Map;this.hideTopLevelSubtasks=!1;this.suppressRenderUntil=0;this.postDropTimer=null;this.dropQueue=new tT;this.activeDropCount=0;this.postDropRefreshRequested=!1;this.touchDragActive=!1;this.touchDragGhost=null;this.touchStartX=0;this.touchStartY=0;this.longPressTimer=null;this.autoScrollTimer=null;this.autoScrollDirection=0;this.LONG_PRESS_DELAY=350;this.TOUCH_MOVE_THRESHOLD=10;this.AUTO_SCROLL_EDGE=60;this.AUTO_SCROLL_SPEED=8;this.touchDragType=null;this.draggedColumnKey=null;this.boundContextMenuBlocker=t=>{t.preventDefault(),t.stopPropagation()};this.LARGE_REORDER_WARNING_THRESHOLD=10;this.swimLanePropertyId=null;this.columnWidth=280;this.maxSwimlaneHeight=600;this.hideEmptyColumns=!1;this.explodeListColumns=!0;this.consolidateStatusIcon=!1;this.columnOrders={};this.pinnedColumns=[];this.wipLimits={};this.swimLaneOrders={};this.hideEmptySwimLanes=!1;this.cardLayout="default";this.configLoaded=!1;this.VIRTUAL_SCROLL_THRESHOLD=15;this.handleBoardClick=async t=>{let r=this.getTaskContextFromEvent(t);if(!r)return;let{task:a,card:i}=r,o=t.target.closest("[data-tn-action]");if(o&&o!==i){let l=o.dataset.tnAction;if(l){t.preventDefault(),t.stopPropagation(),await this.handleCardAction(l,a,o,t);return}}};this.handleBoardContextMenu=async t=>{let r=this.getTaskContextFromEvent(t);if(!r)return;t.preventDefault(),t.stopPropagation();let{showTaskContextMenu:a}=await Promise.resolve().then(()=>(Ua(),fv));await a(t,r.task.path,this.plugin,VE(r.task))};this.basesController=t,this.dataAdapter.basesView=this}onload(){this.readViewOptions(),super.onload()}onDataUpdated(){if(this.draggedTaskPath){this.debugLog("ON-DATA-UPDATED: deferred (drag active)",{draggedTask:this.draggedTaskPath.split("/").pop()}),this.pendingRender=!0;return}if(this.activeDropCount>0||Date.now(){let c=l.getAttribute("data-group"),d=l.querySelector(".kanban-view__cards");c&&d&&!(c in a)&&(a[c]=d.scrollTop)}),this.boardEl.querySelectorAll(".kanban-view__swimlane-column").forEach(l=>{let c=l.getAttribute("data-column"),d=l.getAttribute("data-swimlane");if(c&&d){let u=`${d}:${c}`,p=l.querySelector(".kanban-view__tasks-container");p&&!(u in a)&&(a[u]=p.scrollTop)}})),{...r,scrollTop:((i=this.rootElement)==null?void 0:i.scrollTop)||0,columnScroll:a}}setEphemeralState(t){if(!G7e(t))return;super.setEphemeralState(t);let r=Y7e(t);if(typeof t.scrollTop=="number"&&this.rootElement){let a=t.scrollTop;window.requestAnimationFrame(()=>{this.rootElement&&this.rootElement.isConnected&&(this.rootElement.scrollTop=a)})}r&&window.requestAnimationFrame(()=>{for(let[a,i]of this.columnScrollers){let s=r[a];if(s!==void 0){let o=i.scrollContainer;o&&(o.scrollTop=s)}}this.boardEl&&(this.boardEl.querySelectorAll(".kanban-view__column").forEach(s=>{let o=s.getAttribute("data-group");if(o&&r[o]!==void 0){let l=s.querySelector(".kanban-view__cards");l&&!this.columnScrollers.has(o)&&(l.scrollTop=r[o])}}),this.boardEl.querySelectorAll(".kanban-view__swimlane-column").forEach(s=>{let o=s.getAttribute("data-column"),l=s.getAttribute("data-swimlane");if(o&&l){let c=`${l}:${o}`;if(r[c]!==void 0){let d=s.querySelector(".kanban-view__tasks-container");d&&!this.columnScrollers.has(c)&&(d.scrollTop=r[c])}}}))})}async render(){var t,r;if(!(!this.boardEl||!this.rootElement)&&(t=this.data)!=null&&t.data){this.debugLog("RENDER-START",{activeDropCount:this.activeDropCount,suppressRenderRemaining:Math.max(0,this.suppressRenderUntil-Date.now()),draggedTaskPath:((r=this.draggedTaskPath)==null?void 0:r.split("/").pop())||null,currentTaskElementsCount:this.currentTaskElements.size}),this.config&&this.readViewOptions(),this.rootElement&&this.setupSearch(this.rootElement);try{let a=this.dataAdapter.extractDataItems();LE(this.data,a);let i=await yu(a,this.plugin),s=this.applySearchFilter(i);this.setExpandedRelationshipTaskScope(s);let o=this.getTopLevelRenderTasks(s),l=this.getTopLevelRenderTasks(i);if(this.setCurrentVisibleTaskPaths(o),this.destroyColumnScrollers(),this.boardEl.empty(),this.sortScopeTaskPaths.clear(),this.sortScopeCandidateTaskPaths.clear(),o.length===0&&!(s.length>0&&!this.hideEmptySwimLanes&&this.isPropertyField(this.swimLanePropertyId,"priority"))){this.isSearchWithNoResults(s,i.length)?this.renderSearchNoResults(this.boardEl):this.renderEmptyState();return}let c=rF(a);this.swimLanePropertyId&&KSe(a,c,this.swimLanePropertyId);let d=this.getGroupByPropertyId();if(!d){this.renderNoGroupByError();return}let u=this.groupTasks(o,d,c),p=this.groupTasks(l,d,c);this.swimLanePropertyId?await this.renderWithSwimLanes(u,o,p,l,c,d):await this.renderFlat(u,p)}catch(a){ag.error("[TaskNotes][KanbanView] Error rendering:",{category:"internal",operation:"rendering",error:a}),this.renderError(a instanceof Error?a:new Error(String(a)))}}}getGroupByPropertyId(){var r;let t=this.basesController;if((r=t==null?void 0:t.query)!=null&&r.views&&(t!=null&&t.viewName)){let a=t.query.views,i=t.viewName;for(let s=0;st-r).map(([t])=>t)}setCurrentVisibleTaskPathOrder(t){this.currentVisibleTaskPaths.clear(),this.currentVisibleTaskOrder.clear(),t.forEach((r,a)=>{this.currentVisibleTaskPaths.add(r),this.currentVisibleTaskOrder.set(r,a)}),this.hideTopLevelSubtasks||(this.expandedRelationshipTaskPaths.clear(),this.expandedRelationshipTaskOrder.clear(),t.forEach((r,a)=>{this.expandedRelationshipTaskPaths.add(r),this.expandedRelationshipTaskOrder.set(r,a)}))}applyOptimisticSortOrderResult(t,r,a,i,s,o){let l=this.getVisibleSortScopePaths(i,s);if(!l)return!1;let c=UE(l,[t],r,a);if(!c)return!1;let d=this.getCurrentVisibleTaskPathOrder(),u=UE(d,[t],r,a);if(!u)return!1;let p=this.columnScrollers.get(this.getColumnScrollerKey(i,s));if(p&&!p.reorderItems({movedKeys:[t],targetKey:r,position:a?"before":"after"}))return!1;let m=BE(t,o);return jE(this.taskInfoCache,m),p&&($E(p.getItems(),f=>f,m,f=>{this.taskInfoCache.set(f.path,f)}),p.invalidateItems([...m.keys()])),this.setSortScopePathsForScope(i,s,c),this.setCurrentVisibleTaskPathOrder(u),!0}applySuccessfulKanbanDropLocally({path:t,dropPlan:r,dropTarget:a,sortOrderPlan:i,updatedTask:s,optimisticReorderApplied:o}){var C;if(!r.needsGroupUpdate&&!r.needsSwimlaneUpdate||r.isGroupByListProperty||r.isSwimlaneListProperty)return!1;let l=r.sourceColumn;if(!l)return!1;let c=this.swimLanePropertyId&&(C=r.sourceSwimlane)!=null?C:null,d=r.newGroupValue,u=this.swimLanePropertyId?r.newSwimLaneValue:null,p=this.getVisibleSortScopePaths(l,c),m=this.getVisibleSortScopePaths(d,u);if(!p||!m||!p.includes(t))return!1;let f=p.filter(x=>x!==t),h=this.insertPathIntoDropScope(m,t,a);if(!h)return!1;let g=this.moveVisiblePathForDrop(t,a);if(!g)return!1;let v=s!=null?s:this.buildTaskInfoForLocalDropPatch(t,r,i);if(!v)return!1;let k=i?BE(t,i):new Map,T=k.get(t);T&&(v.sortOrder=T);let b=this.columnScrollers.get(this.getColumnScrollerKey(l,c)),w=this.columnScrollers.get(this.getColumnScrollerKey(d,u)),S={items:[v],targetKey:a==null?void 0:a.taskPath,position:a?a.above?"before":"after":"end"};if(b&&!b.canRemoveItems([t])||w&&!w.canInsertItems(S)||!w&&!this.getTaskContainerForScope(d,u)||!w&&!o&&!a||b&&!b.removeItems([t]))return!1;if(w){if(!w.insertItems(S))return!1;w.invalidateItems([t]),this.removeNormalRenderedTask(t)}else if(!this.renderNormalTaskInDropScope(v,d,u,a))return!1;this.taskInfoCache.set(t,v),jE(this.taskInfoCache,k);for(let x of[b,w]){if(!x)continue;let E=x.getItems();$E(E,I=>I,k,I=>{this.taskInfoCache.set(I.path,I)});let _=new Set(E.map(I=>I.path)),F=[...k.keys()].filter(I=>_.has(I));x.invalidateItems(F)}return this.setSortScopePathsForScope(l,c,f),this.setSortScopePathsForScope(d,u,h),this.setCurrentVisibleTaskPathOrder(g),this.updateScopeEmptyHint(l,c),this.updateScopeEmptyHint(d,u),this.updateCountDisplaysForScope(l,c),this.updateCountDisplaysForScope(d,u),!0}insertPathIntoDropScope(t,r,a){let i=t.filter(s=>s!==r);return a?i.includes(a.taskPath)?UE([...i,r],[r],a.taskPath,a.above):null:[...i,r]}moveVisiblePathForDrop(t,r){let a=this.getCurrentVisibleTaskPathOrder();return a.includes(t)?r?a.includes(r.taskPath)?UE(a,[t],r.taskPath,r.above):null:[...a.filter(i=>i!==t),t]:null}buildTaskInfoForLocalDropPatch(t,r,a){var o;let i=this.taskInfoCache.get(t);if(!i)return null;let s={...i,customProperties:{...(o=i.customProperties)!=null?o:{}}};return r.needsGroupUpdate&&this.applyLocalDropValue(s,r.groupByTaskProp,r.groupByFrontmatterKey,r.newGroupValue),r.needsSwimlaneUpdate&&r.swimlaneFrontmatterKey&&r.newSwimLaneValue!==null&&this.applyLocalDropValue(s,r.swimlaneTaskProp,r.swimlaneFrontmatterKey,r.newSwimLaneValue),a!=null&&a.sortOrder&&(s.sortOrder=a.sortOrder),s}applyLocalDropValue(t,r,a,i){var o;let s=i==="None"?null:i;r&&(t[r]=s),t.customProperties={...(o=t.customProperties)!=null?o:{},[a]:s}}createRenderedTaskWrapper(t){let r=this.containerEl.ownerDocument,a=Ie(r,"div");a.className="kanban-view__card-wrapper",a.setAttribute("draggable","true"),a.setAttribute("data-task-path",t.path);let i=pr(t,this.plugin,this.getVisibleProperties(),this.getCardOptions());return a.appendChild(i),this.setupCardDragHandlers(a,t),a}renderNormalTaskInDropScope(t,r,a,i){let s=this.getTaskContainerForScope(r,a);if(!s)return!1;let o=this.currentTaskElements.get(t.path),l=this.createRenderedTaskWrapper(t);if(this.removeEmptyCellHint(s),o&&s.contains(o))o.replaceWith(l);else{let c=i?this.currentTaskElements.get(i.taskPath):null;c&&s.contains(c)?i!=null&&i.above?s.insertBefore(l,c):s.insertBefore(l,c.nextSibling):s.appendChild(l),o==null||o.remove()}return this.currentTaskElements.set(t.path,l),!0}removeNormalRenderedTask(t){let r=this.currentTaskElements.get(t);r==null||r.remove(),this.currentTaskElements.delete(t)}getTaskContainerForScope(t,r){if(!this.boardEl)return null;let a=cF(t);if(r===null)return this.boardEl.querySelector(`.kanban-view__column[data-group="${a}"] .kanban-view__cards`);let i=cF(r);return this.boardEl.querySelector(`.kanban-view__swimlane-column[data-column="${a}"][data-swimlane="${i}"] .kanban-view__tasks-container`)}updateScopeEmptyHint(t,r){var s;let a=this.getTaskContainerForScope(t,r);if(!a)return;let i=(s=this.getVisibleSortScopePaths(t,r))!=null?s:[];this.removeEmptyCellHint(a),i.length===0&&this.renderEmptyCellHint(a,t,r)}updateCountDisplaysForScope(t,r){this.updateColumnCountDisplay(t),r!==null&&this.updateSwimLaneCountDisplay(r)}updateColumnCountDisplay(t){var o;let r=this.getVisibleColumnTaskCount(t),a=oF(r,this.wipLimits[t]),i=cF(t),s=(o=this.boardEl)==null?void 0:o.querySelector(`.kanban-view__column[data-group="${i}"] .kanban-view__column-count, .kanban-view__column-header-cell[data-column-key="${i}"] .kanban-view__column-count`);s&&(s.textContent=a.text,s.classList.toggle("kanban-view__column-count--exceeded",a.isExceeded))}getVisibleColumnTaskCount(t){var i,s;if(!this.swimLanePropertyId)return(s=(i=this.getVisibleSortScopePaths(t,null))==null?void 0:i.length)!=null?s:0;let r=`::${t}`,a=0;for(let[o,l]of this.sortScopeTaskPaths)o.endsWith(r)&&(a+=l.length);return a}updateSwimLaneCountDisplay(t){var l,c;let r=cF(t),a=(c=(l=this.boardEl)==null?void 0:l.querySelector(`.kanban-view__swimlane-column[data-swimlane="${r}"]`))==null?void 0:c.closest(".kanban-view__swimlane-row"),i=a==null?void 0:a.querySelector(".kanban-view__swimlane-count");if(!i)return;let s=`${t}::`,o=0;for(let[d,u]of this.sortScopeTaskPaths)d.startsWith(s)&&(o+=u.length);i.textContent=`${o}`}async confirmLargeReorder(t,r,a){let i=this.plugin.settings.fieldMapping.sortOrder,s=a===null?this.plugin.i18n.translate("views.kanban.reorder.scope.column",{group:r}):this.plugin.i18n.translate("views.kanban.reorder.scope.columnInSwimlane",{group:r,swimlane:a});return ur(this.plugin.app,{title:this.plugin.i18n.translate("common.reorder.confirmLargeTitle"),message:this.plugin.i18n.translate("common.reorder.confirmLargeMessage",{field:i,count:t,scope:s}),confirmText:this.plugin.i18n.translate("common.reorder.confirmButton"),cancelText:this.plugin.i18n.translate("common.cancel")})}groupTasks(t,r,a){var s,o;let i=this.plugin.settings.fieldMapping.sortOrder;return HCe({taskNotes:t,groupByPropertyId:r,pathToProps:a,explodeListColumns:this.explodeListColumns,groupedData:this.dataAdapter.getGroupedData(),convertGroupKeyToString:l=>this.dataAdapter.convertGroupKeyToString(l),isListTypeProperty:l=>this.isListTypeProperty(l),getListPropertyValue:(l,c)=>this.getListPropertyValue(l,c,a),canonicalizeGroupKey:(l,c)=>this.canonicalizeConfiguredGroupKey(l,c),sortOrderValues:_E(this.dataAdapter,i)?this.getSortOrderValues(t,i):void 0,statusConfigs:this.plugin.settings.customStatuses||[],priorityConfigs:((o=(s=this.plugin.priorityManager)==null?void 0:s.getAllPriorities)==null?void 0:o.call(s))||this.plugin.settings.customPriorities||[],isStatusGroupingProperty:l=>this.isStatusGroupingProperty(l),isPriorityGroupingProperty:l=>this.isPriorityGroupingProperty(l),getStatusGroupKeyAliases:l=>this.getStatusGroupKeyAliases(l),pinnedColumns:this.pinnedColumns})}getSortOrderValues(t,r){var i;let a=new Map;for(let s of t){let o=this.plugin.app.vault.getAbstractFileByPath(s.path),l=o instanceof En.TFile?(i=this.plugin.app.metadataCache.getFileCache(o))==null?void 0:i.frontmatter:void 0,c=l==null?void 0:l[r];c!=null&&a.set(s.path,c)}return a}isListTypeProperty(t){return OCe(t,{contextsField:this.plugin.fieldMapper.toUserField("contexts"),projectsField:this.plugin.fieldMapper.toUserField("projects")},r=>tF(this.plugin.app,r))}getListPropertyValue(t,r,a){return zCe(t,r,a,{contextsField:this.plugin.fieldMapper.toUserField("contexts"),projectsField:this.plugin.fieldMapper.toUserField("projects")})}getSwimLaneKeys(t,r){return UCe({task:t,pathToProps:r,swimLanePropertyId:this.swimLanePropertyId,explodeListColumns:this.explodeListColumns,isListTypeProperty:a=>this.isListTypeProperty(a),getListPropertyValue:(a,i)=>this.getListPropertyValue(a,i,r),canonicalizeGroupKey:(a,i)=>this.canonicalizeConfiguredGroupKey(a,i)})}isStatusGroupingProperty(t){return lF(t,this.plugin.fieldMapper.toUserField("status"))}isPriorityGroupingProperty(t){return y4(t,this.plugin.fieldMapper.toUserField("priority"))}canonicalizeConfiguredGroupKey(t,r){var s,o;let a=this.plugin.fieldMapper.toUserField("status"),i=this.plugin.fieldMapper.toUserField("priority");return jCe({groupKey:t,propertyId:r,fields:{statusField:a,priorityField:i},statuses:lF(r,a)?((o=(s=this.plugin.statusManager)==null?void 0:s.getAllStatuses)==null?void 0:o.call(s))||[]:[],normalizeStatusValue:l=>{var c,d,u;return(u=(d=(c=this.plugin.statusManager)==null?void 0:c.normalizeStatusValue)==null?void 0:d.call(c,l))!=null?u:l},normalizePriorityValue:l=>{var c,d,u;return(u=(d=(c=this.plugin.priorityManager)==null?void 0:c.normalizePriorityValue)==null?void 0:d.call(c,l))!=null?u:l},getStatusGroupKeyAliases:l=>this.getStatusGroupKeyAliases(l)})}findStatusConfigForGroupKey(t){var r,a;return v4(t,((a=(r=this.plugin.statusManager)==null?void 0:r.getAllStatuses)==null?void 0:a.call(r))||[],i=>{var s,o,l;return(l=(o=(s=this.plugin.statusManager)==null?void 0:s.normalizeStatusValue)==null?void 0:o.call(s,i))!=null?l:i},i=>this.getStatusGroupKeyAliases(i))}getStatusGroupKeyAliases(t){return BCe(t,r=>Zo(r,this.plugin.app))}isUnknownStatusGroup(t,r){if(!r||!this.isStatusGroupingProperty(r))return!1;let a=t.trim();return!a||a==="None"?!1:!this.findStatusConfigForGroupKey(a)}markUnknownStatusColumn(t,r){t.addClass("kanban-view__column--unknown-status"),t.setAttribute("data-unknown-status",r),(0,En.setTooltip)(t,"Status is not defined in TaskNotes settings")}markUnknownStatusColumnHeader(t,r){t.addClass("kanban-view__column-header--unknown-status"),t.setAttribute("data-unknown-status",r),(0,En.setTooltip)(t,"Status is not defined in TaskNotes settings")}async renderFlat(t,r){if(!this.boardEl)return;this.boardEl.classList.remove("kanban-view__board--swimlanes"),this.sortScopeTaskPaths.clear(),this.setSortScopeCandidatePaths(Array.from(r.entries()).map(([l,c])=>[this.getSortScopeKey(l),c.map(d=>d.path)])),this.boardEl.style.setProperty("--kanban-column-width",`${this.columnWidth}px`);let a=this.getVisibleProperties(),i=this.getGroupByPropertyId(),s=Array.from(t.keys()),o=i?this.applyColumnOrder(i,s):s;for(let l of o){let c=t.get(l)||[];if(!g4(this.hideEmptyColumns,l,c,this.pinnedColumns))continue;this.sortScopeTaskPaths.set(this.getSortScopeKey(l),c.map(u=>u.path));let d=await this.createColumn(l,c,a,i);this.boardEl&&this.boardEl.appendChild(d)}}async renderWithSwimLanes(t,r,a,i,s,o){if(!this.swimLanePropertyId)return;this.sortScopeTaskPaths.clear();let l=k4(r,t,f=>this.getSwimLaneKeys(f,s)),c=k4(i,a,f=>this.getSwimLaneKeys(f,s));this.setSortScopeCandidatePaths(Array.from(c.entries()).flatMap(([f,h])=>Array.from(h.entries()).map(([g,v])=>[this.getSortScopeKey(g,f),v.map(k=>k.path)])));let d=Array.from(t.keys()),u=this.applyColumnOrder(o,d),p=VCe(u,l,this.hideEmptyColumns,this.pinnedColumns),m=this.applySwimLaneOrderToMap(this.swimLanePropertyId,l,d);await this.renderSwimLaneTable(m,p,s,o)}async renderSwimLaneTable(t,r,a,i){var c;if(!this.boardEl)return;this.boardEl.style.setProperty("--kanban-column-width",`${this.columnWidth}px`),this.boardEl.style.setProperty("--kanban-swimlane-max-height",`${this.maxSwimlaneHeight}px`),this.boardEl.addClass("kanban-view__board--swimlanes");let s=this.boardEl.createDiv({cls:"kanban-view__swimlane-row kanban-view__swimlane-row--header"});s.createDiv({cls:"kanban-view__swimlane-label"});let o=T4(t,r);for(let d of r){let u=s.createDiv({cls:"kanban-view__column-header-cell"});u.setAttribute("draggable","true"),u.setAttribute("data-column-key",d),this.isUnknownStatusGroup(d,i)&&this.markUnknownStatusColumnHeader(u,d);let m=u.createSpan({cls:"kanban-view__drag-handle"});if(m.setAttribute("aria-hidden","true"),(0,En.setIcon)(m,"grip-vertical"),this.consolidateStatusIcon&&this.isGroupedByStatus()){let h=this.plugin.statusManager.getStatusConfig(d);if(h!=null&&h.icon){let g=u.createSpan({cls:"kanban-view__column-icon"});g.style.color=h.color,(0,En.setIcon)(g,h.icon)}}let f=u.createSpan({cls:"kanban-view__column-title"});this.renderGroupTitleWrapper(f,d,!1,!0),this.renderColumnCount(u,d,(c=o.get(d))!=null?c:0),this.setupColumnHeaderDragHandlers(u)}let l=this.getVisibleProperties();for(let[d,u]of t){let p=this.boardEl.createDiv({cls:"kanban-view__swimlane-row"}),m=p.createDiv({cls:"kanban-view__swimlane-label"}),f=m.createDiv({cls:"kanban-view__swimlane-title"});this.renderGroupTitleWrapper(f,d,!0);let h=Array.from(u.values()).reduce((g,v)=>g+v.length,0);m.createDiv({cls:"kanban-view__swimlane-count",text:`${h}`});for(let g of r){let v=u.get(g)||[],k=this.isUnknownStatusGroup(g,i);this.sortScopeTaskPaths.set(this.getSortScopeKey(g,d),v.map(w=>w.path));let T=p.createDiv({cls:"kanban-view__swimlane-column",attr:{"data-column":g,"data-swimlane":d}});k&&this.markUnknownStatusColumn(T,g),this.setupSwimLaneCellDragDrop(T,g,d);let b=T.createDiv({cls:"kanban-view__tasks-container"});if(v.length>=this.VIRTUAL_SCROLL_THRESHOLD)await this.createVirtualSwimLaneCell(b,`${d}:${g}`,v,l);else{let w=this.getCardOptions();for(let S of v){let C=b.createDiv({cls:"kanban-view__card-wrapper"});C.setAttribute("draggable","true"),C.setAttribute("data-task-path",S.path);let x=pr(S,this.plugin,l,w);C.appendChild(x),this.currentTaskElements.set(S.path,C),this.taskInfoCache.set(S.path,S),this.setupCardDragHandlers(C,S)}}v.length===0&&this.renderEmptyCellHint(b,g,d),this.createAddTaskButton(T,i,g,d)}}}async createColumn(t,r,a,i){let s=this.containerEl.ownerDocument,o=Ie(s,"div");o.className="kanban-view__column",o.style.width=`${this.columnWidth}px`,o.setAttribute("data-group",t);let l=this.isUnknownStatusGroup(t,i);l&&this.markUnknownStatusColumn(o,t);let c=o.createDiv({cls:"kanban-view__column-header"});c.setAttribute("draggable","true"),c.setAttribute("data-column-key",t),l&&this.markUnknownStatusColumnHeader(c,t);let d=c.createSpan({cls:"kanban-view__drag-handle"});if(d.setAttribute("aria-hidden","true"),(0,En.setIcon)(d,"grip-vertical"),this.consolidateStatusIcon&&this.isGroupedByStatus()){let f=this.plugin.statusManager.getStatusConfig(t);if(f!=null&&f.icon){let h=c.createSpan({cls:"kanban-view__column-icon"});h.style.color=f.color,(0,En.setIcon)(h,f.icon)}}let u=c.createSpan({cls:"kanban-view__column-title"});this.renderGroupTitleWrapper(u,t,!1,!0),this.renderColumnCount(c,t,r.length),this.setupColumnHeaderDragHandlers(c);let p=o.createDiv({cls:"kanban-view__cards"});this.setupColumnDragDrop(o,p,t);let m=this.getCardOptions();return r.length>=this.VIRTUAL_SCROLL_THRESHOLD?this.createVirtualColumn(p,t,r,a,m):this.createNormalColumn(p,r,a,m),r.length===0&&this.renderEmptyCellHint(p,t),this.createAddTaskButton(o,i,t),o}renderColumnCount(t,r,a){let i=oF(a,this.wipLimits[r]),s=t.createSpan({cls:"kanban-view__column-count",text:i.text});i.isExceeded&&s.addClass("kanban-view__column-count--exceeded")}createAddTaskButton(t,r,a,i=null){let o=t.createDiv({cls:"kanban-view__add-task-footer"}).createEl("button",{cls:"kanban-view__add-task-button clickable-icon",attr:{type:"button","aria-label":this.getAddTaskLabel(a,i)}});(0,En.setIcon)(o,"plus"),(0,En.setTooltip)(o,this.getAddTaskLabel(a,i)),o.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),this.openTaskCreationForKanbanCell(r,a,i)})}getAddTaskLabel(t,r){return r?`Add task to ${t} / ${r}`:`Add task to ${t}`}renderEmptyCellHint(t,r,a=null){let i=this.plugin.i18n.translate("views.kanban.noTasks"),s=a?`${i}: ${r} / ${a}`:`${i}: ${r}`,o=t.createDiv({cls:"kanban-view__empty-cell",attr:{"aria-label":s}}),l=o.createSpan({cls:"kanban-view__empty-cell-icon",attr:{"aria-hidden":"true"}});(0,En.setIcon)(l,"plus-circle"),o.createSpan({cls:"kanban-view__empty-cell-text",text:i})}removeEmptyCellHint(t){var r;(r=t==null?void 0:t.querySelector(".kanban-view__empty-cell"))==null||r.remove()}async openTaskCreationForKanbanCell(t,r,a=null){await this.createFileForView(void 0,i=>{let s=(o,l)=>{ECe({frontmatter:i,propertyId:o,groupKey:l,propertyMapper:this.propertyMapper,fieldMapper:this.plugin.fieldMapper,userFields:this.plugin.settings.userFields,isListTypeProperty:c=>this.isListTypeProperty(c),coerceGroupKeyForFrontmatter:(c,d)=>this.coerceGroupKeyForFrontmatter(c,d)})};s(t,r),s(this.swimLanePropertyId,a)})}coerceGroupKeyForFrontmatter(t,r){return nF(this.plugin.app,t,r,this.plugin.settings.userFields)}createVirtualColumn(t,r,a,i,s){t.addClass("kanban-view__cards--virtual");let o=this.containerEl.ownerDocument,l=new hm({container:t,items:a,overscan:3,renderItem:c=>{let d=Ie(o,"div");d.className="kanban-view__card-wrapper",d.setAttribute("draggable","true"),d.setAttribute("data-task-path",c.path);let u=pr(c,this.plugin,i,s);return d.appendChild(u),this.taskInfoCache.set(c.path,c),this.setupCardDragHandlers(d,c),d},getItemKey:c=>c.path});this.columnScrollers.set(r,l)}async createVirtualSwimLaneCell(t,r,a,i){t.addClass("kanban-view__tasks-container--virtual");let s=this.getCardOptions(),o=this.containerEl.ownerDocument,l=new hm({container:t,items:a,overscan:3,renderItem:c=>{let d=Ie(o,"div");d.className="kanban-view__card-wrapper",d.setAttribute("draggable","true"),d.setAttribute("data-task-path",c.path);let u=pr(c,this.plugin,i,s);return d.appendChild(u),this.taskInfoCache.set(c.path,c),this.setupCardDragHandlers(d,c),d},getItemKey:c=>c.path});this.columnScrollers.set(r,l)}createNormalColumn(t,r,a,i){for(let s of r){let o=t.createDiv({cls:"kanban-view__card-wrapper"});o.setAttribute("draggable","true"),o.setAttribute("data-task-path",s.path);let l=pr(s,this.plugin,a,i);o.appendChild(l),this.currentTaskElements.set(s.path,o),this.taskInfoCache.set(s.path,s),this.setupCardDragHandlers(o,s)}}setupColumnHeaderDragHandlers(t){let r=t.dataset.columnKey;if(!r)return;let a=t.classList.contains("kanban-view__column-header-cell"),i=a?"kanban-view__column-header-cell--dragging":"kanban-view__column-header--dragging",s=a?"kanban-view__column-header-cell--dragover":"kanban-view__column-header--dragover";t.addEventListener("dragstart",o=>{o.dataTransfer&&(o.dataTransfer.effectAllowed="move",o.dataTransfer.setData("text/x-kanban-column",r),t.classList.add(i))}),t.addEventListener("dragover",o=>{var l;(l=o.dataTransfer)!=null&&l.types.includes("text/x-kanban-column")&&(o.preventDefault(),o.stopPropagation(),o.dataTransfer.dropEffect="move",t.classList.add(s))}),t.addEventListener("dragleave",o=>{var l;(l=o.dataTransfer)!=null&&l.types.includes("text/x-kanban-column")&&o.target===t&&t.classList.remove(s)}),t.addEventListener("drop",o=>{(async()=>{var g;if(!((g=o.dataTransfer)!=null&&g.types.includes("text/x-kanban-column")))return;o.preventDefault(),o.stopPropagation(),t.classList.remove(s);let l=o.dataTransfer.getData("text/x-kanban-column"),c=t.dataset.columnKey;if(!c||!l||l===c)return;let d=this.getGroupByPropertyId();if(!d)return;let u=a?".kanban-view__column-header-cell":".kanban-view__column-header",p=Array.from(this.boardEl.querySelectorAll(u)).map(v=>v.dataset.columnKey).filter(Boolean),m=p.indexOf(l),f=p.indexOf(c),h=[...p];h.splice(m,1),h.splice(f,0,l),await this.saveColumnOrder(d,h),await this.render()})()}),t.addEventListener("dragend",()=>{t.classList.remove(i)}),this.setupColumnHeaderTouchHandlers(t,r,a,i)}setupColumnHeaderTouchHandlers(t,r,a,i){KCe(En.Platform.isMobile)&&(t.addEventListener("contextmenu",s=>{(this.longPressTimer||this.touchDragActive)&&(s.preventDefault(),s.stopPropagation())}),t.addEventListener("touchstart",s=>{if(s.touches.length!==1)return;let o=s.touches[0];this.touchStartX=o.clientX,this.touchStartY=o.clientY,this.longPressTimer=window.setTimeout(()=>{var l;this.touchDragActive=!0,this.touchDragType="column",this.draggedColumnKey=r,this.containerEl.ownerDocument.addEventListener("contextmenu",this.boundContextMenuBlocker,!0),t.classList.add(i),this.touchDragGhost=this.createTouchDragGhost(t,o.clientX,o.clientY),(l=navigator.vibrate)==null||l.call(navigator,50)},this.LONG_PRESS_DELAY)},{passive:!0}),t.addEventListener("touchmove",s=>{if(s.touches.length!==1)return;let o=s.touches[0];if(!this.touchDragActive&&this.longPressTimer){let l=Math.abs(o.clientX-this.touchStartX),c=Math.abs(o.clientY-this.touchStartY);(l>this.TOUCH_MOVE_THRESHOLD||c>this.TOUCH_MOVE_THRESHOLD)&&(window.clearTimeout(this.longPressTimer),this.longPressTimer=null);return}this.touchDragActive&&this.touchDragType==="column"&&(s.preventDefault(),this.updateTouchDragGhost(o.clientX,o.clientY),this.updateDropTargetFeedback(o.clientX,o.clientY),this.handleAutoScroll(o.clientX))},{passive:!1}),t.addEventListener("touchend",s=>{(async()=>{if(this.longPressTimer&&(window.clearTimeout(this.longPressTimer),this.longPressTimer=null),t.classList.remove(i),!this.touchDragActive||this.touchDragType!=="column")return;let o=s.changedTouches[0];if(!o){this.clearTouchDragState();return}let l=this.findDropTargetAt(o.clientX,o.clientY);if(l.type&&l.groupKey&&this.draggedColumnKey&&l.groupKey!==this.draggedColumnKey){let c=this.getGroupByPropertyId();if(c){let d=a?".kanban-view__column-header-cell":".kanban-view__column-header",u=Array.from(this.boardEl.querySelectorAll(d)).map(f=>f.dataset.columnKey).filter(Boolean),p=u.indexOf(this.draggedColumnKey),m=u.indexOf(l.groupKey);if(p!==-1&&m!==-1){let f=[...u];f.splice(p,1),f.splice(m,0,this.draggedColumnKey),await this.saveColumnOrder(c,f),await this.render()}}}this.clearTouchDragState()})()}),t.addEventListener("touchcancel",()=>{t.classList.remove(i),this.clearTouchDragState()}))}setupColumnDragDrop(t,r,a){t.addEventListener("dragover",i=>{var s;(s=i.dataTransfer)!=null&&s.types.includes("text/x-kanban-column")||(i.preventDefault(),i.stopPropagation(),i.dataTransfer&&(i.dataTransfer.dropEffect="move"),t.classList.add("kanban-view__column--dragover"))}),t.addEventListener("dragleave",i=>{let s=t.getBoundingClientRect(),o=i.clientX,l=i.clientY;(o=s.right||l=s.bottom)&&t.classList.remove("kanban-view__column--dragover")}),t.addEventListener("drop",i=>{(async()=>{var f,h,g,v,k,T;if((f=i.dataTransfer)!=null&&f.types.includes("text/x-kanban-column"))return;if(i.preventDefault(),i.stopPropagation(),this.debugLog("COLUMN-DROP-EVENT-RECEIVED",{targetColumn:a,draggedTaskPath:((h=this.draggedTaskPath)==null?void 0:h.split("/").pop())||"(null)",dropTargetPath:((g=this.dropTargetPath)==null?void 0:g.split("/").pop())||"(null)",eventTarget:(k=(v=i.target)==null?void 0:v.className)==null?void 0:k.slice(0,60)}),!this.draggedTaskPath){this.debugLog("COLUMN-DROP: bail — draggedTaskPath is null (dragend already fired?)"),t.classList.remove("kanban-view__column--dragover"),this.cleanupDragShift();return}let s=iF(this.dropTargetPath,this.dropAbove),o=t.querySelector(".kanban-view__cards"),l=this.draggedFromColumn!==a,c=!!s&&(o==null?void 0:o.querySelector(`[data-task-path="${CSS.escape(s.taskPath)}"]`))!=null,d=o?u4({cardsContainer:o,draggedTaskPaths:this.draggedTaskPaths,currentInsertionIndex:this.currentInsertionIndex,clientY:i.clientY}):void 0,u=d4({dropTarget:d!=null?d:s,isCrossScope:l,targetInDropScope:!!d||c,fallbackDropTarget:l?void 0:d});this.debugLog("COLUMN-DROP",{draggedTask:(T=this.draggedTaskPath)==null?void 0:T.split("/").pop(),sourceColumn:this.draggedFromColumn,targetColumn:a,isCrossColumn:l,dropTarget:u?{file:u.taskPath.split("/").pop(),above:u.above}:null,cardsContainerFound:!!o,cardsContainerChildCount:o==null?void 0:o.childElementCount,draggedTaskPaths:this.draggedTaskPaths.map(b=>b.split("/").pop())});let p=WE(this.draggedTaskPaths,this.draggedTaskPath),m=this.performOptimisticReorder(p,u,o);this.debugLog("COLUMN-DROP-OPTIMISTIC-RESULT",{success:m}),t.classList.remove("kanban-view__column--dragover"),this.cleanupDragShift(),await this.handleTaskDrop(this.draggedTaskPath,a,null,u,{optimisticReorderApplied:m,draggedPaths:p}),this.draggedTaskPath=null,this.draggedFromColumn=null})()}),t.addEventListener("dragend",()=>{t.classList.remove("kanban-view__column--dragover")})}setupSwimLaneCellDragDrop(t,r,a){t.addEventListener("dragover",i=>{i.preventDefault(),i.stopPropagation(),i.dataTransfer&&(i.dataTransfer.dropEffect="move"),t.classList.add("kanban-view__swimlane-column--dragover")}),t.addEventListener("dragleave",i=>{let s=t.getBoundingClientRect(),o=i.clientX,l=i.clientY;(o=s.right||l=s.bottom)&&t.classList.remove("kanban-view__swimlane-column--dragover")}),t.addEventListener("drop",i=>{(async()=>{var g,v,k,T,b;if(i.preventDefault(),i.stopPropagation(),this.debugLog("SWIMLANE-CELL-DROP-EVENT-RECEIVED",{targetColumn:r,targetSwimlane:a,draggedTaskPath:((g=this.draggedTaskPath)==null?void 0:g.split("/").pop())||"(null)",dropTargetPath:((v=this.dropTargetPath)==null?void 0:v.split("/").pop())||"(null)",eventTarget:(T=(k=i.target)==null?void 0:k.className)==null?void 0:T.slice(0,60)}),!this.draggedTaskPath){this.debugLog("SWIMLANE-CELL-DROP: bail — draggedTaskPath is null (dragend already fired?)"),t.classList.remove("kanban-view__swimlane-column--dragover"),this.cleanupDragShift();return}let s=iF(this.dropTargetPath,this.dropAbove),o=t.querySelector(".kanban-view__tasks-container"),l=this.draggedFromColumn!==r,c=this.draggedFromSwimlane!==a,d=l||c,u=!!s&&(o==null?void 0:o.querySelector(`[data-task-path="${CSS.escape(s.taskPath)}"]`))!=null,p=o?u4({cardsContainer:o,draggedTaskPaths:this.draggedTaskPaths,currentInsertionIndex:this.currentInsertionIndex,clientY:i.clientY}):void 0,m=d4({dropTarget:p!=null?p:s,isCrossScope:d,targetInDropScope:!!p||u,fallbackDropTarget:d?void 0:p}),f=WE(this.draggedTaskPaths,this.draggedTaskPath);this.debugLog("SWIMLANE-CELL-DROP",{draggedTask:(b=this.draggedTaskPath)==null?void 0:b.split("/").pop(),isCrossColumn:l,isCrossSwimlane:c,dropTarget:m?{file:m.taskPath.split("/").pop(),above:m.above}:null,cardsContainerFound:!!o,cardsContainerChildCount:o==null?void 0:o.childElementCount});let h=this.performOptimisticReorder(f,m,o);this.debugLog("SWIMLANE-CELL-DROP-OPTIMISTIC-RESULT",{success:h}),t.classList.remove("kanban-view__swimlane-column--dragover"),this.cleanupDragShift(),await this.handleTaskDrop(this.draggedTaskPath,r,a,m,{optimisticReorderApplied:h,draggedPaths:f}),this.draggedTaskPath=null,this.draggedFromColumn=null})()}),t.addEventListener("dragend",()=>{t.classList.remove("kanban-view__swimlane-column--dragover")})}createTouchDragGhost(t,r,a){let i=t.cloneNode(!0);return i.classList.add("kanban-view__touch-ghost"),i.style.cssText=` + position: fixed; + left: ${r}px; + top: ${a}px; + width: ${t.offsetWidth}px; + pointer-events: none; + z-index: 10000; + opacity: 0.8; + transform: translate(-50%, -50%) rotate(3deg); + box-shadow: 0 8px 24px rgba(0,0,0,0.3); + `,this.containerEl.ownerDocument.body.appendChild(i),i}updateTouchDragGhost(t,r){this.touchDragGhost&&(this.touchDragGhost.style.left=`${t}px`,this.touchDragGhost.style.top=`${r}px`)}removeTouchDragGhost(){this.touchDragGhost&&(this.touchDragGhost.remove(),this.touchDragGhost=null)}findDropTargetAt(t,r){this.touchDragGhost&&(this.touchDragGhost.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-min-height-800px-997b4c8c"),this.touchDragGhost.classList.add("tn-static-display-none-6b99de8b"));let i=this.containerEl.ownerDocument.elementFromPoint(t,r);if(this.touchDragGhost&&(this.touchDragGhost.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),this.touchDragGhost.style.removeProperty("display")),!i)return{type:null,groupKey:null,swimLaneKey:null,element:null};let s=i.closest(".kanban-view__card-wrapper"),o=s==null?void 0:s.dataset.taskPath;if(s&&o&&!this.draggedTaskPaths.includes(o)){let u=s.closest("[data-group]"),p=s.closest("[data-column]"),m=s.closest("[data-swimlane]"),f=(u==null?void 0:u.dataset.group)||(p==null?void 0:p.dataset.column)||null,h=s.getBoundingClientRect();return{type:"task",groupKey:f,swimLaneKey:(m==null?void 0:m.dataset.swimlane)||null,element:s,taskPath:o,above:r{s.classList.remove("kanban-view__column--dragover")}),(r=this.boardEl)==null||r.querySelectorAll(".kanban-view__swimlane-column--dragover").forEach(s=>{s.classList.remove("kanban-view__swimlane-column--dragover")}),(a=this.boardEl)==null||a.querySelectorAll(".kanban-view__column-header--dragover").forEach(s=>{s.classList.remove("kanban-view__column-header--dragover")}),(i=this.boardEl)==null||i.querySelectorAll(".kanban-view__column-header-cell--dragover").forEach(s=>{s.classList.remove("kanban-view__column-header-cell--dragover")})}updateDropTargetFeedback(t,r){var i;this.clearDragoverFeedback();let a=this.findDropTargetAt(t,r);if(a.element)if(a.type==="column")a.element.classList.add("kanban-view__column--dragover");else if(a.type==="swimlane")a.element.classList.add("kanban-view__swimlane-column--dragover");else if(a.type==="task"){let s=a.element.closest(".kanban-view__swimlane-column");s?s.classList.add("kanban-view__swimlane-column--dragover"):(i=a.element.closest(".kanban-view__column"))==null||i.classList.add("kanban-view__column--dragover")}else a.type==="columnHeader"&&this.touchDragType==="column"&&(a.element.classList.contains("kanban-view__column-header-cell")?a.element.classList.add("kanban-view__column-header-cell--dragover"):a.element.classList.add("kanban-view__column-header--dragover"))}clearTouchDragState(){var t,r;this.touchDragActive=!1,this.containerEl.ownerDocument.removeEventListener("contextmenu",this.boundContextMenuBlocker,!0),this.removeTouchDragGhost(),this.stopAutoScroll(),this.longPressTimer&&(window.clearTimeout(this.longPressTimer),this.longPressTimer=null),this.clearDragoverFeedback();for(let a of this.draggedTaskPaths)(t=this.currentTaskElements.get(a))==null||t.classList.remove("kanban-view__card--dragging");(r=this.activeDragSourceElement)==null||r.classList.remove("kanban-view__card--dragging"),this.activeDragSourceElement=null,this.draggedTaskPath=null,this.draggedTaskPaths=[],this.draggedFromColumn=null,this.draggedFromSwimlane=null,this.draggedSourceColumns.clear(),this.draggedSourceSwimlanes.clear(),this.touchDragType=null,this.draggedColumnKey=null}handleAutoScroll(t){if(!this.boardEl)return;let r=this.boardEl.getBoundingClientRect(),a=r.left+this.AUTO_SCROLL_EDGE,i=r.right-this.AUTO_SCROLL_EDGE,s=0;ti&&(s=1),s!==this.autoScrollDirection&&(this.stopAutoScroll(),this.autoScrollDirection=s,s!==0&&(this.autoScrollTimer=window.setInterval(()=>{this.boardEl&&(this.boardEl.scrollLeft+=this.autoScrollDirection*this.AUTO_SCROLL_SPEED)},16)))}stopAutoScroll(){this.autoScrollTimer&&(window.clearInterval(this.autoScrollTimer),this.autoScrollTimer=null),this.autoScrollDirection=0}setupCardDragHandlers(t,r){let a=null,i=()=>{a=null};t.addEventListener("mousedown",s=>{a=c4(s.target,t)},{capture:!0}),t.addEventListener("mouseup",i),t.addEventListener("click",i,{capture:!0}),t.addEventListener("click",s=>{if(this.handleSelectionClick(s,r.path)){s.stopPropagation();return}}),t.addEventListener("contextmenu",s=>{if(s.preventDefault(),s.stopPropagation(),this.longPressTimer||this.touchDragActive)return;let o=this.plugin.taskSelectionService;if(o&&o.getSelectionCount()>1){o.isSelected(r.path)||o.addToSelection(r.path),this.showBatchContextMenu(s);return}uo(s,r.path,this.plugin,new Date)}),t.addEventListener("dragover",s=>{if(this.draggedTaskPath===r.path)return;s.preventDefault(),s.stopPropagation(),s.dataTransfer&&(s.dataTransfer.dropEffect="move");let o=s.clientY;this.dragOverRafId||(this.dragOverRafId=window.requestAnimationFrame(()=>{this.dragOverRafId=0;let l=t.getBoundingClientRect(),c=o!this.draggedTaskPaths.includes(m.dataset.taskPath||"")),p=u.length;for(let m=0;m=p);vCe(d,u,p)}}))}),t.addEventListener("dragleave",()=>{}),t.addEventListener("drop",s=>{(async()=>{var h,g;if((h=s.dataTransfer)!=null&&h.types.includes("text/x-kanban-column")||(s.preventDefault(),s.stopPropagation(),!this.draggedTaskPath))return;let o=t.closest("[data-group]"),l=t.closest("[data-column]"),c=t.closest("[data-swimlane]"),d=(o==null?void 0:o.dataset.group)||(l==null?void 0:l.dataset.column),u=(c==null?void 0:c.dataset.swimlane)||null;if(!d)return;let p=yCe(t,r.path,s.clientY);this.debugLog("CARD-DROP (drop-on-card handler)",{draggedTask:(g=this.draggedTaskPath)==null?void 0:g.split("/").pop(),targetCard:r.path.split("/").pop(),sourceColumn:this.draggedFromColumn,targetColumn:d,isCrossColumn:this.draggedFromColumn!==d,above:p.above,swimLaneKey:u});let m=WE(this.draggedTaskPaths,this.draggedTaskPath),f=this.performOptimisticReorder(m,p);this.cleanupDragShift(),o==null||o.classList.remove("kanban-view__column--dragover"),await this.handleTaskDrop(this.draggedTaskPath,d,u,p,{optimisticReorderApplied:f,draggedPaths:m}),this.draggedTaskPath=null,this.draggedFromColumn=null})()}),t.addEventListener("dragstart",s=>{s.stopPropagation();let o=a!=null?a:{taskPath:r.path,sourceElement:t},l=o.taskPath,c=o.sourceElement;this.debugLog("DRAGSTART",{task:l.split("/").pop(),parentTask:r.path.split("/").pop(),inCurrentTaskElements:this.currentTaskElements.has(l),isNestedSource:l!==r.path}),fCe(s,c,"kanban-view__drag-image");let d=this.plugin.taskSelectionService;if(d&&d.isSelected(l)&&d.getSelectionCount()>1){this.draggedTaskPaths=d.getSelectedPaths(),this.draggedTaskPath=l,this.draggedSourceColumns.clear(),this.draggedSourceSwimlanes.clear();for(let v of this.draggedTaskPaths){let k=this.currentTaskElements.get(v);if(k){k.classList.add("kanban-view__card--dragging");let T=k.closest("[data-group]"),b=k.closest("[data-column]"),w=k.closest("[data-swimlane]"),S=(T==null?void 0:T.dataset.group)||(b==null?void 0:b.dataset.column),C=w==null?void 0:w.dataset.swimlane;S&&this.draggedSourceColumns.set(v,S),C&&this.draggedSourceSwimlanes.set(v,C)}}s.dataTransfer&&(s.dataTransfer.effectAllowed="move",s.dataTransfer.setData("text/plain",this.draggedTaskPaths.join(",")),s.dataTransfer.setData("text/x-batch-drag","true")),c.classList.add("kanban-view__card--dragging")}else this.draggedTaskPath=l,this.draggedTaskPaths=[l],c.classList.add("kanban-view__card--dragging"),s.dataTransfer&&(s.dataTransfer.effectAllowed="move",s.dataTransfer.setData("text/plain",l));this.activeDragSourceElement=c,this.showFloatingDragPreview(c,s);let u=t.closest("[data-group]"),p=t.closest("[data-column]"),m=t.closest("[data-swimlane]");this.draggedFromColumn=(u==null?void 0:u.dataset.group)||(p==null?void 0:p.dataset.column)||null,this.draggedFromSwimlane=(m==null?void 0:m.dataset.swimlane)||null,this.containerEl.ownerDocument.body.classList.add("tn-drag-active");let f=c.getBoundingClientRect().height,h=t.parentElement,g=t.closest(".kanban-view__column, .kanban-view__swimlane-column");g&&(g.style.minHeight=`${g.offsetHeight}px`,this.dragSourceColumnEl=g),window.requestAnimationFrame(()=>{for(let v of this.draggedTaskPaths){let k=this.currentTaskElements.get(v);k&&(k.classList.remove("tn-static-display-flex-4d51fc62","tn-static-height-100-62264068","tn-static-height-12px-06c0747e","tn-static-height-16px-30de4aee","tn-static-height-24px-29a11d37","tn-static-min-height-800px-997b4c8c"),k.classList.add("tn-static-height-0-7a31cef0"),k.classList.remove("tn-static-flex-1-14e3b769"),k.classList.add("tn-static-overflow-hidden-69824400"),k.classList.remove("tn-static-margin-8px-0-0-0-a2eb8382","tn-static-padding-0-16px-16px-16px-f1aa998c","tn-static-padding-12px-43bef435","tn-static-padding-16px-287f770e","tn-static-padding-20px-769fed37","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c","tn-static-padding-2px-8px-c8eea84a","tn-static-padding-2rem-42aa6d9c"),k.classList.add("tn-static-padding-0-41d7d7e2"),k.classList.remove("tn-static-margin-0-auto-266e9b04","tn-static-margin-0-db0d5f36","tn-static-margin-0-var-size-4-2-77f7dc08","tn-static-margin-2px-0-edce9b14","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-padding-12px-43bef435","tn-static-padding-20px-ebe8e48c"),k.classList.add("tn-static-margin-0-11696618"),k.classList.remove("tn-static-border-1px-solid-var-background-mo-b65b5121","tn-static-padding-12px-43bef435"),k.classList.add("tn-static-border-none-2eda1daa"),k.classList.remove("tn-static-opacity-0-6-d95b59ac","tn-static-opacity-1-c6e7979d"),k.classList.add("tn-static-opacity-0-8d919cb5"))}if(h){let v=getComputedStyle(h).gap,k=parseFloat(v)||4;h.style.setProperty("--tn-drag-gap",`${f+k}px`),h.classList.remove("tn-static-margin-top-12px-91e0f558");let T=h.querySelectorAll(".kanban-view__card-wrapper");for(let b of T)this.draggedTaskPaths.includes(b.dataset.taskPath||"")||b.classList.add("kanban-view__card-wrapper--drag-shift");this.dragContainer=h,this.currentInsertionIndex=-1}})}),t.addEventListener("dragend",s=>{var o,l,c,d,u;s.stopPropagation(),this.debugLog("DRAGEND-FIRED",{draggedTask:r.path.split("/").pop(),draggedTaskPath:((o=this.draggedTaskPath)==null?void 0:o.split("/").pop())||"(already null)",draggedTaskPathsCount:this.draggedTaskPaths.length,pendingRender:this.pendingRender,activeDropCount:this.activeDropCount,suppressRenderRemaining:Math.max(0,this.suppressRenderUntil-Date.now())}),this.cleanupFloatingDragPreview();for(let p of this.draggedTaskPaths){let m=this.currentTaskElements.get(p);if(m){let f=((l=m.parentElement)==null?void 0:l.className)||"(detached)";this.debugLog("DRAGEND-RESTORE-CARD",{path:p.split("/").pop(),parentClass:f,currentStyles:m.style.cssText.slice(0,80)}),vm(m),m.classList.remove("kanban-view__card--dragging")}}vm(t),t.classList.remove("kanban-view__card--dragging"),(c=this.activeDragSourceElement)==null||c.classList.remove("kanban-view__card--dragging"),this.activeDragSourceElement=null,i(),this.cleanupDragShift(),this.dragSourceColumnEl&&(this.dragSourceColumnEl.classList.remove("tn-static-flex-1-14e3b769","tn-static-min-height-800px-997b4c8c"),this.dragSourceColumnEl.style.removeProperty("min-height"),this.dragSourceColumnEl=null),this.containerEl.ownerDocument.body.classList.remove("tn-drag-active"),this.draggedTaskPath=null,this.draggedFromColumn=null,this.draggedFromSwimlane=null,this.draggedTaskPaths=[],this.draggedSourceColumns.clear(),this.draggedSourceSwimlanes.clear(),(d=this.boardEl)==null||d.querySelectorAll(".kanban-view__column--dragover").forEach(p=>{p.classList.remove("kanban-view__column--dragover")}),(u=this.boardEl)==null||u.querySelectorAll(".kanban-view__swimlane-column--dragover").forEach(p=>{p.classList.remove("kanban-view__swimlane-column--dragover")}),this.dropTargetPath=null,this.dragOverRafId&&(cancelAnimationFrame(this.dragOverRafId),this.dragOverRafId=0),this.pendingRender?(this.debugLog("DRAGEND-PENDING-RENDER: flushing deferred render via debouncedRefresh"),this.pendingRender=!1,this.debouncedRefresh()):this.debugLog("DRAGEND: no pending render to flush")}),this.setupCardTouchHandlers(t,r)}performOptimisticReorder(t,r,a){return kCe({draggedPaths:t,dropTarget:r,targetContainer:a,currentTaskElements:this.currentTaskElements,removeEmptyCellHint:i=>this.removeEmptyCellHint(i),log:(i,s)=>this.debugLog(i,s)})}cleanupDragShift(){var t;if(this.dragContainer){this.dragContainer.style.removeProperty("--tn-drag-gap"),this.dragContainer.classList.remove("tn-static-margin-top-12px-91e0f558","tn-static-overflow-y-auto-03df744e","tn-static-overflow-y-clip-c5043043"),p4(this.dragContainer),this.dragContainer.style.removeProperty("overflow-y"),this.dragContainer.style.removeProperty("padding-bottom");let r=this.dragContainer.querySelectorAll(".kanban-view__card-wrapper--drag-shift, .kanban-view__card-wrapper--shift-down");for(let a of r)a.classList.remove("kanban-view__card-wrapper--drag-shift","kanban-view__card-wrapper--shift-down");this.dragContainer=null}this.dragTargetColumnEl&&(this.dragTargetColumnEl.classList.remove("tn-static-margin-top-12px-91e0f558","tn-static-max-height-400px-f0787633"),this.dragTargetColumnEl.style.removeProperty("max-height"),this.dragTargetColumnEl=null),this.boardEl&&p4(this.boardEl),(t=this.boardEl)==null||t.querySelectorAll(".kanban-view__card-wrapper--drag-shift, .kanban-view__card-wrapper--shift-down").forEach(r=>{r.classList.remove("kanban-view__card-wrapper--drag-shift","kanban-view__card-wrapper--shift-down")}),this.currentInsertionIndex=-1}showFloatingDragPreview(t,r){this.cleanupFloatingDragPreview();let a=t.ownerDocument,i=a.body;if(!i)return;let s=t.getBoundingClientRect(),o=Ie(a,"div"),l=this.getFloatingDragPreviewTitle(t),c=Ie(a,"span");c.className="kanban-view__floating-drag-preview-title",c.textContent=l,o.classList.add("tasknotes-plugin","kanban-view__floating-drag-preview"),o.appendChild(c),o.setAttribute("aria-hidden","true"),o.setAttribute("draggable","false"),this.draggedTaskPaths.length>1&&(o.dataset.dragCount=`${this.draggedTaskPaths.length}`),this.floatingDragPreviewWidth=Math.min(Math.max(s.width,180),320),this.floatingDragPreviewHeight=40,o.setCssProps({"--tn-kanban-drag-preview-width":`${this.floatingDragPreviewWidth}px`,"--tn-kanban-drag-preview-transform":"translate3d(-9999px, -9999px, 0)"}),i.appendChild(o),this.floatingDragPreviewEl=o,this.floatingDragPreviewDocument=a;let d=u=>{this.positionFloatingDragPreview(u.clientX,u.clientY)};this.floatingDragPreviewMoveHandler=d,a.addEventListener("drag",d,!0),a.addEventListener("dragover",d,!0),this.positionFloatingDragPreview(r.clientX,r.clientY)}positionFloatingDragPreview(t,r){var p;let a=this.floatingDragPreviewEl;if(!a||t===0&&r===0)return;let i=(p=a.ownerDocument.defaultView)!=null?p:window,s=8,o=14,l=this.floatingDragPreviewWidth,c=this.floatingDragPreviewHeight,d=t+o,u=r+o;d+l>i.innerWidth-s&&(d=t-l-o),u+c>i.innerHeight-s&&(u=r-c-o),d=Math.max(s,Math.min(d,Math.max(s,i.innerWidth-l-s))),u=Math.max(s,Math.min(u,Math.max(s,i.innerHeight-c-s))),d+=i.scrollX,u+=i.scrollY,this.floatingDragPreviewPendingX=d,this.floatingDragPreviewPendingY=u,this.floatingDragPreviewRafId===null&&(this.floatingDragPreviewRafId=i.requestAnimationFrame(()=>{var h;this.floatingDragPreviewRafId=null;let m=this.floatingDragPreviewPendingX,f=this.floatingDragPreviewPendingY;(h=this.floatingDragPreviewEl)==null||h.setCssProps({"--tn-kanban-drag-preview-transform":`translate3d(${m}px, ${f}px, 0)`})}))}getFloatingDragPreviewTitle(t){var i,s,o,l;let a=(((i=t.querySelector(".task-card__title-text"))==null?void 0:i.textContent)||((s=t.querySelector(".task-card__title"))==null?void 0:s.textContent)||((l=(o=t.dataset.taskPath)==null?void 0:o.split("/").pop())==null?void 0:l.replace(/\.md$/i,""))||"Task").trim().replace(/\s+/g," ");return a.length>80?`${a.slice(0,77).trimEnd()}...`:a}cleanupFloatingDragPreview(){var t,r,a;this.floatingDragPreviewRafId!==null&&(((r=(t=this.floatingDragPreviewDocument)==null?void 0:t.defaultView)!=null?r:window).cancelAnimationFrame(this.floatingDragPreviewRafId),this.floatingDragPreviewRafId=null),this.floatingDragPreviewMoveHandler&&this.floatingDragPreviewDocument&&(this.floatingDragPreviewDocument.removeEventListener("drag",this.floatingDragPreviewMoveHandler,!0),this.floatingDragPreviewDocument.removeEventListener("dragover",this.floatingDragPreviewMoveHandler,!0)),(a=this.floatingDragPreviewEl)==null||a.remove(),this.floatingDragPreviewEl=null,this.floatingDragPreviewDocument=null,this.floatingDragPreviewMoveHandler=null,this.floatingDragPreviewWidth=280,this.floatingDragPreviewHeight=40,this.floatingDragPreviewPendingX=0,this.floatingDragPreviewPendingY=0}setupCardTouchHandlers(t,r){if(!KCe(En.Platform.isMobile))return;let a=null,i=()=>{a=null};t.addEventListener("touchstart",s=>{if(s.touches.length!==1)return;a=c4(s.target,t);let o=s.touches[0];this.touchStartX=o.clientX,this.touchStartY=o.clientY,this.longPressTimer=window.setTimeout(()=>{this.initiateTouchDrag(t,r,o.clientX,o.clientY,a)},this.LONG_PRESS_DELAY)},{passive:!0}),t.addEventListener("touchmove",s=>{if(s.touches.length!==1)return;let o=s.touches[0];if(!this.touchDragActive&&this.longPressTimer){let l=Math.abs(o.clientX-this.touchStartX),c=Math.abs(o.clientY-this.touchStartY);(l>this.TOUCH_MOVE_THRESHOLD||c>this.TOUCH_MOVE_THRESHOLD)&&(window.clearTimeout(this.longPressTimer),this.longPressTimer=null);return}this.touchDragActive&&this.touchDragType==="task"&&(s.preventDefault(),this.updateTouchDragGhost(o.clientX,o.clientY),this.updateDropTargetFeedback(o.clientX,o.clientY),this.handleAutoScroll(o.clientX))},{passive:!1}),t.addEventListener("touchend",s=>{(async()=>{var c,d,u,p;if(this.longPressTimer&&(window.clearTimeout(this.longPressTimer),this.longPressTimer=null),!this.touchDragActive||this.touchDragType!=="task")return;let o=s.changedTouches[0];if(!o){this.clearTouchDragState();return}let l=this.findDropTargetAt(o.clientX,o.clientY);if(l.groupKey&&this.draggedTaskPath){let m=l.type==="task"?iF(l.taskPath,(c=l.above)!=null?c:!0):void 0,f=(p=(u=l.cardsContainer)!=null?u:(d=l.element)==null?void 0:d.querySelector(".kanban-view__cards, .kanban-view__tasks-container"))!=null?p:null,h=WE(this.draggedTaskPaths,this.draggedTaskPath),g=this.performOptimisticReorder(h,m,f);this.cleanupDragShift(),await this.handleTaskDrop(this.draggedTaskPath,l.groupKey,l.swimLaneKey,m,{optimisticReorderApplied:g,draggedPaths:h})}this.clearTouchDragState(),i()})()}),t.addEventListener("touchcancel",()=>{i(),this.clearTouchDragState()})}initiateTouchDrag(t,r,a,i,s=null){var f;this.touchDragActive=!0,this.touchDragType="task",this.containerEl.ownerDocument.addEventListener("contextmenu",this.boundContextMenuBlocker,!0);let o=s!=null?s:{taskPath:r.path,sourceElement:t},l=o.taskPath,c=o.sourceElement,d=this.plugin.taskSelectionService;if(d!=null&&d.isSelected(l)&&d.getSelectionCount()>1){this.draggedTaskPaths=d.getSelectedPaths(),this.draggedTaskPath=l,this.draggedSourceColumns.clear(),this.draggedSourceSwimlanes.clear();for(let h of this.draggedTaskPaths){let g=this.currentTaskElements.get(h);if(g){g.classList.add("kanban-view__card--dragging");let v=g.closest("[data-group]"),k=g.closest("[data-column]"),T=g.closest("[data-swimlane]"),b=(v==null?void 0:v.dataset.group)||(k==null?void 0:k.dataset.column),w=T==null?void 0:T.dataset.swimlane;b&&this.draggedSourceColumns.set(h,b),w&&this.draggedSourceSwimlanes.set(h,w)}}c.classList.add("kanban-view__card--dragging")}else this.draggedTaskPath=l,this.draggedTaskPaths=[l],c.classList.add("kanban-view__card--dragging");this.activeDragSourceElement=c;let u=t.closest("[data-group]"),p=t.closest("[data-column]"),m=t.closest("[data-swimlane]");this.draggedFromColumn=(u==null?void 0:u.dataset.group)||(p==null?void 0:p.dataset.column)||null,this.draggedFromSwimlane=(m==null?void 0:m.dataset.swimlane)||null,this.touchDragGhost=this.createTouchDragGhost(c,a,i),(f=navigator.vibrate)==null||f.call(navigator,50)}async handleTaskDrop(t,r,a,i,s={}){this.activeDropCount++;let o=!0;try{await this.dropQueue.enqueue(t,async()=>{var pe,oe,X,de,Oe,Q;this.suppressRenderUntil=Date.now()+1e4;let l=this.getGroupByPropertyId();if(!l)return;if(l.startsWith("formula.")){new En.Notice(this.plugin.i18n.translate("views.kanban.errors.formulaGroupingReadOnly"));return}if(a!==null&&((pe=this.swimLanePropertyId)!=null&&pe.startsWith("formula."))){new En.Notice(this.plugin.i18n.translate("views.kanban.errors.formulaSwimlaneReadOnly"));return}let c=Ya(l),d=this.explodeListColumns&&this.isListTypeProperty(c),u=this.swimLanePropertyId?Ya(this.swimLanePropertyId):null,p=u&&this.isListTypeProperty(u),m=this.draggedFromColumn,f=this.draggedFromSwimlane,h=new Map(this.draggedSourceColumns),g=new Map(this.draggedSourceSwimlanes),v=s.draggedPaths&&s.draggedPaths.length>0?[...s.draggedPaths]:[...this.draggedTaskPaths],k=v.length>1?v:[t],T=k.length>1,b=this.canFastPatchManualOrderDrop(s,i,k,r,a),w=this.canFastPatchCrossScopeDrop(s,k),S=!1,C=!1,x=_E(this.dataAdapter,this.plugin.settings.fieldMapping.sortOrder),E=this.plugin.settings.fieldMapping.sortOrder,_=Ya(l),F=this.swimLanePropertyId?Ya(this.swimLanePropertyId):null,I=a!==null&&F?[{property:F,value:a}]:void 0,A=this.getVisibleSortScopePaths(r,a),R=this.getCandidateSortScopePaths(r,a);this.debugLog("SORT-ORDER-CHECK",{hasDropTarget:!!i,hasSortOrder:x,dropTarget:i?{file:i.taskPath.split("/").pop(),above:i.above}:null});let O=this.plugin.fieldMapper.lookupMappingKey(c),U=u?this.plugin.fieldMapper.lookupMappingKey(u):null;for(let Z of k){let Ue=T?h.get(Z):m,le=T?g.get(Z):f,at=TCe({path:Z,sourceColumn:Ue,sourceSwimlane:le,newGroupValue:r,newSwimLaneValue:a,groupByPropertyId:l,swimLanePropertyId:this.swimLanePropertyId,groupByTaskProp:O,swimlaneTaskProp:U,isGroupByListProperty:d,isSwimlaneListProperty:!!p});this.debugLog("HANDLE-DROP-TASK",{taskFile:Z.split("/").pop(),sourceColumn:Ue,newGroupValue:r,isSameColumn:!at.needsGroupUpdate,isGroupByListProperty:d,sourceSwimlane:le,newSwimLaneValue:a});let He=null;if(x){if(i){if(this.debugLog("COMPUTE-SORT-ORDER-CALL",{taskFile:Z.split("/").pop(),targetFile:i.taskPath.split("/").pop(),above:i.above,groupKey:r,cleanGroupBy:_,cleanSwimLane:F}),He=await Q_(i.taskPath,i.above,r,_,Z,this.plugin,{scopeFilters:I,taskInfoCache:this.taskInfoCache,visibleTaskPaths:A,candidateTaskPaths:R}),He.sortOrder===null)continue;let ne=He.additionalWrites.length+1;if(ne>this.LARGE_REORDER_WARNING_THRESHOLD&&!await this.confirmLargeReorder(ne,r,a))return}else this.debugLog("SORT-ORDER-CROSS-COLUMN-PRESERVE",{taskFile:Z.split("/").pop(),groupKey:r});this.debugLog("SORT-ORDER-RESULT",{taskFile:Z.split("/").pop(),newSortOrder:(oe=He==null?void 0:He.sortOrder)!=null?oe:null,isNull:(He==null?void 0:He.sortOrder)===null,additionalWrites:(X=He==null?void 0:He.additionalWrites.length)!=null?X:0})}if(!bCe(at,He!==null))continue;let jn=this.plugin.app.vault.getAbstractFileByPath(Z);if(!jn||!(jn instanceof En.TFile))continue;He&&await J_(Z,He,this.plugin,{includeDragged:!1}),await yr(this.plugin.app,jn,ne=>{wCe(ne,at,{coerceGroupValue:(en,Qm)=>this.coerceGroupKeyForFrontmatter(en,Qm)}),(He==null?void 0:He.sortOrder)!==null&&He&&(ne[E]=He.sortOrder);let Ce=SCe({plan:at,task:this.taskInfoCache.get(Z),dateModifiedField:this.plugin.fieldMapper.toUserField("dateModified"),dateModifiedValue:qe()});Ce&&(this.plugin.taskService.updateCompletedDateInFrontmatter(ne,Ce.statusValue,Ce.isRecurring),ne[Ce.dateModifiedField]=Ce.dateModifiedValue)}),this.debugLog("ATOMIC-WRITE-DONE",{taskFile:Z.split("/").pop(),needsGroupUpdate:at.needsGroupUpdate,needsSwimlaneUpdate:at.needsSwimlaneUpdate,hasSortOrder:He!==null}),b&&i&&He&&!at.needsGroupUpdate&&!at.needsSwimlaneUpdate&&(S=this.applyOptimisticSortOrderResult(Z,i.taskPath,i.above,r,a,He));let Dr=!1,cs=null;if(at.changedTaskProp)try{let ne=(de=this.taskInfoCache.get(Z))!=null?de:await this.plugin.cacheManager.getTaskInfo(Z),Ce=CCe({plan:at,originalTask:ne,dateModifiedValue:qe(),isCompletedStatus:en=>this.plugin.statusManager.isCompletedStatus(en)});Ce&&(await this.plugin.taskService.applyPropertyChangeSideEffects(jn,ne,Ce.updatedTask,Ce.changedTaskProp,Ce.oldPropValue,Ce.newPropValue),cs=Ce.updatedTask)}catch(ne){Dr=!0,ag.warn("[TaskNotes][KanbanView] Side-effect error after drop:",{category:"configuration",operation:"side-effect-drop",error:ne})}w&&!Dr&&(at.needsGroupUpdate||at.needsSwimlaneUpdate)&&(C=this.applySuccessfulKanbanDropLocally({path:Z,dropPlan:at,dropTarget:i,sortOrderPlan:He,updatedTask:cs,optimisticReorderApplied:s.optimisticReorderApplied===!0}))}T&&((Oe=this.plugin.taskSelectionService)==null||Oe.clearSelection(),(Q=this.plugin.taskSelectionService)==null||Q.exitSelectionMode()),this.debugLog("HANDLE-DROP-COMPLETE",{pathsUpdated:k.map(Z=>Z.split("/").pop()),fastPatchedManualOrder:S,fastPatchedCrossScopeDrop:C}),(S||C)&&(this.pendingRender=!1,o=!1)})}catch(l){ag.error("[TaskNotes][KanbanView] Error updating task:",{category:"persistence",operation:"updating-task",error:l})}finally{if(this.activeDropCount--,o&&(this.postDropRefreshRequested=!0),this.activeDropCount===0){let l=this.postDropRefreshRequested;this.postDropRefreshRequested=!1,l?this.schedulePostDropRender():this.finishFastPostDrop()}}}setupContainer(){var a;super.setupContainer();let t=this.containerEl.ownerDocument,r=Ie(t,"div");r.className="kanban-view__board",(a=this.rootElement)==null||a.appendChild(r),this.boardEl=r,this.registerBoardListeners()}async handleTaskUpdate(t){this.debouncedRefresh()}debouncedRefresh(){this.updateDebounceTimer&&(this.debugLog("DEBOUNCED-REFRESH: cancelling previous pending timer"),window.clearTimeout(this.updateDebounceTimer)),this.debugLog("DEBOUNCED-REFRESH: scheduling render in 150ms",{activeDropCount:this.activeDropCount,suppressRenderRemaining:Math.max(0,this.suppressRenderUntil-Date.now())});let t=this.getEphemeralState(),r=this.containerEl.ownerDocument.defaultView||window;this.updateDebounceTimer=r.setTimeout(()=>{(async()=>{if(this.activeDropCount>0||Date.now(){this.debugLog("POST-DROP-TIMER-FIRED: rendering now"),this.postDropTimer=null,this.suppressRenderUntil=0,this.debouncedRefresh()},nT.POST_DROP_RENDER_DELAY)}finishFastPostDrop(){this.debugLog("FAST-POST-DROP-COMPLETE"),this.postDropTimer&&(window.clearTimeout(this.postDropTimer),this.postDropTimer=null),this.suppressRenderUntil=0,this.pendingRender=!1}renderEmptyState(){if(!this.boardEl)return;let t=this.containerEl.ownerDocument,r=Ie(t,"div");r.className="tn-bases-empty",r.textContent="No tasknotes tasks found for this base.",this.boardEl.appendChild(r)}renderNoGroupByError(){if(!this.boardEl)return;let t=this.containerEl.ownerDocument,r=Ie(t,"div");r.className="tn-bases-error",r.textContent=this.plugin.i18n.translate("views.kanban.errors.noGroupBy"),this.boardEl.appendChild(r)}renderError(t){if(!this.boardEl)return;let r=this.containerEl.ownerDocument,a=Ie(r,"div");a.className="tn-bases-error",a.textContent=`Error loading kanban: ${t.message||"Unknown error"}`,this.boardEl.appendChild(a)}getGroupDisplayTitle(t,r){if(!r)return t;let a=Ya(r),i=this.plugin.fieldMapper.toUserField("status");if(a===i){let o=this.plugin.statusManager.getStatusConfig(t);if(o!=null&&o.label)return o.label}let s=this.plugin.fieldMapper.toUserField("priority");if(a===s){let o=this.plugin.priorityManager.getPriorityConfig(t);if(o!=null&&o.label)return o.label}return t}renderGroupTitleWrapper(t,r,a=!1,i=!1){if(a?this.isSwimLaneByStatus():this.isGroupedByStatus()){let c=this.plugin.statusManager.getStatusConfig(r);if(c){if(this.consolidateStatusIcon&&!i&&c.icon){let d=t.createSpan({cls:"kanban-view__column-icon"});d.style.color=c.color,(0,En.setIcon)(d,c.icon)}this.renderLinkAwareGroupTitle(t,c.label);return}}let o=a?this.swimLanePropertyId:this.getGroupByPropertyId(),l=this.getGroupDisplayTitle(r,o);this.renderLinkAwareGroupTitle(t,l)}renderLinkAwareGroupTitle(t,r){let a=this.app||this.plugin.app,i={metadataCache:a.metadataCache,workspace:a.workspace};N_(t,r,i)}applyColumnOrder(t,r){return qCe({groupBy:t,actualKeys:r,columnOrders:this.columnOrders,hideEmptyColumns:this.hideEmptyColumns,pinnedColumns:this.pinnedColumns,isPriorityField:a=>this.isPropertyField(a,"priority"),isStatusField:a=>this.isPropertyField(a,"status"),getPriorityWeight:a=>this.plugin.priorityManager.getPriorityWeight(a),findStatusConfig:a=>this.findStatusConfigForGroupKey(a)})}applySwimLaneOrder(t,r){return b4({swimLanePropertyId:t,actualKeys:r,swimLaneOrders:this.swimLaneOrders,hideEmptySwimLanes:this.hideEmptySwimLanes,isPriorityField:a=>this.isPropertyField(a,"priority"),isStatusField:a=>this.isPropertyField(a,"status"),getPriorityWeight:a=>this.plugin.priorityManager.getPriorityWeight(a),getStatusOrder:a=>this.plugin.statusManager.getStatusOrder(a)})}isPropertyField(t,r){return t?Ya(t)===this.plugin.fieldMapper.toUserField(r):!1}applySwimLaneOrderToMap(t,r,a){return GCe({swimLanePropertyId:t,swimLanes:r,columnKeys:a,swimLaneOrders:this.swimLaneOrders,hideEmptySwimLanes:this.hideEmptySwimLanes,priorityKeys:this.plugin.priorityManager.getAllPriorities().map(i=>i.value),isPriorityField:i=>this.isPropertyField(i,"priority"),isStatusField:i=>this.isPropertyField(i,"status"),getPriorityWeight:i=>this.plugin.priorityManager.getPriorityWeight(i),getStatusOrder:i=>this.plugin.statusManager.getStatusOrder(i)})}async saveColumnOrder(t,r){this.columnOrders[t]=r;try{let a=JSON.stringify(this.columnOrders);this.config.set("columnOrder",a)}catch(a){ag.error("[KanbanView] Failed to save column order:",{category:"persistence",operation:"save-column-order",error:a})}}getCardOptions(){let t=new Date,r=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())),a=this.consolidateStatusIcon&&this.isGroupedByStatus();return this.buildTaskCardOptions({layout:this.cardLayout,targetDate:r,hideStatusIndicator:a,expandedRelationshipFilterMode:this.expandedRelationshipFilterMode,resolveExpandedRelationshipFilterMode:()=>{var i;return YCe((i=this.config)==null?void 0:i.get("expandedRelationshipFilterMode"))},expandedRelationshipTaskPaths:this.expandedRelationshipTaskPaths,expandedRelationshipTaskOrder:this.expandedRelationshipTaskOrder})}getTopLevelRenderTasks(t){return this.hideTopLevelSubtasks?this.filterTopLevelSubtasks(t):[...t]}setExpandedRelationshipTaskScope(t){this.expandedRelationshipTaskPaths.clear(),this.expandedRelationshipTaskOrder.clear(),t.forEach((r,a)=>{this.expandedRelationshipTaskPaths.add(r.path),this.expandedRelationshipTaskOrder.set(r.path,a)})}setCurrentVisibleTaskPaths(t){this.currentVisibleTaskPaths.clear(),this.currentVisibleTaskOrder.clear(),t.forEach((r,a)=>{this.currentVisibleTaskPaths.add(r.path),this.currentVisibleTaskOrder.set(r.path,a)})}isGroupedByStatus(){let t=this.getGroupByPropertyId();if(!t)return!1;let r=this.plugin.fieldMapper.toUserField("status");return t.replace(/^(note\.|file\.|task\.)/,"")===r}isSwimLaneByStatus(){if(!this.swimLanePropertyId)return!1;let t=this.plugin.fieldMapper.toUserField("status");return this.swimLanePropertyId.replace(/^(note\.|file\.|task\.)/,"")===t}registerBoardListeners(){}unregisterBoardListeners(){}getTaskContextFromEvent(t){let r=t.target;if(!r)return null;let a=r.closest(".task-card");if(!a)return null;let i=a.closest(".kanban-view__card-wrapper");if(!i)return null;let s=i.dataset.taskPath;if(!s)return null;let o=this.taskInfoCache.get(s);return o?{task:o,card:a}:null}async handleCardAction(t,r,a,i){await l4({action:t,task:r,target:a,event:i,plugin:this.plugin,app:this.app||this.plugin.app})}async handleToggleStatus(t,r){await l4({action:"toggle-status",task:t,target:this.containerEl,event:r,plugin:this.plugin,app:this.app||this.plugin.app})}getTaskActionDate(t){return VE(t)}destroyColumnScrollers(){for(let t of this.columnScrollers.values())t.destroy();this.columnScrollers.clear()}onunload(){this.postDropTimer&&(window.clearTimeout(this.postDropTimer),this.postDropTimer=null),this.suppressRenderUntil=0,this.unregisterBoardListeners(),this.cleanupFloatingDragPreview(),this.destroyColumnScrollers(),this.currentTaskElements.clear(),this.taskInfoCache.clear(),this.sortScopeTaskPaths.clear(),this.boardEl=null}};nT.POST_DROP_RENDER_DELAY=500;S4=nT});var GE=y(()=>{Jd();yx()});function uF(n,e){let t=[];for(let r=0;r{let k=n[v.index].eventRange.instance.instanceId+":"+v.span.start+":"+(v.span.end-1);return a[k]||1});o.allowReslicing=!0,o.strictOrder=r,e===!0||t===!0?(o.maxCoord=i,o.hiddenConsumes=!0):typeof e=="number"?o.maxStackCnt=e:typeof t=="number"&&(o.maxStackCnt=t,o.hiddenConsumes=!0);let l=[],c=[];for(let v=0;v1,g=m.span.start===o;u+=m.levelCoord-d,d=m.levelCoord+m.thickness,h?(u+=m.thickness,g&&p.push({seg:aT(f,m.span.start,m.span.end,t),isVisible:!0,isAbsolute:!0,absoluteTop:m.levelCoord,marginTop:0})):g&&(p.push({seg:aT(f,m.span.start,m.span.end,t),isVisible:!0,isAbsolute:!1,absoluteTop:m.levelCoord,marginTop:u}),u=0)}a.push(c),i.push(p),s.push(u)}return{singleColPlacements:a,multiColPlacements:i,leftoverMargins:s}}function nZe(n,e){let t=[];for(let r=0;r({seg:r,isVisible:!0,isAbsolute:!0,absoluteTop:t[r.eventRange.instance.instanceId],marginTop:0}))}function iZe(n){let e={};for(let t of n)for(let r of t)e[r.seg.eventRange.instance.instanceId]=r.absoluteTop;return e}function sZe(n,e){return uF(n.filter(oZe),e)}function oZe(n){return n.eventRange.def.allDay}function lZe(n,e){let t;return e.currentRangeUnit.match(/year|month/)&&(t=n.querySelector(`[data-date="${pk(e.currentDate)}-01"]`)),t||(t=n.querySelector(`[data-date="${Wp(e.currentDate)}"]`)),t}function M4(n,e){let t=new yh(n.renderRange,e);return new vh(t,/year|month|week/.test(n.currentRangeUnit))}function I4(n){let{dateEnv:e,currentRange:t}=n,{start:r,end:a}=t,i;if(n.snapToWeek&&(r=e.startOfWeek(r),i=e.startOfWeek(a),i.valueOf()!==a.valueOf()&&(a=WN(i,1))),n.fixedWeekCount){let s=e.startOfWeek(e.startOfMonth(Kr(t.end,-1))),o=Math.ceil(TV(s,a));a=WN(a,6-o)}return{start:r,end:a}}var x4,XCe,pF,mF,E4,J7e,D4,P4,fF,YE,A4,KE,ZE,hF,iT,cZe,gF=y(()=>{Dh();GE();x4=class extends On{constructor(){super(...arguments),this.headerElRef=sn()}renderSimpleLayout(e,t){let{props:r,context:a}=this,i=[],s=xh(a.options);return e&&i.push({type:"header",key:"header",isSticky:s,chunk:{elRef:this.headerElRef,tableClassName:"fc-col-header",rowContent:e}}),i.push({type:"body",key:"body",liquid:!0,chunk:{content:t}}),P(As,{elClasses:["fc-daygrid"],viewSpec:a.viewSpec},P(Up,{liquid:!r.isHeightAuto&&!r.forPrint,collapsibleWidth:r.forPrint,cols:[],sections:i}))}renderHScrollLayout(e,t,r,a){let i=this.context.pluginHooks.scrollGridImpl;if(!i)throw new Error("No ScrollGrid implementation");let{props:s,context:o}=this,l=!s.forPrint&&xh(o.options),c=!s.forPrint&&Yx(o.options),d=[];return e&&d.push({type:"header",key:"header",isSticky:l,chunks:[{key:"main",elRef:this.headerElRef,tableClassName:"fc-col-header",rowContent:e}]}),d.push({type:"body",key:"body",liquid:!0,chunks:[{key:"main",content:t}]}),c&&d.push({type:"footer",key:"footer",isSticky:!0,chunks:[{key:"main",content:Tk}]}),P(As,{elClasses:["fc-daygrid"],viewSpec:o.viewSpec},P(i,{liquid:!s.isHeightAuto&&!s.forPrint,forPrint:s.forPrint,collapsibleWidth:s.forPrint,colGroups:[{cols:[{span:r,minWidth:a}]}],sections:d}))}};XCe=zt({hour:"numeric",minute:"2-digit",omitZeroMinute:!0,meridiem:"narrow"});pF=class extends Tt{render(){let{props:e}=this;return P(Hp,Object.assign({},e,{elClasses:["fc-daygrid-event","fc-daygrid-block-event","fc-h-event"],defaultTimeFormat:XCe,defaultDisplayEventEnd:e.defaultDisplayEventEnd,disableResizing:!e.seg.eventRange.def.allDay}))}},mF=class extends Tt{render(){let{props:e,context:t}=this,{options:r}=t,{seg:a}=e,i=r.eventTimeFormat||XCe,s=Gp(a,i,t,!0,e.defaultDisplayEventEnd);return P(nu,Object.assign({},e,{elTag:"a",elClasses:["fc-daygrid-event","fc-daygrid-dot-event"],elAttrs:yk(e.seg,t),defaultGenerator:Z7e,timeText:s,isResizing:!1,isDateSelecting:!1}))}};E4=class extends Tt{constructor(){super(...arguments),this.compileSegs=Ae(Q7e)}render(){let{props:e}=this,{allSegs:t,invisibleSegs:r}=this.compileSegs(e.singlePlacements);return P(bh,{elClasses:["fc-daygrid-more-link"],dateProfile:e.dateProfile,todayRange:e.todayRange,allDayDate:e.allDayDate,moreCnt:e.moreCnt,allSegs:t,hiddenSegs:r,alignmentElRef:e.alignmentElRef,alignGridTop:e.alignGridTop,extraDateSpan:e.extraDateSpan,popoverContent:()=>{let a=(e.eventDrag?e.eventDrag.affectedInstances:null)||(e.eventResize?e.eventResize.affectedInstances:null)||{};return P(Ot,null,t.map(i=>{let s=i.eventRange.instance.instanceId;return P("div",{className:"fc-daygrid-event-harness",key:s,style:{visibility:a[s]?"hidden":""}},exe(i)?P(mF,Object.assign({seg:i,isDragging:!1,isSelected:s===e.eventSelection,defaultDisplayEventEnd:!1},Is(i,e.todayRange))):P(pF,Object.assign({seg:i,isDragging:!1,isResizing:!1,isDateSelecting:!1,isSelected:s===e.eventSelection,defaultDisplayEventEnd:!1},Is(i,e.todayRange))))}))}})}};J7e=zt({week:"narrow"}),D4=class extends On{constructor(){super(...arguments),this.rootElRef=sn(),this.state={dayNumberId:Hi()},this.handleRootEl=e=>{Ms(this.rootElRef,e),Ms(this.props.elRef,e)}}render(){let{context:e,props:t,state:r,rootElRef:a}=this,{options:i,dateEnv:s}=e,{date:o,dateProfile:l}=t,c=t.showDayNumber&&eZe(o,l.currentRange,s);return P(Vp,{elTag:"td",elRef:this.handleRootEl,elClasses:["fc-daygrid-day",...t.extraClassNames||[]],elAttrs:Object.assign(Object.assign(Object.assign({},t.extraDataAttrs),t.showDayNumber?{"aria-labelledby":r.dayNumberId}:{}),{role:"gridcell"}),defaultGenerator:X7e,date:o,dateProfile:l,todayRange:t.todayRange,showDayNumber:t.showDayNumber,isMonthStart:c,extraRenderProps:t.extraRenderProps},(d,u)=>P("div",{ref:t.innerElRef,className:"fc-daygrid-day-frame fc-scrollgrid-sync-inner",style:{minHeight:t.minHeight}},t.showWeekNumber&&P(Qx,{elTag:"a",elClasses:["fc-daygrid-week-number"],elAttrs:Cc(e,o,"week"),date:o,defaultFormat:J7e}),!u.isDisabled&&(t.showDayNumber||bk(i)||t.forceDayTop)?P("div",{className:"fc-daygrid-day-top"},P(d,{elTag:"a",elClasses:["fc-daygrid-day-number",c&&"fc-daygrid-month-start"],elAttrs:Object.assign(Object.assign({},Cc(e,o)),{id:r.dayNumberId})})):t.showDayNumber?P("div",{className:"fc-daygrid-day-top",style:{visibility:"hidden"}},P("a",{className:"fc-daygrid-day-number"}," ")):void 0,P("div",{className:"fc-daygrid-day-events",ref:t.fgContentElRef},t.fgContent,P("div",{className:"fc-daygrid-day-bottom",style:{marginTop:t.moreMarginTop}},P(E4,{allDayDate:o,singlePlacements:t.singlePlacements,moreCnt:t.moreCnt,alignmentElRef:a,alignGridTop:!t.showDayNumber,extraDateSpan:t.extraDateSpan,dateProfile:t.dateProfile,eventSelection:t.eventSelection,eventDrag:t.eventDrag,eventResize:t.eventResize,todayRange:t.todayRange}))),P("div",{className:"fc-daygrid-day-bg"},t.bgContent)))}};P4=class extends gh{constructor(){super(...arguments),this.hiddenConsumes=!1,this.forceHidden={}}addSegs(e){let t=super.addSegs(e),{entriesByLevel:r}=this,a=i=>!this.forceHidden[vc(i)];for(let i=0;i{e&&this.updateSizing(!0)}}render(){let{props:e,state:t,context:r}=this,{options:a}=r,i=e.cells.length,s=dF(e.businessHourSegs,i),o=dF(e.bgEventSegs,i),l=dF(this.getHighlightSegs(),i),c=dF(this.getMirrorSegs(),i),{singleColPlacements:d,multiColPlacements:u,moreCnts:p,moreMarginTops:m}=tZe(Sh(e.fgEventSegs,a.eventOrder),e.dayMaxEvents,e.dayMaxEventRows,a.eventOrderStrict,t.segHeights,t.maxContentHeight,e.cells),f=e.eventDrag&&e.eventDrag.affectedInstances||e.eventResize&&e.eventResize.affectedInstances||{};return P("tr",{ref:this.rootElRef,role:"row"},e.renderIntro&&e.renderIntro(),e.cells.map((h,g)=>{let v=this.renderFgSegs(g,e.forPrint?d[g]:u[g],e.todayRange,f),k=this.renderFgSegs(g,aZe(c[g],u),e.todayRange,{},!!e.eventDrag,!!e.eventResize,!1);return P(D4,{key:h.key,elRef:this.cellElRefs.createRef(h.key),innerElRef:this.frameElRefs.createRef(h.key),dateProfile:e.dateProfile,date:h.date,showDayNumber:e.showDayNumbers,showWeekNumber:e.showWeekNumbers&&g===0,forceDayTop:e.showWeekNumbers,todayRange:e.todayRange,eventSelection:e.eventSelection,eventDrag:e.eventDrag,eventResize:e.eventResize,extraRenderProps:h.extraRenderProps,extraDataAttrs:h.extraDataAttrs,extraClassNames:h.extraClassNames,extraDateSpan:h.extraDateSpan,moreCnt:p[g],moreMarginTop:m[g],singlePlacements:d[g],fgContentElRef:this.fgElRefs.createRef(h.key),fgContent:P(Ot,null,P(Ot,null,v),P(Ot,null,k)),bgContent:P(Ot,null,this.renderFillSegs(l[g],"highlight"),this.renderFillSegs(s[g],"non-business"),this.renderFillSegs(o[g],"bg-event")),minHeight:e.cellMinHeight})}))}componentDidMount(){this.updateSizing(!0),this.context.addResizeHandler(this.handleResize)}componentDidUpdate(e,t){let r=this.props;this.updateSizing(!Va(e,r))}componentWillUnmount(){this.context.removeResizeHandler(this.handleResize)}getHighlightSegs(){let{props:e}=this;return e.eventDrag&&e.eventDrag.segs.length?e.eventDrag.segs:e.eventResize&&e.eventResize.segs.length?e.eventResize.segs:e.dateSelectionSegs}getMirrorSegs(){let{props:e}=this;return e.eventResize&&e.eventResize.segs.length?e.eventResize.segs:[]}renderFgSegs(e,t,r,a,i,s,o){let{context:l}=this,{eventSelection:c}=this.props,{framePositions:d}=this.state,u=this.props.cells.length===1,p=i||s||o,m=[];if(d)for(let f of t){let{seg:h}=f,{instanceId:g}=h.eventRange.instance,v=f.isVisible&&!a[g],k=f.isAbsolute,T="",b="";k&&(l.isRtl?(b=0,T=d.lefts[h.lastCol]-d.lefts[h.firstCol]):(T=0,b=d.rights[h.firstCol]-d.rights[h.lastCol])),m.push(P("div",{className:"fc-daygrid-event-harness"+(k?" fc-daygrid-event-harness-abs":""),key:txe(h),ref:p?null:this.segHarnessRefs.createRef(rxe(h)),style:{visibility:v?"":"hidden",marginTop:k?"":f.marginTop,top:k?f.absoluteTop:"",left:T,right:b}},exe(h)?P(mF,Object.assign({seg:h,isDragging:i,isSelected:g===c,defaultDisplayEventEnd:u},Is(h,r))):P(pF,Object.assign({seg:h,isDragging:i,isResizing:s,isDateSelecting:o,isSelected:g===c,defaultDisplayEventEnd:u},Is(h,r)))))}return m}renderFillSegs(e,t){let{isRtl:r}=this.context,{todayRange:a}=this.props,{framePositions:i}=this.state,s=[];if(i)for(let o of e){let l=r?{right:0,left:i.lefts[o.lastCol]-i.lefts[o.firstCol]}:{left:0,right:i.rights[o.firstCol]-i.rights[o.lastCol]};s.push(P("div",{key:$x(o.eventRange),className:"fc-daygrid-bg-harness",style:l},t==="bg-event"?P(Th,Object.assign({seg:o},Is(o,a))):Zx(t)))}return P(Ot,{},...s)}updateSizing(e){let{props:t,state:r,frameElRefs:a}=this;if(!t.forPrint&&t.clientWidth!==null){if(e){let l=t.cells.map(c=>a.currentMap[c.key]);if(l.length){let c=this.rootElRef.current,d=new gl(c,l,!0,!1);(!r.framePositions||!r.framePositions.similarTo(d))&&this.setState({framePositions:new gl(c,l,!0,!1)})}}let i=this.state.segHeights,s=this.querySegHeights(),o=t.dayMaxEvents===!0||t.dayMaxEventRows===!0;this.safeSetState({segHeights:Object.assign(Object.assign({},i),s),maxContentHeight:o?this.computeMaxContentHeight():null})}}querySegHeights(){let e=this.segHarnessRefs.currentMap,t={};for(let r in e){let a=Math.round(e[r].getBoundingClientRect().height);t[r]=Math.max(t[r]||0,a)}return t}computeMaxContentHeight(){let e=this.props.cells[0].key,t=this.cellElRefs.currentMap[e],r=this.fgElRefs.currentMap[e];return t.getBoundingClientRect().bottom-r.getBoundingClientRect().top}getCellEls(){let e=this.cellElRefs.currentMap;return this.props.cells.map(t=>e[t.key])}};fF.addStateEquality({segHeights:Va});YE=class extends On{constructor(){super(...arguments),this.splitBusinessHourSegs=Ae(uF),this.splitBgEventSegs=Ae(sZe),this.splitFgEventSegs=Ae(uF),this.splitDateSelectionSegs=Ae(uF),this.splitEventDrag=Ae(JCe),this.splitEventResize=Ae(JCe),this.rowRefs=new Ui}render(){let{props:e,context:t}=this,r=e.cells.length,a=this.splitBusinessHourSegs(e.businessHourSegs,r),i=this.splitBgEventSegs(e.bgEventSegs,r),s=this.splitFgEventSegs(e.fgEventSegs,r),o=this.splitDateSelectionSegs(e.dateSelectionSegs,r),l=this.splitEventDrag(e.eventDrag,r),c=this.splitEventResize(e.eventResize,r),d=r>=7&&e.clientWidth?e.clientWidth/t.options.aspectRatio/6:null;return P($i,{unit:"day"},(u,p)=>P(Ot,null,e.cells.map((m,f)=>P(fF,{ref:this.rowRefs.createRef(f),key:m.length?m[0].date.toISOString():f,showDayNumbers:r>1,showWeekNumbers:e.showWeekNumbers,todayRange:p,dateProfile:e.dateProfile,cells:m,renderIntro:e.renderRowIntro,businessHourSegs:a[f],eventSelection:e.eventSelection,bgEventSegs:i[f],fgEventSegs:s[f],dateSelectionSegs:o[f],eventDrag:l[f],eventResize:c[f],dayMaxEvents:e.dayMaxEvents,dayMaxEventRows:e.dayMaxEventRows,clientWidth:e.clientWidth,clientHeight:e.clientHeight,cellMinHeight:d,forPrint:e.forPrint}))))}componentDidMount(){this.registerInteractiveComponent()}componentDidUpdate(){this.registerInteractiveComponent()}registerInteractiveComponent(){if(!this.rootEl){let e=this.rowRefs.currentMap[0].getCellEls()[0],t=e?e.closest(".fc-daygrid-body"):null;t&&(this.rootEl=t,this.context.registerInteractiveComponent(this,{el:t,isHitComboAllowed:this.props.isHitComboAllowed}))}}componentWillUnmount(){this.rootEl&&(this.context.unregisterInteractiveComponent(this),this.rootEl=null)}prepareHits(){this.rowPositions=new gl(this.rootEl,this.rowRefs.collect().map(e=>e.getCellEls()[0]),!1,!0),this.colPositions=new gl(this.rootEl,this.rowRefs.currentMap[0].getCellEls(),!0,!1)}queryHit(e,t){let{colPositions:r,rowPositions:a}=this,i=r.leftToIndex(e),s=a.topToIndex(t);if(s!=null&&i!=null){let o=this.props.cells[s][i];return{dateProfile:this.props.dateProfile,dateSpan:Object.assign({range:this.getCellRange(s,i),allDay:!0},o.extraDateSpan),dayEl:this.getCellEl(s,i),rect:{left:r.lefts[i],right:r.rights[i],top:a.tops[s],bottom:a.bottoms[s]},layer:0}}return null}getCellEl(e,t){return this.rowRefs.currentMap[e].getCellEls()[t]}getCellRange(e,t){let r=this.props.cells[e][t].date,a=Kr(r,1);return{start:r,end:a}}};A4=class extends On{constructor(){super(...arguments),this.elRef=sn(),this.needsScrollReset=!1}render(){let{props:e}=this,{dayMaxEventRows:t,dayMaxEvents:r,expandRows:a}=e,i=r===!0||t===!0;i&&!a&&(i=!1,t=null,r=null);let s=["fc-daygrid-body",i?"fc-daygrid-body-balanced":"fc-daygrid-body-unbalanced",a?"":"fc-daygrid-body-natural"];return P("div",{ref:this.elRef,className:s.join(" "),style:{width:e.clientWidth,minWidth:e.tableMinWidth}},P("table",{role:"presentation",className:"fc-scrollgrid-sync-table",style:{width:e.clientWidth,minWidth:e.tableMinWidth,height:a?e.clientHeight:""}},e.colGroupNode,P("tbody",{role:"presentation"},P(YE,{dateProfile:e.dateProfile,cells:e.cells,renderRowIntro:e.renderRowIntro,showWeekNumbers:e.showWeekNumbers,clientWidth:e.clientWidth,clientHeight:e.clientHeight,businessHourSegs:e.businessHourSegs,bgEventSegs:e.bgEventSegs,fgEventSegs:e.fgEventSegs,dateSelectionSegs:e.dateSelectionSegs,eventSelection:e.eventSelection,eventDrag:e.eventDrag,eventResize:e.eventResize,dayMaxEvents:r,dayMaxEventRows:t,forPrint:e.forPrint,isHitComboAllowed:e.isHitComboAllowed}))))}componentDidMount(){this.requestScrollReset()}componentDidUpdate(e){e.dateProfile!==this.props.dateProfile?this.requestScrollReset():this.flushScrollReset()}requestScrollReset(){this.needsScrollReset=!0,this.flushScrollReset()}flushScrollReset(){if(this.needsScrollReset&&this.props.clientWidth){let e=lZe(this.elRef.current,this.props.dateProfile);if(e){let t=e.closest(".fc-daygrid-body"),r=t.closest(".fc-scroller"),a=e.getBoundingClientRect().top-t.getBoundingClientRect().top;r.scrollTop=a?a+1:0}this.needsScrollReset=!1}}};KE=class extends kh{constructor(){super(...arguments),this.forceDayIfListItem=!0}sliceRange(e,t){return t.sliceRange(e)}},ZE=class extends On{constructor(){super(...arguments),this.slicer=new KE,this.tableRef=sn()}render(){let{props:e,context:t}=this;return P(A4,Object.assign({ref:this.tableRef},this.slicer.sliceProps(e,e.dateProfile,e.nextDayThreshold,t,e.dayTableModel),{dateProfile:e.dateProfile,cells:e.dayTableModel.cells,colGroupNode:e.colGroupNode,tableMinWidth:e.tableMinWidth,renderRowIntro:e.renderRowIntro,dayMaxEvents:e.dayMaxEvents,dayMaxEventRows:e.dayMaxEventRows,showWeekNumbers:e.showWeekNumbers,expandRows:e.expandRows,headerAlignElRef:e.headerAlignElRef,clientWidth:e.clientWidth,clientHeight:e.clientHeight,forPrint:e.forPrint}))}},hF=class extends x4{constructor(){super(...arguments),this.buildDayTableModel=Ae(M4),this.headerRef=sn(),this.tableRef=sn()}render(){let{options:e,dateProfileGenerator:t}=this.context,{props:r}=this,a=this.buildDayTableModel(r.dateProfile,t),i=e.dayHeaders&&P(ru,{ref:this.headerRef,dateProfile:r.dateProfile,dates:a.headerDates,datesRepDistinctDays:a.rowCnt===1}),s=o=>P(ZE,{ref:this.tableRef,dateProfile:r.dateProfile,dayTableModel:a,businessHours:r.businessHours,dateSelection:r.dateSelection,eventStore:r.eventStore,eventUiBases:r.eventUiBases,eventSelection:r.eventSelection,eventDrag:r.eventDrag,eventResize:r.eventResize,nextDayThreshold:e.nextDayThreshold,colGroupNode:o.tableColGroupNode,tableMinWidth:o.tableMinWidth,dayMaxEvents:e.dayMaxEvents,dayMaxEventRows:e.dayMaxEventRows,showWeekNumbers:e.weekNumbers,expandRows:!r.isHeightAuto,headerAlignElRef:this.headerElRef,clientWidth:o.clientWidth,clientHeight:o.clientHeight,forPrint:r.forPrint});return e.dayMinWidth?this.renderHScrollLayout(i,s,a.colCnt,e.dayMinWidth):this.renderSimpleLayout(i,s)}};iT=class extends ph{buildRenderRange(e,t,r){let a=super.buildRenderRange(e,t,r),{props:i}=this;return I4({currentRange:a,snapToWeek:/^(year|month)$/.test(t),fixedWeekCount:i.fixedWeekCount,dateEnv:i.dateEnv})}};cZe=':root{--fc-daygrid-event-dot-width:8px}.fc-daygrid-day-events:after,.fc-daygrid-day-events:before,.fc-daygrid-day-frame:after,.fc-daygrid-day-frame:before,.fc-daygrid-event-harness:after,.fc-daygrid-event-harness:before{clear:both;content:"";display:table}.fc .fc-daygrid-body{position:relative;z-index:1}.fc .fc-daygrid-day.fc-day-today{background-color:var(--fc-today-bg-color)}.fc .fc-daygrid-day-frame{min-height:100%;position:relative}.fc .fc-daygrid-day-top{display:flex;flex-direction:row-reverse}.fc .fc-day-other .fc-daygrid-day-top{opacity:.3}.fc .fc-daygrid-day-number{padding:4px;position:relative;z-index:4}.fc .fc-daygrid-month-start{font-size:1.1em;font-weight:700}.fc .fc-daygrid-day-events{margin-top:1px}.fc .fc-daygrid-body-balanced .fc-daygrid-day-events{left:0;position:absolute;right:0}.fc .fc-daygrid-body-unbalanced .fc-daygrid-day-events{min-height:2em;position:relative}.fc .fc-daygrid-body-natural .fc-daygrid-day-events{margin-bottom:1em}.fc .fc-daygrid-event-harness{position:relative}.fc .fc-daygrid-event-harness-abs{left:0;position:absolute;right:0;top:0}.fc .fc-daygrid-bg-harness{bottom:0;position:absolute;top:0}.fc .fc-daygrid-day-bg .fc-non-business{z-index:1}.fc .fc-daygrid-day-bg .fc-bg-event{z-index:2}.fc .fc-daygrid-day-bg .fc-highlight{z-index:3}.fc .fc-daygrid-event{margin-top:1px;z-index:6}.fc .fc-daygrid-event.fc-event-mirror{z-index:7}.fc .fc-daygrid-day-bottom{font-size:.85em;margin:0 2px}.fc .fc-daygrid-day-bottom:after,.fc .fc-daygrid-day-bottom:before{clear:both;content:"";display:table}.fc .fc-daygrid-more-link{border-radius:3px;cursor:pointer;line-height:1;margin-top:1px;max-width:100%;overflow:hidden;padding:2px;position:relative;white-space:nowrap;z-index:4}.fc .fc-daygrid-more-link:hover{background-color:rgba(0,0,0,.1)}.fc .fc-daygrid-week-number{background-color:var(--fc-neutral-bg-color);color:var(--fc-neutral-text-color);min-width:1.5em;padding:2px;position:absolute;text-align:center;top:0;z-index:5}.fc .fc-more-popover .fc-popover-body{min-width:220px;padding:10px}.fc-direction-ltr .fc-daygrid-event.fc-event-start,.fc-direction-rtl .fc-daygrid-event.fc-event-end{margin-left:2px}.fc-direction-ltr .fc-daygrid-event.fc-event-end,.fc-direction-rtl .fc-daygrid-event.fc-event-start{margin-right:2px}.fc-direction-ltr .fc-daygrid-more-link{float:left}.fc-direction-ltr .fc-daygrid-week-number{border-radius:0 0 3px 0;left:0}.fc-direction-rtl .fc-daygrid-more-link{float:right}.fc-direction-rtl .fc-daygrid-week-number{border-radius:0 0 0 3px;right:0}.fc-liquid-hack .fc-daygrid-day-frame{position:static}.fc-daygrid-event{border-radius:3px;font-size:var(--fc-small-font-size);position:relative;white-space:nowrap}.fc-daygrid-block-event .fc-event-time{font-weight:700}.fc-daygrid-block-event .fc-event-time,.fc-daygrid-block-event .fc-event-title{padding:1px}.fc-daygrid-dot-event{align-items:center;display:flex;padding:2px 0}.fc-daygrid-dot-event .fc-event-title{flex-grow:1;flex-shrink:1;font-weight:700;min-width:0;overflow:hidden}.fc-daygrid-dot-event.fc-event-mirror,.fc-daygrid-dot-event:hover{background:rgba(0,0,0,.1)}.fc-daygrid-dot-event.fc-event-selected:before{bottom:-10px;top:-10px}.fc-daygrid-event-dot{border:calc(var(--fc-daygrid-event-dot-width)/2) solid var(--fc-event-border-color);border-radius:calc(var(--fc-daygrid-event-dot-width)/2);box-sizing:content-box;height:0;margin:0 4px;width:0}.fc-direction-ltr .fc-daygrid-event .fc-event-time{margin-right:3px}.fc-direction-rtl .fc-daygrid-event .fc-event-time{margin-left:3px}';kc(cZe)});var nxe,axe=y(()=>{Eh();gF();nxe=Wa({name:"@fullcalendar/daygrid",initialView:"dayGridMonth",views:{dayGrid:{component:hF,dateProfileGeneratorClass:iT},dayGridDay:{type:"dayGrid",duration:{days:1}},dayGridWeek:{type:"dayGrid",duration:{weeks:1}},dayGridMonth:{type:"dayGrid",duration:{months:1},fixedWeekCount:!0},dayGridYear:{type:"dayGrid",duration:{years:1}}}})});function cxe(n){let e=["fc-timegrid-slot","fc-timegrid-slot-label",n.isLabeled?"fc-scrollgrid-shrink":"fc-timegrid-slot-minor"];return P(bo.Consumer,null,t=>{if(!n.isLabeled)return P("td",{className:e.join(" "),"data-time":n.isoTimeStr});let{dateEnv:r,options:a,viewApi:i}=t,s=a.slotLabelFormat==null?dZe:Array.isArray(a.slotLabelFormat)?zt(a.slotLabelFormat[0]):zt(a.slotLabelFormat),o={level:0,time:n.time,date:r.toDate(n.date),view:i,text:r.format(n.date,s)};return P(gn,{elTag:"td",elClasses:e,elAttrs:{"data-time":n.isoTimeStr},renderProps:o,generatorName:"slotLabelContent",customGenerator:a.slotLabelContent,defaultGenerator:uZe,classNameGenerator:a.slotLabelClassNames,didMount:a.slotLabelDidMount,willUnmount:a.slotLabelWillUnmount},l=>P("div",{className:"fc-timegrid-slot-label-frame fc-scrollgrid-shrink-frame"},P(l,{elTag:"div",elClasses:["fc-timegrid-slot-label-cushion","fc-scrollgrid-shrink-cushion"]})))})}function uZe(n){return n.text}function fZe(n){return n.text}function hZe(n,e){return e.map(t=>n[t.key])}function QE(n,e){let t=[],r;for(r=0;rr+":"+a,(r,a)=>{let i=bZe(n,r,a),s=sxe(i,t),o=e[r][a];return[Object.assign(Object.assign({},o),{nextLevelNodes:s[0]}),o.thickness+s[1]]});return sxe(e.length?{level:0,lateralStart:0,lateralEnd:e[0].length}:null,t)[0]}function sxe(n,e){if(!n)return[[],0];let{level:t,lateralStart:r,lateralEnd:a}=n,i=r,s=[];for(;ivc(r),(r,a,i)=>{let{nextLevelNodes:s,thickness:o}=r,l=o+i,c=o/l,d,u=[];if(!s.length)d=e;else for(let m of s)if(d===void 0){let f=t(m,a,l);d=f[0],u.push(f[1])}else{let f=t(m,d,0);u.push(f[1])}let p=(d-a)*c;return[d-p,Object.assign(Object.assign({},r),{thickness:p,nextLevelNodes:u})]});return n.map(r=>t(r,0,0)[1])}function SZe(n){let e=[],t=W4((a,i,s)=>vc(a),(a,i,s)=>{let o=Object.assign(Object.assign({},a),{levelCoord:i,stackDepth:s,stackForward:0});return e.push(o),o.stackForward=r(a.nextLevelNodes,i+a.thickness,s+1)+1});function r(a,i,s){let o=0;for(let l of a)o=Math.max(t(l,i,s),o);return o}return r(n,0,0),e}function W4(n,e){let t={};return(...r)=>{let a=n(...r);return a in t?t[a]:t[a]=e(...r)}}function oxe(n,e,t=null,r=0){let a=[];if(t)for(let i=0;i{let l=o.eventRange.instance.instanceId;return P("div",{key:l,style:{visibility:s[l]?"hidden":""}},P(yF,Object.assign({seg:o,isDragging:!1,isResizing:!1,isDateSelecting:!1,isSelected:l===r,isShort:!1},Is(o,e,t))))}))}function N4(n){return n?{top:n.start,bottom:-n.end}:{top:"",bottom:""}}function EZe(n,e){return n.map(t=>e[t.index])}function DZe(n,e){return e.map(t=>n[t.key])}function PZe(n,e){let t=e||n,r=Lx(n,t);return r===null&&(t=n,r=1),{snapDuration:t,snapsPerSlot:r}}function AZe(n,e,t){let r=[];for(let a of n.headerDates)r.push({start:t.add(a,e.slotMinTime),end:t.add(a,e.slotMaxTime)});return r}function MZe(n,e,t,r,a){let i=new Date(0),s=n,o=lt(0),l=t||IZe(r),c=[];for(;Ps(s)=0;e-=1)if(t=lt(lxe[e]),r=Lx(t,n),r!==null&&r>1)return t;return n}function NZe(n,e){let t=new yh(n.renderRange,e);return new vh(t,!1)}var R4,dZe,_4,pZe,mZe,F4,L4,O4,z4,B4,xZe,yF,j4,$4,U4,H4,V4,lxe,vF,RZe,uxe=y(()=>{Dh();GE();gF();R4=class extends Dx{getKeyInfo(){return{allDay:{},timed:{}}}getKeysForDateSpan(e){return e.allDay?["allDay"]:["timed"]}getKeysForEventDef(e){return e.allDay?BV(e)?["timed","allDay"]:["allDay"]:["timed"]}},dZe=zt({hour:"numeric",minute:"2-digit",omitZeroMinute:!0,meridiem:"short"});_4=class extends Tt{render(){return this.props.slatMetas.map(e=>P("tr",{key:e.key},P(cxe,Object.assign({},e))))}},pZe=zt({week:"short"}),mZe=5,F4=class extends On{constructor(){super(...arguments),this.allDaySplitter=new R4,this.headerElRef=sn(),this.rootElRef=sn(),this.scrollerElRef=sn(),this.state={slatCoords:null},this.handleScrollTopRequest=e=>{let t=this.scrollerElRef.current;t&&(t.scrollTop=e)},this.renderHeadAxis=(e,t="")=>{let{options:r}=this.context,{dateProfile:a}=this.props,i=a.renderRange,o=bc(i.start,i.end)===1?Cc(this.context,i.start,"week"):{};return r.weekNumbers&&e==="day"?P(Qx,{elTag:"th",elClasses:["fc-timegrid-axis","fc-scrollgrid-shrink"],elAttrs:{"aria-hidden":!0},date:i.start,defaultFormat:pZe},l=>P("div",{className:["fc-timegrid-axis-frame","fc-scrollgrid-shrink-frame","fc-timegrid-axis-frame-liquid"].join(" "),style:{height:t}},P(l,{elTag:"a",elClasses:["fc-timegrid-axis-cushion","fc-scrollgrid-shrink-cushion","fc-scrollgrid-sync-inner"],elAttrs:o}))):P("th",{"aria-hidden":!0,className:"fc-timegrid-axis"},P("div",{className:"fc-timegrid-axis-frame",style:{height:t}}))},this.renderTableRowAxis=e=>{let{options:t,viewApi:r}=this.context,a={text:t.allDayText,view:r};return P(gn,{elTag:"td",elClasses:["fc-timegrid-axis","fc-scrollgrid-shrink"],elAttrs:{"aria-hidden":!0},renderProps:a,generatorName:"allDayContent",customGenerator:t.allDayContent,defaultGenerator:fZe,classNameGenerator:t.allDayClassNames,didMount:t.allDayDidMount,willUnmount:t.allDayWillUnmount},i=>P("div",{className:["fc-timegrid-axis-frame","fc-scrollgrid-shrink-frame",e==null?" fc-timegrid-axis-frame-liquid":""].join(" "),style:{height:e}},P(i,{elTag:"span",elClasses:["fc-timegrid-axis-cushion","fc-scrollgrid-shrink-cushion","fc-scrollgrid-sync-inner"]})))},this.handleSlatCoords=e=>{this.setState({slatCoords:e})}}renderSimpleLayout(e,t,r){let{context:a,props:i}=this,s=[],o=xh(a.options);return e&&s.push({type:"header",key:"header",isSticky:o,chunk:{elRef:this.headerElRef,tableClassName:"fc-col-header",rowContent:e}}),t&&(s.push({type:"body",key:"all-day",chunk:{content:t}}),s.push({type:"body",key:"all-day-divider",outerContent:P("tr",{role:"presentation",className:"fc-scrollgrid-section"},P("td",{className:"fc-timegrid-divider "+a.theme.getClass("tableCellShaded")}))})),s.push({type:"body",key:"body",liquid:!0,expandRows:!!a.options.expandRows,chunk:{scrollerElRef:this.scrollerElRef,content:r}}),P(As,{elRef:this.rootElRef,elClasses:["fc-timegrid"],viewSpec:a.viewSpec},P(Up,{liquid:!i.isHeightAuto&&!i.forPrint,collapsibleWidth:i.forPrint,cols:[{width:"shrink"}],sections:s}))}renderHScrollLayout(e,t,r,a,i,s,o){let l=this.context.pluginHooks.scrollGridImpl;if(!l)throw new Error("No ScrollGrid implementation");let{context:c,props:d}=this,u=!d.forPrint&&xh(c.options),p=!d.forPrint&&Yx(c.options),m=[];e&&m.push({type:"header",key:"header",isSticky:u,syncRowHeights:!0,chunks:[{key:"axis",rowContent:h=>P("tr",{role:"presentation"},this.renderHeadAxis("day",h.rowSyncHeights[0]))},{key:"cols",elRef:this.headerElRef,tableClassName:"fc-col-header",rowContent:e}]}),t&&(m.push({type:"body",key:"all-day",syncRowHeights:!0,chunks:[{key:"axis",rowContent:h=>P("tr",{role:"presentation"},this.renderTableRowAxis(h.rowSyncHeights[0]))},{key:"cols",content:t}]}),m.push({key:"all-day-divider",type:"body",outerContent:P("tr",{role:"presentation",className:"fc-scrollgrid-section"},P("td",{colSpan:2,className:"fc-timegrid-divider "+c.theme.getClass("tableCellShaded")}))}));let f=c.options.nowIndicator;return m.push({type:"body",key:"body",liquid:!0,expandRows:!!c.options.expandRows,chunks:[{key:"axis",content:h=>P("div",{className:"fc-timegrid-axis-chunk"},P("table",{"aria-hidden":!0,style:{height:h.expandRows?h.clientHeight:""}},h.tableColGroupNode,P("tbody",null,P(_4,{slatMetas:s}))),P("div",{className:"fc-timegrid-now-indicator-container"},P($i,{unit:f?"minute":"day"},g=>{let v=f&&o&&o.safeComputeTop(g);return typeof v=="number"?P(Kx,{elClasses:["fc-timegrid-now-indicator-arrow"],elStyle:{top:v},isAxis:!0,date:g}):null})))},{key:"cols",scrollerElRef:this.scrollerElRef,content:r}]}),p&&m.push({key:"footer",type:"footer",isSticky:!0,chunks:[{key:"axis",content:Tk},{key:"cols",content:Tk}]}),P(As,{elRef:this.rootElRef,elClasses:["fc-timegrid"],viewSpec:c.viewSpec},P(l,{liquid:!d.isHeightAuto&&!d.forPrint,forPrint:d.forPrint,collapsibleWidth:!1,colGroups:[{width:"shrink",cols:[{width:"shrink"}]},{cols:[{span:a,minWidth:i}]}],sections:m}))}getAllDayMaxEventProps(){let{dayMaxEvents:e,dayMaxEventRows:t}=this.context.options;return(e===!0||t===!0)&&(e=void 0,t=mZe),{dayMaxEvents:e,dayMaxEventRows:t}}};L4=class{constructor(e,t,r){this.positions=e,this.dateProfile=t,this.slotDuration=r}safeComputeTop(e){let{dateProfile:t}=this;if(ko(t.currentRange,e)){let r=nr(e),a=e.valueOf()-r.valueOf();if(a>=Ps(t.slotMinTime)&&a{let o={time:i.time,date:t.dateEnv.toDate(i.date),view:t.viewApi};return P("tr",{key:i.key,ref:a.createRef(i.key)},e.axis&&P(cxe,Object.assign({},i)),P(gn,{elTag:"td",elClasses:["fc-timegrid-slot","fc-timegrid-slot-lane",!i.isLabeled&&"fc-timegrid-slot-minor"],elAttrs:{"data-time":i.isoTimeStr},renderProps:o,generatorName:"slotLaneContent",customGenerator:r.slotLaneContent,classNameGenerator:r.slotLaneClassNames,didMount:r.slotLaneDidMount,willUnmount:r.slotLaneWillUnmount}))}))}},z4=class extends Tt{constructor(){super(...arguments),this.rootElRef=sn(),this.slatElRefs=new Ui}render(){let{props:e,context:t}=this;return P("div",{ref:this.rootElRef,className:"fc-timegrid-slots"},P("table",{"aria-hidden":!0,className:t.theme.getClass("table"),style:{minWidth:e.tableMinWidth,width:e.clientWidth,height:e.minHeight}},e.tableColGroupNode,P(O4,{slatElRefs:this.slatElRefs,axis:e.axis,slatMetas:e.slatMetas})))}componentDidMount(){this.updateSizing()}componentDidUpdate(){this.updateSizing()}componentWillUnmount(){this.props.onCoords&&this.props.onCoords(null)}updateSizing(){let{context:e,props:t}=this;t.onCoords&&t.clientWidth!==null&&this.rootElRef.current.offsetHeight&&t.onCoords(new L4(new gl(this.rootElRef.current,hZe(this.slatElRefs.currentMap,t.slatMetas),!1,!0),this.props.dateProfile,e.options.slotDuration))}};B4=class extends Tt{render(){let{props:e}=this;return P(bh,{elClasses:["fc-timegrid-more-link"],elStyle:{top:e.top,bottom:e.bottom},allDayDate:null,moreCnt:e.hiddenSegs.length,allSegs:e.hiddenSegs,hiddenSegs:e.hiddenSegs,extraDateSpan:e.extraDateSpan,dateProfile:e.dateProfile,todayRange:e.todayRange,popoverContent:()=>dxe(e.hiddenSegs,e),defaultGenerator:gZe,forceTimed:!0},t=>P(t,{elTag:"div",elClasses:["fc-timegrid-more-link-inner","fc-sticky"]}))}};xZe=zt({hour:"numeric",minute:"2-digit",meridiem:!1}),yF=class extends Tt{render(){return P(Hp,Object.assign({},this.props,{elClasses:["fc-timegrid-event","fc-v-event",this.props.isShort&&"fc-timegrid-event-short"],defaultTimeFormat:xZe}))}},j4=class extends Tt{constructor(){super(...arguments),this.sortEventSegs=Ae(Sh)}render(){let{props:e,context:t}=this,{options:r}=t,a=r.selectMirror,i=e.eventDrag&&e.eventDrag.segs||e.eventResize&&e.eventResize.segs||a&&e.dateSelectionSegs||[],s=e.eventDrag&&e.eventDrag.affectedInstances||e.eventResize&&e.eventResize.affectedInstances||{},o=this.sortEventSegs(e.fgEventSegs,r.eventOrder);return P(Vp,{elTag:"td",elRef:e.elRef,elClasses:["fc-timegrid-col",...e.extraClassNames||[]],elAttrs:Object.assign({role:"gridcell"},e.extraDataAttrs),date:e.date,dateProfile:e.dateProfile,todayRange:e.todayRange,extraRenderProps:e.extraRenderProps},l=>P("div",{className:"fc-timegrid-col-frame"},P("div",{className:"fc-timegrid-col-bg"},this.renderFillSegs(e.businessHourSegs,"non-business"),this.renderFillSegs(e.bgEventSegs,"bg-event"),this.renderFillSegs(e.dateSelectionSegs,"highlight")),P("div",{className:"fc-timegrid-col-events"},this.renderFgSegs(o,s,!1,!1,!1)),P("div",{className:"fc-timegrid-col-events"},this.renderFgSegs(i,{},!!e.eventDrag,!!e.eventResize,!!a,"mirror")),P("div",{className:"fc-timegrid-now-indicator-container"},this.renderNowIndicator(e.nowIndicatorSegs)),bk(r)&&P(l,{elTag:"div",elClasses:["fc-timegrid-col-misc"]})))}renderFgSegs(e,t,r,a,i,s){let{props:o}=this;return o.forPrint?dxe(e,o):this.renderPositionedFgSegs(e,t,r,a,i,s)}renderPositionedFgSegs(e,t,r,a,i,s){let{eventMaxStack:o,eventShortHeight:l,eventOrderStrict:c,eventMinHeight:d}=this.context.options,{date:u,slatCoords:p,eventSelection:m,todayRange:f,nowDate:h}=this.props,g=r||a||i,v=oxe(e,u,p,d),{segPlacements:k,hiddenGroups:T}=CZe(e,v,c,o);return P(Ot,null,this.renderHiddenGroups(T,e),k.map(b=>{let{seg:w,rect:S}=b,C=w.eventRange.instance.instanceId,x=g||!!(!t[C]&&S),E=N4(S&&S.span),_=!g&&S?this.computeSegHStyle(S):{left:0,right:0},F=!!S&&S.stackForward>0,I=!!S&&S.span.end-S.span.start{let u=N4(d.span),p=EZe(d.entries,t);return P(B4,{key:qN(nR(p)),hiddenSegs:p,top:u.top,bottom:u.bottom,extraDateSpan:r,dateProfile:a,todayRange:i,nowDate:s,eventSelection:o,eventDrag:l,eventResize:c})}))}renderFillSegs(e,t){let{props:r,context:a}=this,s=oxe(e,r.date,r.slatCoords,a.options.eventMinHeight).map((o,l)=>{let c=e[l];return P("div",{key:$x(c.eventRange),className:"fc-timegrid-bg-harness",style:N4(o)},t==="bg-event"?P(Th,Object.assign({seg:c},Is(c,r.todayRange,r.nowDate))):Zx(t))});return P(Ot,null,s)}renderNowIndicator(e){let{slatCoords:t,date:r}=this.props;return t?e.map((a,i)=>P(Kx,{key:i,elClasses:["fc-timegrid-now-indicator-line"],elStyle:{top:t.computeDateTop(a.start,r)},isAxis:!1,date:r})):null}computeSegHStyle(e){let{isRtl:t,options:r}=this.context,a=r.slotEventOverlap,i=e.levelCoord,s=e.levelCoord+e.thickness,o,l;a&&(s=Math.min(1,i+(s-i)*2)),t?(o=1-s,l=i):(o=i,l=1-s);let c={zIndex:e.stackDepth+1,left:o*100+"%",right:l*100+"%"};return a&&!e.stackForward&&(c[t?"marginLeft":"marginRight"]=20),c}};$4=class extends Tt{constructor(){super(...arguments),this.splitFgEventSegs=Ae(QE),this.splitBgEventSegs=Ae(QE),this.splitBusinessHourSegs=Ae(QE),this.splitNowIndicatorSegs=Ae(QE),this.splitDateSelectionSegs=Ae(QE),this.splitEventDrag=Ae(ixe),this.splitEventResize=Ae(ixe),this.rootElRef=sn(),this.cellElRefs=new Ui}render(){let{props:e,context:t}=this,r=t.options.nowIndicator&&e.slatCoords&&e.slatCoords.safeComputeTop(e.nowDate),a=e.cells.length,i=this.splitFgEventSegs(e.fgEventSegs,a),s=this.splitBgEventSegs(e.bgEventSegs,a),o=this.splitBusinessHourSegs(e.businessHourSegs,a),l=this.splitNowIndicatorSegs(e.nowIndicatorSegs,a),c=this.splitDateSelectionSegs(e.dateSelectionSegs,a),d=this.splitEventDrag(e.eventDrag,a),u=this.splitEventResize(e.eventResize,a);return P("div",{className:"fc-timegrid-cols",ref:this.rootElRef},P("table",{role:"presentation",style:{minWidth:e.tableMinWidth,width:e.clientWidth}},e.tableColGroupNode,P("tbody",{role:"presentation"},P("tr",{role:"row"},e.axis&&P("td",{"aria-hidden":!0,className:"fc-timegrid-col fc-timegrid-axis"},P("div",{className:"fc-timegrid-col-frame"},P("div",{className:"fc-timegrid-now-indicator-container"},typeof r=="number"&&P(Kx,{elClasses:["fc-timegrid-now-indicator-arrow"],elStyle:{top:r},isAxis:!0,date:e.nowDate})))),e.cells.map((p,m)=>P(j4,{key:p.key,elRef:this.cellElRefs.createRef(p.key),dateProfile:e.dateProfile,date:p.date,nowDate:e.nowDate,todayRange:e.todayRange,extraRenderProps:p.extraRenderProps,extraDataAttrs:p.extraDataAttrs,extraClassNames:p.extraClassNames,extraDateSpan:p.extraDateSpan,fgEventSegs:i[m],bgEventSegs:s[m],businessHourSegs:o[m],nowIndicatorSegs:l[m],dateSelectionSegs:c[m],eventDrag:d[m],eventResize:u[m],slatCoords:e.slatCoords,eventSelection:e.eventSelection,forPrint:e.forPrint}))))))}componentDidMount(){this.updateCoords()}componentDidUpdate(){this.updateCoords()}updateCoords(){let{props:e}=this;e.onColCoords&&e.clientWidth!==null&&e.onColCoords(new gl(this.rootElRef.current,DZe(this.cellElRefs.currentMap,e.cells),!0,!1))}};U4=class extends On{constructor(){super(...arguments),this.processSlotOptions=Ae(PZe),this.state={slatCoords:null},this.handleRootEl=e=>{e?this.context.registerInteractiveComponent(this,{el:e,isHitComboAllowed:this.props.isHitComboAllowed}):this.context.unregisterInteractiveComponent(this)},this.handleScrollRequest=e=>{let{onScrollTopRequest:t}=this.props,{slatCoords:r}=this.state;if(t&&r){if(e.time){let a=r.computeTimeTop(e.time);a=Math.ceil(a),a&&(a+=1),t(a)}return!0}return!1},this.handleColCoords=e=>{this.colCoords=e},this.handleSlatCoords=e=>{this.setState({slatCoords:e}),this.props.onSlatCoords&&this.props.onSlatCoords(e)}}render(){let{props:e,state:t}=this;return P("div",{className:"fc-timegrid-body",ref:this.handleRootEl,style:{width:e.clientWidth,minWidth:e.tableMinWidth}},P(z4,{axis:e.axis,dateProfile:e.dateProfile,slatMetas:e.slatMetas,clientWidth:e.clientWidth,minHeight:e.expandRows?e.clientHeight:"",tableMinWidth:e.tableMinWidth,tableColGroupNode:e.axis?e.tableColGroupNode:null,onCoords:this.handleSlatCoords}),P($4,{cells:e.cells,axis:e.axis,dateProfile:e.dateProfile,businessHourSegs:e.businessHourSegs,bgEventSegs:e.bgEventSegs,fgEventSegs:e.fgEventSegs,dateSelectionSegs:e.dateSelectionSegs,eventSelection:e.eventSelection,eventDrag:e.eventDrag,eventResize:e.eventResize,todayRange:e.todayRange,nowDate:e.nowDate,nowIndicatorSegs:e.nowIndicatorSegs,clientWidth:e.clientWidth,tableMinWidth:e.tableMinWidth,tableColGroupNode:e.tableColGroupNode,slatCoords:t.slatCoords,onColCoords:this.handleColCoords,forPrint:e.forPrint}))}componentDidMount(){this.scrollResponder=this.context.createScrollResponder(this.handleScrollRequest)}componentDidUpdate(e){this.scrollResponder.update(e.dateProfile!==this.props.dateProfile)}componentWillUnmount(){this.scrollResponder.detach()}queryHit(e,t){let{dateEnv:r,options:a}=this.context,{colCoords:i}=this,{dateProfile:s}=this.props,{slatCoords:o}=this.state,{snapDuration:l,snapsPerSlot:c}=this.processSlotOptions(this.props.slotDuration,a.snapDuration),d=i.leftToIndex(e),u=o.positions.topToIndex(t);if(d!=null&&u!=null){let p=this.props.cells[d],m=o.positions.tops[u],f=o.positions.getHeight(u),h=(t-m)/f,g=Math.floor(h*c),v=u*c+g,k=this.props.cells[d].date,T=Fx(s.slotMinTime,kV(l,v)),b=r.add(k,T),w=r.add(b,l);return{dateProfile:s,dateSpan:Object.assign({range:{start:b,end:w},allDay:!1},p.extraDateSpan),dayEl:i.els[d],rect:{left:i.lefts[d],right:i.rights[d],top:m,bottom:m+f},layer:0}}return null}};H4=class extends kh{sliceRange(e,t){let r=[];for(let a=0;aP(U4,Object.assign({ref:this.timeColsRef},this.slicer.sliceProps(e,r,null,t,o),{forPrint:e.forPrint,axis:e.axis,dateProfile:r,slatMetas:e.slatMetas,slotDuration:e.slotDuration,cells:a.cells[0],tableColGroupNode:e.tableColGroupNode,tableMinWidth:e.tableMinWidth,clientWidth:e.clientWidth,clientHeight:e.clientHeight,expandRows:e.expandRows,nowDate:l,nowIndicatorSegs:i&&this.slicer.sliceNowDate(l,r,s,t,o),todayRange:c,onScrollTopRequest:e.onScrollTopRequest,onSlatCoords:e.onSlatCoords})))}};lxe=[{hours:1},{minutes:30},{minutes:15},{seconds:30},{seconds:15}];vF=class extends F4{constructor(){super(...arguments),this.buildTimeColsModel=Ae(NZe),this.buildSlatMetas=Ae(MZe)}render(){let{options:e,dateEnv:t,dateProfileGenerator:r}=this.context,{props:a}=this,{dateProfile:i}=a,s=this.buildTimeColsModel(i,r),o=this.allDaySplitter.splitProps(a),l=this.buildSlatMetas(i.slotMinTime,i.slotMaxTime,e.slotLabelInterval,e.slotDuration,t),{dayMinWidth:c}=e,d=!c,u=c,p=e.dayHeaders&&P(ru,{dates:s.headerDates,dateProfile:i,datesRepDistinctDays:!0,renderIntro:d?this.renderHeadAxis:null}),m=e.allDaySlot!==!1&&(h=>P(ZE,Object.assign({},o.allDay,{dateProfile:i,dayTableModel:s,nextDayThreshold:e.nextDayThreshold,tableMinWidth:h.tableMinWidth,colGroupNode:h.tableColGroupNode,renderRowIntro:d?this.renderTableRowAxis:null,showWeekNumbers:!1,expandRows:!1,headerAlignElRef:this.headerElRef,clientWidth:h.clientWidth,clientHeight:h.clientHeight,forPrint:a.forPrint},this.getAllDayMaxEventProps()))),f=h=>P(V4,Object.assign({},o.timed,{dayTableModel:s,dateProfile:i,axis:d,slotDuration:e.slotDuration,slatMetas:l,forPrint:a.forPrint,tableColGroupNode:h.tableColGroupNode,tableMinWidth:h.tableMinWidth,clientWidth:h.clientWidth,clientHeight:h.clientHeight,onSlatCoords:this.handleSlatCoords,expandRows:h.expandRows,onScrollTopRequest:this.handleScrollTopRequest}));return u?this.renderHScrollLayout(p,m,f,s.colCnt,c,l,this.state.slatCoords):this.renderSimpleLayout(p,m,f)}};RZe='.fc-v-event{background-color:var(--fc-event-bg-color);border:1px solid var(--fc-event-border-color);display:block}.fc-v-event .fc-event-main{color:var(--fc-event-text-color);height:100%}.fc-v-event .fc-event-main-frame{display:flex;flex-direction:column;height:100%}.fc-v-event .fc-event-time{flex-grow:0;flex-shrink:0;max-height:100%;overflow:hidden}.fc-v-event .fc-event-title-container{flex-grow:1;flex-shrink:1;min-height:0}.fc-v-event .fc-event-title{bottom:0;max-height:100%;overflow:hidden;top:0}.fc-v-event:not(.fc-event-start){border-top-left-radius:0;border-top-right-radius:0;border-top-width:0}.fc-v-event:not(.fc-event-end){border-bottom-left-radius:0;border-bottom-right-radius:0;border-bottom-width:0}.fc-v-event.fc-event-selected:before{left:-10px;right:-10px}.fc-v-event .fc-event-resizer-start{cursor:n-resize}.fc-v-event .fc-event-resizer-end{cursor:s-resize}.fc-v-event:not(.fc-event-selected) .fc-event-resizer{height:var(--fc-event-resizer-thickness);left:0;right:0}.fc-v-event:not(.fc-event-selected) .fc-event-resizer-start{top:calc(var(--fc-event-resizer-thickness)/-2)}.fc-v-event:not(.fc-event-selected) .fc-event-resizer-end{bottom:calc(var(--fc-event-resizer-thickness)/-2)}.fc-v-event.fc-event-selected .fc-event-resizer{left:50%;margin-left:calc(var(--fc-event-resizer-dot-total-width)/-2)}.fc-v-event.fc-event-selected .fc-event-resizer-start{top:calc(var(--fc-event-resizer-dot-total-width)/-2)}.fc-v-event.fc-event-selected .fc-event-resizer-end{bottom:calc(var(--fc-event-resizer-dot-total-width)/-2)}.fc .fc-timegrid .fc-daygrid-body{z-index:2}.fc .fc-timegrid-divider{padding:0 0 2px}.fc .fc-timegrid-body{min-height:100%;position:relative;z-index:1}.fc .fc-timegrid-axis-chunk{position:relative}.fc .fc-timegrid-axis-chunk>table,.fc .fc-timegrid-slots{position:relative;z-index:1}.fc .fc-timegrid-slot{border-bottom:0;height:1.5em}.fc .fc-timegrid-slot:empty:before{content:"\\00a0"}.fc .fc-timegrid-slot-minor{border-top-style:dotted}.fc .fc-timegrid-slot-label-cushion{display:inline-block;white-space:nowrap}.fc .fc-timegrid-slot-label{vertical-align:middle}.fc .fc-timegrid-axis-cushion,.fc .fc-timegrid-slot-label-cushion{padding:0 4px}.fc .fc-timegrid-axis-frame-liquid{height:100%}.fc .fc-timegrid-axis-frame{align-items:center;display:flex;justify-content:flex-end;overflow:hidden}.fc .fc-timegrid-axis-cushion{flex-shrink:0;max-width:60px}.fc-direction-ltr .fc-timegrid-slot-label-frame{text-align:right}.fc-direction-rtl .fc-timegrid-slot-label-frame{text-align:left}.fc-liquid-hack .fc-timegrid-axis-frame-liquid{bottom:0;height:auto;left:0;position:absolute;right:0;top:0}.fc .fc-timegrid-col.fc-day-today{background-color:var(--fc-today-bg-color)}.fc .fc-timegrid-col-frame{min-height:100%;position:relative}.fc-media-screen.fc-liquid-hack .fc-timegrid-col-frame{bottom:0;height:auto;left:0;position:absolute;right:0;top:0}.fc-media-screen .fc-timegrid-cols{bottom:0;left:0;position:absolute;right:0;top:0}.fc-media-screen .fc-timegrid-cols>table{height:100%}.fc-media-screen .fc-timegrid-col-bg,.fc-media-screen .fc-timegrid-col-events,.fc-media-screen .fc-timegrid-now-indicator-container{left:0;position:absolute;right:0;top:0}.fc .fc-timegrid-col-bg{z-index:2}.fc .fc-timegrid-col-bg .fc-non-business{z-index:1}.fc .fc-timegrid-col-bg .fc-bg-event{z-index:2}.fc .fc-timegrid-col-bg .fc-highlight{z-index:3}.fc .fc-timegrid-bg-harness{left:0;position:absolute;right:0}.fc .fc-timegrid-col-events{z-index:3}.fc .fc-timegrid-now-indicator-container{bottom:0;overflow:hidden}.fc-direction-ltr .fc-timegrid-col-events{margin:0 2.5% 0 2px}.fc-direction-rtl .fc-timegrid-col-events{margin:0 2px 0 2.5%}.fc-timegrid-event-harness{position:absolute}.fc-timegrid-event-harness>.fc-timegrid-event{bottom:0;left:0;position:absolute;right:0;top:0}.fc-timegrid-event-harness-inset .fc-timegrid-event,.fc-timegrid-event.fc-event-mirror,.fc-timegrid-more-link{box-shadow:0 0 0 1px var(--fc-page-bg-color)}.fc-timegrid-event,.fc-timegrid-more-link{border-radius:3px;font-size:var(--fc-small-font-size)}.fc-timegrid-event{margin-bottom:1px}.fc-timegrid-event .fc-event-main{padding:1px 1px 0}.fc-timegrid-event .fc-event-time{font-size:var(--fc-small-font-size);margin-bottom:1px;white-space:nowrap}.fc-timegrid-event-short .fc-event-main-frame{flex-direction:row;overflow:hidden}.fc-timegrid-event-short .fc-event-time:after{content:"\\00a0-\\00a0"}.fc-timegrid-event-short .fc-event-title{font-size:var(--fc-small-font-size)}.fc-timegrid-more-link{background:var(--fc-more-link-bg-color);color:var(--fc-more-link-text-color);cursor:pointer;margin-bottom:1px;position:absolute;z-index:9999}.fc-timegrid-more-link-inner{padding:3px 2px;top:0}.fc-direction-ltr .fc-timegrid-more-link{right:0}.fc-direction-rtl .fc-timegrid-more-link{left:0}.fc .fc-timegrid-now-indicator-arrow,.fc .fc-timegrid-now-indicator-line{pointer-events:none}.fc .fc-timegrid-now-indicator-line{border-color:var(--fc-now-indicator-color);border-style:solid;border-width:1px 0 0;left:0;position:absolute;right:0;z-index:4}.fc .fc-timegrid-now-indicator-arrow{border-color:var(--fc-now-indicator-color);border-style:solid;margin-top:-5px;position:absolute;z-index:4}.fc-direction-ltr .fc-timegrid-now-indicator-arrow{border-bottom-color:transparent;border-top-color:transparent;border-width:5px 0 5px 6px;left:0}.fc-direction-rtl .fc-timegrid-now-indicator-arrow{border-bottom-color:transparent;border-top-color:transparent;border-width:5px 6px 5px 0;right:0}';kc(RZe)});var _Ze,pxe,mxe=y(()=>{Eh();uxe();_Ze={allDaySlot:Boolean},pxe=Wa({name:"@fullcalendar/timegrid",initialView:"timeGridWeek",optionRefiners:_Ze,views:{timeGrid:{component:vF,usesMinMaxTime:!0,allDaySlot:!0,slotDuration:"00:30:00",slotEventOverlap:!0},timeGridDay:{type:"timeGrid",duration:{days:1}},timeGridWeek:{type:"timeGrid",duration:{weeks:1}}}})});function FZe(n){return P(Ot,null,n.text&&P("a",Object.assign({id:n.textId,className:"fc-list-day-text"},n.navLinkAttrs),n.text),n.sideText&&P("a",Object.assign({"aria-hidden":!0,className:"fc-list-day-side-text"},n.sideNavLinkAttrs),n.sideText))}function OZe(n,e){let t=yk(n,e);return P("a",Object.assign({},t),n.eventRange.def.title)}function zZe(n,e,t,r,a){let{options:i}=t;if(i.displayEventTime!==!1){let s=n.eventRange.def,o=n.eventRange.instance,l=!1,c;if(s.allDay?l=!0:IV(n.eventRange.range)?n.isStart?c=Gp(n,e,t,null,null,o.range.start,n.end):n.isEnd?c=Gp(n,e,t,null,null,n.start,o.range.end):l=!0:c=Gp(n,e,t),l){let d={text:t.options.allDayText,view:t.viewApi};return P(gn,{elTag:"td",elClasses:["fc-list-event-time"],elAttrs:{headers:`${r} ${a}`},renderProps:d,generatorName:"allDayContent",customGenerator:i.allDayContent,defaultGenerator:BZe,classNameGenerator:i.allDayClassNames,didMount:i.allDayDidMount,willUnmount:i.allDayWillUnmount})}return P("td",{className:"fc-list-event-time"},c)}return null}function BZe(n){return n.text}function jZe(n){return n.text}function $Ze(n){let e=nr(n.renderRange.start),t=n.renderRange.end,r=[],a=[];for(;e{Dh();GE();q4=class extends Tt{constructor(){super(...arguments),this.state={textId:Hi()}}render(){let{theme:e,dateEnv:t,options:r,viewApi:a}=this.context,{cellId:i,dayDate:s,todayRange:o}=this.props,{textId:l}=this.state,c=Hx(s,o),d=r.listDayFormat?t.format(s,r.listDayFormat):"",u=r.listDaySideFormat?t.format(s,r.listDaySideFormat):"",p=Object.assign({date:t.toDate(s),view:a,textId:l,text:d,sideText:u,navLinkAttrs:Cc(this.context,s),sideNavLinkAttrs:Cc(this.context,s,"day",!1)},c);return P(gn,{elTag:"tr",elClasses:["fc-list-day",...vk(c,e)],elAttrs:{"data-date":Wp(s)},renderProps:p,generatorName:"dayHeaderContent",customGenerator:r.dayHeaderContent,defaultGenerator:FZe,classNameGenerator:r.dayHeaderClassNames,didMount:r.dayHeaderDidMount,willUnmount:r.dayHeaderWillUnmount},m=>P("th",{scope:"colgroup",colSpan:3,id:i,"aria-labelledby":l},P(m,{elTag:"div",elClasses:["fc-list-day-cushion",e.getClass("tableCellShaded")]})))}};LZe=zt({hour:"numeric",minute:"2-digit",meridiem:"short"}),G4=class extends Tt{render(){let{props:e,context:t}=this,{options:r}=t,{seg:a,timeHeaderId:i,eventHeaderId:s,dateHeaderId:o}=e,l=r.eventTimeFormat||LZe;return P(nu,Object.assign({},e,{elTag:"tr",elClasses:["fc-list-event",a.eventRange.def.url&&"fc-event-forced-url"],defaultGenerator:()=>OZe(a,t),seg:a,timeText:"",disableDragging:!0,disableResizing:!0}),(c,d)=>P(Ot,null,zZe(a,l,t,i,o),P("td",{"aria-hidden":!0,className:"fc-list-event-graphic"},P("span",{className:"fc-list-event-dot",style:{borderColor:d.borderColor||d.backgroundColor}})),P(c,{elTag:"td",elClasses:["fc-list-event-title"],elAttrs:{headers:`${s} ${o}`}})))}};kF=class extends On{constructor(){super(...arguments),this.computeDateVars=Ae($Ze),this.eventStoreToSegs=Ae(this._eventStoreToSegs),this.state={timeHeaderId:Hi(),eventHeaderId:Hi(),dateHeaderIdRoot:Hi()},this.setRootEl=e=>{e?this.context.registerInteractiveComponent(this,{el:e}):this.context.unregisterInteractiveComponent(this)}}render(){let{props:e,context:t}=this,{dayDates:r,dayRanges:a}=this.computeDateVars(e.dateProfile),i=this.eventStoreToSegs(e.eventStore,e.eventUiBases,a);return P(As,{elRef:this.setRootEl,elClasses:["fc-list",t.theme.getClass("table"),t.options.stickyHeaderDates!==!1?"fc-list-sticky":""],viewSpec:t.viewSpec},P(lk,{liquid:!e.isHeightAuto,overflowX:e.isHeightAuto?"visible":"hidden",overflowY:e.isHeightAuto?"visible":"auto"},i.length>0?this.renderSegList(i,r):this.renderEmptyMessage()))}renderEmptyMessage(){let{options:e,viewApi:t}=this.context,r={text:e.noEventsText,view:t};return P(gn,{elTag:"div",elClasses:["fc-list-empty"],renderProps:r,generatorName:"noEventsContent",customGenerator:e.noEventsContent,defaultGenerator:jZe,classNameGenerator:e.noEventsClassNames,didMount:e.noEventsDidMount,willUnmount:e.noEventsWillUnmount},a=>P(a,{elTag:"div",elClasses:["fc-list-empty-cushion"]}))}renderSegList(e,t){let{theme:r,options:a}=this.context,{timeHeaderId:i,eventHeaderId:s,dateHeaderIdRoot:o}=this.state,l=UZe(e);return P($i,{unit:"day"},(c,d)=>{let u=[];for(let p=0;p{Eh();fxe();Dh();VZe={listDayFormat:hxe,listDaySideFormat:hxe,noEventsClassNames:B,noEventsContent:B,noEventsDidMount:B,noEventsWillUnmount:B};gxe=Wa({name:"@fullcalendar/list",optionRefiners:VZe,views:{list:{component:kF,buttonTextKey:"list",listDayFormat:{month:"long",day:"numeric",year:"numeric"}},listDay:{type:"list",duration:{days:1},listDayFormat:{weekday:"long"}},listWeek:{type:"list",duration:{weeks:1},listDayFormat:{weekday:"long"},listDaySideFormat:{month:"long",day:"numeric",year:"numeric"}},listMonth:{type:"list",duration:{month:1},listDaySideFormat:{weekday:"long"}},listYear:{type:"list",duration:{year:1},listDaySideFormat:{weekday:"long"}}}})});function qZe(n,e,t,r,a){let{start:i,end:s}=e.currentRange,o=i,l=[];for(;o.valueOf(){Eh();gF();Dh();GE();Y4=class extends On{constructor(){super(...arguments),this.buildDayTableModel=Ae(M4),this.slicer=new KE,this.state={labelId:Hi()}}render(){let{props:e,state:t,context:r}=this,{dateProfile:a,forPrint:i}=e,{options:s}=r,o=this.buildDayTableModel(a,r.dateProfileGenerator),l=this.slicer.sliceProps(e,a,s.nextDayThreshold,r,o),c=e.tableWidth!=null?e.tableWidth/s.aspectRatio:null,d=o.cells.length,u=c!=null?c/d:null;return P("div",{ref:e.elRef,"data-date":e.isoDateStr,className:"fc-multimonth-month",style:{width:e.width},role:"grid","aria-labelledby":t.labelId},P("div",{className:"fc-multimonth-header",style:{marginBottom:u},role:"presentation"},P("div",{className:"fc-multimonth-title",id:t.labelId},r.dateEnv.format(e.dateProfile.currentRange.start,e.titleFormat)),P("table",{className:["fc-multimonth-header-table",r.theme.getClass("table")].join(" "),role:"presentation"},P("thead",{role:"rowgroup"},P(ru,{dateProfile:e.dateProfile,dates:o.headerDates,datesRepDistinctDays:!1})))),P("div",{className:["fc-multimonth-daygrid","fc-daygrid","fc-daygrid-body",!i&&"fc-daygrid-body-balanced",i&&"fc-daygrid-body-unbalanced",i&&"fc-daygrid-body-natural"].join(" "),style:{marginTop:-u}},P("table",{className:["fc-multimonth-daygrid-table",r.theme.getClass("table")].join(" "),style:{height:i?"":c},role:"presentation"},P("tbody",{role:"rowgroup"},P(YE,Object.assign({},l,{dateProfile:a,cells:o.cells,eventSelection:e.eventSelection,dayMaxEvents:!i,dayMaxEventRows:!i,showWeekNumbers:s.weekNumbers,clientWidth:e.clientWidth,clientHeight:e.clientHeight,forPrint:i}))))))}},K4=class extends On{constructor(){super(...arguments),this.splitDateProfileByMonth=Ae(qZe),this.buildMonthFormat=Ae(KZe),this.scrollElRef=sn(),this.firstMonthElRef=sn(),this.needsScrollReset=!1,this.handleSizing=e=>{e&&this.updateSize()}}render(){let{context:e,props:t,state:r}=this,{options:a}=e,{clientWidth:i,clientHeight:s}=r,o=r.monthHPadding||0,l=Math.min(i!=null?Math.floor(i/(a.multiMonthMinWidth+o)):1,a.multiMonthMaxColumns)||1,c=100/l+"%",d=i==null?null:i/l-o,u=i!=null&&l===1,p=this.splitDateProfileByMonth(e.dateProfileGenerator,t.dateProfile,e.dateEnv,u?!1:a.fixedWeekCount,a.showNonCurrentDates),m=this.buildMonthFormat(a.multiMonthTitleFormat,p),f=["fc-multimonth",u?"fc-multimonth-singlecol":"fc-multimonth-multicol",d!=null&&d<400?"fc-multimonth-compact":"",t.isHeightAuto?"":"fc-scroller"];return P(As,{elRef:this.scrollElRef,elClasses:f,viewSpec:e.viewSpec},p.map((h,g)=>{let v=pk(h.currentRange.start);return P(Y4,Object.assign({},t,{key:v,isoDateStr:v,elRef:g===0?this.firstMonthElRef:void 0,titleFormat:m,dateProfile:h,width:c,tableWidth:d,clientWidth:i,clientHeight:s}))}))}componentDidMount(){this.updateSize(),this.context.addResizeHandler(this.handleSizing),this.requestScrollReset()}componentDidUpdate(e){Va(e,this.props)||this.handleSizing(!1),e.dateProfile!==this.props.dateProfile?this.requestScrollReset():this.flushScrollReset()}componentWillUnmount(){this.context.removeResizeHandler(this.handleSizing)}updateSize(){let e=this.scrollElRef.current,t=this.firstMonthElRef.current;e&&this.setState({clientWidth:e.clientWidth,clientHeight:e.clientHeight}),t&&e&&this.state.monthHPadding==null&&this.setState({monthHPadding:e.clientWidth-t.firstChild.offsetWidth})}requestScrollReset(){this.needsScrollReset=!0,this.flushScrollReset()}flushScrollReset(){if(this.needsScrollReset&&this.state.monthHPadding!=null){let{currentDate:e}=this.props.dateProfile,t=this.scrollElRef.current,r=t.querySelector(`[data-date="${pk(e)}"]`);t.scrollTop=r.getBoundingClientRect().top-this.firstMonthElRef.current.getBoundingClientRect().top,this.needsScrollReset=!1}}shouldComponentUpdate(){return!0}},WZe=lt(1,"month");GZe=zt({year:"numeric",month:"long"}),YZe=zt({month:"long"});ZZe={multiMonthTitleFormat:zt,multiMonthMaxColumns:Number,multiMonthMinWidth:Number},QZe=".fc .fc-multimonth{border:1px solid var(--fc-border-color);display:flex;flex-wrap:wrap;overflow-x:hidden;overflow-y:auto}.fc .fc-multimonth-title{font-size:1.2em;font-weight:700;padding:1em 0;text-align:center}.fc .fc-multimonth-daygrid{background:var(--fc-page-bg-color)}.fc .fc-multimonth-daygrid-table,.fc .fc-multimonth-header-table{table-layout:fixed;width:100%}.fc .fc-multimonth-daygrid-table{border-top-style:hidden!important}.fc .fc-multimonth-singlecol .fc-multimonth{position:relative}.fc .fc-multimonth-singlecol .fc-multimonth-header{background:var(--fc-page-bg-color);position:relative;top:0;z-index:2}.fc .fc-multimonth-singlecol .fc-multimonth-daygrid{position:relative;z-index:1}.fc .fc-multimonth-singlecol .fc-multimonth-daygrid-table,.fc .fc-multimonth-singlecol .fc-multimonth-header-table{border-left-style:hidden;border-right-style:hidden}.fc .fc-multimonth-singlecol .fc-multimonth-month:last-child .fc-multimonth-daygrid-table{border-bottom-style:hidden}.fc .fc-multimonth-multicol{line-height:1}.fc .fc-multimonth-multicol .fc-multimonth-month{padding:0 1.2em 1.2em}.fc .fc-multimonth-multicol .fc-daygrid-more-link{border:1px solid var(--fc-event-border-color);display:block;float:none;padding:1px}.fc .fc-multimonth-compact{line-height:1}.fc .fc-multimonth-compact .fc-multimonth-daygrid-table,.fc .fc-multimonth-compact .fc-multimonth-header-table{font-size:.9em}.fc-media-screen .fc-multimonth-singlecol .fc-multimonth-header{position:sticky}.fc-media-print .fc-multimonth{overflow:visible}";kc(QZe);vxe=Wa({name:"@fullcalendar/multimonth",initialView:"multiMonthYear",optionRefiners:ZZe,views:{multiMonth:{component:K4,dateProfileGeneratorClass:iT,multiMonthMinWidth:350,multiMonthMaxColumns:3},multiMonthYear:{type:"multiMonth",duration:{years:1},fixedWeekCount:!0,showNonCurrentDates:!1}}})});function Txe(n,e){return(0,_t.moment)(n,e)}function bxe(n){let e=(0,_t.parseYaml)(n);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}var _t,ku,JE,TF,wxe=y(()=>{_t=require("obsidian");SC();co();ku=tt(od());xe();Ll();va();ya();q();JE=M({tag:"Modals/TimeblockInfoModal"});TF=class extends _t.Modal{constructor(t,r,a,i,s,o){super(t);this.selectedAttachments=[];this.keyboardHandler=null;this.plugin=r,this.timeblock={...a},this.originalTimeblock=a,this.eventDate=i,this.timeblockDate=s||ae(i),this.translate=r.i18n.translate.bind(r.i18n),this.onChange=o}async onOpen(){let{contentEl:t}=this;t.empty(),t.addClass("timeblock-info-modal"),this.keyboardHandler=d=>{d.key==="Enter"&&(d.ctrlKey||d.metaKey)&&(d.preventDefault(),this.handleSave())},this.containerEl.addEventListener("keydown",this.keyboardHandler),new _t.Setting(t).setName(this.translate("modals.timeblockInfo.editHeading")).setHeading();let r=t.createDiv({cls:"timeblock-date-display"});r.createEl("strong",{text:this.translate("modals.timeblockInfo.dateTimeLabel")});let a=`${this.eventDate.toLocaleDateString()} from ${this.timeblock.startTime} to ${this.timeblock.endTime}`;r.createSpan({text:a}),new _t.Setting(t).setName(this.translate("modals.timeblockInfo.titleLabel")).setDesc(this.translate("modals.timeblockInfo.titleDesc")).addText(d=>{this.titleInput=d.inputEl,d.setPlaceholder(this.translate("modals.timeblockInfo.titlePlaceholder")).setValue(this.timeblock.title||"").onChange(()=>this.validateForm())}),new _t.Setting(t).setName(this.translate("modals.timeblockInfo.descriptionLabel")).setDesc(this.translate("modals.timeblockInfo.descriptionDesc")).addTextArea(d=>{this.descriptionInput=d.inputEl,d.setPlaceholder(this.translate("modals.timeblockInfo.descriptionPlaceholder")).setValue(this.timeblock.description||""),this.descriptionInput.rows=3}),new _t.Setting(t).setName(this.translate("modals.timeblockInfo.colorLabel")).setDesc(this.translate("modals.timeblockInfo.colorDesc")).addText(d=>{this.colorInput=d.inputEl,d.setPlaceholder(this.translate("modals.timeblockInfo.colorPlaceholder")).setValue(xd(this.timeblock.color||this.plugin.settings.calendarViewSettings.defaultTimeblockColor)),qf(this.colorInput)}),new _t.Setting(t).setName(this.translate("modals.timeblockInfo.attachmentsLabel")).setDesc(this.translate("modals.timeblockInfo.attachmentsDesc")).addButton(d=>{d.setButtonText(this.translate("modals.timeblockInfo.addAttachmentButton")).setTooltip(this.translate("modals.timeblockInfo.addAttachmentTooltip")).onClick(()=>{pp(this.plugin,u=>{u instanceof _t.TAbstractFile&&this.addAttachment(u)},{placeholder:"Search files or type to create new...",filter:"all",sortOrder:this.plugin.settings.calendarViewSettings.timeblockAttachmentSearchOrder})})}).addButton(d=>{d.setButtonText("Add task").setTooltip("Select task").onClick(()=>{this.openTaskSelectorForTitle()})}),this.attachmentsList=t.createDiv({cls:"timeblock-attachments-list"}),await this.initializeAttachments(),this.renderAttachmentsList();let i=t.createDiv({cls:"timeblock-modal-buttons"});i.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),i.classList.add("tn-static-display-flex-75816cae"),i.classList.remove("tn-static-justify-content-center-03c4bb6f","tn-static-justify-content-flex-end-455f8cca"),i.classList.add("tn-static-justify-content-space-between-a562f4fd"),i.classList.remove("tn-static-align-items-baseline-4b95b5c7","tn-static-align-items-flex-start-0486f781"),i.classList.add("tn-static-align-items-center-7c619740"),i.classList.remove("tn-static-font-size-12px-b0cc7e05","tn-static-margin-top-0-5rem-3dc98b5e","tn-static-margin-top-0-d462248a","tn-static-margin-top-12px-91e0f558","tn-static-margin-top-16px-1b0f4999","tn-static-margin-top-1rem-2239d6d5","tn-static-margin-top-30px-2fbbbcd4","tn-static-margin-top-4px-96ad6099","tn-static-margin-top-8px-8a77e5a3","tn-static-margin-top-8px-f4f01e68"),i.classList.add("tn-static-margin-top-20px-a26bda7d"),i.createEl("button",{text:this.translate("modals.timeblockInfo.deleteButton"),cls:"mod-warning timeblock-delete-button"}).addEventListener("click",()=>{this.handleDelete()});let o=i.createDiv({cls:"timeblock-modal-buttons-right"});o.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),o.classList.add("tn-static-display-flex-75816cae"),o.classList.remove("tn-static-display-flex-8bb39979","tn-static-gap-0-5rem-ce2fca4d","tn-static-gap-10px-f3d7ce77","tn-static-gap-12px-ed7b3d87","tn-static-gap-6px-f0abc1db"),o.classList.add("tn-static-gap-8px-33fcd4c3"),o.createEl("button",{text:this.translate("common.cancel")}).addEventListener("click",()=>this.close()),o.createEl("button",{text:this.translate("modals.timeblockInfo.saveButton"),cls:"mod-cta timeblock-save-button"}).addEventListener("click",()=>{this.handleSave()}),this.validateForm(),window.setTimeout(()=>this.titleInput.focus(),50)}validateForm(){var i;let t=this.contentEl.querySelector(".timeblock-save-button");if(!t)return;let a=!!((i=this.titleInput)==null?void 0:i.value.trim());t.disabled=!a,t.style.opacity=a?"1":"0.5"}async initializeAttachments(){if(this.timeblock.attachments)for(let t of this.timeblock.attachments){let r=t.replace(/^\[\[|\]\]$/g,""),a=this.app.vault.getAbstractFileByPath(r);a&&this.selectedAttachments.push(a)}}addAttachment(t){if(this.selectedAttachments.some(r=>r.path===t.path)){new _t.Notice(this.translate("notices.timeblockAttachmentExists",{fileName:t.name}));return}if(this.titleInput&&!this.titleInput.value.trim()){let r=t instanceof _t.TFile?t.basename:t.name;this.titleInput.value=r,this.timeblock.title=r,this.validateForm()}this.selectedAttachments.push(t),this.renderAttachmentsList(),new _t.Notice(this.translate("notices.timeblockAttachmentAdded",{fileName:t.name}))}async openTaskSelectorForTitle(){var t,r,a;try{let s=((a=await((r=(t=this.plugin.cacheManager).getAllTasks)==null?void 0:r.call(t)))!=null?a:[]).filter(o=>!o.archived);if(s.length===0){new _t.Notice("No tasks available to select");return}fn(this.plugin,s,o=>{if(!o)return;this.titleInput.value=o.title||"",this.timeblock.title=o.title||"",this.validateForm();let l=this.app.vault.getAbstractFileByPath(o.path);l&&this.addAttachment(l)},{title:"Select task"})}catch(i){JE.error("Failed to open task selector for timeblock edit:",{category:"persistence",operation:"open-task-selector-timeblock-edit",error:i}),new _t.Notice("Failed to open task selector")}}removeAttachment(t){this.selectedAttachments=this.selectedAttachments.filter(r=>r.path!==t.path),this.renderAttachmentsList(),new _t.Notice(this.translate("notices.timeblockAttachmentRemoved",{fileName:t.name}))}openAttachment(t){t instanceof _t.TFile?this.app.workspace.getLeaf(!1).openFile(t):new _t.Notice(this.translate("notices.timeblockFileTypeNotSupported",{fileName:t.name}))}renderAttachmentsList(){if(this.attachmentsList.empty(),this.selectedAttachments.length===0){let t=this.attachmentsList.createDiv({cls:"timeblock-attachments-empty"});t.textContent="No attachments";return}this.selectedAttachments.forEach(t=>{let r=this.attachmentsList.createDiv({cls:"timeblock-attachment-item"}),a=r.createDiv({cls:"timeblock-attachment-info"});a.classList.remove("tn-static-cursor-grab-dad79857","tn-static-cursor-pointer-2723efcc"),a.classList.add("tn-static-cursor-pointer-3b6a3a65"),(0,_t.setTooltip)(a,"Click to open",{placement:"top"}),a.addEventListener("click",()=>this.openAttachment(t));let i=a.createSpan({cls:"timeblock-attachment-name"});if(i.textContent=t.name,t.path!==t.name){let o=a.createDiv({cls:"timeblock-attachment-path"});o.textContent=t.path}let s=r.createEl("button",{cls:"timeblock-attachment-remove",text:"×"});(0,_t.setTooltip)(s,"Remove attachment",{placement:"top"}),s.addEventListener("click",o=>{o.stopPropagation(),this.removeAttachment(t)})})}async handleSave(){var t;try{let r=this.titleInput.value.trim();if(!r){new _t.Notice(this.translate("notices.timeblockTitleRequired"));return}this.timeblock.title=r,this.timeblock.description=this.descriptionInput.value.trim()||void 0,this.timeblock.color=hr(this.colorInput.value||void 0)||void 0;let a=this.selectedAttachments.map(i=>`[[${i.path}]]`);this.timeblock.attachments=a.length>0?a:void 0,await this.updateTimeblockInDailyNote(),(t=this.onChange)==null||t.call(this),this.plugin.emitter.trigger("data-changed"),new _t.Notice(this.translate("notices.timeblockUpdatedSuccess",{title:r})),this.close()}catch(r){JE.error("Error updating timeblock:",{category:"internal",operation:"updating-timeblock",error:r}),new _t.Notice(this.translate("notices.timeblockUpdateFailed"))}}async updateTimeblockInDailyNote(){if(!(0,ku.appHasDailyNotesPluginLoaded)())throw new Error("Daily Notes plugin is not enabled");let t=this.timeblockDate,r=Txe(t,"YYYY-MM-DD"),a=(0,ku.getAllDailyNotes)(),i=(0,ku.getDailyNote)(r,a);if(!i)throw new Error("Daily note not found");let s=await this.app.vault.read(i),o={},l=s;if(s.startsWith("---")){let u=s.indexOf("---",3);if(u!==-1){let p=s.substring(3,u);l=s.substring(u+3);try{o=bxe(p)}catch(m){JE.error("Error parsing existing frontmatter:",{category:"validation",operation:"parsing-existing-frontmatter",error:m}),o={}}}}if(o.timeblocks&&Array.isArray(o.timeblocks)){let u=o.timeblocks.findIndex(p=>p.id===this.originalTimeblock.id||p.title===this.originalTimeblock.title&&p.startTime===this.originalTimeblock.startTime&&p.endTime===this.originalTimeblock.endTime);if(u>=0)o.timeblocks[u]=this.timeblock;else throw new Error("Timeblock not found in daily note")}else throw new Error("No timeblocks found in daily note");let d=`--- +${(0,_t.stringifyYaml)(o)}---${l}`;await Gs(this.app,i,d)}async handleDelete(){var r;if(await this.showDeleteConfirmation())try{await this.deleteTimeblockFromDailyNote(),(r=this.onChange)==null||r.call(this),this.plugin.emitter.trigger("data-changed"),new _t.Notice(this.translate("notices.timeblockDeletedSuccess",{title:this.timeblock.title})),this.close()}catch(a){JE.error("Error deleting timeblock:",{category:"internal",operation:"deleting-timeblock",error:a}),new _t.Notice(this.translate("notices.timeblockDeleteFailed"))}}async showDeleteConfirmation(){return new Promise(t=>{let r=new _t.Modal(this.app);r.titleEl.setText(this.translate("modals.timeblockInfo.deleteConfirmationTitle"));let a=r.contentEl;a.createEl("p",{text:`Are you sure you want to delete the timeblock "${this.timeblock.title}"?`}),a.createEl("p",{text:"This action cannot be undone.",cls:"mod-warning"});let i=a.createDiv({cls:"modal-button-container"});i.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),i.classList.add("tn-static-display-flex-75816cae"),i.classList.remove("tn-static-justify-content-center-03c4bb6f","tn-static-justify-content-space-between-a562f4fd"),i.classList.add("tn-static-justify-content-flex-end-455f8cca"),i.classList.remove("tn-static-display-flex-8bb39979","tn-static-gap-0-5rem-ce2fca4d","tn-static-gap-10px-f3d7ce77","tn-static-gap-12px-ed7b3d87","tn-static-gap-6px-f0abc1db"),i.classList.add("tn-static-gap-8px-33fcd4c3"),i.classList.remove("tn-static-font-size-12px-b0cc7e05","tn-static-margin-top-0-5rem-3dc98b5e","tn-static-margin-top-0-d462248a","tn-static-margin-top-12px-91e0f558","tn-static-margin-top-16px-1b0f4999","tn-static-margin-top-1rem-2239d6d5","tn-static-margin-top-30px-2fbbbcd4","tn-static-margin-top-4px-96ad6099","tn-static-margin-top-8px-8a77e5a3","tn-static-margin-top-8px-f4f01e68"),i.classList.add("tn-static-margin-top-20px-a26bda7d");let s=i.createEl("button",{text:this.translate("common.cancel")});s.addEventListener("click",()=>{r.close(),t(!1)}),i.createEl("button",{text:"Delete",cls:"mod-warning"}).addEventListener("click",()=>{r.close(),t(!0)}),r.open(),window.setTimeout(()=>s.focus(),50)})}async deleteTimeblockFromDailyNote(){if(!(0,ku.appHasDailyNotesPluginLoaded)())throw new Error("Daily Notes plugin is not enabled");let t=this.timeblockDate,r=Txe(t,"YYYY-MM-DD"),a=(0,ku.getAllDailyNotes)(),i=(0,ku.getDailyNote)(r,a);if(!i)throw new Error("Daily note not found");let s=await this.app.vault.read(i),o={},l=s;if(s.startsWith("---")){let u=s.indexOf("---",3);if(u!==-1){let p=s.substring(3,u);l=s.substring(u+3);try{o=bxe(p)}catch(m){JE.error("Error parsing existing frontmatter:",{category:"validation",operation:"parsing-existing-frontmatter",error:m}),o={}}}}if(o.timeblocks&&Array.isArray(o.timeblocks)){let u=o.timeblocks.findIndex(p=>p.id===this.originalTimeblock.id||p.title===this.originalTimeblock.title&&p.startTime===this.originalTimeblock.startTime&&p.endTime===this.originalTimeblock.endTime);if(u>=0)o.timeblocks.splice(u,1),o.timeblocks.length===0&&delete o.timeblocks;else throw new Error("Timeblock not found in daily note")}else throw new Error("No timeblocks found in daily note");let c=Object.keys(o).length>0?(0,_t.stringifyYaml)(o):"",d=c?`--- +${c}---${l}`:l.trim();await Gs(this.app,i,d)}onClose(){this.keyboardHandler&&(this.containerEl.removeEventListener("keydown",this.keyboardHandler),this.keyboardHandler=null);let{contentEl:t}=this;t.empty()}}});function sT(n,e){if(!e)return;let t=Math.ceil(e/1440),r=st(n),a=new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate()+t));return ae(a)}function Sxe(n,e){if(!n.scheduled)return null;let t=Jt(n.scheduled),r=n.scheduled,a;if(t&&n.timeEstimate){let o=et(r),l=new Date(o.getTime()+n.timeEstimate*60*1e3);a=D(l,"yyyy-MM-dd'T'HH:mm")}else t||(a=sT(r,n.timeEstimate));let i=hr(e.getPriorityColor(n.priority),"var(--color-accent)"),s=Ed(i)?e.getThemeTextColor(!0):i;return{id:`scheduled-${n.path}`,title:n.title,start:r,end:a,allDay:!t,backgroundColor:"transparent",borderColor:i,textColor:s,editable:!0,extendedProps:{taskInfo:n,eventType:"scheduled",isCompleted:e.isCompletedStatus(n.status)}}}function Cxe(n,e){if(!n.due)return null;let t=Jt(n.due),r=n.due,a;if(t){let o=et(r),l=new Date(o.getTime()+1800*1e3);a=D(l,"yyyy-MM-dd'T'HH:mm")}let i=hr(e.getPriorityColor(n.priority),"var(--color-orange)"),s=Ed(i)?e.getThemeTextColor(!0):i;return{id:`due-${n.path}`,title:n.title,start:r,end:a,allDay:!t,backgroundColor:iy(i,.15),borderColor:i,textColor:s,editable:!0,extendedProps:{taskInfo:n,eventType:"due",isCompleted:e.isCompletedStatus(n.status)}}}function xxe(n,e,t){if(!e||!t)return!0;let r=et(n.start),a=n.end?et(n.end):r;return r.getTime()=e.getTime()}function JZe(n,e){if(!n.scheduled||!n.due)return null;let t=et(n.scheduled),r=et(n.due);if(r<=t)return null;let a=new Date(r);a.setDate(a.getDate()+1);let i=hr(e.getPriorityColor(n.priority),"var(--color-accent)"),s=Ed(i)?e.getThemeTextColor(!0):i;return{id:`span-${n.path}`,title:n.title,start:D(t,"yyyy-MM-dd"),end:D(a,"yyyy-MM-dd"),allDay:!0,backgroundColor:iy(i,.2),borderColor:i,textColor:s,editable:!0,extendedProps:{taskInfo:n,eventType:"scheduledToDueSpan",isCompleted:e.isCompletedStatus(n.status)}}}function XZe(n,e,t,r){if(!n.scheduled||!n.due)return[];let a=et(n.scheduled);if(et(n.due)<=a)return[];let s=si(n.scheduled);if(!s)return[];let[o,l]=s.split(":").map(Number),c=et(re(n.scheduled)),d=et(re(n.due)),u=hr(e.getPriorityColor(n.priority),"var(--color-accent)"),p=Ed(u)?e.getThemeTextColor(!0):u,m=e.isCompletedStatus(n.status),f=[];for(let h=new Date(c);h.getTime()<=d.getTime();h.setDate(h.getDate()+1)){let g=new Date(h);g.setHours(o,l,0,0);let v;if(n.timeEstimate){let b=new Date(g.getTime()+n.timeEstimate*60*1e3);v=D(b,"yyyy-MM-dd'T'HH:mm")}let k=D(h,"yyyy-MM-dd"),T={id:`span-${n.path}-${k}`,title:n.title,start:D(g,"yyyy-MM-dd'T'HH:mm"),end:v,allDay:!1,backgroundColor:iy(u,.2),borderColor:u,textColor:p,editable:!0,extendedProps:{taskInfo:n,eventType:"scheduledToDueSpan",isCompleted:m}};xxe(T,t,r)&&f.push(T)}return f}function Exe(n,e,t,r){if(!n.scheduled||!n.due)return[];if(Jt(n.scheduled))return XZe(n,e,t,r);let a=JZe(n,e);return!a||!xxe(a,t,r)?[]:[a]}function eQe(n){return typeof n.endTime=="string"&&n.endTime.length>0}function Dxe(n,e){if(!n.timeEntries)return[];let t=e.isCompletedStatus(n.status);return n.timeEntries.map((r,a)=>({entry:r,index:a})).filter(({entry:r})=>eQe(r)).map(({entry:r,index:a})=>({id:`timeentry-${n.path}-${a}`,title:n.title,start:r.startTime,end:r.endTime,allDay:!1,editable:!0,extendedProps:{taskInfo:n,eventType:"timeEntry",isCompleted:t,timeEntryIndex:a}}))}var Z4=y(()=>{Cr();xe();Ll()});function eD(n,e){return(e?re(e):"")||D(n,"yyyy-MM-dd")}function Rxe(n){return n instanceof Error?n.message:String(n)}function _xe(n){return!!(n!=null&&n.ctrlKey||n!=null&&n.metaKey||n!=null&&n.altKey)}function Fxe(n){return window.moment(n)}function bF(n,e){return iy(n,e)}function nQe(){return activeDocument.body.classList.contains("theme-dark")}function ig(n=!1){return n?nQe()?"#e8eaed":"#202124":""}function wF(n){return Ed(n)}function Lxe(n,e){let t=n.title;if(n.projects&&n.projects.length>0&&(t+=` +Project: ${n.projects[0]}`),n.priority){let r=e.priorityManager.getPriorityConfig(n.priority);t+=` +Priority: ${(r==null?void 0:r.label)||n.priority}`}if(n.status){let r=e.statusManager.getStatusConfig(n.status);t+=` +Status: ${(r==null?void 0:r.label)||n.status}`}if(n.timeEstimate){let r=Math.floor(n.timeEstimate/60),a=n.timeEstimate%60;t+=` +Estimate: ${r>0?`${r}h `:""}${a}m`}return t}function Oxe(n,e){let{isNextScheduledOccurrence:t=!1,isPatternInstance:r=!1,isRecurringInstance:a=!1,isCompleted:i=!1}=e;if(t?(n.classList.remove("tn-static-border-style-dashed-12296c91"),n.classList.add("tn-static-border-style-solid-11080b69"),n.classList.add("tn-static-border-width-2px-a1222254"),n.setAttribute("data-next-scheduled","true"),n.classList.add("fc-next-scheduled-event"),i&&(n.classList.remove("tn-static-opacity-0-8d919cb5","tn-static-opacity-1-c6e7979d"),n.classList.add("tn-static-opacity-0-6-d95b59ac"))):r?(n.classList.remove("tn-static-border-style-solid-11080b69"),n.classList.add("tn-static-border-style-dashed-12296c91"),n.classList.add("tn-static-border-width-2px-a1222254"),n.style.opacity=i?"0.4":"0.7",n.setAttribute("data-pattern-instance","true"),n.classList.add("fc-pattern-instance-event")):a&&(n.classList.remove("tn-static-border-style-solid-11080b69"),n.classList.add("tn-static-border-style-dashed-12296c91"),n.classList.add("tn-static-border-width-2px-a1222254"),n.setAttribute("data-recurring","true"),n.classList.add("fc-recurring-event"),i&&(n.classList.remove("tn-static-opacity-0-8d919cb5","tn-static-opacity-1-c6e7979d"),n.classList.add("tn-static-opacity-0-6-d95b59ac"))),e.isMaterializedOccurrence&&(n.setAttribute("data-materialized-occurrence","true"),n.classList.add("fc-materialized-occurrence-event")),i){let s=n.querySelector(".fc-event-title, .fc-event-title-container");s?(s.classList.remove("tn-static-text-decoration-none-80d654f9"),s.classList.add("tn-static-text-decoration-line-through-7059a4e5")):(n.classList.remove("tn-static-text-decoration-none-80d654f9"),n.classList.add("tn-static-text-decoration-line-through-7059a4e5")),n.classList.add("fc-completed-event")}}async function aQe(n,e,t,r){try{if(!n.recurrence||typeof n.recurrence!="string")throw new Error("Task does not have a valid RRULE string");let a=n.recurrence.match(/DTSTART:(\d{8}(?:T\d{6}Z?)?)/),i;if(a){let s=a[1],o;if(t)o=s.slice(0,8);else{let l=s.slice(0,8),c=String(e.getHours()).padStart(2,"0"),d=String(e.getMinutes()).padStart(2,"0");o=`${l}T${c}${d}00Z`}i=n.recurrence.replace(/DTSTART:[^;]+/,`DTSTART:${o}`),new Dn.Notice("Updated recurring pattern time. All future instances now appear at this time.")}else{let s=Qte(n,e,t);if(!s)throw new Error("Failed to add DTSTART to recurrence rule");i=s,new Dn.Notice("Added time information to recurring pattern. All future instances now appear at this time.")}await r.taskService.updateProperty(n,"recurrence",i)}catch(a){throw Hc.error("Error updating pattern instance time:",{category:"provider",operation:"updating-pattern-instance-time",error:a}),a}}async function zxe(n,e,t){var l,c;let{isRecurringInstance:r,isNextScheduledOccurrence:a,isPatternInstance:i}=(l=n.event.extendedProps)!=null?l:{},s=n.event.start;if(!s){n.revert();return}let o=(c=n.event.allDay)!=null?c:!1;if(a){let d;o?d=D(s,"yyyy-MM-dd"):d=D(s,"yyyy-MM-dd'T'HH:mm"),await t.taskService.updateProperty(e,"scheduled",d),new Dn.Notice("Rescheduled next occurrence. This does not change the recurrence pattern.")}else if(i)await aQe(e,s,o,t);else if(r){let d=re(e.scheduled),u;if(o)u=d,new Dn.Notice("Updated recurring task to all-day. This affects all future instances.");else{let p=D(s,"HH:mm");u=`${d}T${p}`,new Dn.Notice(`Updated recurring task time to ${p}. This affects all future instances.`)}await t.taskService.updateProperty(e,"scheduled",u)}}function Bxe(n,e){var i;if(!n.recurrence)return;let t=e,a=(i=(t.event||t).extendedProps)==null?void 0:i.instanceDate;if(!(typeof a!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(a)))return st(a)}function SF(n){let e=n,t=e.event||e,r=t.extendedProps||{},{isRecurringInstance:a,isNextScheduledOccurrence:i,isPatternInstance:s,isMaterializedOccurrence:o,instanceDate:l}=r;if((a||i||s||o)&&l)return st(l);let c=t.start;if(c){let d=D(c,"yyyy-MM-dd");return st(d)}return Xt()}function CF(n){return{getPriorityColor:e=>{var t;return(t=n.priorityManager.getPriorityConfig(e))==null?void 0:t.color},isCompletedStatus:e=>n.statusManager.isCompletedStatus(e),getThemeTextColor:(e=!1)=>ig(e)}}function iQe(n){return n?typeof n.has=="function"?n:new Set(n):new Set}function sQe(n,e){var l,c;let t=n.recurrence_parent;if(!t)return"";let r=eh(t),a=(l=e.app)==null?void 0:l.metadataCache,i=vt(t),s=(c=a==null?void 0:a.getFirstLinkpathDest)==null?void 0:c.call(a,i,n.path),o=s&&typeof s.path=="string"?s.path:void 0;return o?eh(o):r}function oQe(n){return eh(n.path)}function lQe(n,e){let t=new Map;for(let r of n){if(!FC(r))continue;let a=sQe(r,e),i=re(r.occurrence_date);if(!a||!i)continue;let s=t.get(a);s||(s=new Set,t.set(a,s)),s.add(i)}return t}function oT(n,e){if(!FC(e))return n;let t=re(e.occurrence_date);return{...n,extendedProps:{...n.extendedProps,isMaterializedOccurrence:!0,instanceDate:t,occurrenceDate:t,occurrenceParent:e.recurrence_parent}}}function Pxe(n,e){return Sxe(n,CF(e))}function Axe(n,e){return Cxe(n,CF(e))}function jxe(n,e,t,r){return Exe(n,CF(e),t,r)}function cQe(n,e){return Dxe(n,CF(e))}function X4(n,e,t={}){var r;try{let a=n.subscriptionId.startsWith("google-"),i=n.subscriptionId.startsWith("microsoft-"),s,o,l,c;if(a)o=n.color||"#4285F4",s=bF(o,.2),l=ig(!0),c="Google Calendar";else if(i)o=n.color||"#0078D4",s=bF(o,.2),l=ig(!0),c="Microsoft Calendar";else{let p=(r=e.icsSubscriptionService)==null?void 0:r.getSubscriptions().find(m=>m.id===n.subscriptionId);if(!p||!p.enabled)return null;o=hr(p.color,"#3788d8"),s=bF(o,.2),l=wF(o)?ig(!0):o,c=p.name}let{start:d,end:u}=dQe(n.start,n.end,n.allDay);return{id:n.id,title:n.title,start:d,end:u,allDay:n.allDay,backgroundColor:s,borderColor:o,textColor:l,editable:a||i,extendedProps:{icsEvent:n,eventType:"ics",subscriptionName:c,isGoogleCalendar:a,isMicrosoftCalendar:i,relatedNoteCount:t.relatedNoteCount&&t.relatedNoteCount>0?t.relatedNoteCount:void 0}}}catch(a){return Hc.error("Error creating ICS event:",{category:"provider",operation:"creating-ics-event",error:a}),null}}function dQe(n,e,t){if(t||!e)return{start:n,end:e};let r=new Date(n),a=new Date(e);if(Number.isNaN(r.getTime())||Number.isNaN(a.getTime())||a.getTime()!==r.getTime())return{start:n,end:e};let i=new Date(a.getTime()+tQe);return{start:n,end:uQe(i,e)}}function uQe(n,e){if(/Z$/i.test(e))return n.toISOString();let t=e.match(/([+-])(\d{2}):?(\d{2})$/);if(t){let[,r,a,i]=t,o=(Number(a)*60+Number(i))*60*1e3*(r==="+"?1:-1),l=new Date(n.getTime()+o),c=(p,m=2)=>String(p).padStart(m,"0"),d=`${l.getUTCFullYear()}-${c(l.getUTCMonth()+1)}-${c(l.getUTCDate())}`,u=`${c(l.getUTCHours())}:${c(l.getUTCMinutes())}:${c(l.getUTCSeconds())}.${c(l.getUTCMilliseconds(),3)}`;return`${d}T${u}${r}${a}:${i}`}return D(n,"yyyy-MM-dd'T'HH:mm:ss.SSS")}function pQe(n){if(n.recurrence&&typeof n.recurrence=="string"){let e=n.recurrence.match(/DTSTART:(\d{8}(?:T\d{6}Z?)?)/);if(e&&e[1].includes("T")){let t=e[1].split("T")[1];if(t.length>=4){let r=t.slice(0,2),a=t.slice(2,4);return`${r}:${a}`}}}if(n.scheduled){let e=si(n.scheduled);if(e)return e}return"09:00"}function mQe(n){if(!n.scheduled||!n.due)return null;let e=et(n.scheduled);if(et(n.due)<=e)return null;let r=et(re(n.scheduled)),a=et(re(n.due)),i=Date.UTC(r.getFullYear(),r.getMonth(),r.getDate()),s=Date.UTC(a.getFullYear(),a.getMonth(),a.getDate());return Math.round((s-i)/rQe)}function fQe(n,e){let t=new Date(n);return t.setDate(t.getDate()+e),t}function hQe(n,e){let t=new Date(n);return t.setUTCDate(t.getUTCDate()+e),t}function $xe(n,e){let t=si(n);return t?`${e}T${t}`:e}function gQe(n){return!!(n.scheduled&&n.due&&!Jt(n.due)&&re(n.scheduled)===re(n.due))}function Q4(n,e,t,r,a,i,s,o){var h,g;if(!n.scheduled||!n.due)return[];let l=fQe(et(e),a),c=D(l,"yyyy-MM-dd"),d=Jt(n.scheduled)?t:null,u={...n,scheduled:d?`${e}T${d}`:e,due:$xe(n.due,c)},p=((h=n.complete_instances)==null?void 0:h.includes(e))||!1,m=((g=n.skipped_instances)==null?void 0:g.includes(e))||!1,f={isCompleted:p,isSkipped:m,isNextScheduledOccurrence:r==="next-scheduled",isPatternInstance:r==="pattern",isRecurringInstance:r==="recorded",instanceDate:e,recurringTemplateTime:t};return jxe(u,i,s,o).map(v=>{let k=re(v.start);return{...v,id:`span-${r}-${n.path}-${e}-${k}`,editable:!1,extendedProps:{...v.extendedProps,taskInfo:n,...f}}})}function yQe(n,e,t,r,a){var m,f;let i=Jt(e),s;if(i&&n.timeEstimate){let h=et(e),g=new Date(h.getTime()+n.timeEstimate*60*1e3);s=D(g,"yyyy-MM-dd'T'HH:mm")}else i||(s=sT(e,n.timeEstimate));let o=a.priorityManager.getPriorityConfig(n.priority),l=hr(o==null?void 0:o.color,"var(--color-accent)"),c=((m=n.complete_instances)==null?void 0:m.includes(t))||!1,d=((f=n.skipped_instances)==null?void 0:f.includes(t))||!1,u=wF(l)?ig(!0):l,p="transparent";return c?p="rgba(0,0,0,0.3)":d&&(p="rgba(128,128,128,0.2)"),{id:`next-scheduled-${n.path}-${t}`,title:n.title,start:e,end:s,allDay:!i,backgroundColor:p,borderColor:l,textColor:u,editable:!0,extendedProps:{taskInfo:n,eventType:"scheduled",isCompleted:c,isSkipped:d,isNextScheduledOccurrence:!0,instanceDate:t,recurringTemplateTime:r}}}function vQe(n,e,t,r,a){var f,h;let i=Jt(e),s;if(i&&n.timeEstimate){let g=et(e),v=new Date(g.getTime()+n.timeEstimate*60*1e3);s=D(v,"yyyy-MM-dd'T'HH:mm")}else i||(s=sT(e,n.timeEstimate));let o=a.priorityManager.getPriorityConfig(n.priority),l=hr(o==null?void 0:o.color,"var(--color-accent)"),c=((f=n.complete_instances)==null?void 0:f.includes(t))||!1,d=((h=n.skipped_instances)==null?void 0:h.includes(t))||!1,u=bF(l,.5),p=wF(l)?ig(!0):u,m="transparent";return c?m="rgba(0,0,0,0.2)":d&&(m="rgba(128,128,128,0.15)"),{id:`recurring-${n.path}-${t}`,title:n.title,start:e,end:s,allDay:!i,backgroundColor:m,borderColor:u,textColor:p,editable:!0,extendedProps:{taskInfo:n,eventType:"recurring",isCompleted:c,isSkipped:d,isPatternInstance:!0,instanceDate:t,recurringTemplateTime:r}}}function kQe(n,e,t,r,a){var m,f;let i=Jt(e),s;if(i&&n.timeEstimate){let h=et(e),g=new Date(h.getTime()+n.timeEstimate*60*1e3);s=D(g,"yyyy-MM-dd'T'HH:mm")}else i||(s=sT(e,n.timeEstimate));let o=a.priorityManager.getPriorityConfig(n.priority),l=hr(o==null?void 0:o.color,"var(--color-accent)"),c=((m=n.complete_instances)==null?void 0:m.includes(t))||!1,d=((f=n.skipped_instances)==null?void 0:f.includes(t))||!1,u=wF(l)?ig(!0):l,p="transparent";return c?p="rgba(0,0,0,0.3)":d&&(p="rgba(128,128,128,0.2)"),{id:`recurring-recorded-${n.path}-${t}`,title:n.title,start:e,end:s,allDay:!i,backgroundColor:p,borderColor:l,textColor:u,editable:!1,extendedProps:{taskInfo:n,eventType:"recurring",isCompleted:c,isSkipped:d,isRecurringInstance:!0,instanceDate:t,recurringTemplateTime:r}}}function TQe(n,e,t,r,a={}){if(!n.recurrence||!n.scheduled)return[];let{showCompletedRecurringInstances:i=!0,showSkippedRecurringInstances:s=!0,showProjectedRecurringInstances:o=!0,showScheduledToDueSpan:l=!1,materializedOccurrenceDates:c,visibleStartDate:d,visibleEndDate:u}=a,p=[],m=new Set,f=iQe(c),h=eD(e,d),g=eD(t,u),v=Jt(n.scheduled),k=pQe(n),T=re(n.scheduled),b=new Set(n.googleCalendarMovedOriginalDates||[]);n.googleCalendarExceptionOriginalScheduled&&b.add(re(n.googleCalendarExceptionOriginalScheduled));let w=l?mQe(n):null,S=w!==null,C=S?hQe(e,-Math.max(w,0)):e;if(o){let x=v?si(n.scheduled):null,E=x?`${T}T${x}`:T,_=yQe(n,E,T,x||"09:00",r);if(_&&!f.has(T)&&Mxe(n,T,i,s))if(S){let R=Q4(n,T,x||k,"next-scheduled",w,r,e,t);R.length>0&&(p.push(...R),m.add(T))}else p.push(_),m.add(T);let F=t;typeof n.recurrence=="string"&&n.recurrence.includes("FREQ=YEARLY")&&(F=new Date(e.getTime()+800*24*60*60*1e3));let I=ly(n,C,F),A=S?eD(C):h;for(let R of I){let O=ae(R);if(O=g||O===T||b.has(O)||f.has(O)||!Mxe(n,O,i,s))continue;if(S){let oe=Q4(n,O,k,"pattern",w,r,e,t);oe.length>0&&(p.push(...oe),m.add(O));continue}let U=v?`${O}T${k}`:O,pe=vQe(n,U,O,k,r);pe&&(p.push(pe),m.add(O))}}for(let x of bQe(n,C,t,i,s,h,g)){if(f.has(x)||m.has(x))continue;if(S){let F=Q4(n,x,k,"recorded",w,r,e,t);F.length>0&&(p.push(...F),m.add(x));continue}let E=v?`${x}T${k}`:x,_=kQe(n,E,x,k,r);_&&(p.push(_),m.add(x))}return p}function bQe(n,e,t,r,a,i=eD(e),s=eD(t)){let o=new Set;if(r)for(let l of n.complete_instances||[])l>=i&&l=i&&lCQe)&&(J4=(0,Vc.getAllDailyNotes)(),Ixe=r);let a=J4,i=[];for(let s=new Date(e);s<=t;s.setUTCDate(s.getUTCDate()+1)){let o=ae(s),l=new Date(`${o}T12:00:00`),c=(0,Vc.getDailyNote)(Fxe(l),a);if(c){let d=n.app.metadataCache.getFileCache(c);if(d!=null&&d.frontmatter){let u=SQe(d.frontmatter,c.path);for(let p of u)i.push(wQe(p,o,n.settings.calendarViewSettings.defaultTimeblockColor))}}}return i}catch(r){return Hc.error("Error getting timeblock events:",{category:"provider",operation:"getting-timeblock-events",error:r}),[]}}function XE(n,e,t,r){if(!e||!t)return!0;try{let i=et(n).getTime();if(isNaN(i))return!0;let s=i;return r&&(s=i+r*60*1e3),i=e.getTime()}catch(a){return!0}}function EQe(n,e){return e?D(n,"yyyy-MM-dd'T'HH:mm"):D(n,"yyyy-MM-dd")}function Uxe(n,e){if(n)return $xe(n,e)}function DQe(n,e){if(n.end)try{let t=et(n.start),r=et(n.end),a=et(e),i=new Date(a.getTime()+(r.getTime()-t.getTime()));return EQe(i,Jt(n.end))}catch(t){return Uxe(n.end,re(e))}}function Nxe(n,e,t,r,a,i){if(!e||!XE(t,a,i)||re(e)===t)return null;let s=!!n.extendedProps.isCompleted;if(!ps(e,s,r))return null;let o=Uxe(n.start,t);return o?{...n,id:`${n.id}-overdue-today`,start:o,end:DQe(n,o),extendedProps:{...n.extendedProps,isOverdueOnToday:!0}}:null}async function Hxe(n,e,t={}){var S,C,x;let{showScheduled:r=!0,showDue:a=!0,showScheduledToDueSpan:i=!1,showTimeEntries:s=!0,showRecurring:o=!0,showCompletedRecurringInstances:l=!0,showSkippedRecurringInstances:c=!0,showICSEvents:d=!0,showTimeblocks:u=!1,showOverdueOnToday:p=!1,visibleStart:m,visibleEnd:f,visibleStartDate:h,visibleEndDate:g}=t,v=[],k=lQe(n,e),T=p?Yo():null,b=(C=(S=e.settings)==null?void 0:S.hideCompletedFromOverdue)!=null?C:!0,w=(E,_,F,I=a,A=!1,R=!1)=>{let O=!1,U=!1;if(F&&i&&E.scheduled&&E.due){let X=jxe(E,e,m,f).map(de=>oT(de,E));X.length>0&&(v.push(...X),O=!0)}if(O)return;if(_&&E.scheduled){if(XE(E.scheduled,m,f,E.timeEstimate)){let X=Pxe(E,e);X&&v.push(oT(X,E))}else if(T){let X=Pxe(E,e),de=X?Nxe(oT(X,E),E.scheduled,T,b,m,f):null;de&&(v.push(de),U=!0)}}let pe=I&&(_||A)&&gQe(E);if(I&&!pe&&E.due){if(XE(E.due,m,f)){let X=Axe(E,e);X&&v.push(oT(X,E))}else if(T&&!((U||R)&&!Jt(E.due))){let X=Axe(E,e),de=X?Nxe(oT(X,E),E.due,T,b,m,f):null;de&&v.push(de)}}};for(let E of n)try{if(E.recurrence){let _=r,F=a,I=!0,A=!1,R=!1;if((o||l||c)&&m&&f&&E.scheduled){let O=TQe(E,m,f,e,{showCompletedRecurringInstances:l,showSkippedRecurringInstances:c,showProjectedRecurringInstances:o,showScheduledToDueSpan:i,materializedOccurrenceDates:(x=k.get(oQe(E)))!=null?x:new Set,visibleStartDate:h,visibleEndDate:g});v.push(...O),o&&(A=O.length>0,R=!!(T&&O.some(U=>re(U.start)===T)),_=!1,I=!1,O.some(U=>U.extendedProps.eventType==="scheduledToDueSpan")&&(F=!1))}w(E,_,I,F,A,R)}else w(E,r,!0);if(s&&E.timeEntries){let _=cQe(E,e);for(let F of _)XE(F.start,m,f)&&v.push(oT(F,E))}}catch(_){Hc.warn(`[TaskNotes][Calendar] Error processing task "${E.title}" (${E.path}):`,{category:"provider",operation:"processing-task",error:_})}if(d&&e.icsSubscriptionService){let E=e.icsSubscriptionService.getAllEvents();for(let _ of E)if(XE(_.start,m,f)){let F=X4(_,e);F&&v.push(F)}}if(u&&m&&f){let E=await xQe(e,m,f);v.push(...E)}return v}async function Vxe(n,e,t,r,a){if(t){new Dn.Notice("Timeblocks must have specific times. Please select a time range in week or day view.");return}let i=D(n,"yyyy-MM-dd"),s=D(n,"HH:mm"),o=D(e,"HH:mm");new dv(r.app,r,{date:i,startTime:s,endTime:o,onCreated:a}).open()}async function Wxe(n,e,t,r){if(t){new Dn.Notice(r.i18n.translate("modals.timeEntry.mustHaveSpecificTime"));return}try{let i=(await r.cacheManager.getAllTasks()).filter(s=>!s.archived);if(i.length===0){new Dn.Notice(r.i18n.translate("modals.timeEntry.noTasksAvailable"));return}fn(r,i,s=>{(async()=>{if(s)try{let o=Math.round((e.getTime()-n.getTime())/6e4),l={startTime:n.toISOString(),endTime:e.toISOString(),description:""},c=[...s.timeEntries||[],l].map(d=>{let u={...d};return delete u.duration,u});await r.taskService.updateTask(s,{timeEntries:c}),r.emitter.trigger(Ra),new Dn.Notice(r.i18n.translate("modals.timeEntry.created",{taskTitle:s.title,duration:o.toString()}))}catch(o){Hc.error("Error creating time entry:",{category:"provider",operation:"creating-time-entry",error:o}),new Dn.Notice(r.i18n.translate("modals.timeEntry.createFailed"))}})()})}catch(a){Hc.error("Error opening task selector for time entry:",{category:"provider",operation:"opening-task-selector-time-entry",error:a}),new Dn.Notice(r.i18n.translate("modals.timeEntry.createFailed"))}}async function qxe(n,e,t,r,a=!1){try{let i=n.event.start,s=n.event.end;if(!i||!s){n.revert();return}let o=D(i,"yyyy-MM-dd"),l=D(i,"HH:mm"),c=D(s,"HH:mm");if(a){await Yte(r.app,o,e,l,c),n.revert(),r.emitter.trigger(Ra),new Dn.Notice("Timeblock duplicated successfully");return}await Xz(r.app,e.id,t,o,l,c),new Dn.Notice("Timeblock moved successfully")}catch(i){Hc.error("Error moving timeblock:",{category:"provider",operation:"moving-timeblock",error:i}),new Dn.Notice(`Failed to move timeblock: ${Rxe(i)}`),n.revert()}}async function Gxe(n,e,t,r){try{let a=n.event.start,i=n.event.end;if(!a||!i){n.revert();return}let s=D(a,"HH:mm"),o=D(i,"HH:mm");await Xz(r.app,e.id,t,t,s,o),new Dn.Notice("Timeblock duration updated")}catch(a){Hc.error("Error resizing timeblock:",{category:"provider",operation:"resizing-timeblock",error:a}),new Dn.Notice(`Failed to resize timeblock: ${Rxe(a)}`),n.revert()}}async function xF(n,e,t,r,a){new TF(r.app,r,n,e,t,a).open()}function Yxe(n,e){n.setAttribute("data-timeblock-id",e.id||""),n.classList.remove("tn-static-border-style-dashed-12296c91"),n.classList.add("tn-static-border-style-solid-11080b69"),n.classList.add("tn-static-border-width-2px-a1222254"),n.classList.add("fc-timeblock-event")}function Kxe(n){var t;let e=((t=n.attachments)==null?void 0:t.length)||0;return`${n.title||"Timeblock"}${n.description?` - ${n.description}`:""}${e>0?` (${e} attachment${e>1?"s":""})`:""}`}function Zxe(n,e,t,r="tasknotes-calendar"){n.addEventListener("mouseover",a=>{t.app.vault.getAbstractFileByPath(e.path)&&t.app.workspace.trigger("hover-link",{event:a,source:r,hoverParent:n,targetEl:n,linktext:e.path,sourcePath:e.path})})}async function e3(n,e,t={}){try{let{createIfMissing:r=!0}=t;if(!(0,Vc.appHasDailyNotesPluginLoaded)()){new Dn.Notice("Daily notes core plugin is not enabled. Please enable it in settings > core plugins.");return}let a=Fxe(n),i=(0,Vc.getAllDailyNotes)(),s=(0,Vc.getDailyNote)(a,i);if(!s){if(!r){new Dn.Notice(e.i18n.translate("views.basesCalendar.notices.noDailyNoteForDate"));return}try{s=await(0,Vc.createDailyNote)(a)}catch(o){let l=o instanceof Error?o.message:String(o);Hc.error("Failed to create daily note:",{category:"provider",operation:"create-daily-note",error:o}),new Dn.Notice(`Failed to create daily note: ${l}`);return}}s&&await e.app.workspace.getLeaf(!1).openFile(s)}catch(r){let a=r instanceof Error?r.message:String(r);Hc.error("Failed to navigate to daily note:",{category:"provider",operation:"navigate-daily-note",error:r}),new Dn.Notice(`Failed to navigate to daily note: ${a}`)}}function t3(n,e,t,r,a=e3){if(t!=="timeGridDay")return;let i=n.querySelector(".fc-col-header-cell-cushion")||n,s=`Go to ${D(e,"d MMMM yyyy")}`;i.setAttribute("data-navlink",""),i.setAttribute("title",s),i.setAttribute("aria-label",s),i.classList.add("tasknotes-calendar-daily-note-link"),i.dataset.tasknotesDailyNoteDate=e.toISOString(),i.matches("a")&&!i.getAttribute("href")&&i.setAttribute("href","#"),i.dataset.tasknotesDailyNoteLinkAttached!=="true"&&(i.dataset.tasknotesDailyNoteLinkAttached="true",i.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation();let l=o.currentTarget,c=l!=null&&l.dataset.tasknotesDailyNoteDate?new Date(l.dataset.tasknotesDailyNoteDate):e;a(c,r)}))}function Qxe(n,e,t,r){let a=t?D(n,"yyyy-MM-dd"):D(n,"yyyy-MM-dd'T'HH:mm"),i=Math.round((e.getTime()-n.getTime())/(1e3*60)),s=!t&&i>r,o={scheduled:a};if(t){let c=Math.round((e.getTime()-n.getTime())/864e5);c>1&&(o.timeEstimate=c*1440)}else s&&(o.timeEstimate=i);return o}var Dn,Vc,Hc,tQe,rQe,J4,Ixe,CQe,tD=y(()=>{Cr();Pr();xe();yt();Cn();Dn=require("obsidian");TU();Vc=tt(od());x2();co();wxe();Ll();Z4();q();Z4();Hc=M({tag:"Bases/CalendarCore"}),tQe=1,rQe=1440*60*1e3;J4=null,Ixe=0,CQe=5e3});function PQe(n,e){return e?D(n,"yyyy-MM-dd"):D(n,"yyyy-MM-dd'T'HH:mm")}function EF(n){return n?n.includes(".")?n.split(".").pop()||null:n:null}function Jxe(n,e){let t=et(n),r=new Date(t.getTime()+e);return Jt(n)?D(r,"yyyy-MM-dd'T'HH:mm"):D(r,"yyyy-MM-dd")}function eEe(n){let{eventType:e,taskInfo:t,newStart:r,oldStart:a,allDay:i}=n;if(e==="scheduled"||e==="due")return r?{kind:"update-date-property",property:e,value:PQe(r,i)}:{kind:"revert",reason:"missing-new-start"};if(e==="scheduledToDueSpan"){if(!a)return{kind:"revert",reason:"missing-old-start"};if(!r)return{kind:"revert",reason:"missing-new-start"};let s=r.getTime()-a.getTime();return{kind:"update-scheduled-due-span",scheduled:t.scheduled?Jxe(t.scheduled,s):void 0,due:t.due?Jxe(t.due,s):void 0}}return{kind:"ignore",reason:"unsupported-event-type"}}function tEe(n){let{eventType:e,start:t,end:r,allDay:a}=n;return e!=="scheduled"&&e!=="recurring"?{kind:"revert",reason:"unsupported-event-type"}:!t||!r?{kind:"ignore",reason:"missing-range"}:{kind:"update-time-estimate",value:a?Math.round((r.getTime()-t.getTime())/(1440*60*1e3))*60*24:Math.round((r.getTime()-t.getTime())/(1e3*60))}}function rEe(n){return n.map(e=>{let t={...e};return delete t.duration,t})}function sg(n){return Number.isNaN(n.getTime())}function nEe(n,e){return D(n,e?"yyyy-MM-dd":"yyyy-MM-dd'T'HH:mm")}function Xxe(n){if(!n.value)return null;let e=new Date(Y(n.value));if(sg(e))return null;let t=new Date(e.getTime()+n.timeDiffMs);return sg(t)?null:nEe(t,n.allDay)}function aEe(n){let{frontmatter:e,startProperty:t,endProperty:r,oldStart:a,newStart:i,allDay:s}=n;if(!t)return{kind:"revert",reason:"missing-start-property"};if(!a||!i)return{kind:"revert",reason:"missing-start-date"};let o=i.getTime()-a.getTime(),l={},c=e[t];if(c){let d=Xxe({value:c,timeDiffMs:o,allDay:s});if(!d)return{kind:"ignore",reason:"invalid-start-value"};l[t]=d}if(r){let d=e[r],u=Xxe({value:d,timeDiffMs:o,allDay:s});u&&(l[r]=u)}return Object.keys(l).length===0?{kind:"ignore",reason:"no-date-values"}:{kind:"update-frontmatter",updates:l}}function iEe(n){let{endProperty:e,newEnd:t,allDay:r}=n;return e?t?sg(t)?{kind:"ignore",reason:"invalid-end-date"}:{kind:"update-frontmatter",updates:{[e]:nEe(t,r)}}:{kind:"revert",reason:"missing-end-date"}:{kind:"revert",reason:"missing-end-property"}}function sEe(n){let{timeEntries:e,timeEntryIndex:t,oldStart:r,newStart:a,newEnd:i}=n;if(typeof t!="number")return{kind:"revert",reason:"missing-index"};if(!a||!i)return{kind:"revert",reason:"missing-new-range"};if(!r)return{kind:"revert",reason:"missing-old-start"};let s=rEe(e!=null?e:[]),o=s[t];if(!o)return{kind:"ignore",reason:"missing-entry"};if(!o.endTime)return{kind:"revert",reason:"missing-entry-end"};let l=new Date(o.startTime),c=new Date(o.endTime);if(sg(l)||sg(c))return{kind:"revert",reason:"invalid-date"};let d=a.getTime()-r.getTime();return o.startTime=new Date(l.getTime()+d).toISOString(),o.endTime=new Date(c.getTime()+d).toISOString(),{kind:"update-time-entries",timeEntries:s}}function oEe(n){let{timeEntries:e,timeEntryIndex:t,newStart:r,newEnd:a}=n;if(typeof t!="number")return{kind:"revert",reason:"missing-index"};if(!r||!a)return{kind:"revert",reason:"missing-new-range"};if(sg(r)||sg(a))return{kind:"revert",reason:"invalid-date"};let i=rEe(e!=null?e:[]),s=i[t];return s?(s.startTime=r.toISOString(),s.endTime=a.toISOString(),{kind:"update-time-entries",timeEntries:i}):{kind:"ignore",reason:"missing-entry"}}function r3(n){let{start:e,allDay:t,timezone:r,requireEnd:a=!1}=n,{end:i}=n;if(!e)return{kind:"revert",reason:"missing-start"};if(!i){if(a)return{kind:"revert",reason:"missing-end"};i=new Date(e),t?i.setDate(i.getDate()+1):i.setHours(i.getHours()+1)}return t?{kind:"update-provider-event",updates:{start:{date:D(e,"yyyy-MM-dd")},end:{date:D(i,"yyyy-MM-dd")}}}:{kind:"update-provider-event",updates:{start:{dateTime:D(e,"yyyy-MM-dd'T'HH:mm:ss"),timeZone:r},end:{dateTime:D(i,"yyyy-MM-dd'T'HH:mm:ss"),timeZone:r}}}}var lEe=y(()=>{Cr();xe();dr()});function MQe(n,e){if(e){let r=n.findIndex(a=>a.provider.providerId==="google"&&a.calendar.id===e);if(r>=0)return r}let t=n.findIndex(r=>r.calendar.primary);return t>=0?t:0}var Ls,AQe,DF,cEe=y(()=>{Ls=require("obsidian");Cr();q();AQe=M({tag:"Modals/CalendarEventCreationModal"});DF=class extends Ls.Modal{constructor(t,r,a){super(t);this.writableCalendars=[];this.keyboardHandler=null;this.plugin=r,this.options=a,this.translate=r.i18n.translate.bind(r.i18n),this.writableCalendars=this.getWritableCalendars()}getWritableCalendars(){let t=[],r=this.plugin.calendarProviderRegistry;if(!r)return t;for(let a of r.getAllProviders())for(let i of a.getAvailableCalendars())t.push({provider:a,calendar:i});return t}onOpen(){let{contentEl:t}=this;t.empty(),t.addClass("tasknotes-plugin","calendar-event-creation-modal"),this.keyboardHandler=l=>{l.key==="Enter"&&(l.ctrlKey||l.metaKey)&&(l.preventDefault(),this.handleSubmit())},this.containerEl.addEventListener("keydown",this.keyboardHandler),new Ls.Setting(t).setName(this.translate("modals.calendarEventCreation.heading")).setHeading();let r=t.createDiv({cls:"calendar-event-date-display"});r.createEl("strong",{text:this.translate("modals.calendarEventCreation.dateTimeLabel")});let a=this.options.allDay?D(this.options.start,"PPP"):`${D(this.options.start,"PPP p")} – ${D(this.options.end,"p")}`;r.createSpan({text:a}),new Ls.Setting(t).setName(this.translate("modals.calendarEventCreation.titleLabel")).setDesc(this.translate("modals.calendarEventCreation.titleDesc")).addText(l=>{this.titleInput=l.inputEl,l.setPlaceholder(this.translate("modals.calendarEventCreation.titlePlaceholder")).onChange(()=>this.validateForm()),window.setTimeout(()=>this.titleInput.focus(),100)}),this.writableCalendars.length>1&&new Ls.Setting(t).setName(this.translate("modals.calendarEventCreation.calendarLabel")).setDesc(this.translate("modals.calendarEventCreation.calendarDesc")).addDropdown(l=>{this.calendarDropdown=l.selectEl;for(let d=0;d{this.descriptionInput=l.inputEl,l.setPlaceholder(this.translate("modals.calendarEventCreation.descriptionPlaceholder")),this.descriptionInput.rows=3}),new Ls.Setting(t).setName(this.translate("modals.calendarEventCreation.locationLabel")).setDesc(this.translate("modals.calendarEventCreation.locationDesc")).addText(l=>{this.locationInput=l.inputEl,l.setPlaceholder(this.translate("modals.calendarEventCreation.locationPlaceholder"))});let i=t.createDiv({cls:"calendar-event-modal-buttons"});i.createEl("button",{text:this.translate("common.cancel")}).addEventListener("click",()=>this.close()),i.createEl("button",{text:this.translate("modals.calendarEventCreation.createButton"),cls:"mod-cta calendar-event-create-button"}).addEventListener("click",()=>{this.handleSubmit()}),this.validateForm()}validateForm(){var a;let t=this.contentEl.querySelector(".calendar-event-create-button");if(!t)return;let r=!!((a=this.titleInput)!=null&&a.value.trim());t.disabled=!r,t.style.opacity=r?"1":"0.5"}async handleSubmit(){var i,s,o,l;let t=this.titleInput.value.trim();if(!t){new Ls.Notice(this.translate("modals.calendarEventCreation.titleRequired"));return}let r=this.calendarDropdown?parseInt(this.calendarDropdown.value):0,a=this.writableCalendars[r];if(!a){new Ls.Notice(this.translate("modals.calendarEventCreation.noCalendarSelected"));return}try{let{start:c,end:d,allDay:u}=this.options,p=Intl.DateTimeFormat().resolvedOptions().timeZone,m={summary:t,start:u?{date:D(c,"yyyy-MM-dd")}:{dateTime:D(c,"yyyy-MM-dd'T'HH:mm:ss"),timeZone:p},end:u?{date:D(d,"yyyy-MM-dd")}:{dateTime:D(d,"yyyy-MM-dd'T'HH:mm:ss"),timeZone:p}},f=(i=this.descriptionInput)==null?void 0:i.value.trim();f&&(m.description=f);let h=(s=this.locationInput)==null?void 0:s.value.trim();h&&(m.location=h),await a.provider.createEvent(a.calendar.id,m),new Ls.Notice(this.translate("modals.calendarEventCreation.success",{title:t})),(l=(o=this.options).onEventCreated)==null||l.call(o),this.close()}catch(c){AQe.error("[TaskNotes] Error creating calendar event:",{category:"provider",operation:"creating-calendar-event",error:c}),new Ls.Notice(this.translate("modals.calendarEventCreation.error",{message:c instanceof Error?c.message:String(c)}))}}onClose(){this.keyboardHandler&&(this.containerEl.removeEventListener("keydown",this.keyboardHandler),this.keyboardHandler=null);let{contentEl:t}=this;t.empty()}}});function n3(n,{showNotice:e=!0,noticeHandler:t}){e&&(t==null||t(n))}var dEe,Xi,PF=y(()=>{q();dEe=M({tag:"Utils/SafeAsync"});Xi=class{static async execute(e,t={}){let{fallback:r,errorMessage:a="An error occurred",showNotice:i=!0,noticeHandler:s,logError:o=!0}=t;try{return await e()}catch(l){if(o&&dEe.error(a,{category:"provider",operation:"execute-safe-operation",error:l}),i){let c=l instanceof Error?l.message:String(l);n3(`${a}: ${c}`,{showNotice:i,noticeHandler:s})}return r}}static async executeWithRetry(e,t={}){let{maxRetries:r=3,retryDelay:a=1e3,errorMessage:i="Operation failed",showNotice:s=!0,noticeHandler:o}=t,l;for(let c=0;c<=r;c++)try{return await e()}catch(d){if(l=d instanceof Error?d:new Error(String(d)),cwindow.setTimeout(u,a));continue}dEe.error(`${i} after ${r+1} attempts:`,{category:"provider",operation:"execute-with-retry",details:{attempts:r+1},error:l}),s&&n3(`${i}: ${l.message}`,{showNotice:s,noticeHandler:o});return}}static async executeWithValidation(e,t,r={}){let{showNotice:a=!0,noticeHandler:i}=r;for(let s of t)if(!s.condition){a&&n3(s.message,{showNotice:a,noticeHandler:i});return}return this.execute(e,r)}}});var Tu,lT,a3=y(()=>{Tu=require("obsidian");Cr();PF();Wd();lT=class extends Tu.Modal{constructor(t,r,a){super(t);this.title="";this.folder="";this.template="";this.useTemplate=!1;this.keyboardHandler=null;this.plugin=r,this.options=a,this.translate=r.i18n.translate.bind(r.i18n),this.title=this.generateDefaultTitle(),this.folder=this.getDefaultFolder(),this.template=this.getDefaultTemplate()}onOpen(){this.containerEl.addClass("tasknotes-plugin","ics-note-creation-modal"),this.keyboardHandler=t=>{t.key==="Enter"&&(t.ctrlKey||t.metaKey)&&(t.preventDefault(),this.handleCreate())},this.containerEl.addEventListener("keydown",this.keyboardHandler),this.createModalContent()}onClose(){this.keyboardHandler&&(this.containerEl.removeEventListener("keydown",this.keyboardHandler),this.keyboardHandler=null),this.contentEl.empty()}createModalContent(){let{contentEl:t}=this;t.empty(),t.createDiv("modal-header").createEl("h2",{text:this.translate("modals.icsNoteCreation.heading")});let a=t.createDiv("ics-event-preview");this.createEventPreview(a),new Tu.Setting(t).setName(this.translate("modals.icsNoteCreation.titleLabel")).setDesc(this.translate("modals.icsNoteCreation.titleDesc")).addText(l=>{this.titleInput=l.inputEl,l.setValue(this.title).onChange(c=>{this.title=c,this.updatePreview()})}),new Tu.Setting(t).setName(this.translate("modals.icsNoteCreation.folderLabel")).setDesc(this.translate("modals.icsNoteCreation.folderDesc")).addText(l=>{this.folderInput=l.inputEl,l.setValue(this.folder).setPlaceholder(this.translate("modals.icsNoteCreation.folderPlaceholder")).onChange(c=>{this.folder=c,this.updatePreview()})}),this.templateContainer=t.createDiv("template-settings"),this.createTemplateSettings(),this.previewContainer=t.createDiv("content-preview"),this.updatePreview();let i=t.createDiv("modal-button-container"),s=i.createEl("button",{text:this.translate("modals.icsNoteCreation.createButton"),cls:"mod-cta"});s.onclick=l=>{l.preventDefault(),l.stopPropagation(),this.handleCreate()};let o=i.createEl("button",{text:this.translate("common.cancel")});o.onclick=l=>{l.preventDefault(),l.stopPropagation(),this.close()},window.setTimeout(()=>{var l;return(l=this.titleInput)==null?void 0:l.focus()},100)}createEventPreview(t){let{icsEvent:r,subscriptionName:a}=this.options;t.createEl("h3",{text:r.title});let i=t.createDiv("event-details");if(r.start){let o=r.allDay&&/^\d{4}-\d{2}-\d{2}$/.test(r.start)?r.start+"T00:00:00":r.start,l=new Date(o),c=i.createDiv();c.createEl("strong",{text:this.translate("modals.icsNoteCreation.startLabel")}),c.appendText(D(l,"PPPp"))}if(r.end&&!r.allDay){let o=/^\d{4}-\d{2}-\d{2}$/.test(r.end)?r.end+"T00:00:00":r.end,l=new Date(o),c=i.createDiv();c.createEl("strong",{text:this.translate("modals.icsNoteCreation.endLabel")}),c.appendText(D(l,"PPPp"))}if(r.location){let o=i.createDiv();o.createEl("strong",{text:this.translate("modals.icsNoteCreation.locationLabel")}),o.appendText(r.location)}let s=i.createDiv();s.createEl("strong",{text:this.translate("modals.icsNoteCreation.calendarLabel")}),s.appendText(a)}createTemplateSettings(){this.templateContainer.empty(),new Tu.Setting(this.templateContainer).setName(this.translate("modals.icsNoteCreation.useTemplateLabel")).setDesc(this.translate("modals.icsNoteCreation.useTemplateDesc")).addToggle(t=>{t.setValue(this.useTemplate).onChange(r=>{this.useTemplate=r,this.updateTemplateInput(),this.updatePreview()})}),this.useTemplate&&new Tu.Setting(this.templateContainer).setName(this.translate("modals.icsNoteCreation.templatePathLabel")).setDesc(this.translate("modals.icsNoteCreation.templatePathDesc")).addText(t=>{this.templateInput=t.inputEl,t.setValue(this.template).setPlaceholder(this.translate("modals.icsNoteCreation.templatePathPlaceholder")).onChange(r=>{this.template=r,this.updatePreview()})})}updateDefaultsForContentType(){var t,r;this.folder=((t=this.plugin.settings.icsIntegration)==null?void 0:t.defaultNoteFolder)||"",this.template=((r=this.plugin.settings.icsIntegration)==null?void 0:r.defaultNoteTemplate)||"",this.folderInput&&(this.folderInput.value=this.folder),this.templateInput&&(this.templateInput.value=this.template)}updateTemplateInput(){this.createTemplateSettings()}updatePreview(){if(!this.previewContainer)return;this.previewContainer.empty(),this.previewContainer.createEl("h4",{text:"Summary"});let t=this.previewContainer.createDiv("preview-details"),r=t.createDiv();r.createEl("strong",{text:"Type: "}),r.appendText("Note");let a=t.createDiv();a.createEl("strong",{text:"Title: "}),a.appendText(this.title||"Untitled");let i=t.createDiv();if(i.createEl("strong",{text:"Folder: "}),i.appendText(this.folder||"Vault root"),this.useTemplate&&this.template){let c=t.createDiv();c.createEl("strong",{text:"Template: "}),c.appendText(this.template)}else{let c=t.createDiv();c.createEl("strong",{text:"Template: "}),c.appendText("Default format")}let s=this.previewContainer.createDiv("template-variables");s.createEl("h5",{text:"Available template variables"});let o=["{{title}}","{{icsEventTitle}}","{{icsEventStart}}","{{icsEventEnd}}","{{icsEventLocation}}","{{icsEventDescription}}","{{icsEventUrl}}","{{icsEventSubscription}}","{{icsEventId}}","{{date}}","{{time}}"],l=s.createDiv("variables-list");o.forEach(c=>{l.createSpan({text:c,cls:"template-variable"})})}generateDefaultTitle(){let{icsEvent:t}=this.options,r=t.allDay&&/^\d{4}-\d{2}-\d{2}$/.test(t.start)?t.start+"T00:00:00":t.start,a=new Date(r);return`${t.title} - ${D(a,"PPP")}`}getDefaultFolder(){var t;return((t=this.plugin.settings.icsIntegration)==null?void 0:t.defaultNoteFolder)||""}getDefaultTemplate(){var t;return((t=this.plugin.settings.icsIntegration)==null?void 0:t.defaultNoteTemplate)||""}async handleCreate(){await Xi.executeWithValidation(async()=>{var a,i;let{icsEvent:t}=this.options,r=await this.plugin.icsNoteService.createNoteFromICS(t,{title:this.title,folder:this.folder||void 0,template:this.useTemplate&&this.template?this.template:void 0});new Tu.Notice(`Note created: ${this.title}`),(i=(a=this.options).onContentCreated)==null||i.call(a,r.file,r.noteInfo),this.close()},[{condition:!!this.title.trim(),message:"Title is required"}],{errorMessage:"Failed to create note from ICS event",noticeHandler:Ze})}}});var kr,i3,Wc,rD=y(()=>{kr=require("obsidian");a3();SC();PF();q();Wd();i3=M({tag:"Modals/ICSEventInfoModal"}),Wc=class extends kr.Modal{constructor(t,r,a,i){super(t);this.relatedNotes=[];this.plugin=r,this.icsEvent=a,this.subscriptionName=i,this.translate=r.i18n.translate.bind(r.i18n)}async onOpen(){await this.renderContent()}async renderContent(){let{contentEl:t}=this;t.empty(),await this.loadRelatedNotes(),new kr.Setting(t).setName(this.translate("modals.icsEventInfo.calendarEventHeading")).setHeading(),new kr.Setting(t).setName(this.translate("modals.icsEventInfo.titleLabel")).setDesc(this.icsEvent.title||this.translate("ui.icsCard.untitledEvent")),this.subscriptionName&&new kr.Setting(t).setName(this.translate("modals.icsEventInfo.calendarLabel")).setDesc(this.subscriptionName);let r=this.icsEvent.allDay&&/^\d{4}-\d{2}-\d{2}$/.test(this.icsEvent.start)?this.icsEvent.start+"T00:00:00":this.icsEvent.start,a=new Date(r),i=a.toLocaleDateString("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric"});if(!this.icsEvent.allDay&&(i+=` at ${a.toLocaleTimeString()}`,this.icsEvent.end)){let s=/^\d{4}-\d{2}-\d{2}$/.test(this.icsEvent.end)?this.icsEvent.end+"T00:00:00":this.icsEvent.end,o=new Date(s);i+=` - ${o.toLocaleTimeString()}`}new kr.Setting(t).setName(this.translate("modals.icsEventInfo.dateTimeLabel")).setDesc(i),this.icsEvent.location&&new kr.Setting(t).setName(this.translate("modals.icsEventInfo.locationLabel")).setDesc(this.icsEvent.location),this.icsEvent.description&&new kr.Setting(t).setName(this.translate("modals.icsEventInfo.descriptionLabel")).setDesc(this.icsEvent.description),this.icsEvent.url&&new kr.Setting(t).setName(this.translate("modals.icsEventInfo.urlLabel")).descEl.createEl("a",{cls:"external-link",href:this.icsEvent.url,text:this.icsEvent.url}).setAttribute("target","_blank"),new kr.Setting(t).setName(this.translate("modals.icsEventInfo.relatedNotesHeading")).setHeading(),this.relatedNotes.length===0?new kr.Setting(t).setDesc(this.translate("modals.icsEventInfo.noRelatedItems")):this.relatedNotes.forEach(s=>{let l=this.isTaskNote(s)?this.translate("modals.icsEventInfo.typeTask"):this.translate("modals.icsEventInfo.typeNote");new kr.Setting(t).setName(s.title).setDesc(`Type: ${l}`).addButton(c=>{c.setButtonText("Open").onClick(async()=>{await this.safeOpenFile(s.path),this.close()})})}),new kr.Setting(t).setName(this.translate("modals.icsEventInfo.actionsHeading")).setHeading(),new kr.Setting(t).setName(this.translate("modals.icsEventInfo.createFromEventLabel")).setDesc(this.translate("modals.icsEventInfo.createFromEventDesc")).addButton(s=>{s.setButtonText("Create note").onClick(()=>{this.openCreationModal()})}).addButton(s=>{s.setButtonText("Create task").onClick(async()=>{await this.createTaskDirectly()})}),new kr.Setting(t).setName(this.translate("modals.icsEventInfo.linkExistingLabel")).setDesc(this.translate("modals.icsEventInfo.linkExistingDesc")).addButton(s=>{s.setButtonText("Link note").onClick(()=>{this.linkExistingNote()})}).addButton(s=>{s.setButtonText("Refresh").onClick(()=>{this.refreshRelatedNotes()})})}async loadRelatedNotes(){let t=await Xi.execute(()=>this.plugin.icsNoteService.findRelatedNotes(this.icsEvent),{fallback:[],errorMessage:"Failed to load related notes",showNotice:!1});this.relatedNotes=t||[]}openCreationModal(){try{new lT(this.app,this.plugin,{icsEvent:this.icsEvent,subscriptionName:this.subscriptionName||"Unknown Calendar",onContentCreated:(r,a)=>{(async()=>(new kr.Notice(this.translate("notices.icsNoteCreatedSuccess")),this.refreshRelatedNotes(),await this.safeOpenFile(r.path)))()}}).open()}catch(t){i3.error("Error opening creation modal:",{category:"provider",operation:"opening-creation-modal",error:t}),new kr.Notice(this.translate("notices.icsCreationModalOpenFailed"))}}async linkExistingNote(){await Xi.execute(async()=>{pp(this.plugin,t=>{t instanceof kr.TAbstractFile&&Xi.execute(async()=>{await this.plugin.icsNoteService.linkNoteToICS(t.path,this.icsEvent),new kr.Notice(this.translate("notices.icsNoteLinkSuccess",{fileName:t.name})),this.refreshRelatedNotes()},{errorMessage:"Failed to link note",noticeHandler:Ze})},{placeholder:"Search notes to link...",filter:"markdown"})},{errorMessage:"Failed to open note selection",noticeHandler:Ze})}async createTaskDirectly(){await Xi.execute(async()=>{let t=await this.plugin.icsNoteService.createTaskFromICS(this.icsEvent);new kr.Notice(this.translate("notices.icsTaskCreatedSuccess",{taskTitle:t.taskInfo.title})),await this.safeOpenFile(t.file.path),this.refreshRelatedNotes()},{errorMessage:"Failed to create task from ICS event",noticeHandler:Ze})}async refreshRelatedNotes(){await Xi.execute(async()=>{await this.loadRelatedNotes(),await this.renderContent(),new kr.Notice(this.translate("notices.icsRelatedItemsRefreshed"))},{errorMessage:"Failed to refresh related notes",noticeHandler:Ze})}isTaskNote(t){var a;let r=this.plugin.settings.taskTag;return((a=t.tags)==null?void 0:a.includes(r))||!1}async safeOpenFile(t){try{let r=this.app.vault.getAbstractFileByPath(t);r instanceof kr.TFile?await this.app.workspace.getLeaf().openFile(r):(new kr.Notice(this.translate("notices.icsFileNotFound")),i3.error("Invalid file path or file not found:",{category:"provider",operation:"invalid-file-path-or-file-not-found",details:{value:t}}))}catch(r){i3.error("Error opening file:",{category:"provider",operation:"opening-file",error:r}),new kr.Notice(this.translate("notices.icsFileOpenFailed"))}}onClose(){let{contentEl:t}=this;t.empty()}}});var Ca,IQe,cT,s3=y(()=>{Ca=require("obsidian");rD();a3();SC();PF();Md();Id();q();Wd();IQe=M({tag:"Components/ICSEventContextMenu"}),cT=class{constructor(e){this.menu=new ra,this.options=e,this.buildMenu()}t(e,t){return this.options.plugin.i18n.translate(e,t)}getLocale(){return this.options.plugin.i18n.getCurrentLocale()||"en"}buildMenu(){let{icsEvent:e,plugin:t,subscriptionName:r}=this.options;this.menu.addItem(a=>a.setTitle(this.t("contextMenus.ics.showDetails")).setIcon("info").onClick(()=>{new Wc(t.app,t,e,r).open()})),this.menu.addSeparator(),this.menu.addItem(a=>a.setTitle(this.t("contextMenus.ics.createTask")).setIcon("check-circle").onClick(async()=>{await this.createTaskFromEvent()})),this.menu.addItem(a=>a.setTitle(this.t("contextMenus.ics.createNote")).setIcon("file-plus").onClick(()=>{this.createNoteFromEvent()})),this.menu.addItem(a=>a.setTitle(this.t("contextMenus.ics.linkNote")).setIcon("link").onClick(()=>{this.linkExistingNote()})),this.menu.addSeparator(),this.menu.addItem(a=>a.setTitle(this.t("contextMenus.ics.copyTitle")).setIcon("copy").onClick(async()=>{try{await navigator.clipboard.writeText(e.title),new Ca.Notice(this.t("contextMenus.ics.notices.copyTitleSuccess"))}catch(i){new Ca.Notice(this.t("contextMenus.ics.notices.copyFailure"))}})),e.location&&this.menu.addItem(a=>a.setTitle(this.t("contextMenus.ics.copyLocation")).setIcon("map-pin").onClick(async()=>{try{await navigator.clipboard.writeText(e.location||""),new Ca.Notice(this.t("contextMenus.ics.notices.copyLocationSuccess"))}catch(i){new Ca.Notice(this.t("contextMenus.ics.notices.copyFailure"))}})),e.url&&this.menu.addItem(a=>a.setTitle(this.t("contextMenus.ics.copyUrl")).setIcon("external-link").onClick(async()=>{try{await navigator.clipboard.writeText(e.url||""),new Ca.Notice(this.t("contextMenus.ics.notices.copyUrlSuccess"))}catch(i){new Ca.Notice(this.t("contextMenus.ics.notices.copyFailure"))}})),this.menu.addItem(a=>a.setTitle(this.t("contextMenus.ics.copyMarkdown")).setIcon("file-text").onClick(async()=>{let i=this.formatEventAsMarkdown();try{await navigator.clipboard.writeText(i),new Ca.Notice(this.t("contextMenus.ics.notices.copyMarkdownSuccess"))}catch(s){new Ca.Notice(this.t("contextMenus.ics.notices.copyFailure"))}}))}async createTaskFromEvent(){await Xi.execute(async()=>{let e=await this.options.plugin.icsNoteService.createTaskFromICS(this.options.icsEvent);new Ca.Notice(this.t("contextMenus.ics.notices.taskCreated",{title:e.taskInfo.title}));let t=this.options.plugin.app.vault.getAbstractFileByPath(e.file.path);t instanceof Ca.TFile&&await this.options.plugin.app.workspace.getLeaf().openFile(t),this.options.onUpdate&&this.options.onUpdate()},{errorMessage:this.t("contextMenus.ics.notices.taskCreateFailure"),noticeHandler:Ze})}createNoteFromEvent(){try{new lT(this.options.plugin.app,this.options.plugin,{icsEvent:this.options.icsEvent,subscriptionName:this.options.subscriptionName||this.t("contextMenus.ics.subscriptionUnknown"),onContentCreated:t=>{(async()=>(new Ca.Notice(this.t("contextMenus.ics.notices.noteCreated")),await this.options.plugin.app.workspace.getLeaf().openFile(t),this.options.onUpdate&&this.options.onUpdate()))()}}).open()}catch(e){IQe.error("Error opening creation modal:",{category:"provider",operation:"opening-creation-modal",error:e}),new Ca.Notice(this.t("contextMenus.ics.notices.creationFailure"))}}async linkExistingNote(){await Xi.execute(async()=>{pp(this.options.plugin,e=>{e instanceof Ca.TAbstractFile&&Xi.execute(async()=>{await this.options.plugin.icsNoteService.linkNoteToICS(e.path,this.options.icsEvent),new Ca.Notice(this.t("contextMenus.ics.notices.linkSuccess",{name:e.name})),this.options.onUpdate&&this.options.onUpdate()},{errorMessage:this.t("contextMenus.ics.notices.linkFailure"),noticeHandler:Ze})},{placeholder:"Search notes to link...",filter:"markdown"})},{errorMessage:this.t("contextMenus.ics.notices.linkSelectionFailure"),noticeHandler:Ze})}formatEventAsMarkdown(){let{icsEvent:e,subscriptionName:t}=this.options,r=[],a=e.title||this.t("contextMenus.ics.markdown.titleFallback");r.push(`## ${a}`),r.push(""),t&&r.push(this.t("contextMenus.ics.markdown.calendar",{value:t}));let i=this.getLocale(),s=e.allDay&&/^\d{4}-\d{2}-\d{2}$/.test(e.start)?e.start+"T00:00:00":e.start,o=new Date(s),l=new Intl.DateTimeFormat(i,{weekday:"long",year:"numeric",month:"long",day:"numeric"}),c=new Intl.DateTimeFormat(i,{hour:"numeric",minute:"2-digit"}),d=l.format(o);if(!e.allDay&&(d+=this.t("contextMenus.ics.markdown.at",{time:c.format(o)}),e.end)){let u=/^\d{4}-\d{2}-\d{2}$/.test(e.end)?e.end+"T00:00:00":e.end,p=new Date(u);d+=` - ${c.format(p)}`}return r.push(this.t("contextMenus.ics.markdown.date",{value:d})),e.location&&r.push(this.t("contextMenus.ics.markdown.location",{value:e.location})),e.description&&(r.push(""),r.push(this.t("contextMenus.ics.markdown.descriptionHeading")),r.push(e.description)),e.url&&(r.push(""),r.push(this.t("contextMenus.ics.markdown.url",{value:e.url}))),r.join(` +`)}show(e){za(this.menu,e)}showAtElement(e){jl(this.menu,e)}}});function uEe(n,e){return n.initialDate===e.initialDate&&n.initialDateProperty===e.initialDateProperty&&n.initialDateStrategy===e.initialDateStrategy}var pEe=y(()=>{});function nD(n){if(typeof n=="string"){let e=n.trim(),t=e.toLowerCase();if(!e||t==="null"||t==="undefined")return null;if(Jt(e)){let r=et(e);return Number.isNaN(r.getTime())?null:{value:D(r,"yyyy-MM-dd'T'HH:mm"),isAllDay:!1}}try{let r=st(e);return{value:ae(r),isAllDay:!0}}catch(r){return null}}if(typeof n=="number"){let e=new Date(n);return Number.isNaN(e.getTime())?null:{value:ae(e),isAllDay:!0}}return n instanceof Date?Number.isNaN(n.getTime())?null:n.getHours()!==0||n.getMinutes()!==0||n.getSeconds()!==0||n.getMilliseconds()!==0?{value:D(n,"yyyy-MM-dd'T'HH:mm"),isAllDay:!1}:{value:ae(n),isAllDay:!0}:null}function mEe(n){return typeof n.value=="string"?n.value:D(n.value,"yyyy-MM-dd'T'HH:mm")}function NQe(n,e,t,r){if(e){let a=r(n,e);if(typeof a=="string"&&a.trim())return a.trim()}return t.basename||t.name||t.path}function fEe({entry:n,file:e,startDateProperty:t,endDateProperty:r,titleProperty:a,getPropertyValue:i}){if(!e)return null;let s=nD(i(n,t));if(!s)return null;let o=mEe(s),l,c=s.isAllDay;if(r){let d=nD(i(n,r));d&&(l=mEe(d),c=d.isAllDay)}return{id:`property-${e.path}`,title:NQe(n,a,e,i),start:o,end:l,allDay:s.isAllDay&&(l?c:!0),backgroundColor:"var(--color-accent)",borderColor:"var(--color-accent)",textColor:"var(--text-on-accent)",editable:!0,extendedProps:{eventType:"property-based",filePath:e.path,file:e,basesEntry:n}}}var o3=y(()=>{Cr();xe()});function hEe({viewOptions:n,taskNotes:e,entries:t,getEntryPropertyValue:r,getContextPropertyValue:a,mapPropertyToTaskField:i}){var o;if(n.initialDate){let l=nD(n.initialDate);return(o=l==null?void 0:l.value)!=null?o:n.initialDate}if(!n.initialDateProperty)return;let s=RQe({propertyId:n.initialDateProperty,taskNotes:e,entries:t,getEntryPropertyValue:r,mapPropertyToTaskField:i});if(s.length===0){let l=a?l3(a(n.initialDateProperty)):null;return l==null?void 0:l.value}return n.initialDateStrategy==="earliest"?s.reduce((l,c)=>c.compare.getTime()c.compare.getTime()>l.compare.getTime()?c:l).value:s[0].value}function RQe({propertyId:n,taskNotes:e,entries:t,getEntryPropertyValue:r,mapPropertyToTaskField:a}){var o,l;let i=[];if(t&&r)for(let c of t){let d=l3(r(c,n));d&&i.push(d)}if(i.length>0)return i;let s=a(n);for(let c of e){let d=c,u=c.customProperties,p=(l=(o=d[s])!=null?o:u==null?void 0:u[s])!=null?l:u==null?void 0:u[n],m=l3(p);m&&i.push(m)}return i}function l3(n){let e=nD(n);if(!e)return null;let t=e.isAllDay?st(e.value):new Date(e.value);return Number.isNaN(t.getTime())?null:{compare:t,value:e.value}}function gEe(n){return{initialDate:n.initialDate,initialDateProperty:n.initialDateProperty,initialDateStrategy:n.initialDateStrategy}}var yEe=y(()=>{xe();o3()});function LQe(n){return typeof n=="object"&&n!==null}function OQe(n){let e=n.split(".");return e.length>1&&["note","file","formula"].includes(e[0])?e.slice(1).join("."):n}function zQe(n,e){if(Object.prototype.hasOwnProperty.call(n,e))return n[e];let t=OQe(e);return t!==e&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:null}function c3(n,e=new WeakSet){return n===void 0||typeof n=="function"||typeof n=="symbol"?null:typeof n=="bigint"?n.toString():n instanceof Date?n.toISOString():Array.isArray(n)?n.map(t=>c3(t,e)):LQe(n)?e.has(n)?"[Circular]":(e.add(n),Object.keys(n).sort().reduce((t,r)=>(t[r]=c3(n[r],e),t),{})):n}function vEe(n){var r,a,i;let e=new Set,t=s=>{if(typeof s!="string")return;let o=s.trim();o&&e.add(o)};for(let s of _Qe)t((a=(r=n.mapField(s))!=null?r:FQe[s])!=null?a:s);t("tags"),t("archived");for(let s of(i=n.visiblePropertyIds)!=null?i:[])t(s);return n.showPropertyBasedEvents&&(t(n.startDateProperty),t(n.endDateProperty),t(n.titleProperty)),Array.from(e)}function kEe(n,e){let t=n.map(r=>{let a=r.properties||r.frontmatter||{},i=e.map(s=>[s,c3(zQe(a,s))]);return{path:r.path||"",values:i}});return JSON.stringify({propertyIds:e,rows:t})}function TEe(n){return n.map(e=>{var t,r;return(r=(t=e.file)==null?void 0:t.path)!=null?r:""}).join("\0")}var _Qe,FQe,bEe=y(()=>{_Qe=["title","status","priority","due","scheduled","contexts","projects","timeEstimate","completedDate","recurrence","recurrenceAnchor","timeEntries","completeInstances","skippedInstances","blockedBy","icsEventId","googleCalendarEventId","googleCalendarExceptionOriginalScheduled","googleCalendarMovedOriginalDates","reminders","sortOrder"],FQe={completeInstances:"complete_instances",recurrenceAnchor:"recurrence_anchor",skippedInstances:"skipped_instances"}});function jQe(n){return typeof n=="object"&&n!==null}function d3(n){let e=[];for(let t of n!=null?n:[]){if(typeof t!="string")continue;let r=t.trim();r&&e.push(r)}return e.sort()}function u3(n,e){if(!n||typeof n.get!="function")return;let t=n.get(e);if(t!=null)return t;let r=n.get("options");if(jQe(r))return r[e]}function p3(n,e,t){let r=u3(n,e);return r==null?t:r}function $Qe(n={}){return[...BQe,...d3(n.icsCalendarIds).map(e=>`showICS_${e}`),...d3(n.googleCalendarIds).map(e=>`showGoogleCalendar_${e}`),...d3(n.microsoftCalendarIds).map(e=>`showMicrosoftCalendar_${e}`)]}function wEe(n){if(!n.config||typeof n.config.get!="function")return"";let e=$Qe({icsCalendarIds:n.icsCalendarIds,googleCalendarIds:n.googleCalendarIds,microsoftCalendarIds:n.microsoftCalendarIds});return JSON.stringify(e.map(t=>u3(n.config,t)))}var BQe,m3=y(()=>{BQe=["showScheduled","showDue","showScheduledToDueSpan","showRecurring","showCompletedRecurringInstances","showSkippedRecurringInstances","showTimeEntries","showTimeblocks","showPropertyBasedEvents","showOverdueOnToday","calendarView","heightMode","customDayCount","listDayCount","slotMinTime","slotMaxTime","slotDuration","snapDuration","firstDay","weekNumbers","nowIndicator","showWeekends","showAllDaySlot","showTimeGrid","showTodayHighlight","todayColumnWidthMultiplier","selectMirror","timeFormat","scrollTime","eventMinHeight","slotEventOverlap","eventMaxStack","dayMaxEvents","dayMaxEventRows","startDateProperty","endDateProperty","titleProperty","initialDate","initialDateProperty","initialDateStrategy","createDailyNotesFromDateLinks"]});function UQe(n,e){return e==="google"?n.subscriptionId.replace("google-",""):e==="microsoft"?n.subscriptionId.replace("microsoft-",""):n.subscriptionId}function AF(n,e,t){n.set(e.id,t),e.primary&&n.set(nq,t)}function HQe(n,e,t){return(t==null?void 0:t.get(UQe(n,e)))!==!1}function MF({events:n,provider:e,plugin:t,toggles:r,relatedNoteCountsByEventId:a,createEvent:i=X4}){let s=[];for(let o of n){if(!HQe(o,e,r))continue;let l=i(o,t,{relatedNoteCount:a==null?void 0:a.get(o.id)});l&&s.push(l)}return s}var f3=y(()=>{tD();nm()});function SEe(n,e){return`${n.i18n.translate("modals.icsEventInfo.relatedNotesHeading")}: ${e}`}function WQe(n,e,t){let r=typeof t=="number"&&t>0?t:0,a=n.querySelector(".ics-card__related-note-indicator");if(!r){a==null||a.remove();return}let i=a||n.createSpan({cls:"ics-card__related-note-indicator"});i.dataset.relatedNoteCount=String(r),i.setAttribute("aria-label",SEe(e,r)),(0,aD.setIcon)(i,"file-text"),(0,aD.setTooltip)(i,SEe(e,r),{placement:"top"})}function qQe(n,e,t){var a;if(t!=null&&t.name)return t.name;let r=(a=e.calendarProviderRegistry)==null?void 0:a.findProviderForEvent(n);if(r){let{calendarId:i}=r.extractEventIds(n),s=rm(r.getAvailableCalendars(),i);return(s==null?void 0:s.summary)||r.providerName}return e.i18n.translate("ui.icsCard.calendarFallback")}function GQe(n,e){try{if(!n.start)return"";let t=new Date(n.start);if(n.allDay)return e.i18n.translate("ui.icsCard.allDay");let r=e.settings.calendarViewSettings.timeFormat,a=Wu(t,r);if(n.end){let i=new Date(n.end),s=Wu(i,r);return`${a} – ${s}`}return a}catch(t){return""}}function CEe(n,e,t={}){var v;let r={...VQe,...t},a=activeWindow.createDiv();a.className="task-card task-card--ics",a.dataset.key=n.id,r.relatedNoteCount&&r.relatedNoteCount>0&&(a.classList.add("has-related-note","task-card--ics-has-related-note"),a.dataset.relatedNoteCount=String(r.relatedNoteCount));let i=(v=e.icsSubscriptionService)==null?void 0:v.getSubscriptions().find(k=>k.id===n.subscriptionId),s=n.color||(i==null?void 0:i.color)||"var(--color-accent)",o=qQe(n,e,i),l=a.createDiv({cls:"task-card__main-row"}),c=l.createSpan({cls:"ics-card__icon"}),d=c.createDiv({attr:{"aria-label":e.i18n.translate("ui.icsCard.calendarEvent")}});(0,aD.setIcon)(d,"calendar");let u=c;u.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),u.classList.add("tn-static-display-inline-flex-f984c520"),u.classList.remove("tn-static-width-100-0466783d","tn-static-width-12px-fbf353fb","tn-static-width-1px-aa77e27e","tn-static-width-200px-2acaf3b5","tn-static-width-60px-bd09c419","tn-static-width-80px-8573bae3"),u.classList.add("tn-static-width-16px-7375d50b"),u.classList.remove("tn-static-display-flex-4d51fc62","tn-static-height-0-7a31cef0","tn-static-height-100-62264068","tn-static-height-12px-06c0747e","tn-static-height-24px-29a11d37","tn-static-min-height-800px-997b4c8c"),u.classList.add("tn-static-height-16px-30de4aee"),u.classList.remove("tn-static-margin-right-4px-c6b76b85"),u.classList.add("tn-static-margin-right-8px-539fa9a0"),u.classList.remove("tn-static-align-items-baseline-4b95b5c7","tn-static-align-items-flex-start-0486f781"),u.classList.add("tn-static-align-items-center-7c619740"),u.classList.remove("tn-static-justify-content-flex-end-455f8cca","tn-static-justify-content-space-between-a562f4fd"),u.classList.add("tn-static-justify-content-center-03c4bb6f"),u.classList.add("tn-static-flex-shrink-0-6ee0661e"),d.classList.remove("tn-static-width-12px-fbf353fb","tn-static-width-16px-7375d50b","tn-static-width-1px-aa77e27e","tn-static-width-200px-2acaf3b5","tn-static-width-60px-bd09c419","tn-static-width-80px-8573bae3"),d.classList.add("tn-static-width-100-0466783d"),d.classList.remove("tn-static-display-flex-4d51fc62","tn-static-height-0-7a31cef0","tn-static-height-12px-06c0747e","tn-static-height-16px-30de4aee","tn-static-height-24px-29a11d37","tn-static-min-height-800px-997b4c8c"),d.classList.add("tn-static-height-100-62264068"),d.style.color=s;let p=l.createDiv({cls:"task-card__content"}),m=p.createDiv({cls:"task-card__title",text:n.title||e.i18n.translate("ui.icsCard.untitledEvent")});WQe(m,e,r.relatedNoteCount);let f=p.createDiv({cls:"task-card__metadata"}),h=[],g=GQe(n,e);return g&&h.push(g),n.location&&h.push(n.location),h.push(o),f.textContent=h.join(" • "),a.addEventListener("click",()=>{new Wc(e.app,e,n,o).open()}),a.addEventListener("contextmenu",k=>{k.preventDefault(),k.stopPropagation(),new cT({icsEvent:n,plugin:e,subscriptionName:o,onUpdate:()=>{e.app.workspace.trigger("tasknotes:refresh-views")}}).show(k)}),a.style.setProperty("--current-status-color",s),a}var aD,VQe,xEe=y(()=>{aD=require("obsidian");s3();xe();rD();nm();VQe={showDate:!0}});function DEe(n,e,t,r={}){var u,p,m;let a={...KQe,...r},i=activeWindow.createDiv();i.className="task-card task-card--property-event";let s=n.file;if(!s)return i.textContent=e.i18n.translate("ui.propertyEventCard.unknownFile"),i;i.dataset.key=`property-${s.path}`,i.dataset.filePath=s.path;let o=i.createDiv({cls:"task-card__main-row"}),l=o.createSpan({cls:"property-event-card__icon"}),c=l.createDiv();(0,EEe.setIcon)(c,"file-text"),l.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),l.classList.add("tn-static-display-inline-flex-f984c520"),l.classList.remove("tn-static-width-100-0466783d","tn-static-width-12px-fbf353fb","tn-static-width-1px-aa77e27e","tn-static-width-200px-2acaf3b5","tn-static-width-60px-bd09c419","tn-static-width-80px-8573bae3"),l.classList.add("tn-static-width-16px-7375d50b"),l.classList.remove("tn-static-display-flex-4d51fc62","tn-static-height-0-7a31cef0","tn-static-height-100-62264068","tn-static-height-12px-06c0747e","tn-static-height-24px-29a11d37","tn-static-min-height-800px-997b4c8c"),l.classList.add("tn-static-height-16px-30de4aee"),l.classList.remove("tn-static-margin-right-4px-c6b76b85"),l.classList.add("tn-static-margin-right-8px-539fa9a0"),l.classList.remove("tn-static-align-items-baseline-4b95b5c7","tn-static-align-items-flex-start-0486f781"),l.classList.add("tn-static-align-items-center-7c619740"),l.classList.remove("tn-static-justify-content-flex-end-455f8cca","tn-static-justify-content-space-between-a562f4fd"),l.classList.add("tn-static-justify-content-center-03c4bb6f"),l.classList.add("tn-static-flex-shrink-0-6ee0661e"),c.classList.remove("tn-static-width-12px-fbf353fb","tn-static-width-16px-7375d50b","tn-static-width-1px-aa77e27e","tn-static-width-200px-2acaf3b5","tn-static-width-60px-bd09c419","tn-static-width-80px-8573bae3"),c.classList.add("tn-static-width-100-0466783d"),c.classList.remove("tn-static-display-flex-4d51fc62","tn-static-height-0-7a31cef0","tn-static-height-12px-06c0747e","tn-static-height-16px-30de4aee","tn-static-height-24px-29a11d37","tn-static-min-height-800px-997b4c8c"),c.classList.add("tn-static-height-100-62264068"),c.classList.remove("tn-static-color-var-text-accent-65b47ee3","tn-static-color-var-text-muted-5872de20","tn-static-color-var-text-on-accent-f3e1679d","tn-static-color-var-text-warning-783d5f03","tn-static-color-var-tn-text-muted-a90fb6f3","tn-static-color-white-0a43e56a","tn-static-cursor-pointer-2723efcc","tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-2px-0-edce9b14","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c"),c.classList.add("tn-static-color-var-color-accent-d2cad743");let d=o.createDiv({cls:"task-card__content"});if(d.createDiv({cls:"task-card__title",text:s.basename||s.name}),a.showProperties&&t){let f=d.createDiv({cls:"task-card__metadata"}),h=0;try{let g=f.ownerDocument,v=((u=t.getOrder)==null?void 0:u.call(t))||[],k=(p=t.getAsPropertyId)==null?void 0:p.call(t,"startDateProperty"),T=(m=t.getAsPropertyId)==null?void 0:m.call(t,"endDateProperty");for(let b of v){if(b===k||b===T)continue;let w=n.getValue(b);if(!lC(w)){h>0&&f.appendChild(g.createTextNode(" • "));let S=t.getDisplayName(b)||b,C=f.createSpan({cls:"property-event-card__metadata-property"});C.createSpan({text:`${S}: `});let x=C.createSpan({cls:"property-event-card__metadata-value"});GA(x,w,e.app.renderContext),h++}}}catch(g){YQe.debug("[TaskNotes][PropertyEventCard] Error reading properties:",{category:"persistence",operation:"reading-properties",error:g})}h===0&&(f.textContent=s.path)}return i.addEventListener("click",f=>{let h=f.ctrlKey||f.metaKey;e.app.workspace.openLinkText(s.path,"",h)}),i.addEventListener("mouseover",f=>{e.app.workspace.trigger("hover-link",{event:f,source:"tasknotes-property-event-card",hoverParent:i,targetEl:i,linktext:s.path,sourcePath:s.path})}),i.setCssProps({"--current-status-color":"var(--color-accent)"}),i}var EEe,YQe,KQe,PEe=y(()=>{EEe=require("obsidian");cC();q();YQe=M({tag:"Ui/PropertyEventCard"}),KQe={showProperties:!0}});function MEe(n,e,t={}){let r={...ZQe,...t},a=activeWindow.createDiv();a.className="task-card task-card--timeblock",a.dataset.key=`timeblock-${n.id}`;let i=a.createDiv({cls:"task-card__main-row"}),s=i.createSpan({cls:"timeblock-card__icon"}),o=s.createDiv();(0,AEe.setIcon)(o,"clock"),s.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-none-6b99de8b","tn-static-min-height-800px-997b4c8c"),s.classList.add("tn-static-display-inline-flex-f984c520"),s.classList.remove("tn-static-width-100-0466783d","tn-static-width-12px-fbf353fb","tn-static-width-1px-aa77e27e","tn-static-width-200px-2acaf3b5","tn-static-width-60px-bd09c419","tn-static-width-80px-8573bae3"),s.classList.add("tn-static-width-16px-7375d50b"),s.classList.remove("tn-static-display-flex-4d51fc62","tn-static-height-0-7a31cef0","tn-static-height-100-62264068","tn-static-height-12px-06c0747e","tn-static-height-24px-29a11d37","tn-static-min-height-800px-997b4c8c"),s.classList.add("tn-static-height-16px-30de4aee"),s.classList.remove("tn-static-margin-right-4px-c6b76b85"),s.classList.add("tn-static-margin-right-8px-539fa9a0"),s.classList.remove("tn-static-align-items-baseline-4b95b5c7","tn-static-align-items-flex-start-0486f781"),s.classList.add("tn-static-align-items-center-7c619740"),s.classList.remove("tn-static-justify-content-flex-end-455f8cca","tn-static-justify-content-space-between-a562f4fd"),s.classList.add("tn-static-justify-content-center-03c4bb6f"),s.classList.add("tn-static-flex-shrink-0-6ee0661e"),o.classList.remove("tn-static-width-12px-fbf353fb","tn-static-width-16px-7375d50b","tn-static-width-1px-aa77e27e","tn-static-width-200px-2acaf3b5","tn-static-width-60px-bd09c419","tn-static-width-80px-8573bae3"),o.classList.add("tn-static-width-100-0466783d"),o.classList.remove("tn-static-display-flex-4d51fc62","tn-static-height-0-7a31cef0","tn-static-height-12px-06c0747e","tn-static-height-16px-30de4aee","tn-static-height-24px-29a11d37","tn-static-min-height-800px-997b4c8c"),o.classList.add("tn-static-height-100-62264068"),o.style.color=n.color||"var(--color-accent)";let l=i.createDiv({cls:"task-card__content"}),c=n.title||"Timeblock",d=`${n.startTime} - ${n.endTime}`;l.createDiv({cls:"task-card__title",text:c});let u=l.createDiv({cls:"task-card__metadata"});if(u.textContent=d,r.showDescription&&n.description){let p=l.createDiv({cls:"task-card__description",text:n.description});p.classList.remove("tn-static-font-size-0-75em-948e16e5","tn-static-font-size-0-8em-19dc7c13","tn-static-font-size-0-9em-65025e95","tn-static-font-size-1-2em-3a352995","tn-static-font-size-12px-65574819","tn-static-font-size-12px-b0cc7e05","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-margin-top-8px-f4f01e68"),p.classList.add("tn-static-font-size-var-tn-font-size-sm-0274a31d"),p.classList.remove("tn-static-color-var-color-accent-d2cad743","tn-static-color-var-text-accent-65b47ee3","tn-static-color-var-text-muted-5872de20","tn-static-color-var-text-on-accent-f3e1679d","tn-static-color-var-text-warning-783d5f03","tn-static-color-white-0a43e56a","tn-static-cursor-pointer-2723efcc","tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-2px-0-edce9b14","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c"),p.classList.add("tn-static-color-var-tn-text-muted-a90fb6f3"),p.classList.remove("tn-static-font-size-12px-b0cc7e05","tn-static-margin-top-0-5rem-3dc98b5e","tn-static-margin-top-0-d462248a","tn-static-margin-top-12px-91e0f558","tn-static-margin-top-16px-1b0f4999","tn-static-margin-top-1rem-2239d6d5","tn-static-margin-top-20px-a26bda7d","tn-static-margin-top-30px-2fbbbcd4","tn-static-margin-top-8px-8a77e5a3","tn-static-margin-top-8px-f4f01e68"),p.classList.add("tn-static-margin-top-4px-96ad6099")}if(r.showAttachments&&n.attachments&&n.attachments.length>0){let p=l.createDiv({cls:"timeblock-card__attachments"});p.classList.remove("tn-static-font-size-0-75em-948e16e5","tn-static-font-size-0-8em-19dc7c13","tn-static-font-size-0-9em-65025e95","tn-static-font-size-1-2em-3a352995","tn-static-font-size-12px-65574819","tn-static-font-size-12px-b0cc7e05","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-margin-top-8px-f4f01e68"),p.classList.add("tn-static-font-size-var-tn-font-size-sm-0274a31d"),p.classList.remove("tn-static-color-var-color-accent-d2cad743","tn-static-color-var-text-accent-65b47ee3","tn-static-color-var-text-muted-5872de20","tn-static-color-var-text-on-accent-f3e1679d","tn-static-color-var-text-warning-783d5f03","tn-static-color-white-0a43e56a","tn-static-cursor-pointer-2723efcc","tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-2px-0-edce9b14","tn-static-padding-20px-7a035d95","tn-static-padding-20px-ebe8e48c"),p.classList.add("tn-static-color-var-tn-text-muted-a90fb6f3"),p.classList.remove("tn-static-font-size-12px-b0cc7e05","tn-static-margin-top-0-5rem-3dc98b5e","tn-static-margin-top-0-d462248a","tn-static-margin-top-12px-91e0f558","tn-static-margin-top-16px-1b0f4999","tn-static-margin-top-1rem-2239d6d5","tn-static-margin-top-20px-a26bda7d","tn-static-margin-top-30px-2fbbbcd4","tn-static-margin-top-8px-8a77e5a3","tn-static-margin-top-8px-f4f01e68"),p.classList.add("tn-static-margin-top-4px-96ad6099");let m=n.attachments.length===1?"1 attachment":`${n.attachments.length} attachments`;p.textContent=`📎 ${m}`}return a.addEventListener("click",p=>{r.eventDate&&r.originalDate&&xF(n,r.eventDate,r.originalDate,e)}),n.color?a.style.setProperty("--current-status-color",n.color):a.setCssProps({"--current-status-color":"var(--color-accent)"}),a}var AEe,ZQe,IEe=y(()=>{AEe=require("obsidian");tD();ZQe={showDescription:!0,showAttachments:!0}});function IF(n,e){return`${n.i18n.translate("modals.icsEventInfo.relatedNotesHeading")}: ${e}`}function h3(n){return typeof n=="number"&&n>0?n:0}function QQe(n,e,t){if(t<=0||n.querySelector(".ics-related-note-indicator"))return;let r=n.ownerDocument,a=Ie(r,"span");a.classList.add("ics-related-note-indicator"),a.setAttribute("aria-label",IF(e,t)),a.dataset.relatedNoteCount=String(t),(0,iD.setIcon)(a,"file-text"),(0,iD.setTooltip)(a,IF(e,t),{placement:"top"}),n.appendChild(a)}function NEe({element:n,viewType:e,icsEvent:t,relatedNoteCount:r,plugin:a}){var o;if(!t||(n.setAttribute("data-ics-event","true"),n.classList.add("fc-ics-event"),r>0&&(n.classList.add("has-related-note","fc-event--has-related-note"),n.dataset.relatedNoteCount=String(r)),e==="listWeek"))return;if(((o=a.calendarProviderRegistry)==null?void 0:o.findProviderForEvent(t))&&!n.querySelector(".fc-event-provider-icon")){let l=Ie(n.ownerDocument,"span");l.classList.add("fc-event-provider-icon"),l.setAttribute("aria-hidden","true"),(0,iD.setIcon)(l,"calendar"),n.appendChild(l)}let s=n.querySelector(".fc-event-title");s&&r>0&&QQe(s,a,r)}function JQe({taskInfo:n,basesEntry:e,visibleProperties:t,logDebug:r}){var i,s,o;let a={...n};if(!e)return a;a.basesData=e;for(let l of t)if(l.startsWith("formula."))try{(i=e.getValue)==null||i.call(e,l)}catch(c){r==null||r("[TaskNotes][CalendarView] Error getting formula:",l,c)}if(!a.dateCreated)try{let l=(s=e.getValue)==null?void 0:s.call(e,"file.ctime");l!=null&&l.data&&(a.dateCreated=l.data)}catch(l){r==null||r("[TaskNotes][CalendarView] Error getting file.ctime:",l)}if(!a.dateModified)try{let l=(o=e.getValue)==null?void 0:o.call(e,"file.mtime");l!=null&&l.data&&(a.dateModified=l.data)}catch(l){r==null||r("[TaskNotes][CalendarView] Error getting file.mtime:",l)}return a}function REe({arg:n,plugin:e,config:t,visibleProperties:r,basesEntryByPath:a,buildTaskCardOptions:i,logDebug:s,factories:o={}}){var v,k,T,b,w;if(n.view.type!=="listWeek")return!1;n.el.innerHTML="";let{taskInfo:l,timeblock:c,icsEvent:d,eventType:u,basesEntry:p,relatedNoteCount:m}=n.event.extendedProps||{},f=h3(m),h=null;if(l&&u!=="ics"&&u!=="property-based"){let S=JQe({taskInfo:l,basesEntry:a.get(l.path),visibleProperties:r,logDebug:s}),C=SF(n);h=((v=o.createTaskCard)!=null?v:pr)(S,e,r,i({targetDate:C,promoteOccurrenceControlsInContextMenu:!!(l.recurrence||l.recurrence_parent&&l.occurrence_date)}))}else if(d&&u==="ics")h=((k=o.createICSEventCard)!=null?k:CEe)(d,e,{relatedNoteCount:f});else if(u==="property-based"&&p)h=((T=o.createPropertyEventCard)!=null?T:DEe)(p,e,t);else if(u==="timeblock"&&c){let S=n.event.start?D(n.event.start,"yyyy-MM-dd"):void 0;h=((b=o.createTimeBlockCard)!=null?b:MEe)(c,e,{eventDate:(w=n.event.start)!=null?w:void 0,originalDate:S})}if(!h)return n.el.classList.add("fc-event-default-list"),!1;let g=Ie(n.el.ownerDocument,"td");return g.className="fc-list-event-title fc-list-card-content",g.colSpan=3,g.appendChild(h),n.el.appendChild(g),l!=null&&l.path&&(n.el.setAttribute("data-task-path",l.path),n.el.classList.add("fc-task-event")),n.el.classList.add("fc-list-task-card"),n.el.classList.remove("fc-event","fc-event-start","fc-event-end"),!0}var iD,_Ee=y(()=>{iD=require("obsidian");Cr();Ua();xEe();PEe();IEe();tD();Li()});function NF(n,e,t={}){var l,c,d;if(!n)return{value:e,isValid:!0};let r=/^(\d{2}):([0-5]\d)(?::([0-5]\d))?$/.exec(n);if(!r)return{value:e,isValid:!1};let a=Number(r[1]),i=Number(r[2]),s=Number((l=r[3])!=null?l:"00"),o=(c=t.maxHour)!=null?c:23;return a<0||a>o?{value:e,isValid:!1}:t.allowMaxHourOnlyAtZero&&a===o&&(i!==0||s!==0)?{value:e,isValid:!1}:{value:`${r[1]}:${r[2]}:${(d=r[3])!=null?d:"00"}`,isValid:!0}}var g3=y(()=>{});function XQe(n){Jn.Platform.isMobile&&(n.classList.add("tn-calendar-event-touch-target"),n.addEventListener("contextmenu",e=>{e.preventDefault(),e.stopImmediatePropagation()},{capture:!0}))}function eJe(n,e){let t=n.querySelector(".fc-refreshCalendars-button");if(!t)return;let r=e.trim()||"Refresh calendar subscriptions";t.replaceChildren(),(0,Jn.setIcon)(t,"refresh-cw"),t.classList.add("tasknotes-calendar-refresh-button--icon"),t.setAttribute("aria-label",r),t.setAttribute("title",r)}function og(n){return typeof n=="object"&&n!==null}function jEe(n){return Array.isArray(n)?n.length>0:!!n}function LEe(n){return jEe(n)?`start,allDay,${BEe},-duration,title`:rJe}function aJe(n){let e=n.extendedProps;if(!og(e))return null;let t=e.taskInfo;return og(t)&&typeof t.path=="string"?t.path:typeof e.filePath=="string"?e.filePath:null}function OEe(n,e){if(e.size!==0)for(let t of n){let r=aJe(t);if(!r)continue;let a=e.get(r);a!==void 0&&(t.extendedProps={...og(t.extendedProps)?t.extendedProps:{},[BEe]:a})}}function iJe(n,e){return!e&&!!(n!=null&&n.startsWith("list"))}function sJe(n,e,t){return iJe(e,t)?n.filter(r=>r.allDay!==!0):n}function oJe(n){return og(n)}function lJe(n){return og(n)&&typeof n.scrollTop=="number"&&typeof n.scrollLeft=="number"}function cJe(n,e){return e<=1?!1:n==="timeGridWeek"||n==="timeGridCustom"}function dJe(n){return n==="timeGridWeek"||n==="timeGridCustom"||n==="timeGridDay"}function zEe(n,e){return!n&&dJe(e)}function uJe(n){return typeof n=="string"&&n.trim().toLowerCase()==="auto"?"auto":"fill"}function pJe(n){return n==="auto"?{height:"auto",contentHeight:"auto",expandRows:!1}:{height:"100%",expandRows:!0}}function mJe(n,e,t){return n==="auto"||!!(t!=null&&t.closest(".internal-embed, .markdown-embed"))?"auto":"fill"}function $Ee(n){let e=n.closest("table");if(!e)return null;let t=Array.from(e.children).find(a=>a.tagName==="COLGROUP");if(!t)return null;let r=t.children[n.cellIndex];return(r==null?void 0:r.tagName)==="COL"?r:null}function hJe(n){n.querySelectorAll(fJe).forEach(t=>{t.style.removeProperty("width"),t.style.removeProperty("min-width"),t.style.removeProperty("max-width");let r=$Ee(t);r&&r.style.removeProperty("width")})}function gJe(n,e){return!n||!n.isConnected||!e.isConnected||n.ownerDocument!==e.ownerDocument?!1:n.clientWidth>0&&n.clientHeight>0}function yJe(n,e=window){if(!n)return!1;let t=n.ownerDocument.defaultView;return!!(t&&t!==e)}function UEe(n){return n?[n,...Array.from(n.querySelectorAll(".fc-scroller"))]:[]}function vJe(n){return UEe(n).map(e=>({scrollTop:e.scrollTop,scrollLeft:e.scrollLeft}))}function kJe(n,e){if(!Array.isArray(e))return;let t=UEe(n);e.forEach((r,a)=>{if(!lJe(r))return;let i=t[a];i&&(i.scrollTop=r.scrollTop,i.scrollLeft=r.scrollLeft)})}function TJe(n,e,t){if(t<=1||n.length<=1)return null;let r=Array.from(new Set(n));if(!r.includes(e))return null;let a=100/(r.length-1+t),i=a*t;return new Map(r.map(s=>[s,`${s===e?i:a}%`]))}function HEe(n){return function(e,t){if(!t)throw Nr.error("[TaskNotes][CalendarView] No containerEl provided",{category:"provider",operation:"no-containerel-provided"}),new Error("CalendarView requires a containerEl");return new v3(e,t,n)}}var Jn,Nr,FEe,tJe,y3,rJe,BEe,nJe,fJe,v3,VEe=y(()=>{Li();IE();ME();Eh();axe();mxe();yxe();SW();kxe();tD();lEe();oB();UM();cEe();rD();Jn=require("obsidian");Cr();DC();s3();xe();pEe();yEe();bEe();m3();o3();f3();_Ee();g3();yt();ya();q();m3();Nr=M({tag:"Bases/CalendarView"});FEe=5e3,tJe=250,y3=2e3,rJe="start,-duration,allDay,title",BEe="tasknotesSortIndex",nJe=sR;fJe=".fc-col-header-cell[data-date], .fc-timegrid-col[data-date], .fc-daygrid-day[data-date], .fc-timegrid-axis, .fc-timegrid-slot-label";v3=class extends Bc{constructor(t,r,a){super(t,r,a);this.type="tasknotesCalendar";this.calendar=null;this.calendarEl=null;this.currentTasks=[];this.basesEntryByPath=new Map;this.basesSortIndexByPath=new Map;this._isRendering=!1;this._pendingRender=!1;this._expectingImmediateUpdate=!1;this._isFirstDataUpdate=!0;this._previousConfigSnapshot=null;this._saveViewTypeTimer=null;this._configChangedNeedsRecreate=!1;this._recreateTargetDate=null;this._previousDataSignature=null;this._previousControllerViewName=null;this.icsCalendarToggles=new Map;this.googleCalendarToggles=new Map;this.microsoftCalendarToggles=new Map;this.configLoaded=!1;this.basesController=t,this.dataAdapter.basesView=this;let i=this.plugin.settings.calendarViewSettings;this.viewOptions={showScheduled:i.defaultShowScheduled,showDue:i.defaultShowDue,showScheduledToDueSpan:i.defaultShowScheduledToDueSpan,showRecurring:i.defaultShowRecurring,showCompletedRecurringInstances:!0,showSkippedRecurringInstances:!0,showTimeEntries:i.defaultShowTimeEntries,showTimeblocks:i.defaultShowTimeblocks,showPropertyBasedEvents:!0,showOverdueOnToday:!1,initialDate:"",initialDateProperty:null,initialDateStrategy:"first",createDailyNotesFromDateLinks:!0,calendarView:i.defaultView,heightMode:"fill",customDayCount:i.customDayCount,listDayCount:7,slotMinTime:this.validateTimeValue(i.slotMinTime,"00:00:00"),slotMaxTime:this.validateTimeValue(i.slotMaxTime,"24:00:00",48,!0),slotDuration:this.validateTimeValue(i.slotDuration,"00:30:00"),snapDuration:this.validateTimeValue(i.slotDuration,"00:30:00"),scrollTime:this.validateTimeValue(i.scrollTime,"08:00:00"),firstDay:i.firstDay,weekNumbers:i.weekNumbers,nowIndicator:i.nowIndicator,showWeekends:i.showWeekends,showAllDaySlot:!0,showTimeGrid:!0,showTodayHighlight:i.showTodayHighlight,todayColumnWidthMultiplier:1,selectMirror:i.selectMirror,timeFormat:i.timeFormat,eventMinHeight:i.eventMinHeight,slotEventOverlap:i.slotEventOverlap,eventMaxStack:i.eventMaxStack,dayMaxEvents:i.dayMaxEvents,dayMaxEventRows:i.dayMaxEventRows,locale:i.locale,startDateProperty:null,endDateProperty:null,titleProperty:null}}onload(){this.readViewOptions(),this._previousConfigSnapshot=this.getConfigSnapshot(),this._previousDataSignature=this.getDataSignature(),this._previousControllerViewName=this.getControllerViewName(),super.onload()}onResize(){if(this.isPopoutWindow()){this.renderPopoutUnsupported();return}!this.calendar||!this.canUpdateCalendarSize()||(this.calendar.updateSize(),this.scheduleTodayColumnWidthUpdate(),this.scheduleDailyNoteHeaderLinkUpdate())}onDataUpdated(){var i;if(!((i=this.rootElement)!=null&&i.isConnected))return;if(this.dataUpdateDebounceTimer&&(window.clearTimeout(this.dataUpdateDebounceTimer),this.dataUpdateDebounceTimer=null),this._isFirstDataUpdate){this._isFirstDataUpdate=!1,this.render();return}if(this._expectingImmediateUpdate){this._expectingImmediateUpdate=!1,this.renderPreservingEphemeralState();return}let t=this.hasConfigChanged(),r=this.hasControllerViewChanged(),a=this.hasDataSignatureChanged();if(t){this._configChangedNeedsRecreate=!0,this.renderPreservingEphemeralState();return}if(a){this.renderPreservingEphemeralState();return}this.scheduleDeferredDataUpdate(Date.now(),r)}expectImmediateUpdate(){this._expectingImmediateUpdate=!0,window.setTimeout(()=>{this._expectingImmediateUpdate=!1},2e3)}getConfigSnapshot(){var t,r,a,i,s,o;return wEe({config:this.config,icsCalendarIds:(r=(t=this.plugin.icsSubscriptionService)==null?void 0:t.getSubscriptions().map(l=>l.id))!=null?r:[],googleCalendarIds:(i=(a=this.plugin.googleCalendarService)==null?void 0:a.getAvailableCalendars().map(l=>l.id))!=null?i:[],microsoftCalendarIds:(o=(s=this.plugin.microsoftCalendarService)==null?void 0:s.getAvailableCalendars().map(l=>l.id))!=null?o:[]})}hasConfigChanged(){let t=this.getConfigSnapshot();return this._previousConfigSnapshot===null?(this._previousConfigSnapshot=t,!1):t!==this._previousConfigSnapshot?(this._previousConfigSnapshot=t,!0):!1}getDataSignature(){var r;if(!((r=this.data)!=null&&r.data))return"";let t=this.getDataSignaturePropertyIds();try{return kEe(this.dataAdapter.extractDataItems(),t)}catch(a){return TEe(this.data.data)}}getDataSignaturePropertyIds(){var r,a,i,s;let t=[];try{t=this.dataAdapter.getVisiblePropertyIds()}catch(o){}return vEe({mapField:o=>{var l,c;return(c=(l=this.plugin)==null?void 0:l.fieldMapper)==null?void 0:c.toUserField(o)},visiblePropertyIds:t,showPropertyBasedEvents:!!((r=this.viewOptions)!=null&&r.showPropertyBasedEvents),startDateProperty:(a=this.viewOptions)==null?void 0:a.startDateProperty,endDateProperty:(i=this.viewOptions)==null?void 0:i.endDateProperty,titleProperty:(s=this.viewOptions)==null?void 0:s.titleProperty})}hasDataSignatureChanged(){let t=this.getDataSignature();return this._previousDataSignature===null?(this._previousDataSignature=t,!1):t!==this._previousDataSignature?(this._previousDataSignature=t,!0):!1}getControllerViewName(){if(!og(this.basesController))return null;let t=this.basesController.viewName;return typeof t=="string"?t:null}hasControllerViewChanged(){let t=this.getControllerViewName();return this._previousControllerViewName===null?(this._previousControllerViewName=t,t!==null):t!==this._previousControllerViewName?(this._previousControllerViewName=t,!0):!1}scheduleDeferredDataUpdate(t=Date.now(),r=!1){let a=this.containerEl.ownerDocument.defaultView||window,i=Date.now()-t,s;i{this.dataUpdateDebounceTimer=null;let o=Date.now()-t;if(this.hasDataSignatureChanged()){this.renderPreservingEphemeralState();return}if(o=1&&t<=5?Math.round(t*2)/2:1,this.viewOptions.selectMirror=this.getConfigOption("selectMirror",this.viewOptions.selectMirror),this.viewOptions.timeFormat=this.getConfigOption("timeFormat",this.viewOptions.timeFormat),this.viewOptions.eventMinHeight=this.getConfigOption("eventMinHeight",this.viewOptions.eventMinHeight),this.viewOptions.slotEventOverlap=this.getConfigOption("slotEventOverlap",this.viewOptions.slotEventOverlap);let r=this.getConfigOption("eventMaxStack",void 0);r!==void 0&&(this.viewOptions.eventMaxStack=r===0?null:r);let a=this.getConfigOption("dayMaxEvents",void 0);a!==void 0&&(this.viewOptions.dayMaxEvents=a===0?!0:a);let i=this.getConfigOption("dayMaxEventRows",void 0);i!==void 0&&(this.viewOptions.dayMaxEventRows=i===0?!1:i),this.viewOptions.startDateProperty=this.getConfigOption("startDateProperty",this.viewOptions.startDateProperty),this.viewOptions.endDateProperty=this.getConfigOption("endDateProperty",this.viewOptions.endDateProperty),this.viewOptions.titleProperty=this.getConfigOption("titleProperty",this.viewOptions.titleProperty),this.enableSearch=this.getConfigOption("enableSearch",!1),this.configLoaded=!0,this.applyLayoutClasses(),this.calendar&&(this.applyTodayHighlightStyling(),this.scheduleTodayColumnWidthUpdate(),this.scheduleDailyNoteHeaderLinkUpdate())}catch(t){Nr.error("[TaskNotes][CalendarView] Error reading view options:",{category:"provider",operation:"reading-view-options",error:t})}}async render(){var t,r,a;if(this._isRendering){this._pendingRender=!0;return}if(this._isRendering=!0,this._pendingRender=!1,!this.calendarEl||!this.rootElement){this._isRendering=!1;return}if(this.isPopoutWindow()){this.renderPopoutUnsupported(),this._isRendering=!1;return}if(!((t=this.data)!=null&&t.data)){this._isRendering=!1;return}if(!this.configLoaded&&this.config)this.readViewOptions();else if(this.config)if(this._configChangedNeedsRecreate){this._configChangedNeedsRecreate=!1;let i=this.getNavigationConfigState();if(this.readViewOptions(),this.calendar){let s=this.getNavigationConfigState();this._recreateTargetDate=uEe(i,s)?this.calendar.getDate():null,this.calendar.destroy(),this.calendar=null}}else this.readEventToggles();this.rootElement&&this.setupSearch(this.rootElement);try{let i=this.dataAdapter.extractDataItems(),s=await yu(i,this.plugin),o=this.applySearchFilter(s);if(this.currentTasks=o,this.updateBasesSortIndexes(o),this.basesEntryByPath.clear(),(r=this.data)!=null&&r.data)for(let l of this.data.data)(a=l.file)!=null&&a.path&&this.basesEntryByPath.set(l.file.path,l);this.calendar?await this.updateCalendarEvents(o):await this.initializeCalendar(o)}catch(i){Nr.error("[TaskNotes][CalendarView] Error rendering:",{category:"provider",operation:"rendering",error:i}),this.renderError(i instanceof Error?i:new Error(String(i)))}finally{this._isRendering=!1}this._pendingRender&&(this._pendingRender=!1,window.setTimeout(()=>void this.render(),0))}async initializeCalendar(t){var i,s;if(!this.calendarEl)return;let r=(i=this._recreateTargetDate)!=null?i:this.determineInitialDate(t),a={plugins:[nxe,pxe,gxe,Eye,vxe],initialView:this.viewOptions.calendarView,initialDate:r,headerToolbar:{left:"prev,next today refreshCalendars",center:"title",right:"multiMonthYear,dayGridMonth,timeGridWeek,timeGridCustom,timeGridDay,listWeek"},buttonText:{today:this.plugin.i18n.translate("views.basesCalendar.today"),month:this.plugin.i18n.translate("views.basesCalendar.buttonText.month"),week:this.plugin.i18n.translate("views.basesCalendar.buttonText.week"),day:this.plugin.i18n.translate("views.basesCalendar.buttonText.day"),year:this.plugin.i18n.translate("views.basesCalendar.buttonText.year"),list:this.plugin.i18n.translate("views.basesCalendar.buttonText.list")},buttonHints:{today:this.plugin.i18n.translate("views.basesCalendar.hints.today")||"Go to today",prev:this.plugin.i18n.translate("views.basesCalendar.hints.prev")||"Previous",next:this.plugin.i18n.translate("views.basesCalendar.hints.next")||"Next",month:this.plugin.i18n.translate("views.basesCalendar.hints.month")||"Month view",week:this.plugin.i18n.translate("views.basesCalendar.hints.week")||"Week view",day:this.plugin.i18n.translate("views.basesCalendar.hints.day")||"Day view",year:this.plugin.i18n.translate("views.basesCalendar.hints.year")||"Year view",list:this.plugin.i18n.translate("views.basesCalendar.hints.list")||"List view"},customButtons:{refreshCalendars:{text:this.plugin.i18n.translate("views.basesCalendar.buttonText.refresh")||"Refresh",hint:this.plugin.i18n.translate("views.basesCalendar.hints.refresh")||"Refresh calendar subscriptions",click:()=>{this.refreshExternalCalendars()}}},views:{timeGridCustom:{type:"timeGrid",duration:{days:this.viewOptions.customDayCount},buttonText:this.plugin.i18n.translate("views.basesCalendar.buttonText.customDays",{count:this.viewOptions.customDayCount.toString()}),titleFormat:{year:"numeric",month:"short",day:"numeric"}},listWeek:{type:"list",duration:{days:this.viewOptions.listDayCount},buttonText:this.plugin.i18n.translate("views.basesCalendar.buttonText.list")}},...pJe(this.getEffectiveHeightMode()),handleWindowResize:!1,stickyHeaderDates:!1,locale:this.viewOptions.locale||this.plugin.settings.uiLanguage||navigator.language||"en",slotMinTime:this.viewOptions.slotMinTime,slotMaxTime:this.viewOptions.slotMaxTime,slotDuration:this.viewOptions.slotDuration,snapDuration:this.viewOptions.snapDuration,firstDay:this.viewOptions.firstDay,weekNumbers:this.viewOptions.weekNumbers,nowIndicator:this.viewOptions.nowIndicator,weekends:this.viewOptions.showWeekends,allDaySlot:this.viewOptions.showAllDaySlot,dayMaxEvents:this.viewOptions.dayMaxEvents,dayMaxEventRows:this.viewOptions.dayMaxEventRows,eventMaxStack:(s=this.viewOptions.eventMaxStack)!=null?s:void 0,navLinks:!0,navLinkDayClick:o=>{this.openDailyNoteFromDateLink(o)},dayHeaderDidMount:o=>{t3(o.el,o.date,o.view.type,this.plugin,l=>this.openDailyNoteFromDateLink(l))},editable:!0,selectable:!0,...Jn.Platform.isMobile?{longPressDelay:350,eventLongPressDelay:350,selectLongPressDelay:350}:{},selectMirror:this.viewOptions.selectMirror,eventTimeFormat:this.viewOptions.timeFormat==="12"?{hour:"numeric",minute:"2-digit",omitZeroMinute:!0,meridiem:"short",hour12:!0}:{hour:"2-digit",minute:"2-digit",hour12:!1},slotLabelFormat:{hour:"2-digit",minute:"2-digit",hour12:this.viewOptions.timeFormat==="12"},scrollTime:this.viewOptions.scrollTime,eventMinHeight:this.viewOptions.eventMinHeight,slotEventOverlap:this.viewOptions.slotEventOverlap,eventAllow:()=>!0,eventOrder:LEe(this.dataAdapter.getSortConfig()),events:(o,l,c)=>{this.fetchEvents(o,l,c)},eventDidMount:o=>this.handleEventDidMount(o),eventClick:o=>{this.handleEventClick(o)},eventDrop:o=>{this.handleEventDrop(o)},eventResize:o=>{this.handleEventResize(o)},select:o=>{this.handleDateSelect(o)},viewDidMount:o=>{let l=o.view.type;l&&l!==this.viewOptions.calendarView&&(this.viewOptions.calendarView=l,this.debouncedSaveViewType(l)),this.applyLayoutClasses(),this.scheduleTodayColumnWidthUpdate(),this.scheduleDailyNoteHeaderLinkUpdate(),this.scheduleRefreshButtonIconUpdate()},datesSet:()=>{this.applyLayoutClasses(),this.scheduleTodayColumnWidthUpdate(),this.scheduleDailyNoteHeaderLinkUpdate(),this.scheduleRefreshButtonIconUpdate()}};this.calendar=new nJe(this.calendarEl,a),this.calendar.render(),this._recreateTargetDate=null,this.applyLayoutClasses(),this.applyTodayHighlightStyling(),this.scheduleTodayColumnWidthUpdate(),this.scheduleDailyNoteHeaderLinkUpdate(),this.scheduleRefreshButtonIconUpdate()}updateBasesSortIndexes(t){var r,a;this.basesSortIndexByPath.clear(),jEe(this.dataAdapter.getSortConfig())&&(t.forEach((i,s)=>{this.basesSortIndexByPath.set(i.path,s)}),(a=(r=this.data)==null?void 0:r.data)==null||a.forEach((i,s)=>{var l;let o=(l=i.file)==null?void 0:l.path;o&&!this.basesSortIndexByPath.has(o)&&this.basesSortIndexByPath.set(o,s)}))}scheduleDailyNoteHeaderLinkUpdate(){let t=this.containerEl.ownerDocument.defaultView||window;t.setTimeout(()=>this.attachDailyNoteHeaderLinks(),0),t.setTimeout(()=>this.attachDailyNoteHeaderLinks(),50)}scheduleRefreshButtonIconUpdate(){let t=this.containerEl.ownerDocument.defaultView||window;t.setTimeout(()=>this.applyRefreshButtonIcon(),0),t.setTimeout(()=>this.applyRefreshButtonIcon(),50)}applyRefreshButtonIcon(){this.calendarEl&&eJe(this.calendarEl,this.plugin.i18n.translate("views.basesCalendar.hints.refresh")||this.plugin.i18n.translate("views.basesCalendar.buttonText.refresh")||"Refresh calendar subscriptions")}attachDailyNoteHeaderLinks(){var s;if(!this.calendar||!this.calendarEl||!(((s=this.calendar.view)==null?void 0:s.type)==="timeGridDay"||!!this.calendarEl.querySelector(".fc-timeGridDay-view")))return;let a=this.calendar.getDate();this.calendarEl.querySelectorAll(".fc-col-header-cell").forEach(o=>{let l=o.dataset.date?et(o.dataset.date):a;t3(o,l,"timeGridDay",this.plugin,c=>this.openDailyNoteFromDateLink(c))})}openDailyNoteFromDateLink(t){e3(t,this.plugin,{createIfMissing:this.viewOptions.createDailyNotesFromDateLinks})}async refreshExternalCalendars(){var t;try{this.plugin.icsSubscriptionService&&await this.plugin.icsSubscriptionService.refreshAllSubscriptions(),this.plugin.googleCalendarService&&await this.plugin.googleCalendarService.refreshAllCalendars(),this.plugin.microsoftCalendarService&&await this.plugin.microsoftCalendarService.refreshAllCalendars(),(t=this.calendar)==null||t.refetchEvents()}catch(r){Nr.error("[TaskNotes][CalendarView] Error refreshing calendars:",{category:"provider",operation:"refreshing-calendars",error:r})}}applyTodayHighlightStyling(){this.calendarEl&&(this.viewOptions.showTodayHighlight?this.calendarEl.classList.remove("hide-today-highlight"):this.calendarEl.classList.add("hide-today-highlight"))}applyHeightModeClass(){var r;let t=this.getEffectiveHeightMode()==="auto";this.rootElement&&(this.rootElement.classList.toggle("advanced-calendar-view--auto-height",t),this.rootElement.classList.toggle("tn-static-min-height-800px-997b4c8c",!t)),(r=this.calendarEl)==null||r.classList.toggle("advanced-calendar-view__calendar--auto-height",t)}applyTimeGridVisibilityClass(){var r,a;let t=zEe(this.viewOptions.showTimeGrid,this.viewOptions.calendarView);(r=this.rootElement)==null||r.classList.toggle("advanced-calendar-view--hide-time-grid",t),(a=this.calendarEl)==null||a.classList.toggle("advanced-calendar-view__calendar--hide-time-grid",t)}applyCalendarModeClass(){var r,a;let t=this.viewOptions.calendarView.startsWith("list");(r=this.rootElement)==null||r.classList.toggle("advanced-calendar-view--list",t),(a=this.calendarEl)==null||a.classList.toggle("advanced-calendar-view__calendar--list",t)}applyLayoutClasses(){this.applyHeightModeClass(),this.applyTimeGridVisibilityClass(),this.applyCalendarModeClass()}getEffectiveHeightMode(){return zEe(this.viewOptions.showTimeGrid,this.viewOptions.calendarView)?"auto":mJe(this.viewOptions.heightMode,this.viewOptions.calendarView,this.containerEl)}scheduleTodayColumnWidthUpdate(){if(!this.canUpdateCalendarSize())return;(this.containerEl.ownerDocument.defaultView||window).setTimeout(()=>{this.canUpdateCalendarSize()&&this.applyTodayColumnWidth()},0)}applyTodayColumnWidth(){var d;let t=this.calendar;if(!this.calendarEl||!t||!this.canUpdateCalendarSize())return;let r=(d=t.view)==null?void 0:d.type;if(!r)return;let a=Array.from(this.calendarEl.querySelectorAll(".fc-col-header-cell[data-date]")),i=a.map(u=>u.dataset.date).filter(u=>!!u);if(this.resetTodayColumnWidths(),!cJe(r,this.viewOptions.todayColumnWidthMultiplier))return;let s=a.find(u=>u.classList.contains("fc-day-today")),o=s==null?void 0:s.dataset.date;if(!o)return;let l=TJe(i,o,this.viewOptions.todayColumnWidthMultiplier);if(!l)return;this.calendarEl.querySelectorAll(".fc-col-header-cell[data-date], .fc-timegrid-col[data-date], .fc-daygrid-day[data-date]").forEach(u=>{let p=u.dataset.date;if(!p)return;let m=l.get(p);if(!m)return;u.style.width=m,u.style.minWidth=m,u.style.maxWidth=m;let f=$Ee(u);f?f.style.width=m:Nr.warn("Calendar column width target was not found",{category:"provider",operation:"apply-today-column-width",details:{dateKey:p,reason:"FullCalendar DOM may have changed; today-column width skipped."}})})}canUpdateCalendarSize(){return gJe(this.calendarEl,this.containerEl)}isPopoutWindow(){return yJe(this.containerEl)}renderPopoutUnsupported(){if(!this.calendarEl)return;this.calendar&&(this.calendar.destroy(),this.calendar=null),this.calendarEl.replaceChildren(),this.calendarEl.classList.add("advanced-calendar-view__calendar--popout-blocked");let t=this.calendarEl.ownerDocument,r=Ie(t,"div");r.className="advanced-calendar-view__popout-blocked";let a=Ie(t,"h3");a.textContent="Calendar view is unavailable in a separate window",r.appendChild(a);let i=Ie(t,"p");i.textContent="Open this calendar view in the main Obsidian window. The calendar can freeze Obsidian when restored inside a separate window.",r.appendChild(i),this.calendarEl.appendChild(r)}resetTodayColumnWidths(){this.calendarEl&&hJe(this.calendarEl)}debouncedSaveViewType(t){this._saveViewTypeTimer&&window.clearTimeout(this._saveViewTypeTimer),this._saveViewTypeTimer=window.setTimeout(()=>{this._saveViewTypeTimer=null;try{this.config&&typeof this.config.set=="function"&&(this.config.set("calendarView",t),Nr.debug("[TaskNotes][CalendarView] View type saved to config:",{category:"provider",operation:"view-type-saved-config",details:{value:t}}))}catch(r){Nr.error("[TaskNotes][CalendarView] Failed to save view type:",{category:"provider",operation:"save-view-type",error:r})}},1e3)}determineInitialDate(t){var r;return hEe({viewOptions:this.viewOptions,taskNotes:t,entries:(r=this.data)==null?void 0:r.data,getEntryPropertyValue:(a,i)=>this.dataAdapter.getPropertyValue(a,i),getContextPropertyValue:a=>this.getEmbeddedMarkdownDateNavigationPropertyValue(a),mapPropertyToTaskField:a=>this.propertyMapper.basesToTaskCardProperty(a)})}getEmbeddedMarkdownDateNavigationPropertyValue(t){var s;if(!this.containerEl.closest(".internal-embed, .markdown-embed"))return null;let r=this.getContainingMarkdownFile();if(!r)return null;let a=(s=this.plugin.app.metadataCache.getFileCache(r))==null?void 0:s.frontmatter;if(!a)return null;let i=[t,this.propertyMapper.basesToTaskCardProperty(t),t.replace(/^(note\.|task\.)/,"")];for(let o of new Set(i))if(Object.prototype.hasOwnProperty.call(a,o))return a[o];return null}getContainingMarkdownFile(){var r;let t=this.plugin.app.workspace.getLeavesOfType("markdown");for(let a of t){let i=a.view;if((r=i.containerEl)!=null&&r.contains(this.containerEl)&&i.file instanceof Jn.TFile&&i.file.extension==="md")return i.file}return null}getNavigationConfigState(){return gEe(this.viewOptions)}async fetchEvents(t,r,a){try{let i=await this.buildAllEvents(t);r(i)}catch(i){Nr.error("[TaskNotes][CalendarView] Error fetching events:",{category:"provider",operation:"fetching-events",error:i}),a(i instanceof Error?i:new Error(String(i)))}}async buildAllEvents(t){var l,c,d,u,p;let r=[],a={showScheduled:this.viewOptions.showScheduled,showDue:this.viewOptions.showDue,showScheduledToDueSpan:this.viewOptions.showScheduledToDueSpan,showRecurring:this.viewOptions.showRecurring,showCompletedRecurringInstances:this.viewOptions.showCompletedRecurringInstances,showSkippedRecurringInstances:this.viewOptions.showSkippedRecurringInstances,showTimeEntries:this.viewOptions.showTimeEntries,showTimeblocks:this.viewOptions.showTimeblocks,showICSEvents:!1,showOverdueOnToday:this.viewOptions.showOverdueOnToday,visibleStart:t.start,visibleEnd:t.end,visibleStartDate:t.startStr,visibleEndDate:t.endStr},i=await Hxe(this.currentTasks,this.plugin,a);if(OEe(i,this.basesSortIndexByPath),r.push(...i),this.viewOptions.showPropertyBasedEvents&&this.viewOptions.startDateProperty){let m=await this.buildPropertyBasedEvents();OEe(m,this.basesSortIndexByPath),r.push(...m)}let o=!!((l=this.plugin.icsSubscriptionService)!=null&&l.getAllEvents().length||(c=this.plugin.googleCalendarService)!=null&&c.getAllEvents().length||(d=this.plugin.microsoftCalendarService)!=null&&d.getAllEvents().length)?await this.plugin.icsNoteService.getRelatedNoteCountsByEventId():new Map;return this.plugin.icsSubscriptionService&&r.push(...MF({events:this.plugin.icsSubscriptionService.getAllEvents(),provider:"ics",plugin:this.plugin,toggles:this.icsCalendarToggles,relatedNoteCountsByEventId:o})),this.plugin.googleCalendarService&&r.push(...MF({events:this.plugin.googleCalendarService.getAllEvents(),provider:"google",plugin:this.plugin,toggles:this.googleCalendarToggles,relatedNoteCountsByEventId:o})),this.plugin.microsoftCalendarService&&r.push(...MF({events:this.plugin.microsoftCalendarService.getAllEvents(),provider:"microsoft",plugin:this.plugin,toggles:this.microsoftCalendarToggles,relatedNoteCountsByEventId:o})),sJe(r,((p=(u=this.calendar)==null?void 0:u.view)==null?void 0:p.type)||this.viewOptions.calendarView,this.viewOptions.showAllDaySlot)}async buildPropertyBasedEvents(){var r;if(!((r=this.data)!=null&&r.data))return[];if(!this.viewOptions.startDateProperty)return[];let t=[];for(let a of this.data.data)try{let i=a.file;if(!i)continue;let s=fEe({entry:a,file:i,startDateProperty:this.viewOptions.startDateProperty,endDateProperty:this.viewOptions.endDateProperty,titleProperty:this.viewOptions.titleProperty,getPropertyValue:(o,l)=>this.dataAdapter.getPropertyValue(o,l)});s&&t.push(s)}catch(i){Nr.warn("[TaskNotes][CalendarView] Error processing property-based entry:",{category:"provider",operation:"processing-property-based-entry",error:i})}return t}async updateCalendarEvents(t){this.calendar&&(this.calendar.setOption("eventOrder",LEe(this.dataAdapter.getSortConfig())),this.calendar.refetchEvents())}async refreshCalendarWithFreshData(t){var r;if(this.calendar)try{let a=[],i=!1;for(let s of this.currentTasks){let o=(t==null?void 0:t.path)===s.path?t:this.plugin.cacheManager.getCachedTaskInfoSync(s.path);if(o){if(o.archived)continue;let l={...o,basesData:s.basesData};(t==null?void 0:t.path)===o.path&&(i=!0),a.push(l)}}t!=null&&t.path&&!i&&!t.archived&&a.push((r=this.plugin.cacheManager.getCachedTaskInfoSync(t.path))!=null?r:t),this.currentTasks=a,this.calendar.refetchEvents()}catch(a){Nr.error("[TaskNotes][CalendarView] Error refreshing calendar:",{category:"provider",operation:"refreshing-calendar",error:a})}}async refreshAfterExpectedCalendarTaskWrite(t){this._expectingImmediateUpdate&&(this._expectingImmediateUpdate=!1,await this.refreshCalendarWithFreshData(t))}clearPendingCalendarRefreshTimers(){this.updateDebounceTimer&&(window.clearTimeout(this.updateDebounceTimer),this.updateDebounceTimer=null),this.dataUpdateDebounceTimer&&(window.clearTimeout(this.dataUpdateDebounceTimer),this.dataUpdateDebounceTimer=null)}async refreshAfterDirectCalendarTaskWrite(t){this.clearPendingCalendarRefreshTimers(),await this.refreshCalendarWithFreshData(t),this.clearPendingCalendarRefreshTimers()}async handleEventClick(t){let{taskInfo:r,timeblock:a,eventType:i,filePath:s,icsEvent:o,subscriptionName:l}=t.event.extendedProps||{},c=t.jsEvent;if(i==="timeblock"&&a){let d=t.event.start;if(!d)return;let u=D(d,"yyyy-MM-dd");xF(a,d,u,this.plugin,()=>this.expectImmediateUpdate());return}if(i==="timeEntry"&&r&&c.button===0){this.plugin.openTimeEntryEditor(r,()=>this.expectImmediateUpdate());return}if(i==="ics"&&o){new Wc(this.plugin.app,this.plugin,o,l).open();return}if(i==="property-based"&&s){let d=this.plugin.app.vault.getAbstractFileByPath(s);if(d instanceof Jn.TFile){let p=c.ctrlKey||c.metaKey||c.button===1;this.plugin.app.workspace.getLeaf(p).openFile(d)}return}r!=null&&r.path&&c.button===0&&gre(r,this.plugin,c,t.event.id,()=>this.expectImmediateUpdate())}refetchWhenCreatedTimeblockIsIndexed(t){var c;let r=()=>{var u,p;let d=(p=(u=this.plugin.app.metadataCache.getFileCache(t.dailyNote))==null?void 0:u.frontmatter)==null?void 0:p.timeblocks;return Array.isArray(d)&&d.some(m=>!m||typeof m!="object"?!1:m.id===t.timeblock.id)};if(r()){(c=this.calendar)==null||c.refetchEvents();return}let a=this.containerEl.ownerDocument.defaultView||window,i=null,s=null,o=!1,l=()=>{o||(o=!0,i!==null&&(a.clearTimeout(i),i=null),s&&(this.plugin.app.metadataCache.offref(s),s=null))};s=this.plugin.app.metadataCache.on("changed",d=>{var u;d.path!==t.dailyNote.path||!r()||(l(),(u=this.calendar)==null||u.refetchEvents())}),i=a.setTimeout(()=>{var d;l(),(d=this.calendar)==null||d.refetchEvents()},y3),this.register(l)}async handleEventDrop(t){var p,m,f,h;if(!((p=t==null?void 0:t.event)!=null&&p.extendedProps)){Nr.warn("[TaskNotes][CalendarView] Event dropped without extendedProps",{category:"provider",operation:"event-dropped-without-extendedprops"});return}let{taskInfo:r,timeblock:a,eventType:i,isRecurringInstance:s,isNextScheduledOccurrence:o,isPatternInstance:l,filePath:c,icsEvent:d}=t.event.extendedProps;if(i==="timeblock"){if(!t.oldEvent.start){t.revert();return}let g=D(t.oldEvent.start,"yyyy-MM-dd");await qxe(t,a,g,this.plugin,_xe(t.jsEvent));return}if(i==="property-based"&&c){try{let g=this.plugin.app.vault.getAbstractFileByPath(c);if(!g||!(g instanceof Jn.TFile)){t.revert();return}let v=this.viewOptions.startDateProperty,k=this.viewOptions.endDateProperty,T=EF(v),b=EF(k);if(!T){t.revert();return}let w=t.oldEvent.start,S=t.event.start;if(!w||!S){t.revert();return}await yr(this.plugin.app,g,C=>{let x=aEe({frontmatter:C,startProperty:T,endProperty:b,oldStart:w,newStart:S,allDay:t.event.allDay});if(x.kind==="update-frontmatter")for(let[E,_]of Object.entries(x.updates))C[E]=_})}catch(g){Nr.error("[TaskNotes][CalendarView] Error updating property-based event:",{category:"provider",operation:"updating-property-based-event",error:g}),t.revert()}return}if(i==="ics"&&d){let g=(m=this.plugin.calendarProviderRegistry)==null?void 0:m.findProviderForEvent(d);if(g){try{let{calendarId:v,eventId:k}=g.extractEventIds(d),T=r3({start:t.event.start,end:t.event.end,allDay:t.event.allDay,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"});if(T.kind==="revert"){t.revert();return}await g.updateEvent(v,k,T.updates)}catch(v){Nr.error(`[TaskNotes][CalendarView] Error updating ${g.providerName} event:`,{category:"provider",operation:"updating",error:v}),t.revert()}return}else{t.revert();return}}if(i==="timeEntry"){let g=sEe({timeEntries:r.timeEntries,timeEntryIndex:t.event.extendedProps.timeEntryIndex,oldStart:t.oldEvent.start,newStart:t.event.start,newEnd:t.event.end});if(g.kind==="revert"){t.revert();return}if(g.kind==="update-time-entries")try{let v=await this.plugin.taskService.updateTask(r,{timeEntries:g.timeEntries});await this.refreshAfterDirectCalendarTaskWrite(v)}catch(v){Nr.error("Error updating time entry:",{category:"provider",operation:"updating-time-entry",error:v}),t.revert()}return}let u=!!(r!=null&&r.recurrence_parent&&(r!=null&&r.occurrence_date));if(r&&!u&&(s||o||l)){await zxe(t,r,this.plugin);return}if(r)try{let g=eEe({eventType:i,taskInfo:r,newStart:t.event.start,oldStart:t.oldEvent.start,allDay:t.event.allDay});if(g.kind==="revert"){t.revert();return}if(g.kind==="update-date-property"){let v=await this.plugin.taskService.updateProperty(r,g.property,g.value);await this.refreshAfterDirectCalendarTaskWrite(v)}else if(g.kind==="update-scheduled-due-span"){let v=this.plugin.app.vault.getAbstractFileByPath(r.path);if(v instanceof Jn.TFile){let k=this.plugin.fieldMapper.toUserField("scheduled"),T=this.plugin.fieldMapper.toUserField("due");await yr(this.plugin.app,v,b=>{g.scheduled&&(b[k]=g.scheduled),g.due&&(b[T]=g.due)}),await this.refreshAfterDirectCalendarTaskWrite({...r,scheduled:(f=g.scheduled)!=null?f:r.scheduled,due:(h=g.due)!=null?h:r.due})}}}catch(g){Nr.error("[TaskNotes][CalendarView] Error updating task date:",{category:"provider",operation:"updating-task-date",error:g}),t.revert()}}async handleEventResize(t){var d,u;if(!((d=t==null?void 0:t.event)!=null&&d.extendedProps)){Nr.warn("[TaskNotes][CalendarView] Event resized without extendedProps",{category:"provider",operation:"event-resized-without-extendedprops"});return}let{taskInfo:r,timeblock:a,eventType:i,filePath:s,timeEntryIndex:o,icsEvent:l}=t.event.extendedProps;if(i==="timeEntry"){let p=oEe({timeEntries:r.timeEntries,timeEntryIndex:o,newStart:t.event.start,newEnd:t.event.end});if(p.kind==="revert"){t.revert();return}if(p.kind==="update-time-entries")try{let m=await this.plugin.taskService.updateTask(r,{timeEntries:p.timeEntries});await this.refreshAfterDirectCalendarTaskWrite(m)}catch(m){Nr.error("Error resizing time entry:",{category:"provider",operation:"resizing-time-entry",error:m}),t.revert()}return}if(i==="timeblock"){if(!t.event.start){t.revert();return}let p=D(t.event.start,"yyyy-MM-dd");await Gxe(t,a,p,this.plugin);return}if(i==="property-based"&&s){try{let p=this.plugin.app.vault.getAbstractFileByPath(s);if(!p||!(p instanceof Jn.TFile)){t.revert();return}let m=this.viewOptions.endDateProperty,f=EF(m),h=iEe({endProperty:f,newEnd:t.event.end,allDay:t.event.allDay});if(h.kind==="revert"){t.revert();return}if(h.kind==="ignore")return;await yr(this.plugin.app,p,g=>{for(let[v,k]of Object.entries(h.updates))g[v]=k})}catch(p){Nr.error("[TaskNotes][CalendarView] Error resizing property-based event:",{category:"provider",operation:"resizing-property-based-event",error:p}),t.revert()}return}if(i==="ics"&&l){let p=(u=this.plugin.calendarProviderRegistry)==null?void 0:u.findProviderForEvent(l);if(p){try{let{calendarId:m,eventId:f}=p.extractEventIds(l),h=r3({start:t.event.start,end:t.event.end,allDay:t.event.allDay,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC",requireEnd:!0});if(h.kind==="revert"){t.revert();return}await p.updateEvent(m,f,h.updates)}catch(m){Nr.error(`[TaskNotes][CalendarView] Error resizing ${p.providerName} event:`,{category:"provider",operation:"resizing",error:m}),t.revert()}return}}let c=tEe({eventType:i,start:t.event.start,end:t.event.end,allDay:t.event.allDay});if(c.kind==="revert"){t.revert();return}if(c.kind!=="ignore")try{let p=await this.plugin.taskService.updateProperty(r,"timeEstimate",c.value);await this.refreshAfterDirectCalendarTaskWrite(p)}catch(p){Nr.error("[TaskNotes][CalendarView] Error updating task duration:",{category:"provider",operation:"updating-task-duration",error:p}),t.revert()}}async handleDateSelect(t){var s,o,l,c;let r=new Jn.Menu;r.addItem(d=>{d.setTitle("Create task").setIcon("check-square").onClick(async()=>{let u=this.viewOptions.slotDuration.split(":"),p=parseInt(u[0])*60+parseInt(u[1]||"0"),m=Qxe(t.start,t.end,t.allDay,p);new kp(this.plugin.app,this.plugin,{prePopulatedValues:m,onTaskCreated:h=>{this.refreshAfterDirectCalendarTaskWrite(h)}}).open()})}),this.plugin.settings.calendarViewSettings.enableTimeblocking&&r.addItem(d=>{d.setTitle("Create timeblock").setIcon("clock").onClick(async()=>{await Vxe(t.start,t.end,t.allDay,this.plugin,u=>this.refetchWhenCreatedTimeblockIsIndexed(u))})}),r.addItem(d=>{d.setTitle("Create time entry").setIcon("play").onClick(async()=>{this.expectImmediateUpdate(),await Wxe(t.start,t.end,t.allDay,this.plugin)})});let a=this.plugin.calendarProviderRegistry;a&&a.getAllProviders().some(u=>u.getAvailableCalendars().length>0)&&(r.addSeparator(),r.addItem(u=>{u.setTitle("Create external calendar event").setIcon("calendar-plus").onClick(()=>{new DF(this.plugin.app,this.plugin,{start:t.start,end:t.end,allDay:t.allDay,onEventCreated:()=>{this.expectImmediateUpdate(),a.refreshAll()}}).open()})})),r.onHide(()=>{var d;(d=this.calendar)==null||d.unselect()});let i=t.jsEvent;if(i&&"changedTouches"in i){let d=i,u=(s=d.changedTouches[0])!=null?s:d.touches[0];if(u)r.showAtPosition({x:u.clientX,y:u.clientY});else{let p=(o=this.calendarEl)==null?void 0:o.getBoundingClientRect();r.showAtPosition({x:(l=p==null?void 0:p.left)!=null?l:0,y:(c=p==null?void 0:p.top)!=null?c:0})}}else t.jsEvent?r.showAtMouseEvent(t.jsEvent):r.showAtPosition({x:0,y:0})}handleEventDidMount(t){var m;let r;try{let f=(m=t==null?void 0:t.event)==null?void 0:m.extendedProps;if(!f||typeof f!="object")return;r=f}catch(f){Nr.warn("[TaskNotes][CalendarView] Event mounted without readable props",{category:"provider",operation:"event-mounted-readable-props",error:f});return}let{taskInfo:a,timeblock:i,icsEvent:s,eventType:o,relatedNoteCount:l,isRecurringInstance:c,isNextScheduledOccurrence:d,isPatternInstance:u}=r;XQe(t.el);let p=h3(l);if(NEe({element:t.el,viewType:t.view.type,icsEvent:s,relatedNoteCount:p,plugin:this.plugin}),!REe({arg:t,plugin:this.plugin,config:this.config,visibleProperties:this.getVisibleProperties(),basesEntryByPath:this.basesEntryByPath,buildTaskCardOptions:f=>this.buildTaskCardOptions(f),logDebug:(f,...h)=>Nr.debug(f,{category:"provider",operation:"mount-calendar-list-event-card",details:h.length>0?{values:h}:void 0})})){if(t.el.setAttribute("data-event-type",o||"unknown"),o==="timeblock"&&i){Yxe(t.el,i),t.event.setProp&&t.event.setProp("editable",!0);let f=Kxe(i);(0,Jn.setTooltip)(t.el,f,{placement:"top"});return}if(a&&a.path){if(t.el.setAttribute("data-task-path",a.path),t.el.classList.add("fc-task-event"),this.attachTaskEventHoverLink(t.el,a.path),a.tags&&a.tags.length>0&&a.tags.forEach(f=>{let h=f.replace(/[^a-zA-Z0-9-_]/g,"");h&&t.el.classList.add(`fc-tag-${h}`)}),Ko(a.projects||[]).forEach(f=>{let h=Dd(f);h&&t.el.classList.add(`fc-project-${h}`)}),t.event.setProp)switch(o){case"scheduled":case"recurring":case"timeEntry":case"due":case"scheduledToDueSpan":t.event.setProp("editable",o!=="scheduledToDueSpan"||!(c||d||u));break;default:break}Oxe(t.el,r)}if(a){let f=Lxe(a,this.plugin);(0,Jn.setTooltip)(t.el,f)}else if(s){let f=p>0?` + +${IF(this.plugin,p)}`:"",h=s.description?`${s.title} + +${s.description}${f}`:`${s.title}${f}`;(0,Jn.setTooltip)(t.el,h)}a&&o!=="ics"&&Zxe(t.el,a,this.plugin,"tasknotes-bases-calendar"),a&&t.el.addEventListener("contextmenu",f=>{f.preventDefault(),f.stopPropagation();let h=SF(t);new ll({task:a,plugin:this.plugin,targetDate:h,occurrenceDate:Bxe(a,t),promoteOccurrenceControls:!!(a.recurrence||a.recurrence_parent&&a.occurrence_date),onUpdate:()=>{this.refreshCalendarWithFreshData()}}).show(f)}),s&&o==="ics"&&t.el.addEventListener("contextmenu",f=>{f.preventDefault(),f.stopPropagation();let h=r.subscriptionName;new cT({icsEvent:s,plugin:this.plugin,subscriptionName:h,onUpdate:()=>{this.refreshCalendarWithFreshData()}}).show(f)}),o==="property-based"&&r.filePath&&t.el.addEventListener("mouseover",f=>{this.plugin.app.vault.getAbstractFileByPath(r.filePath)&&this.plugin.app.workspace.trigger("hover-link",{event:f,source:"tasknotes-bases-calendar",hoverParent:t.el,targetEl:t.el,linktext:r.filePath,sourcePath:r.filePath})}),o==="property-based"&&r.filePath&&t.el.addEventListener("contextmenu",f=>{f.preventDefault(),f.stopPropagation();let h=this.plugin.app.vault.getAbstractFileByPath(r.filePath);if(h instanceof Jn.TFile){let g=new Jn.Menu;this.plugin.app.workspace.trigger("file-menu",g,h,"tasknotes-bases-calendar"),g.showAtPosition({x:f.clientX,y:f.clientY})}})}}attachTaskEventHoverLink(t,r){let a=i=>{var l,c;let s=`.fc-task-event[data-task-path="${CSS.escape(r)}"]`;((c=(l=this.rootElement)==null?void 0:l.querySelectorAll(s))!=null?c:[]).forEach(d=>{d===t?d.classList.toggle("fc-task-event--hover-source",i):d.classList.toggle("fc-task-event--related-hover",i)})};t.addEventListener("mouseenter",()=>a(!0)),t.addEventListener("mouseleave",()=>a(!1))}setupContainer(){if(super.setupContainer(),this.rootElement){this.rootElement.className="tn-bases-integration tasknotes-plugin advanced-calendar-view",this.rootElement.classList.remove("tn-static-display-block-2a1b75c9","tn-static-display-flex-4d51fc62","tn-static-display-flex-75816cae","tn-static-display-flex-8bb39979","tn-static-display-inline-block-60e32dcb","tn-static-display-inline-cccfa456","tn-static-display-inline-flex-f984c520","tn-static-display-none-6b99de8b","tn-static-flex-1-14e3b769","tn-static-flex-direction-column-06c8b5ed","tn-static-height-0-7a31cef0","tn-static-height-100-62264068","tn-static-height-12px-06c0747e","tn-static-height-16px-30de4aee","tn-static-height-24px-29a11d37"),this.rootElement.classList.add("tn-static-min-height-800px-997b4c8c");let t=this.containerEl.ownerDocument,r=Ie(t,"div");r.id="bases-calendar",r.classList.remove("tn-static-flex-1-97445a8d","tn-static-margin-top-12px-91e0f558","tn-static-min-height-800px-997b4c8c","tn-static-overflow-hidden-69824400"),r.classList.add("tn-static-flex-1-14e3b769"),this.rootElement.appendChild(r),this.calendarEl=r,this.applyLayoutClasses()}}async handleTaskUpdate(t,r){if(this._expectingImmediateUpdate){await this.refreshAfterExpectedCalendarTaskWrite(t);return}if(r==="tasknotes-service"){await this.refreshCalendarWithFreshData(t);return}this.debouncedRefresh()}debouncedRefresh(){this.updateDebounceTimer&&window.clearTimeout(this.updateDebounceTimer);let t=this.containerEl.ownerDocument.defaultView||window;this.updateDebounceTimer=t.setTimeout(()=>{this.updateDebounceTimer=null,this.renderPreservingEphemeralState()},300)}renderPreservingEphemeralState(){let t=this.getEphemeralState();this.render().catch(r=>{Nr.error("[TaskNotes][CalendarView] Render error:",{category:"provider",operation:"render",error:r}),this.renderError(r instanceof Error?r:new Error(String(r)))}).finally(()=>this.setEphemeralState(t))}renderError(t){if(!this.calendarEl)return;let r=this.calendarEl.ownerDocument,a=Ie(r,"div");a.className="tn-bases-error",a.classList.remove("tn-static-border-radius-4px-c290c56e","tn-static-border-radius-6px-0dc8408c","tn-static-color-var-color-accent-d2cad743","tn-static-color-var-text-accent-65b47ee3","tn-static-color-var-text-muted-5872de20","tn-static-color-var-text-on-accent-f3e1679d","tn-static-color-var-text-warning-783d5f03","tn-static-color-var-tn-text-muted-a90fb6f3","tn-static-color-white-0a43e56a","tn-static-cursor-pointer-2723efcc","tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-0-11696618","tn-static-margin-0-auto-266e9b04","tn-static-margin-0-db0d5f36","tn-static-margin-0-var-size-4-2-77f7dc08","tn-static-margin-2px-0-edce9b14","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-padding-0-16px-16px-16px-f1aa998c","tn-static-padding-0-41d7d7e2","tn-static-padding-12px-43bef435","tn-static-padding-16px-287f770e","tn-static-padding-20px-769fed37","tn-static-padding-20px-7a035d95","tn-static-padding-2px-8px-c8eea84a","tn-static-padding-2rem-42aa6d9c"),a.classList.add("tn-static-padding-20px-ebe8e48c"),a.textContent=`Error loading calendar: ${t.message||"Unknown error"}`,this.calendarEl.appendChild(a)}onunload(){this._saveViewTypeTimer&&(window.clearTimeout(this._saveViewTypeTimer),this._saveViewTypeTimer=null),this.calendar&&(this.calendar.destroy(),this.calendar=null),this.calendarEl=null,this.currentTasks=[]}getEphemeralState(){let t=super.getEphemeralState(),r=og(t)?t:{};if(this.calendar){let a=this.calendar.getDate();return{...r,calendarDate:a?a.toISOString():null,calendarScroll:vJe(this.calendarEl)}}return t}setEphemeralState(t){if(super.setEphemeralState(t),!!oJe(t)){if(this.calendar&&typeof t.calendarDate=="string")try{this.calendar.gotoDate(new Date(t.calendarDate))}catch(r){Nr.debug("[CalendarView] Failed to restore calendar date:",{category:"provider",operation:"restore-calendar-date",error:r})}if(Array.isArray(t.calendarScroll)){let r=this.containerEl.ownerDocument.defaultView||window,a=()=>{kJe(this.calendarEl,t.calendarScroll)};r.requestAnimationFrame(()=>{a(),r.requestAnimationFrame(a)})}}}}});function qEe(n){if(n==null||typeof n=="string"&&n.trim()==="")return lg;let e=typeof n=="number"?n:typeof n=="string"?Number(n.trim()):NaN;return Number.isFinite(e)?Math.max(1,Math.round(e)):lg}function bJe(n,e=lg){let t=Math.max(0,Math.floor(n));if(t===0)return"none";let r=qEe(e);if(t>=r)return"very-high";let a=t/r;return a<=1/lg?"low":a<=.5?"medium":"high"}function WEe(n){return(0,ki.moment)(n)}function GEe(n){return function(e,t){if(!t)throw km.error("[TaskNotes][MiniCalendarView] No containerEl provided",{category:"provider",operation:"no-containerel-provided"}),new Error("MiniCalendarView requires a containerEl");return new k3(e,t,n)}}var ki,Ka,km,lg,k3,_F,T3=y(()=>{ki=require("obsidian");IE();Cr();xe();dr();yt();Ka=tt(od());rD();q();Li();nm();f3();km=M({tag:"Bases/MiniCalendarView"}),lg=6;k3=class extends Bc{constructor(t,r,a){super(t,r,a);this.type="tasknotesMiniCalendar";this.calendarEl=null;this.dateProperty=null;this.titleProperty=null;this.heatMapMaxCount=lg;this.icsCalendarToggles=new Map;this.googleCalendarToggles=new Map;this.microsoftCalendarToggles=new Map;this.configLoaded=!1;this.isInitialRender=!0;this.shouldRestoreFocus=!1;this.multiSelectMode=!1;this.selectedDates=new Set;this.notesByDate=new Map;this.monthCalculationCache=new Map;this.keyboardHandler=null;this.dataAdapter.basesView=this;let i=Xt(),s=Br(i);this.selectedDate=s,this.displayedMonth=s.getUTCMonth(),this.displayedYear=s.getUTCFullYear()}onload(){this.readViewOptions(),super.onload()}readViewOptions(){if(!(!this.config||typeof this.config.get!="function"))try{this.dateProperty=this.config.get("dateProperty")||"file.ctime",this.titleProperty=this.config.get("titleProperty")||"file.name",this.heatMapMaxCount=qEe(this.config.get("heatMapMaxCount")),this.readCalendarToggles(),this.configLoaded=!0}catch(t){km.error("[TaskNotes][MiniCalendarView] Error reading view options:",{category:"provider",operation:"reading-view-options",error:t})}}readCalendarToggles(){if(this.icsCalendarToggles.clear(),this.googleCalendarToggles.clear(),this.microsoftCalendarToggles.clear(),!this.config||typeof this.config.get!="function")return;let t=r=>this.config.get(r)!==!1;if(this.plugin.icsSubscriptionService)for(let r of this.plugin.icsSubscriptionService.getSubscriptions())this.icsCalendarToggles.set(r.id,t(`showICS_${r.id}`));if(this.plugin.googleCalendarService)for(let r of this.plugin.googleCalendarService.getAvailableCalendars())AF(this.googleCalendarToggles,r,t(`showGoogleCalendar_${r.id}`));if(this.plugin.microsoftCalendarService)for(let r of this.plugin.microsoftCalendarService.getAvailableCalendars())this.microsoftCalendarToggles.set(r.id,t(`showMicrosoftCalendar_${r.id}`))}async render(){var t;if(!(!this.calendarEl||!this.rootElement)&&(t=this.data)!=null&&t.data){this.config&&this.readViewOptions();try{let r=this.containerEl.ownerDocument,a=this.calendarEl.querySelector(".mini-calendar-view__grid")===r.activeElement;this.calendarEl.empty();let i=this.data.data;this.indexNotesByDate(i),this.renderCalendarControls(),this.renderCalendarGrid(),(this.isInitialRender||this.shouldRestoreFocus||a)&&(this.isInitialRender&&(this.isInitialRender=!1),this.shouldRestoreFocus=!1,window.setTimeout(()=>{var l;let o=(l=this.calendarEl)==null?void 0:l.querySelector(".mini-calendar-view__grid");o&&o.focus()},10))}catch(r){km.error("[TaskNotes][MiniCalendarView] Error rendering:",{category:"provider",operation:"rendering",error:r}),this.renderError(r instanceof Error?r:new Error(String(r)))}}}indexNotesByDate(t){var r;if(this.notesByDate.clear(),!this.dateProperty){this.indexExternalCalendarEvents();return}for(let a of t)try{let i=a.file;if(!i)continue;let s=this.getDateValueFromProperty(a,this.dateProperty);if(!s)continue;let o=re(s);if(!o)continue;let l=i.basename||i.name;if(this.titleProperty)try{let u=(r=a.getValue)==null?void 0:r.call(a,this.titleProperty);if(u!=null)if(typeof u=="object"&&u.toString){let p=u.toString();p&&p!=="null"&&p!==""&&(l=p)}else if(typeof u=="string")l=u;else{let p=Y(u);p&&p!=="null"&&p!==""&&(l=p)}else{let p=this.dataAdapter.getPropertyValue(a,this.titleProperty);if(p!=null)if(typeof p=="object"){let m=Y(p);m&&m!=="null"&&m!==""&&(l=m)}else if(typeof p=="string")l=p;else{let m=Y(p);m&&m!=="null"&&m!==""&&(l=m)}}}catch(u){km.warn("[TaskNotes][MiniCalendarView] Error getting title property:",{category:"provider",operation:"getting-title-property",error:u})}let c={kind:"note",file:i,title:l,path:i.path,dateValue:s,basesEntry:a};this.notesByDate.has(o)||this.notesByDate.set(o,[]);let d=this.notesByDate.get(o);d&&d.push(c)}catch(i){km.warn("[TaskNotes][MiniCalendarView] Error indexing note:",{category:"provider",operation:"indexing-note",error:i})}this.indexExternalCalendarEvents()}addEntryToDate(t,r){var a;this.notesByDate.has(t)||this.notesByDate.set(t,[]),(a=this.notesByDate.get(t))==null||a.push(r)}indexExternalCalendarEvents(){this.indexICSEvents(),this.indexGoogleCalendarEvents(),this.indexMicrosoftCalendarEvents()}indexICSEvents(){if(!this.plugin.icsSubscriptionService)return;let t=new Map(this.plugin.icsSubscriptionService.getSubscriptions().map(r=>[r.id,r]));for(let r of this.plugin.icsSubscriptionService.getAllEvents()){if(this.icsCalendarToggles.get(r.subscriptionId)===!1)continue;let a=t.get(r.subscriptionId);a&&!a.enabled||this.indexExternalEvent(r,(a==null?void 0:a.name)||"Calendar subscription",r.color||(a==null?void 0:a.color))}}indexGoogleCalendarEvents(){if(!this.plugin.googleCalendarService)return;let t=this.plugin.googleCalendarService.getAvailableCalendars();for(let r of this.plugin.googleCalendarService.getAllEvents()){let a=r.subscriptionId.replace("google-","");if(this.googleCalendarToggles.get(a)===!1)continue;let i=rm(t,a);this.indexExternalEvent(r,(i==null?void 0:i.summary)||"Google Calendar",r.color||"#4285F4")}}indexMicrosoftCalendarEvents(){if(!this.plugin.microsoftCalendarService)return;let t=new Map(this.plugin.microsoftCalendarService.getAvailableCalendars().map(r=>[r.id,r]));for(let r of this.plugin.microsoftCalendarService.getAllEvents()){let a=r.subscriptionId.replace("microsoft-","");if(this.microsoftCalendarToggles.get(a)===!1)continue;let i=t.get(a);this.indexExternalEvent(r,(i==null?void 0:i.summary)||"Microsoft Calendar",r.color||"#0078D4")}}indexExternalEvent(t,r,a){for(let i of this.getDateKeysForExternalEvent(t))this.addEntryToDate(i,{kind:"external",title:t.title,path:r,dateValue:t.start,externalEvent:t,sourceName:r,color:a})}getDateKeysForExternalEvent(t){let r=this.extractDateFromString(t.start);if(!r)return[];let a=this.extractDateFromString(t.end||"");if(!a||a===r)return[r];let i=this.createUTCDateFromDateKey(r),s=this.createUTCDateFromDateKey(a);if(!i||!s)return[r];if(t.allDay&&s.setUTCDate(s.getUTCDate()-1),s0?o:[r]}createUTCDateFromDateKey(t){let r=t.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!r)return null;let[,a,i,s]=r;return w0(Number(a),Number(i)-1,Number(s))}getDateValueFromProperty(t,r){try{let a=this.dataAdapter.getPropertyValue(t,r);if(!a)return null;if(typeof a=="string")return this.extractDateFromString(a);if(typeof a=="number")return this.toAnchoredDateString(new Date(a));if(a instanceof Date)return this.toAnchoredDateString(a);if(typeof a=="object"){let i=a.date;if(i instanceof Date)return this.toAnchoredDateString(i);let s=a.toISOString;if(typeof s=="function")return this.extractDateFromString(s.call(a))}return null}catch(a){return km.warn("[TaskNotes][MiniCalendarView] Error getting date value:",{category:"provider",operation:"getting-date-value",error:a}),null}}extractDateFromString(t){let r=t==null?void 0:t.trim();if(!r)return null;if(/^\d{4}-\d{2}-\d{2}$/.test(r))return this.validateCalendarDate(r);if(r.includes("T")||/\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}/.test(r)||/[+-]\d{2}:\d{2}$/.test(r)){let s=r.includes(" ")&&!r.includes("T")?r.replace(" ","T"):r,o=new Date(s);if(!isNaN(o.getTime()))return this.toAnchoredDateString(o)}let a=r.match(/^(\d{4})[/.](\d{2})[/.](\d{2})$/);if(a){let[,s,o,l]=a;return this.validateCalendarDate(`${s}-${o}-${l}`)}let i=r.match(/(\d{4}-\d{2}-\d{2})/);return i?this.validateCalendarDate(i[1]):null}toAnchoredDateString(t){if(!(t instanceof Date)||isNaN(t.getTime()))return null;let r=Br(t);return ae(r)}validateCalendarDate(t){if(!t)return null;let a=t.trim().match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!a)return null;let[,i,s,o]=a,l=Number(i),c=Number(s)-1,d=Number(o);if(Number.isNaN(l)||Number.isNaN(c)||Number.isNaN(d))return null;let u=w0(l,c,d);return u.getUTCFullYear()!==l||u.getUTCMonth()!==c||u.getUTCDate()!==d?null:ae(u)}renderCalendarControls(){if(!this.calendarEl)return;let r=this.calendarEl.createDiv({cls:"mini-calendar-view__controls"}).createDiv({cls:"mini-calendar-view__header"}),a=r.createDiv({cls:"mini-calendar-view__navigation"});a.createEl("button",{text:"‹",cls:"mini-calendar-view__nav-button mini-calendar-view__nav-button--prev tn-btn tn-btn--icon tn-btn--ghost",attr:{"aria-label":"Previous month",title:"Previous month"}}).addEventListener("click",()=>this.navigateToPreviousMonth()),a.createDiv({cls:"mini-calendar-view__month-display",text:D(bd(this.selectedDate),"MMMM yyyy")}),a.createEl("button",{text:"›",cls:"mini-calendar-view__nav-button mini-calendar-view__nav-button--next tn-btn tn-btn--icon tn-btn--ghost",attr:{"aria-label":"Next month",title:"Next month"}}).addEventListener("click",()=>this.navigateToNextMonth()),r.createEl("button",{text:"Today",cls:"mini-calendar-view__today-button tn-btn tn-btn--ghost tn-btn--sm",attr:{"aria-label":"Go to today",title:"Go to today"}}).addEventListener("click",()=>this.navigateToToday())}renderCalendarGrid(){if(!this.calendarEl)return;let t=this.calendarEl.createDiv({cls:"mini-calendar-view__grid-container"}),r=this.displayedMonth,a=this.displayedYear,i=new Date(Date.UTC(a,r,1)),s=new Date(Date.UTC(a,r+1,0)),o=this.plugin.settings.calendarViewSettings.firstDay||0,l=(i.getUTCDay()-o+7)%7,c=t.createDiv({cls:"mini-calendar-view__grid",attr:{role:"grid","aria-label":`Calendar for ${D(bd(new Date(Date.UTC(a,r,1))),"MMMM yyyy")}`,tabindex:"0"}});this.setupKeyboardNavigation(c),c.addEventListener("click",()=>{c.focus()});let d=c.createDiv({cls:"mini-calendar-view__grid-header",attr:{role:"row"}});d.createDiv({text:"",cls:"mini-calendar-view__week-header",attr:{role:"columnheader"}});let u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];[...u.slice(o),...u.slice(0,o)].forEach(b=>{d.createDiv({text:b,cls:"mini-calendar-view__day-header",attr:{role:"columnheader","aria-label":b}})});let m=l,f=42,h=s.getUTCDate(),g=f-h-m,v=new Date(Date.UTC(a,r,0)).getUTCDate(),k=[],T=[];for(let b=0;b0&&k.push(T),k.forEach(b=>{this.renderWeekRow(c,b)})}renderWeekRow(t,r){let a=t.createDiv({cls:"mini-calendar-view__week",attr:{role:"row"}}),i=this.getWeekNumber(r[0]),s=a.createDiv({cls:"mini-calendar-week-number",text:`W${i}`});s.addEventListener("click",o=>{var c;o.preventDefault(),o.stopPropagation(),this.selectWeek(r);let l=(c=this.calendarEl)==null?void 0:c.querySelector(".mini-calendar-view__grid");l&&l.focus()}),s.addEventListener("contextmenu",o=>{o.preventDefault(),o.stopPropagation(),this.showWeekContextMenu(o,r[0])}),r.forEach((o,l)=>{let c=this.displayedMonth,d=this.displayedYear,u=o.getUTCMonth()!==c||o.getUTCFullYear()!==d,p=o.getUTCDate();this.renderDay(a,o,p,u)})}renderDay(t,r,a,i){let s=Xt(),o=Br(s),l=Qz(r,o),c=Qz(r,this.selectedDate),d="mini-calendar-view__day";l&&(d+=" mini-calendar-view__day--today"),c&&(d+=" mini-calendar-view__day--selected"),i&&(d+=" mini-calendar-view__day--outside-month");let u=t.createDiv({cls:d,text:a.toString(),attr:{role:"gridcell","aria-label":D(bd(r),"EEEE, MMMM d, yyyy")+(l?" (Today)":""),"aria-selected":c?"true":"false","aria-current":l?"date":null}}),p=ae(r),m=this.notesByDate.get(p);if(m&&m.length>0){let f=this.getHeatMapIntensity(m.length);u.addClass(`mini-calendar-view__day--intensity-${f}`);let h=this.createNotePreviewText(m);(0,ki.setTooltip)(u,h,{placement:"top"}),this.renderExternalEventIndicators(u,m)}u.addEventListener("click",f=>{var g;f.preventDefault(),f.stopPropagation(),this.handleDayClick(r,f);let h=(g=this.calendarEl)==null?void 0:g.querySelector(".mini-calendar-view__grid");h&&h.focus()}),u.addEventListener("contextmenu",f=>{f.preventDefault(),f.stopPropagation(),this.showDayContextMenu(f,r)})}async handleDayClick(t,r){if(this.selectedDate=t,r&&(r.ctrlKey||r.metaKey)){await this.openDailyNoteForDate(t);return}this.refresh();let a=ae(t),i=this.notesByDate.get(a);i&&i.length>0&&new _F(this.plugin.app,this.plugin,i,o=>{o&&this.openCalendarEntry(o)}).open()}renderExternalEventIndicators(t,r){let a=r.filter(s=>s.kind==="external");if(a.length===0)return;let i=t.createDiv({cls:"mini-calendar-view__external-event-indicators"});for(let s of a){let o=i.createSpan({cls:"mini-calendar-view__external-event-dot",attr:{"aria-label":`${s.title} (${s.sourceName||"Calendar"})`}});s.color&&(o.style.backgroundColor=s.color)}}openCalendarEntry(t){if(t.file){this.plugin.app.workspace.getLeaf(!1).openFile(t.file);return}t.externalEvent&&new Wc(this.plugin.app,this.plugin,t.externalEvent,t.sourceName).open()}showDayContextMenu(t,r){let a=new ki.Menu;a.addItem(i=>{i.setTitle(this.plugin.i18n.translate("views.miniCalendar.contextMenu.openDailyNote")),i.setIcon("calendar-days"),i.onClick(()=>{this.openDailyNoteForDate(r)})}),a.showAtMouseEvent(t)}showWeekContextMenu(t,r){let a=new ki.Menu;a.addItem(i=>{i.setTitle(this.plugin.i18n.translate("views.miniCalendar.contextMenu.openWeeklyNote")),i.setIcon("calendar-range"),i.onClick(()=>{this.openWeeklyNoteForDate(r)})}),a.showAtMouseEvent(t)}async openDailyNoteForDate(t){if(!(0,Ka.appHasDailyNotesPluginLoaded)()){new ki.Notice("Daily notes core plugin is not enabled. Please enable it in settings > core plugins.");return}let r=bd(t),a=new Date(r.getFullYear(),r.getMonth(),r.getDate(),12,0,0,0),i=WEe(a),s=(0,Ka.getAllDailyNotes)(),o=(0,Ka.getDailyNote)(i,s);if(!o)try{o=await(0,Ka.createDailyNote)(i)}catch(l){let c=l instanceof Error?l.message:String(l);km.error("Failed to create daily note:",{category:"provider",operation:"create-daily-note",error:l}),new ki.Notice(`Failed to create daily note: ${c}`);return}o&&await this.plugin.app.workspace.getLeaf(!1).openFile(o)}async openWeeklyNoteForDate(t){if(!(0,Ka.appHasWeeklyNotesPluginLoaded)()){new ki.Notice("Weekly notes core plugin is not enabled. Please enable it in settings > core plugins.");return}let r=bd(t),a=new Date(r.getFullYear(),r.getMonth(),r.getDate(),12,0,0,0),i=WEe(a),s=(0,Ka.getAllWeeklyNotes)(),o=(0,Ka.getWeeklyNote)(i,s);if(!o)try{o=await(0,Ka.createWeeklyNote)(i)}catch(l){let c=l instanceof Error?l.message:String(l);km.error("Failed to create weekly note:",{category:"provider",operation:"create-weekly-note",error:l}),new ki.Notice(`Failed to create weekly note: ${c}`);return}o&&await this.plugin.app.workspace.getLeaf(!1).openFile(o)}navigateToPreviousMonth(){let t=new Date(this.selectedDate.getTime());t.setUTCMonth(this.selectedDate.getUTCMonth()-1),this.selectedDate=t,this.displayedMonth=t.getUTCMonth(),this.displayedYear=t.getUTCFullYear(),this.monthCalculationCache.clear(),this.shouldRestoreFocus=!0,this.refresh()}navigateToNextMonth(){let t=new Date(this.selectedDate.getTime());t.setUTCMonth(this.selectedDate.getUTCMonth()+1),this.selectedDate=t,this.displayedMonth=t.getUTCMonth(),this.displayedYear=t.getUTCFullYear(),this.monthCalculationCache.clear(),this.shouldRestoreFocus=!0,this.refresh()}navigateToToday(){let t=Xt(),r=Br(t);this.selectedDate=r,this.displayedMonth=r.getUTCMonth(),this.displayedYear=r.getUTCFullYear(),this.monthCalculationCache.clear(),this.shouldRestoreFocus=!0,this.refresh()}setupKeyboardNavigation(t){this.keyboardHandler&&t.removeEventListener("keydown",this.keyboardHandler),this.keyboardHandler=r=>{(async()=>{if(r.key==="ArrowLeft"||r.key==="ArrowRight"||r.key==="ArrowUp"||r.key==="ArrowDown"){r.preventDefault(),this.navigateByArrowKey(r.key);return}if(r.key==="PageUp"){r.preventDefault(),r.shiftKey?this.navigateToYear(-1):this.navigateToPreviousMonth();return}if(r.key==="PageDown"){r.preventDefault(),r.shiftKey?this.navigateToYear(1):this.navigateToNextMonth();return}if(r.key==="Home"){r.preventDefault(),r.ctrlKey||r.metaKey?this.navigateToStartOfMonth():this.navigateToStartOfWeek();return}if(r.key==="End"){r.preventDefault(),r.ctrlKey||r.metaKey?this.navigateToEndOfMonth():this.navigateToEndOfWeek();return}if(r.key==="t"||r.key==="T"){r.preventDefault(),this.navigateToToday();return}if(r.key==="Escape"){this.multiSelectMode&&(r.preventDefault(),this.multiSelectMode=!1,this.selectedDates.clear(),this.refresh());return}if(r.key==="Enter"||r.key===" "){r.preventDefault(),r.ctrlKey||r.metaKey?await this.openDailyNoteForDate(this.selectedDate):await this.handleDayClick(this.selectedDate);return}})()},t.addEventListener("keydown",this.keyboardHandler)}navigateByArrowKey(t){let r=new Date(this.selectedDate.getTime());switch(t){case"ArrowLeft":r.setUTCDate(r.getUTCDate()-1);break;case"ArrowRight":r.setUTCDate(r.getUTCDate()+1);break;case"ArrowUp":r.setUTCDate(r.getUTCDate()-7);break;case"ArrowDown":r.setUTCDate(r.getUTCDate()+7);break}this.selectedDate=r,(r.getUTCMonth()!==this.displayedMonth||r.getUTCFullYear()!==this.displayedYear)&&(this.displayedMonth=r.getUTCMonth(),this.displayedYear=r.getUTCFullYear(),this.monthCalculationCache.clear()),this.shouldRestoreFocus=!0,this.refresh()}navigateToStartOfWeek(){let t=this.plugin.settings.calendarViewSettings.firstDay||0,a=(this.selectedDate.getUTCDay()-t+7)%7,i=new Date(this.selectedDate.getTime());i.setUTCDate(i.getUTCDate()-a),this.selectedDate=i,(i.getUTCMonth()!==this.displayedMonth||i.getUTCFullYear()!==this.displayedYear)&&(this.displayedMonth=i.getUTCMonth(),this.displayedYear=i.getUTCFullYear(),this.monthCalculationCache.clear()),this.shouldRestoreFocus=!0,this.refresh()}navigateToEndOfWeek(){let t=this.plugin.settings.calendarViewSettings.firstDay||0,r=this.selectedDate.getUTCDay(),i=((t+6)%7-r+7)%7,s=new Date(this.selectedDate.getTime());s.setUTCDate(s.getUTCDate()+i),this.selectedDate=s,(s.getUTCMonth()!==this.displayedMonth||s.getUTCFullYear()!==this.displayedYear)&&(this.displayedMonth=s.getUTCMonth(),this.displayedYear=s.getUTCFullYear(),this.monthCalculationCache.clear()),this.shouldRestoreFocus=!0,this.refresh()}navigateToStartOfMonth(){let t=new Date(Date.UTC(this.selectedDate.getUTCFullYear(),this.selectedDate.getUTCMonth(),1));this.selectedDate=t,this.shouldRestoreFocus=!0,this.refresh()}navigateToEndOfMonth(){let t=new Date(Date.UTC(this.selectedDate.getUTCFullYear(),this.selectedDate.getUTCMonth()+1,0));this.selectedDate=t,this.shouldRestoreFocus=!0,this.refresh()}navigateToYear(t){let r=new Date(this.selectedDate.getTime());r.setUTCFullYear(r.getUTCFullYear()+t),this.selectedDate=r,this.displayedMonth=r.getUTCMonth(),this.displayedYear=r.getUTCFullYear(),this.monthCalculationCache.clear(),this.shouldRestoreFocus=!0,this.refresh()}getWeekNumber(t){let r=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())),a=r.getUTCDay()||7;r.setUTCDate(r.getUTCDate()+4-a);let i=new Date(Date.UTC(r.getUTCFullYear(),0,1));return Math.ceil(((r.getTime()-i.getTime())/864e5+1)/7)}selectWeek(t){this.multiSelectMode=!0,this.selectedDates.clear(),t.forEach(r=>{this.selectedDates.add(ae(r))}),this.shouldRestoreFocus=!0,this.refresh(),this.showCombinedNotes()}showCombinedNotes(){let t=[];this.selectedDates.forEach(r=>{let a=this.notesByDate.get(r);a&&t.push(...a)}),t.length>0?new _F(this.plugin.app,this.plugin,t,a=>{a&&this.openCalendarEntry(a)}).open():new ki.Notice("No notes found for selected dates")}createNotePreviewText(t){let r=[],a=t.filter(s=>s.kind==="note").length,i=t.length-a;return a>0&&i>0?r.push(`${a} note${a>1?"s":""}, ${i} event${i>1?"s":""}`):i>0?r.push(`${i} event${i>1?"s":""}`):r.push(`${a} note${a>1?"s":""}`),r.push(""),t.slice(0,5).forEach(s=>{var c,d;let o=`• ${s.title}`;if(s.kind==="external"){s.sourceName&&(o+=` (${s.sourceName})`),r.push(o);return}let l=(d=(c=s.basesEntry)==null?void 0:c.getValue)==null?void 0:d.call(c,"note.type");if(l){let u=null;if(typeof l=="object"&&l.toString){let p=l.toString();p&&p!=="null"&&p!==""&&(u=p)}else typeof l=="string"&&(u=l);u&&(o+=` (${u})`)}r.push(o)}),t.length>5&&r.push(`+ ${t.length-5} more...`),r.join(` +`)}getHeatMapIntensity(t){return bJe(t,this.heatMapMaxCount)}setupContainer(){var a;super.setupContainer();let t=this.containerEl.ownerDocument,r=Ie(t,"div");r.className="mini-calendar-bases-view",(a=this.rootElement)==null||a.appendChild(r),this.calendarEl=r}async handleTaskUpdate(t){this.debouncedRefresh()}renderError(t){if(!this.calendarEl)return;let r=this.calendarEl.ownerDocument,a=Ie(r,"div");a.className="tn-bases-error",a.classList.remove("tn-static-border-radius-4px-c290c56e","tn-static-border-radius-6px-0dc8408c","tn-static-color-var-color-accent-d2cad743","tn-static-color-var-text-accent-65b47ee3","tn-static-color-var-text-muted-5872de20","tn-static-color-var-text-on-accent-f3e1679d","tn-static-color-var-text-warning-783d5f03","tn-static-color-var-tn-text-muted-a90fb6f3","tn-static-color-white-0a43e56a","tn-static-cursor-pointer-2723efcc","tn-static-font-size-12px-65574819","tn-static-font-weight-bold-0fe8c30d","tn-static-font-weight-bold-e0b452bd","tn-static-margin-0-11696618","tn-static-margin-0-auto-266e9b04","tn-static-margin-0-db0d5f36","tn-static-margin-0-var-size-4-2-77f7dc08","tn-static-margin-2px-0-edce9b14","tn-static-margin-8px-0-0-0-a2eb8382","tn-static-padding-0-16px-16px-16px-f1aa998c","tn-static-padding-0-41d7d7e2","tn-static-padding-12px-43bef435","tn-static-padding-16px-287f770e","tn-static-padding-20px-769fed37","tn-static-padding-20px-7a035d95","tn-static-padding-2px-8px-c8eea84a","tn-static-padding-2rem-42aa6d9c"),a.classList.add("tn-static-padding-20px-ebe8e48c"),a.textContent=`Error loading mini calendar: ${t.message||"Unknown error"}`,this.calendarEl.appendChild(a)}onunload(){this.calendarEl=null,this.notesByDate.clear(),this.monthCalculationCache.clear(),this.keyboardHandler=null}},_F=class extends ki.FuzzySuggestModal{constructor(e,t,r,a){super(e),this.plugin=t,this.notes=r,this.onChooseNote=a,this.setPlaceholder("Select an item to open"),this.setInstructions([{command:"↑↓",purpose:"Navigate"},{command:"↵",purpose:"Open item"},{command:"esc",purpose:"Dismiss"}])}getItems(){return this.notes.sort((e,t)=>e.title.localeCompare(t.title))}getItemText(e){return e.title}renderSuggestion(e,t){let r=e.item,a=t.createDiv({cls:"note-selector-modal__suggestion"});a.createDiv({cls:"note-selector-modal__title",text:r.title});let i=r.kind==="external"&&r.sourceName||r.path;i!==r.title&&a.createDiv({cls:"note-selector-modal__path",text:i})}onChooseItem(e,t){this.onChooseNote(e)}}});function wJe(n,e=b3){var t,r;try{let a=n.internalPlugins;if(!a)return e.debug("Internal plugins manager not available",{category:"configuration",operation:"get-api"}),null;let i=(t=a.getEnabledPluginById)==null?void 0:t.call(a,"bases");return i?!i.registrations||typeof i.registrations!="object"?(e.warn("Bases plugin found but registrations API is not available",{category:"provider",operation:"get-api"}),null):{registrations:i.registrations,isEnabled:!0,version:((r=i.manifest)==null?void 0:r.version)||"unknown"}:(e.debug("Bases plugin not found or not enabled",{category:"configuration",operation:"get-api"}),null)}catch(a){return e.warn("Error accessing Bases plugin API",{category:"provider",operation:"get-api",error:a}),null}}function sD(n,e,t,r=b3){if(typeof n.registerBasesView=="function")try{return n.registerBasesView(e,t)?(r.debug("Successfully registered view via public API",{category:"configuration",operation:"register-view",details:{viewId:e}}),!0):(r.debug("Public API returned false",{category:"configuration",operation:"register-view",details:{viewId:e}}),!1)}catch(a){return a instanceof Error&&a.message.includes("already exists")?(r.debug("View already registered via public API",{category:"configuration",operation:"register-view",details:{viewId:e}}),!0):(r.warn("Public API registration failed",{category:"provider",operation:"register-view",details:{viewId:e},error:a}),!1)}return r.warn("Cannot register view because Bases public API is not available",{category:"configuration",operation:"register-view",details:{viewId:e}}),!1}function oD(n,e,t=b3){let r=wJe(n.app,t);if(!r)return!0;try{return r.registrations[e]&&delete r.registrations[e],!0}catch(a){return t.error("Error unregistering view",{category:"provider",operation:"unregister-view",details:{viewId:e},error:a}),!1}}var b3,YEe=y(()=>{q();b3=M({tag:"Bases/API"})});function lD(n){return n.startsWith("note.")||n.startsWith("file.")||n.startsWith("formula.")}var KEe=y(()=>{});function ZEe(n){return e=>n.i18n.translate(`views.basesCalendar.settings.${e}`)}function QEe(n,e,t){let r=n.get(e);return r==null?t:r}function CJe(n,e,t){let r=QEe(n,e,t);return typeof r=="string"?r:t}function cD(n,e,t){let r=QEe(n,e,t);return typeof r=="boolean"?r:t}function xJe(n,e){let t=n.get(e);return t==null?!1:typeof t=="string"?t.trim().length>0:!0}function dT(n,e){return CJe(n,"calendarView",e)}function w3(n){return n==="timeGridWeek"||n==="timeGridCustom"||n==="timeGridDay"}function JEe(n){return n==="dayGridMonth"||n==="multiMonthYear"}function EJe(n){return n==="timeGridWeek"||n==="timeGridCustom"}function FF(n,e,t){return t(dT(n,e))}function DJe(n){return{0:n.i18n.translate("common.weekdays.sunday"),1:n.i18n.translate("common.weekdays.monday"),2:n.i18n.translate("common.weekdays.tuesday"),3:n.i18n.translate("common.weekdays.wednesday"),4:n.i18n.translate("common.weekdays.thursday"),5:n.i18n.translate("common.weekdays.friday"),6:n.i18n.translate("common.weekdays.saturday")}}function XEe(n,e){var s,o,l,c,d,u;let t=[],r=(o=(s=n.icsSubscriptionService)==null?void 0:s.getSubscriptions())!=null?o:[];r.length>0&&t.push({type:"group",displayName:e("groups.calendarSubscriptions"),items:r.map(p=>({type:"toggle",key:`showICS_${p.id}`,displayName:p.name,default:!0}))});let a=(c=(l=n.googleCalendarService)==null?void 0:l.getAvailableCalendars())!=null?c:[];a.length>0&&t.push({type:"group",displayName:e("groups.googleCalendars")||"Google Calendars",items:a.map(p=>({type:"toggle",key:`showGoogleCalendar_${p.id}`,displayName:p.summary||p.id,default:!0}))});let i=(u=(d=n.microsoftCalendarService)==null?void 0:d.getAvailableCalendars())!=null?u:[];return i.length>0&&t.push({type:"group",displayName:e("groups.microsoftCalendars")||"Microsoft Calendars",items:i.map(p=>({type:"toggle",key:`showMicrosoftCalendar_${p.id}`,displayName:p.summary||p.id,default:!0}))}),t}function PJe(n,e,t){let r=n.settings.calendarViewSettings;return{type:"group",displayName:t("groups.events"),items:[{type:"toggle",key:"showScheduled",displayName:t("events.showScheduledTasks"),default:r.defaultShowScheduled},{type:"toggle",key:"showDue",displayName:t("events.showDueTasks"),default:r.defaultShowDue},{type:"toggle",key:"showOverdueOnToday",displayName:t("events.showOverdueOnToday"),default:!1,shouldHide:()=>dT(e,r.defaultView)!=="listWeek"},{type:"toggle",key:"showScheduledToDueSpan",displayName:t("layout.spanScheduledToDue"),default:r.defaultShowScheduledToDueSpan,shouldHide:()=>!cD(e,"showScheduled",r.defaultShowScheduled)||!cD(e,"showDue",r.defaultShowDue)},{type:"toggle",key:"showRecurring",displayName:t("events.showRecurringTasks"),default:r.defaultShowRecurring},{type:"toggle",key:"showCompletedRecurringInstances",displayName:t("events.showCompletedRecurringInstances"),default:!0,shouldHide:()=>!cD(e,"showRecurring",r.defaultShowRecurring)},{type:"toggle",key:"showSkippedRecurringInstances",displayName:t("events.showSkippedRecurringInstances"),default:!0,shouldHide:()=>!cD(e,"showRecurring",r.defaultShowRecurring)},{type:"toggle",key:"showTimeEntries",displayName:t("events.showTimeEntries"),default:r.defaultShowTimeEntries},{type:"toggle",key:"showTimeblocks",displayName:t("events.showTimeblocks"),default:r.defaultShowTimeblocks},{type:"toggle",key:"showPropertyBasedEvents",displayName:t("events.showPropertyBasedEvents"),default:!0}]}}function AJe(n,e){return{type:"group",displayName:e("groups.dateNavigation"),items:[{type:"text",key:"initialDate",displayName:e("dateNavigation.navigateToDate"),default:"",placeholder:e("dateNavigation.navigateToDatePlaceholder")},{type:"property",key:"initialDateProperty",displayName:e("dateNavigation.navigateToDateFromProperty"),placeholder:e("dateNavigation.navigateToDateFromPropertyPlaceholder"),filter:t=>t.startsWith("note.")||t.startsWith("file.")},{type:"dropdown",key:"initialDateStrategy",displayName:e("dateNavigation.propertyNavigationStrategy"),default:"first",options:{first:e("dateNavigation.strategies.first"),earliest:e("dateNavigation.strategies.earliest"),latest:e("dateNavigation.strategies.latest")},shouldHide:()=>!xJe(n,"initialDateProperty")},{type:"toggle",key:"createDailyNotesFromDateLinks",displayName:e("dateNavigation.createDailyNotesFromDateLinks"),default:!0}]}}function MJe(n,e,t){let r=n.settings.calendarViewSettings,a=r.defaultView;return{type:"group",displayName:t("groups.view"),items:[{type:"dropdown",key:"calendarView",displayName:t("layout.calendarView"),default:a,options:SJe},{type:"slider",key:"customDayCount",displayName:t("layout.customDayCount"),default:r.customDayCount||3,min:1,max:14,step:1,shouldHide:()=>dT(e,a)!=="timeGridCustom"},{type:"slider",key:"listDayCount",displayName:t("layout.listDayCount"),default:7,min:1,max:365,step:1,shouldHide:()=>dT(e,a)!=="listWeek"},{type:"dropdown",key:"heightMode",displayName:t("layout.heightMode"),default:"fill",options:{fill:t("layout.heightModeFill"),auto:t("layout.heightModeAuto")}}]}}function IJe(n,e,t){let r=n.settings.calendarViewSettings,a=r.defaultView;return{type:"group",displayName:t("groups.display"),items:[{type:"dropdown",key:"firstDay",displayName:t("layout.weekStartsOn"),default:String(r.firstDay),options:DJe(n)},{type:"dropdown",key:"timeFormat",displayName:t("layout.timeFormat"),default:r.timeFormat,options:{12:t("layout.timeFormat12"),24:t("layout.timeFormat24")}},{type:"toggle",key:"weekNumbers",displayName:t("layout.showWeekNumbers"),default:r.weekNumbers,shouldHide:()=>dT(e,a)==="listWeek"},{type:"toggle",key:"showWeekends",displayName:t("layout.showWeekends"),default:r.showWeekends},{type:"toggle",key:"showAllDaySlot",displayName:t("layout.showAllDaySlot"),default:!0},{type:"toggle",key:"showTodayHighlight",displayName:t("layout.showTodayHighlight"),default:r.showTodayHighlight},{type:"slider",key:"todayColumnWidthMultiplier",displayName:t("layout.todayColumnWidthMultiplier"),default:1,min:1,max:5,step:.5,shouldHide:()=>!FF(e,a,i=>EJe(i))},{type:"toggle",key:"enableSearch",displayName:t("layout.enableSearch"),default:!1}]}}function NJe(n,e){let t=n.settings.calendarViewSettings;return[{type:"text",key:"slotMinTime",displayName:e("layout.dayStartTime"),default:t.slotMinTime,placeholder:e("layout.dayStartTimePlaceholder")},{type:"text",key:"slotMaxTime",displayName:e("layout.dayEndTime"),default:t.slotMaxTime,placeholder:e("layout.dayEndTimePlaceholder")},{type:"text",key:"slotDuration",displayName:e("layout.timeSlotDuration"),default:t.slotDuration,placeholder:e("layout.timeSlotDurationPlaceholder")},{type:"text",key:"snapDuration",displayName:e("layout.dragDropResolution"),default:t.slotDuration,placeholder:e("layout.dragDropResolutionPlaceholder")},{type:"text",key:"scrollTime",displayName:e("layout.initialScrollTime"),default:t.scrollTime,placeholder:e("layout.initialScrollTimePlaceholder")},{type:"toggle",key:"nowIndicator",displayName:e("layout.showNowIndicator"),default:t.nowIndicator},{type:"toggle",key:"showTimeGrid",displayName:e("layout.showTimeGrid"),default:!0},{type:"toggle",key:"selectMirror",displayName:e("layout.showSelectionPreview"),default:t.selectMirror}]}function RJe(n,e,t){var o;let r=n.settings.calendarViewSettings,a=r.defaultView,i=()=>!FF(e,a,l=>w3(l)),s=()=>!FF(e,a,l=>JEe(l));return[{type:"toggle",key:"slotEventOverlap",displayName:t("layout.slotEventOverlap"),default:r.slotEventOverlap,shouldHide:i},{type:"slider",key:"eventMinHeight",displayName:t("layout.minimumEventHeight"),default:r.eventMinHeight,min:15,max:100,step:5,shouldHide:i},{type:"slider",key:"eventMaxStack",displayName:t("layout.eventMaxStack"),default:(o=r.eventMaxStack)!=null?o:0,min:0,max:10,step:1,shouldHide:i},{type:"slider",key:"dayMaxEvents",displayName:t("layout.dayMaxEvents"),default:typeof r.dayMaxEvents=="number"?r.dayMaxEvents:0,min:0,max:20,step:1,shouldHide:s},{type:"slider",key:"dayMaxEventRows",displayName:t("layout.dayMaxEventRows"),default:typeof r.dayMaxEventRows=="number"?r.dayMaxEventRows:0,min:0,max:10,step:1,shouldHide:s}]}function _Je(n,e){return{type:"group",displayName:e("groups.propertyBasedEvents"),shouldHide:()=>!cD(n,"showPropertyBasedEvents",!0),items:[{type:"property",key:"startDateProperty",displayName:e("propertyBasedEvents.startDateProperty"),placeholder:e("propertyBasedEvents.startDatePropertyPlaceholder"),filter:t=>lD(t)},{type:"property",key:"endDateProperty",displayName:e("propertyBasedEvents.endDateProperty"),placeholder:e("propertyBasedEvents.endDatePropertyPlaceholder"),filter:t=>lD(t)},{type:"property",key:"titleProperty",displayName:e("propertyBasedEvents.titleProperty"),placeholder:e("propertyBasedEvents.titlePropertyPlaceholder"),filter:t=>lD(t)}]}}function eDe(n,e){let t=ZEe(n),r=n.settings.calendarViewSettings.defaultView;return[PJe(n,e,t),AJe(e,t),MJe(n,e,t),IJe(n,e,t),{type:"group",displayName:t("groups.timeGrid"),shouldHide:()=>!FF(e,r,a=>w3(a)),items:NJe(n,t)},{type:"group",displayName:t("groups.eventLayout"),shouldHide:()=>{let a=dT(e,r);return!w3(a)&&!JEe(a)},items:RJe(n,e,t)},_Je(e,t),...XEe(n,t)]}function tDe(n){let e=ZEe(n),t=[{type:"property",key:"dateProperty",displayName:"Date Property",placeholder:"Select property to show on calendar",default:"file.ctime",filter:r=>r.startsWith("note.")||r.startsWith("file.")||r.startsWith("task.")},{type:"property",key:"titleProperty",displayName:"Title Property",placeholder:"Select property to use as title",default:"file.name",filter:r=>lD(r)},{type:"slider",key:"heatMapMaxCount",displayName:"Max color note count",default:lg,min:1,max:20,step:1}];return t.push(...XEe(n,e)),t}var SJe,rDe=y(()=>{T3();KEe();SJe={dayGridMonth:"Month",timeGridWeek:"Week",timeGridCustom:"Custom days",timeGridDay:"Day",listWeek:"List",multiMonthYear:"Year"}});var iDe={};Xe(iDe,{registerBasesTaskList:()=>OJe,unregisterBasesViews:()=>S3});async function OJe(n){if(!n.settings.enableBases||!(0,aDe.requireApiVersion)("1.10.1"))return!1;let e=M({tag:"Bases/Registration",isDebugEnabled:()=>n.settings.enableDebugLogging});return(async()=>{try{let r=sD(n,"tasknotesTaskList",{name:"TaskNotes Task List",icon:"tasknotes-simple",factory:dCe(n),options:()=>[{type:"property",key:"subGroup",displayName:"Sub-group by",placeholder:"Select property for sub-grouping (optional)",filter:o=>o.startsWith("note.")||o.startsWith("task.")||o.startsWith("formula.")},{type:"toggle",key:"enableSearch",displayName:"Enable search box",default:!1},{type:"dropdown",key:"defaultCollapsedState",displayName:"Default collapsed state",default:"Expanded",options:LJe},{type:"dropdown",key:"expandedRelationshipFilterMode",displayName:"Expanded relationships",default:"inherit",options:nDe},{type:"toggle",key:"hideTopLevelSubtasks",displayName:"Hide top-level subtasks",default:!1}]},e),a=sD(n,"tasknotesKanban",{name:"TaskNotes Kanban",icon:"tasknotes-simple",factory:ZCe(n),options:()=>[{type:"property",key:"swimLane",displayName:"Swim Lane",placeholder:"Select property for swim lanes (optional)",filter:o=>o.startsWith("note.")||o.startsWith("task.")||o.startsWith("formula.")},{type:"slider",key:"columnWidth",displayName:"Column Width",default:280,min:200,max:500,step:20},{type:"slider",key:"maxSwimlaneHeight",displayName:"Max Swimlane Height",default:600,min:300,max:1200,step:50},{type:"toggle",key:"hideEmptyColumns",displayName:"Hide Empty Columns",default:!1},{type:"text",key:"pinnedColumns",displayName:"Pinned Columns",placeholder:"Comma-separated column values to keep visible",default:""},{type:"toggle",key:"hideEmptySwimLanes",displayName:"Hide Empty Swimlanes",default:!1},{type:"toggle",key:"enableSearch",displayName:"Enable search box",default:!1},{type:"toggle",key:"explodeListColumns",displayName:"Show items in multiple columns",default:!0},{type:"toggle",key:"consolidateStatusIcon",displayName:"Show status icon in column header only",default:!1},{type:"dropdown",key:"cardLayout",displayName:"Card layout",default:"default",options:FJe},{type:"text",key:"columnOrder",displayName:"Column Order (Advanced)",placeholder:"Auto-managed when dragging columns",default:"{}"},{type:"text",key:"swimLaneOrder",displayName:"Swim Lane Order (Advanced)",placeholder:"JSON object keyed by swim lane property",default:"{}"},{type:"dropdown",key:"expandedRelationshipFilterMode",displayName:"Expanded relationships",default:"inherit",options:nDe},{type:"toggle",key:"hideTopLevelSubtasks",displayName:"Hide top-level subtasks",default:!1}]},e),i=sD(n,"tasknotesCalendar",{name:"TaskNotes Calendar",icon:"tasknotes-simple",factory:HEe(n),options:o=>eDe(n,o)},e),s=sD(n,"tasknotesMiniCalendar",{name:"TaskNotes Mini Calendar",icon:"tasknotes-simple",factory:GEe(n),options:()=>tDe(n)},e);return!r&&!a&&!i&&!s?(e.debug("Bases plugin not available for registration",{category:"configuration",operation:"register-views"}),!1):!r||!a||!i||!s?(e.warn("Some TaskNotes Bases views failed to register",{category:"configuration",operation:"register-views",details:{taskListSuccess:r,kanbanSuccess:a,calendarSuccess:i,miniCalendarSuccess:s}}),!1):(n.app.workspace.iterateAllLeaves(o=>{var l,c;if(((c=(l=o.view)==null?void 0:l.getViewType)==null?void 0:c.call(l))==="bases"){let d=o.view;if(typeof d.refresh=="function")try{d.refresh()}catch(u){e.debug("Error refreshing Bases view after registration",{category:"provider",operation:"refresh-existing-view",error:u})}}}),!0)}catch(r){return e.warn("Registration attempt failed",{category:"provider",operation:"register-views",error:r}),!1}})()}function S3(n){let e=M({tag:"Bases/Registration",isDebugEnabled:()=>n.settings.enableDebugLogging});try{oD(n,"tasknotesTaskList",e),oD(n,"tasknotesKanban",e),oD(n,"tasknotesCalendar",e),oD(n,"tasknotesMiniCalendar",e)}catch(t){e.error("Error during view unregistration",{category:"provider",operation:"unregister-views",error:t})}}var aDe,FJe,LJe,nDe,C3=y(()=>{aDe=require("obsidian");uCe();QCe();VEe();T3();YEe();rDe();q();FJe={default:"Default",compact:"Compact"},LJe={Expanded:"Expanded",Collapsed:"Collapsed"},nDe={inherit:"Inherit","show-all":"Show all"}});var oDe=te(()=>{var sDe;(function(n){(function(e){var t=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:typeof this=="object"?this:o(),r=a(n);typeof t.Reflect!="undefined"&&(r=a(t.Reflect,r)),e(r,t),typeof t.Reflect=="undefined"&&(t.Reflect=n);function a(l,c){return function(d,u){Object.defineProperty(l,d,{configurable:!0,writable:!0,value:u}),c&&c(d,u)}}function i(){try{return Function("return this;")()}catch(l){}}function s(){try{return(0,eval)("(function() { return this; })()")}catch(l){}}function o(){return i()||s()}})(function(e,t){var r=Object.prototype.hasOwnProperty,a=typeof Symbol=="function",i=a&&typeof Symbol.toPrimitive!="undefined"?Symbol.toPrimitive:"@@toPrimitive",s=a&&typeof Symbol.iterator!="undefined"?Symbol.iterator:"@@iterator",o=typeof Object.create=="function",l={__proto__:[]}instanceof Array,c=!o&&!l,d={create:o?function(){return h1(Object.create(null))}:l?function(){return h1({__proto__:null})}:function(){return h1({})},has:c?function(L,$){return r.call(L,$)}:function(L,$){return $ in L},get:c?function(L,$){return r.call(L,$)?L[$]:void 0}:function(L,$){return L[$]}},u=Object.getPrototypeOf(Function),p=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:mFe(),m=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:fFe(),f=typeof WeakMap=="function"?WeakMap:hFe(),h=a?Symbol.for("@reflect-metadata:registry"):void 0,g=dFe(),v=uFe(g);function k(L,$,G,se){if(Q(G)){if(!cs(L))throw new TypeError;if(!Ce($))throw new TypeError;return I(L,$)}else{if(!cs(L))throw new TypeError;if(!le($))throw new TypeError;if(!le(se)&&!Q(se)&&!Z(se))throw new TypeError;return Z(se)&&(se=void 0),G=Dr(G),A(L,$,G,se)}}e("decorate",k);function T(L,$){function G(se,$e){if(!le(se))throw new TypeError;if(!Q($e)&&!en($e))throw new TypeError;oe(L,$,se,$e)}return G}e("metadata",T);function b(L,$,G,se){if(!le(G))throw new TypeError;return Q(se)||(se=Dr(se)),oe(L,$,G,se)}e("defineMetadata",b);function w(L,$,G){if(!le($))throw new TypeError;return Q(G)||(G=Dr(G)),R(L,$,G)}e("hasMetadata",w);function S(L,$,G){if(!le($))throw new TypeError;return Q(G)||(G=Dr(G)),O(L,$,G)}e("hasOwnMetadata",S);function C(L,$,G){if(!le($))throw new TypeError;return Q(G)||(G=Dr(G)),U(L,$,G)}e("getMetadata",C);function x(L,$,G){if(!le($))throw new TypeError;return Q(G)||(G=Dr(G)),pe(L,$,G)}e("getOwnMetadata",x);function E(L,$){if(!le(L))throw new TypeError;return Q($)||($=Dr($)),X(L,$)}e("getMetadataKeys",E);function _(L,$){if(!le(L))throw new TypeError;return Q($)||($=Dr($)),de(L,$)}e("getOwnMetadataKeys",_);function F(L,$,G){if(!le($))throw new TypeError;if(Q(G)||(G=Dr(G)),!le($))throw new TypeError;Q(G)||(G=Dr(G));var se=ab($,G,!1);return Q(se)?!1:se.OrdinaryDeleteMetadata(L,$,G)}e("deleteMetadata",F);function I(L,$){for(var G=L.length-1;G>=0;--G){var se=L[G],$e=se($);if(!Q($e)&&!Z($e)){if(!Ce($e))throw new TypeError;$=$e}}return $}function A(L,$,G,se){for(var $e=L.length-1;$e>=0;--$e){var vn=L[$e],$n=vn($,G,se);if(!Q($n)&&!Z($n)){if(!le($n))throw new TypeError;se=$n}}return se}function R(L,$,G){var se=O(L,$,G);if(se)return!0;var $e=f1($);return Z($e)?!1:R(L,$e,G)}function O(L,$,G){var se=ab($,G,!1);return Q(se)?!1:qr(se.OrdinaryHasOwnMetadata(L,$,G))}function U(L,$,G){var se=O(L,$,G);if(se)return pe(L,$,G);var $e=f1($);if(!Z($e))return U(L,$e,G)}function pe(L,$,G){var se=ab($,G,!1);if(!Q(se))return se.OrdinaryGetOwnMetadata(L,$,G)}function oe(L,$,G,se){var $e=ab(G,se,!0);$e.OrdinaryDefineOwnMetadata(L,$,G,se)}function X(L,$){var G=de(L,$),se=f1(L);if(se===null)return G;var $e=X(se,$);if($e.length<=0)return G;if(G.length<=0)return $e;for(var vn=new m,$n=[],Ct=0,he=G;Ct=0&&he=this._keys.length?(this._index=-1,this._keys=$,this._values=$):this._index++,{value:Se,done:!1}}return{value:void 0,done:!0}},Ct.prototype.throw=function(he){throw this._index>=0&&(this._index=-1,this._keys=$,this._values=$),he},Ct.prototype.return=function(he){return this._index>=0&&(this._index=-1,this._keys=$,this._values=$),{value:he,done:!0}},Ct})(),se=(function(){function Ct(){this._keys=[],this._values=[],this._cacheKey=L,this._cacheIndex=-2}return Object.defineProperty(Ct.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),Ct.prototype.has=function(he){return this._find(he,!1)>=0},Ct.prototype.get=function(he){var Se=this._find(he,!1);return Se>=0?this._values[Se]:void 0},Ct.prototype.set=function(he,Se){var Ee=this._find(he,!0);return this._values[Ee]=Se,this},Ct.prototype.delete=function(he){var Se=this._find(he,!1);if(Se>=0){for(var Ee=this._keys.length,Re=Se+1;Re."},operator:{type:"string",enum:["is","is-not","contains","does-not-contain","is-before","is-after","is-on-or-before","is-on-or-after","is-empty","is-not-empty","is-checked","is-not-checked","is-greater-than","is-less-than","is-greater-than-or-equal","is-less-than-or-equal"],description:"Comparison operator. Use an operator supported by the selected property."},value:{description:"Comparison value. Empty and checked operators do not require a value.",nullable:!0,oneOf:[{type:"string"},{type:"array",items:{type:"string"}},{type:"number"},{type:"boolean"}]}},required:["type","id","property","operator"]},TaskDependency:{type:"object",properties:{uid:{type:"string",description:"Link or identifier for the blocking task"},reltype:{type:"string",enum:["FINISHTOSTART","FINISHTOFINISH","STARTTOSTART","STARTTOFINISH"],description:"Dependency relationship type"},gap:{type:"string",description:"Optional ISO 8601 duration offset between tasks"}},required:["uid","reltype"]},Reminder:{type:"object",properties:{id:{type:"string",description:"Reminder identifier"},type:{type:"string",enum:["absolute","relative"],description:"Reminder type"},absoluteTime:{type:"string",format:"date-time",description:"Absolute reminder timestamp"},relatedTo:{type:"string",enum:["due","scheduled"],description:"Date field used as the relative reminder anchor"},offset:{type:"string",description:"ISO 8601 duration relative to the anchor date"}},required:["id","type"]},TaskStats:{type:"object",properties:{total:{type:"integer",description:"Total number of tasks"},completed:{type:"integer",description:"Number of completed tasks"},active:{type:"integer",description:"Number of active (non-completed, non-archived) tasks"},overdue:{type:"integer",description:"Number of overdue tasks"},archived:{type:"integer",description:"Number of archived tasks"},withTimeTracking:{type:"integer",description:"Number of tasks with time tracking entries"}},required:["total","completed","active","overdue","archived","withTimeTracking"]},WebhookConfig:{type:"object",properties:{id:{type:"string",description:"Unique webhook identifier"},url:{type:"string",format:"uri",description:"Webhook endpoint URL"},events:{type:"array",items:{type:"string",enum:["task.created","task.updated","task.deleted","task.completed","task.archived","task.unarchived","time.started","time.stopped","pomodoro.started","pomodoro.completed","pomodoro.interrupted","recurring.instance.completed","reminder.triggered"]},description:"Events to subscribe to",minItems:1},active:{type:"boolean",description:"Whether the webhook is active"},transformFile:{type:"string",description:"Optional transform file path for payload customization"},corsHeaders:{type:"boolean",description:"Whether to include custom headers (disable for strict CORS services)"}},required:["url","events"]},PomodoroSession:{type:"object",properties:{id:{type:"string",description:"Unique session identifier"},type:{type:"string",enum:["work","short-break","long-break"],description:"Type of pomodoro session"},duration:{type:"integer",description:"Session duration in seconds"},startTime:{type:"string",format:"date-time",description:"Session start timestamp"},endTime:{type:"string",format:"date-time",description:"Session end timestamp",nullable:!0},task:{$ref:"#/components/schemas/Task",nullable:!0,description:"Associated task (if any)"}},required:["id","type","duration","startTime"]},PomodoroState:{type:"object",properties:{isRunning:{type:"boolean",description:"Whether a pomodoro session is currently running"},timeRemaining:{type:"integer",description:"Time remaining in current session (seconds)"},currentSession:{$ref:"#/components/schemas/PomodoroSession",nullable:!0,description:"Current active session (if any)"},nextSessionType:{type:"string",enum:["work","short-break","long-break"],nullable:!0,description:"Suggested next session type"},totalPomodoros:{type:"integer",description:"Total completed pomodoros (all time)"},currentStreak:{type:"integer",description:"Current consecutive pomodoro streak"},totalMinutesToday:{type:"integer",description:"Total focused minutes today"}},required:["isRunning","timeRemaining"]},PomodoroSessionHistory:{type:"object",properties:{id:{type:"string",description:"Session identifier"},type:{type:"string",enum:["work","short-break","long-break"]},startTime:{type:"string",format:"date-time"},endTime:{type:"string",format:"date-time"},duration:{type:"integer",description:"Actual session duration in seconds"},completed:{type:"boolean",description:"Whether the session was completed (not interrupted)"},taskPath:{type:"string",nullable:!0,description:"Associated task file path"},taskTitle:{type:"string",nullable:!0,description:"Associated task title"}},required:["id","type","startTime","endTime","duration","completed"]},PomodoroStats:{type:"object",properties:{totalSessions:{type:"integer",description:"Total number of sessions"},completedSessions:{type:"integer",description:"Number of completed sessions"},interruptedSessions:{type:"integer",description:"Number of interrupted sessions"},totalFocusTime:{type:"integer",description:"Total focused time in minutes"},workSessions:{type:"integer",description:"Number of work sessions"},breakSessions:{type:"integer",description:"Number of break sessions"},longestStreak:{type:"integer",description:"Longest consecutive completed sessions"},averageSessionLength:{type:"number",description:"Average session length in minutes"}},required:["totalSessions","completedSessions","interruptedSessions","totalFocusTime"]},TimeEntry:{type:"object",properties:{startTime:{type:"string",format:"date-time",description:"ISO timestamp when time tracking started"},endTime:{type:"string",format:"date-time",nullable:!0,description:"ISO timestamp when time tracking ended (null if still running)"},description:{type:"string",nullable:!0,description:"Optional description of work being tracked"},duration:{type:"integer",minimum:0,description:"Duration in minutes (calculated or manually set)"},isActive:{type:"boolean",description:"Whether this time entry is currently active"}},required:["startTime","duration","isActive"]},ActiveTimeSession:{type:"object",properties:{task:{type:"object",properties:{id:{type:"string",description:"Task identifier (file path)"},title:{type:"string",description:"Task title"},status:{type:"string",description:"Task status"},priority:{type:"string",description:"Task priority"},tags:{type:"array",items:{type:"string"},description:"Task tags"},projects:{type:"array",items:{type:"string"},description:"Associated projects"}},required:["id","title","status"]},session:{type:"object",properties:{startTime:{type:"string",format:"date-time",description:"When the session started"},description:{type:"string",nullable:!0,description:"Session description"},elapsedMinutes:{type:"integer",minimum:0,description:"Minutes elapsed since session started"}},required:["startTime","elapsedMinutes"]},elapsedMinutes:{type:"integer",minimum:0,description:"Total elapsed minutes for this session"}},required:["task","session","elapsedMinutes"]},TimeSummary:{type:"object",properties:{period:{type:"string",enum:["today","week","month","all","custom"],description:"Time period for the summary"},dateRange:{type:"object",properties:{from:{type:"string",format:"date-time",description:"Start date of the summary period"},to:{type:"string",format:"date-time",description:"End date of the summary period"}},required:["from","to"]},summary:{type:"object",properties:{totalMinutes:{type:"integer",minimum:0,description:"Total tracked time in minutes"},totalHours:{type:"number",minimum:0,description:"Total tracked time in hours (rounded to 2 decimals)"},tasksWithTime:{type:"integer",minimum:0,description:"Number of tasks with time tracking data"},activeTasks:{type:"integer",minimum:0,description:"Number of tasks with active time tracking"},completedTasks:{type:"integer",minimum:0,description:"Number of completed tasks with time tracking"}},required:["totalMinutes","totalHours","tasksWithTime","activeTasks","completedTasks"]},topTasks:{type:"array",items:{type:"object",properties:{task:{type:"string",description:"Task identifier"},title:{type:"string",description:"Task title"},minutes:{type:"integer",minimum:0,description:"Total minutes tracked for this task"}},required:["task","title","minutes"]},description:"Top 10 tasks by time tracked"},topProjects:{type:"array",items:{type:"object",properties:{project:{type:"string",description:"Project name"},minutes:{type:"integer",minimum:0,description:"Total minutes tracked for this project"}},required:["project","minutes"]},description:"Top 10 projects by time tracked"},topTags:{type:"array",items:{type:"object",properties:{tag:{type:"string",description:"Tag name"},minutes:{type:"integer",minimum:0,description:"Total minutes tracked for this tag"}},required:["tag","minutes"]},description:"Top 10 tags by time tracked"}},required:["period","dateRange","summary","topTasks","topProjects","topTags"]},TaskTimeData:{type:"object",properties:{task:{type:"object",properties:{id:{type:"string",description:"Task identifier (file path)"},title:{type:"string",description:"Task title"},status:{type:"string",description:"Task status"},priority:{type:"string",description:"Task priority"}},required:["id","title","status"]},summary:{type:"object",properties:{totalMinutes:{type:"integer",minimum:0,description:"Total time tracked for this task in minutes"},totalHours:{type:"number",minimum:0,description:"Total time tracked for this task in hours"},totalSessions:{type:"integer",minimum:0,description:"Total number of time tracking sessions"},completedSessions:{type:"integer",minimum:0,description:"Number of completed sessions"},activeSessions:{type:"integer",minimum:0,maximum:1,description:"Number of active sessions (0 or 1)"},averageSessionMinutes:{type:"number",minimum:0,description:"Average session length in minutes"}},required:["totalMinutes","totalHours","totalSessions","completedSessions","activeSessions","averageSessionMinutes"]},activeSession:{type:"object",nullable:!0,properties:{startTime:{type:"string",format:"date-time",description:"When the active session started"},description:{type:"string",nullable:!0,description:"Description of the active session"},elapsedMinutes:{type:"integer",minimum:0,description:"Minutes elapsed since session started"}},required:["startTime","elapsedMinutes"]},timeEntries:{type:"array",items:{$ref:"#/components/schemas/TimeEntry"},description:"All time entries for this task"}},required:["task","summary","timeEntries"]},Error:{type:"object",properties:{success:{type:"boolean",enum:[!1]},error:{type:"string",description:"Error message describing what went wrong"}},required:["success","error"]}}}function x3(n){return Reflect.getMetadata("routes",n)||[]}var wlr,zJe,BJe,dD,lDe,qc=y(()=>{wlr=tt(oDe());q();zJe=M({tag:"Utils/OpenAPIDecorators"}),BJe=Symbol("openapi:operation"),dD=Symbol("openapi:endpoints"),lDe=Symbol("route")});function Os(n){var e;return new URL((e=n.url)!=null?e:"","http://localhost")}var cg=y(()=>{});var BF,uDe=y(()=>{cg();qc();BF=class{constructor(){this.routes=[]}compilePattern(e){let t=[],r=e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(i,s)=>(t.push(s),"([^/]+)"));return{regex:new RegExp(`^${r}$`),paramNames:t}}register(e,t,r){let{regex:a,paramNames:i}=this.compilePattern(t);this.routes.push({method:e,pattern:t,handler:r,regex:a,paramNames:i})}get(e,t){this.register("GET",e,t)}post(e,t){this.register("POST",e,t)}put(e,t){this.register("PUT",e,t)}delete(e,t){this.register("DELETE",e,t)}options(e,t){this.register("OPTIONS",e,t)}async route(e,t){let r=Os(e).pathname,a=e.method;for(let i of this.routes)if(i.method===a){let s=r.match(i.regex);if(s){let o={};for(let l=0;l{let r="";n.on("data",a=>{r+=a.toString()}),n.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(a){t(new Error("Invalid JSON"))}}),n.on("error",t)})}var UJe,HJe,VJe,WJe,E3=y(()=>{UJe="GET, POST, PUT, DELETE, OPTIONS",HJe="Content-Type, Authorization",VJe=new Set(["localhost","127.0.0.1","::1","[::1]"]),WJe=new Set(["chrome-extension:"])});var Za,Tm=y(()=>{E3();Za=class{sendResponse(e,t,r){$F(e,t,r)}successResponse(e,t){return{success:!0,data:e,message:t}}errorResponse(e){return{success:!1,error:e}}getErrorMessage(e){return e instanceof Error?e.message:String(e)}async parseRequestBody(e){return await UF(e)}}});async function HF(n,e){let t=n.vault.getAbstractFileByPath(e.path);if(!(t instanceof mDe.TFile))return e;let r=await n.vault.read(t),{body:a}=Gu(r);return{...e,details:a.replace(/\r\n/g,` +`).trimEnd()}}var mDe,D3=y(()=>{mDe=require("obsidian");yt()});var Qa,fDe=y(()=>{cg();Tm();D3();qc();Qa=class extends Za{constructor(t,r,a,i,s){super();this.plugin=t;this.taskService=r;this.filterService=a;this.cacheManager=i;this.taskStatsService=s}async getTasks(t,r){try{let a=Os(t).searchParams;if(["status","priority","project","context","tag","overdue","completed","archived","due_before","due_after","sort"].some(h=>a.has(h))){this.sendResponse(r,400,this.errorResponse("For filtering tasks, please use POST /api/tasks/query which supports advanced filtering capabilities. GET /api/tasks is for basic listing only. See API documentation for details."));return}let o=await this.cacheManager.getAllTasks(),l=0,c=50,d=a.get("offset");d&&(l=parseInt(d,10),(isNaN(l)||l<0)&&(l=0));let u=a.get("limit");u&&(c=parseInt(u,10),(isNaN(c)||c<1)&&(c=50),c>200&&(c=200));let p=o.slice(l,l+c),m=this.plugin.app.vault.adapter,f=null;try{"basePath"in m&&typeof m.basePath=="string"?f=m.basePath:"path"in m&&typeof m.path=="string"&&(f=m.path)}catch(h){}this.sendResponse(r,200,this.successResponse({tasks:p,pagination:{total:o.length,offset:l,limit:c,hasMore:l+c{cg();Tm();qc();CE();Gc=class extends Za{constructor(t,r,a,i){super();this.plugin=t;this.taskService=r;this.cacheManager=a;this.statusManager=i}async startTimeTracking(t,r,a){try{let i=a==null?void 0:a.id;if(!i){this.sendResponse(r,400,this.errorResponse("Task ID is required"));return}let s=await this.cacheManager.getTaskInfo(i);if(!s){this.sendResponse(r,404,this.errorResponse("Task not found"));return}let o=await this.taskService.startTimeTracking(s);this.sendResponse(r,200,this.successResponse(o))}catch(i){this.sendResponse(r,400,this.errorResponse(this.getErrorMessage(i)))}}async stopTimeTracking(t,r,a){try{let i=a==null?void 0:a.id;if(!i){this.sendResponse(r,400,this.errorResponse("Task ID is required"));return}let s=await this.cacheManager.getTaskInfo(i);if(!s){this.sendResponse(r,404,this.errorResponse("Task not found"));return}let o=await this.taskService.stopTimeTracking(s);this.sendResponse(r,200,this.successResponse(o))}catch(i){this.sendResponse(r,400,this.errorResponse(this.getErrorMessage(i)))}}async startTimeTrackingWithDescription(t,r,a){var i;try{let s=a==null?void 0:a.id;if(!s){this.sendResponse(r,400,this.errorResponse("Task ID is required"));return}let o=await this.cacheManager.getTaskInfo(s);if(!o){this.sendResponse(r,404,this.errorResponse("Task not found"));return}let c=(i=(await this.parseRequestBody(t)).description)!=null?i:"",d=await this.taskService.startTimeTracking(o);if(c&&d.timeEntries&&d.timeEntries.length>0){let u=d.timeEntries[d.timeEntries.length-1];u&&!u.endTime&&(u.description=c,d=await this.taskService.updateTask(d,{timeEntries:d.timeEntries}))}this.sendResponse(r,200,this.successResponse({task:d,message:c?`Time tracking started with description: ${c}`:"Time tracking started"}))}catch(s){this.sendResponse(r,400,this.errorResponse(this.getErrorMessage(s)))}}async getActiveTimeSessions(t,r){try{let a=await this.cacheManager.getAllTasks(),i=Qk(a,s=>this.plugin.getActiveTimeSession(s));this.sendResponse(r,200,this.successResponse(i))}catch(a){this.sendResponse(r,500,this.errorResponse(this.getErrorMessage(a)))}}async getTimeSummary(t,r){try{let a=Os(t).searchParams,i=await this.cacheManager.getAllTasks(),s=a.get("period")||"today",o=a.get("from"),l=a.get("to"),c=o?new Date(o):null,d=l?new Date(l):null,u=Jk(i,{period:s,fromDate:c,toDate:d,includeTags:!0},p=>this.statusManager.isCompletedStatus(p));this.sendResponse(r,200,this.successResponse(u))}catch(a){this.sendResponse(r,500,this.errorResponse(this.getErrorMessage(a)))}}async getTaskTimeData(t,r,a){try{let i=a==null?void 0:a.id;if(!i){this.sendResponse(r,400,this.errorResponse("Task ID is required"));return}let s=await this.cacheManager.getTaskInfo(i);if(!s){this.sendResponse(r,404,this.errorResponse("Task not found"));return}let o=pm(s,l=>this.plugin.getActiveTimeSession(l));this.sendResponse(r,200,this.successResponse(o))}catch(i){this.sendResponse(r,500,this.errorResponse(this.getErrorMessage(i)))}}};Qe([ln("/api/tasks/:id/time/start")],Gc.prototype,"startTimeTracking",1),Qe([ln("/api/tasks/:id/time/stop")],Gc.prototype,"stopTimeTracking",1),Qe([ln("/api/tasks/:id/time/start-with-description")],Gc.prototype,"startTimeTrackingWithDescription",1),Qe([Rr("/api/time/active")],Gc.prototype,"getActiveTimeSessions",1),Qe([Rr("/api/time/summary")],Gc.prototype,"getTimeSummary",1),Qe([Rr("/api/tasks/:id/time")],Gc.prototype,"getTaskTimeData",1)});var kl,gDe=y(()=>{cg();Tm();qc();kl=class extends Za{constructor(t,r){super();this.plugin=t;this.cacheManager=r}async startPomodoro(t,r){try{let a=await this.parseRequestBody(t),i;if(a.taskId){let c=await this.cacheManager.getTaskInfo(a.taskId);if(!c){this.sendResponse(r,404,this.errorResponse("Task not found"));return}i=c}if(this.plugin.pomodoroService.getState().isRunning){this.sendResponse(r,400,this.errorResponse("Pomodoro session is already running. Stop or pause the current session first."));return}let o=a.duration!==void 0?parseInt(String(a.duration),10):void 0;await this.plugin.pomodoroService.startPomodoro(i,o);let l=this.plugin.pomodoroService.getState();this.sendResponse(r,200,this.successResponse({session:l.currentSession,task:i||null,message:"Pomodoro session started"}))}catch(a){this.sendResponse(r,400,this.errorResponse(this.getErrorMessage(a)))}}async stopPomodoro(t,r){try{if(!this.plugin.pomodoroService.getState().currentSession){this.sendResponse(r,400,this.errorResponse("No active pomodoro session to stop"));return}await this.plugin.pomodoroService.stopPomodoro(),this.sendResponse(r,200,this.successResponse({message:"Pomodoro session stopped and reset"}))}catch(a){this.sendResponse(r,400,this.errorResponse(this.getErrorMessage(a)))}}async pausePomodoro(t,r){try{let a=this.plugin.pomodoroService.getState();if(!a.isRunning||!a.currentSession){this.sendResponse(r,400,this.errorResponse("No running pomodoro session to pause"));return}await this.plugin.pomodoroService.pausePomodoro();let i=this.plugin.pomodoroService.getState();this.sendResponse(r,200,this.successResponse({timeRemaining:i.timeRemaining,message:"Pomodoro session paused"}))}catch(a){this.sendResponse(r,400,this.errorResponse(this.getErrorMessage(a)))}}async resumePomodoro(t,r){try{let a=this.plugin.pomodoroService.getState();if(a.isRunning){this.sendResponse(r,400,this.errorResponse("Pomodoro session is already running"));return}if(!a.currentSession){this.sendResponse(r,400,this.errorResponse("No paused session to resume"));return}await this.plugin.pomodoroService.resumePomodoro();let i=this.plugin.pomodoroService.getState();this.sendResponse(r,200,this.successResponse({timeRemaining:i.timeRemaining,message:"Pomodoro session resumed"}))}catch(a){this.sendResponse(r,400,this.errorResponse(this.getErrorMessage(a)))}}async getPomodoroStatus(t,r){try{let i={...this.plugin.pomodoroService.getState(),totalPomodoros:await this.plugin.pomodoroService.getPomodorosCompleted(),currentStreak:await this.plugin.pomodoroService.getCurrentStreak(),totalMinutesToday:await this.plugin.pomodoroService.getTotalMinutesToday()};this.sendResponse(r,200,this.successResponse(i))}catch(a){this.sendResponse(r,500,this.errorResponse(this.getErrorMessage(a)))}}async getPomodoroSessions(t,r){try{let a=Os(t).searchParams,i=await this.plugin.pomodoroService.getSessionHistory(),s=a.get("date");if(s){let c=s;i=i.filter(d=>new Date(d.startTime).toISOString().split("T")[0]===c)}let o=i.length,l=a.get("limit");if(l){let c=parseInt(l,10);c>0&&(i=i.slice(-c))}this.sendResponse(r,200,this.successResponse({sessions:i,total:o}))}catch(a){this.sendResponse(r,500,this.errorResponse(this.getErrorMessage(a)))}}async getPomodoroStats(t,r){try{let a=Os(t).searchParams,i,s=a.get("date");if(s){let o=new Date(s);i=await this.plugin.pomodoroService.getStatsForDate(o)}else i=await this.plugin.pomodoroService.getTodayStats();this.sendResponse(r,200,this.successResponse(i))}catch(a){this.sendResponse(r,500,this.errorResponse(this.getErrorMessage(a)))}}};Qe([ln("/api/pomodoro/start")],kl.prototype,"startPomodoro",1),Qe([ln("/api/pomodoro/stop")],kl.prototype,"stopPomodoro",1),Qe([ln("/api/pomodoro/pause")],kl.prototype,"pausePomodoro",1),Qe([ln("/api/pomodoro/resume")],kl.prototype,"resumePomodoro",1),Qe([Rr("/api/pomodoro/status")],kl.prototype,"getPomodoroStatus",1),Qe([Rr("/api/pomodoro/sessions")],kl.prototype,"getPomodoroSessions",1),Qe([Rr("/api/pomodoro/stats")],kl.prototype,"getPomodoroStats",1)});var yDe,bu,vDe=y(()=>{Tm();TC();qc();q();yDe=M({tag:"Api/SystemController"}),bu=class extends Za{constructor(t,r,a,i){super();this.plugin=t;this.taskService=r;this.nlParser=a;this.httpAPIService=i}async healthCheck(t,r){let a=this.plugin.app.vault.getName(),i=this.plugin.app.vault.adapter,s=null;try{"basePath"in i&&typeof i.basePath=="string"?s=i.basePath:"path"in i&&typeof i.path=="string"&&(s=i.path)}catch(o){}this.sendResponse(r,200,this.successResponse({status:"ok",timestamp:new Date().toISOString(),vault:{name:a,path:s}}))}async handleNLPParse(t,r){try{let a=await this.parseRequestBody(t);if(!a.text||typeof a.text!="string"){this.sendResponse(r,400,this.errorResponse("Text field is required and must be a string"));return}let i=this.nlParser.parseInput(a.text),s=Vd(this.plugin,i);this.sendResponse(r,200,this.successResponse({parsed:i,taskData:s}))}catch(a){this.sendResponse(r,500,this.errorResponse(this.getErrorMessage(a)))}}async handleNLPCreate(t,r){try{let a=await this.parseRequestBody(t);if(!a.text||typeof a.text!="string"){this.sendResponse(r,400,this.errorResponse("Text field is required and must be a string"));return}let i=this.nlParser.parseInput(a.text),s=Vd(this.plugin,i,{creationContext:"api"}),o=await this.taskService.createTask(s);this.sendResponse(r,201,this.successResponse({task:o.taskInfo,parsed:i}))}catch(a){this.sendResponse(r,400,this.errorResponse(this.getErrorMessage(a)))}}async handleOpenAPISpec(t,r){try{let a=this.httpAPIService&&this.httpAPIService.generateOpenAPISpec?this.httpAPIService.generateOpenAPISpec():uD(this);r.statusCode=200,r.setHeader("Content-Type","application/json"),r.end(JSON.stringify(a,null,2))}catch(a){yDe.error("OpenAPI spec generation error:",{category:"provider",operation:"openapi-spec-generation",error:a}),this.sendResponse(r,500,this.errorResponse("Failed to generate API specification"))}}async handleSwaggerUI(t,r){try{let a=this.generateSwaggerUIHTML();r.statusCode=200,r.setHeader("Content-Type","text/html"),r.end(a)}catch(a){yDe.error("Swagger UI generation error:",{category:"provider",operation:"swagger-ui-generation",error:a}),this.sendResponse(r,500,this.errorResponse("Failed to generate API documentation"))}}generateSwaggerUIHTML(){return` + + + + + TaskNotes API Documentation + + + + +
+